diff --git a/python/user_packages/Python313/site-packages/numpy-2.4.4.dist-info/licenses/LICENSE.txt b/python/user_packages/Python313/site-packages/numpy-2.4.4.dist-info/licenses/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..2ee057eeb0bc419bc18d1c5bd9a0683d4b1a6815 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy-2.4.4.dist-info/licenses/LICENSE.txt @@ -0,0 +1,914 @@ +Copyright (c) 2005-2025, NumPy Developers. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + + * Neither the name of the NumPy Developers nor the names of any + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +---- + + +---- + +This binary distribution of NumPy also bundles the following software: + + +Name: OpenBLAS +Files: numpy.libs\libscipy_openblas*.dll +Description: bundled as a dynamically linked library +Availability: https://github.com/OpenMathLib/OpenBLAS/ +License: BSD-3-Clause + Copyright (c) 2011-2014, The OpenBLAS Project + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are + met: + + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the + distribution. + 3. Neither the name of the OpenBLAS project nor the names of + its contributors may be used to endorse or promote products + derived from this software without specific prior written + permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +Name: LAPACK +Files: numpy.libs\libscipy_openblas*.dll +Description: bundled in OpenBLAS +Availability: https://github.com/OpenMathLib/OpenBLAS/ +License: BSD-3-Clause-Open-MPI + Copyright (c) 1992-2013 The University of Tennessee and The University + of Tennessee Research Foundation. All rights + reserved. + Copyright (c) 2000-2013 The University of California Berkeley. All + rights reserved. + Copyright (c) 2006-2013 The University of Colorado Denver. All rights + reserved. + + $COPYRIGHT$ + + Additional copyrights may follow + + $HEADER$ + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are + met: + + - Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + - Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer listed + in this license in the documentation and/or other materials + provided with the distribution. + + - Neither the name of the copyright holders nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + The copyright holders provide no reassurances that the source code + provided does not infringe any patent, copyright, or any other + intellectual property rights of third parties. The copyright holders + disclaim any liability to any recipient for claims brought against + recipient by any third party for infringement of that parties + intellectual property rights. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +Name: GCC runtime library +Files: numpy.libs\libscipy_openblas*.dll +Description: statically linked to files compiled with gcc +Availability: https://gcc.gnu.org/git/?p=gcc.git;a=tree;f=libgfortran +License: GPL-3.0-or-later WITH GCC-exception-3.1 + Copyright (C) 2002-2017 Free Software Foundation, Inc. + + Libgfortran is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3, or (at your option) + any later version. + + Libgfortran is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + Under Section 7 of GPL version 3, you are granted additional + permissions described in the GCC Runtime Library Exception, version + 3.1, as published by the Free Software Foundation. + + You should have received a copy of the GNU General Public License and + a copy of the GCC Runtime Library Exception along with this program; + see the files COPYING3 and COPYING.RUNTIME respectively. If not, see + . + +---- + +Full text of license texts referred to above follows (that they are +listed below does not necessarily imply the conditions apply to the +present binary release): + +---- + +GCC RUNTIME LIBRARY EXCEPTION + +Version 3.1, 31 March 2009 + +Copyright (C) 2009 Free Software Foundation, Inc. + +Everyone is permitted to copy and distribute verbatim copies of this +license document, but changing it is not allowed. + +This GCC Runtime Library Exception ("Exception") is an additional +permission under section 7 of the GNU General Public License, version +3 ("GPLv3"). It applies to a given file (the "Runtime Library") that +bears a notice placed by the copyright holder of the file stating that +the file is governed by GPLv3 along with this Exception. + +When you use GCC to compile a program, GCC may combine portions of +certain GCC header files and runtime libraries with the compiled +program. The purpose of this Exception is to allow compilation of +non-GPL (including proprietary) programs to use, in this way, the +header files and runtime libraries covered by this Exception. + +0. Definitions. + +A file is an "Independent Module" if it either requires the Runtime +Library for execution after a Compilation Process, or makes use of an +interface provided by the Runtime Library, but is not otherwise based +on the Runtime Library. + +"GCC" means a version of the GNU Compiler Collection, with or without +modifications, governed by version 3 (or a specified later version) of +the GNU General Public License (GPL) with the option of using any +subsequent versions published by the FSF. + +"GPL-compatible Software" is software whose conditions of propagation, +modification and use would permit combination with GCC in accord with +the license of GCC. + +"Target Code" refers to output from any compiler for a real or virtual +target processor architecture, in executable form or suitable for +input to an assembler, loader, linker and/or execution +phase. Notwithstanding that, Target Code does not include data in any +format that is used as a compiler intermediate representation, or used +for producing a compiler intermediate representation. + +The "Compilation Process" transforms code entirely represented in +non-intermediate languages designed for human-written code, and/or in +Java Virtual Machine byte code, into Target Code. Thus, for example, +use of source code generators and preprocessors need not be considered +part of the Compilation Process, since the Compilation Process can be +understood as starting with the output of the generators or +preprocessors. + +A Compilation Process is "Eligible" if it is done using GCC, alone or +with other GPL-compatible software, or if it is done without using any +work based on GCC. For example, using non-GPL-compatible Software to +optimize any GCC intermediate representations would not qualify as an +Eligible Compilation Process. + +1. Grant of Additional Permission. + +You have permission to propagate a work of Target Code formed by +combining the Runtime Library with Independent Modules, even if such +propagation would otherwise violate the terms of GPLv3, provided that +all Target Code was generated by Eligible Compilation Processes. You +may then convey such a combination under terms of your choice, +consistent with the licensing of the Independent Modules. + +2. No Weakening of GCC Copyleft. + +The availability of this Exception does not imply any general +presumption that third-party software is unaffected by the copyleft +requirements of the license of GCC. + +---- + + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. + diff --git a/python/user_packages/Python313/site-packages/numpy-2.4.4.dist-info/licenses/numpy/_core/include/numpy/libdivide/LICENSE.txt b/python/user_packages/Python313/site-packages/numpy-2.4.4.dist-info/licenses/numpy/_core/include/numpy/libdivide/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..375a7faa07019536b6b9aad67949fbfa5b4c12db --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy-2.4.4.dist-info/licenses/numpy/_core/include/numpy/libdivide/LICENSE.txt @@ -0,0 +1,21 @@ + zlib License + ------------ + + Copyright (C) 2010 - 2019 ridiculous_fish, + Copyright (C) 2016 - 2019 Kim Walisch, + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. diff --git a/python/user_packages/Python313/site-packages/numpy-2.4.4.dist-info/licenses/numpy/_core/src/common/pythoncapi-compat/COPYING b/python/user_packages/Python313/site-packages/numpy-2.4.4.dist-info/licenses/numpy/_core/src/common/pythoncapi-compat/COPYING new file mode 100644 index 0000000000000000000000000000000000000000..6a223f9f6b2d351e52b2112af654c49cdcd742df --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy-2.4.4.dist-info/licenses/numpy/_core/src/common/pythoncapi-compat/COPYING @@ -0,0 +1,14 @@ +BSD Zero Clause License + +Copyright Contributors to the pythoncapi_compat project. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. diff --git a/python/user_packages/Python313/site-packages/numpy-2.4.4.dist-info/licenses/numpy/_core/src/highway/LICENSE b/python/user_packages/Python313/site-packages/numpy-2.4.4.dist-info/licenses/numpy/_core/src/highway/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..70cc735458ff85838fb08a61148eb8c9fe4ef8ad --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy-2.4.4.dist-info/licenses/numpy/_core/src/highway/LICENSE @@ -0,0 +1,371 @@ +This project is primarily dual-licensed under your choice of either the Apache +License 2.0 or the BSD 3-Clause License. + +The following files are licensed under different terms: +* hwy/contrib/random/random-inl.h: CC0 1.0 Universal + +The full texts of all applicable licenses are included below, separated by +'---'. + +-------------------------------------------------------------------------------- +Apache License 2.0 +-------------------------------------------------------------------------------- + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +-------------------------------------------------------------------------------- +BSD 3-Clause License +-------------------------------------------------------------------------------- + +Copyright (c) The Highway Project Authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +-------------------------------------------------------------------------------- +CC0 1.0 Universal +-------------------------------------------------------------------------------- + +Creative Commons Legal Code + +CC0 1.0 Universal + + CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE + LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN + ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS + INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES + REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS + PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM + THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED + HEREUNDER. + +Statement of Purpose + +The laws of most jurisdictions throughout the world automatically confer +exclusive Copyright and Related Rights (defined below) upon the creator +and subsequent owner(s) (each and all, an "owner") of an original work of +authorship and/or a database (each, a "Work"). + +Certain owners wish to permanently relinquish those rights to a Work for +the purpose of contributing to a commons of creative, cultural and +scientific works ("Commons") that the public can reliably and without fear +of later claims of infringement build upon, modify, incorporate in other +works, reuse and redistribute as freely as possible in any form whatsoever +and for any purposes, including without limitation commercial purposes. +These owners may contribute to the Commons to promote the ideal of a free +culture and the further production of creative, cultural and scientific +works, or to gain reputation or greater distribution for their Work in +part through the use and efforts of others. + +For these and/or other purposes and motivations, and without any +expectation of additional consideration or compensation, the person +associating CC0 with a Work (the "Affirmer"), to the extent that he or she +is an owner of Copyright and Related Rights in the Work, voluntarily +elects to apply CC0 to the Work and publicly distribute the Work under its +terms, with knowledge of his or her Copyright and Related Rights in the +Work and the meaning and intended legal effect of CC0 on those rights. + +1. Copyright and Related Rights. A Work made available under CC0 may be +protected by copyright and related or neighboring rights ("Copyright and +Related Rights"). Copyright and Related Rights include, but are not +limited to, the following: + + i. the right to reproduce, adapt, distribute, perform, display, + communicate, and translate a Work; + ii. moral rights retained by the original author(s) and/or performer(s); +iii. publicity and privacy rights pertaining to a person's image or + likeness depicted in a Work; + iv. rights protecting against unfair competition in regards to a Work, + subject to the limitations in paragraph 4(a), below; + v. rights protecting the extraction, dissemination, use and reuse of data + in a Work; + vi. database rights (such as those arising under Directive 96/9/EC of the + European Parliament and of the Council of 11 March 1996 on the legal + protection of databases, and under any national implementation + thereof, including any amended or successor version of such + directive); and +vii. other similar, equivalent or corresponding rights throughout the + world based on applicable law or treaty, and any national + implementations thereof. + +2. Waiver. To the greatest extent permitted by, but not in contravention +of, applicable law, Affirmer hereby overtly, fully, permanently, +irrevocably and unconditionally waives, abandons, and surrenders all of +Affirmer's Copyright and Related Rights and associated claims and causes +of action, whether now known or unknown (including existing as well as +future claims and causes of action), in the Work (i) in all territories +worldwide, (ii) for the maximum duration provided by applicable law or +treaty (including future time extensions), (iii) in any current or future +medium and for any number of copies, and (iv) for any purpose whatsoever, +including without limitation commercial, advertising or promotional +purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each +member of the public at large and to the detriment of Affirmer's heirs and +successors, fully intending that such Waiver shall not be subject to +revocation, rescission, cancellation, termination, or any other legal or +equitable action to disrupt the quiet enjoyment of the Work by the public +as contemplated by Affirmer's express Statement of Purpose. + +3. Public License Fallback. Should any part of the Waiver for any reason +be judged legally invalid or ineffective under applicable law, then the +Waiver shall be preserved to the maximum extent permitted taking into +account Affirmer's express Statement of Purpose. In addition, to the +extent the Waiver is so judged Affirmer hereby grants to each affected +person a royalty-free, non transferable, non sublicensable, non exclusive, +irrevocable and unconditional license to exercise Affirmer's Copyright and +Related Rights in the Work (i) in all territories worldwide, (ii) for the +maximum duration provided by applicable law or treaty (including future +time extensions), (iii) in any current or future medium and for any number +of copies, and (iv) for any purpose whatsoever, including without +limitation commercial, advertising or promotional purposes (the +"License"). The License shall be deemed effective as of the date CC0 was +applied by Affirmer to the Work. Should any part of the License for any +reason be judged legally invalid or ineffective under applicable law, such +partial invalidity or ineffectiveness shall not invalidate the remainder +of the License, and in such case Affirmer hereby affirms that he or she +will not (i) exercise any of his or her remaining Copyright and Related +Rights in the Work or (ii) assert any associated claims and causes of +action with respect to the Work, in either case contrary to Affirmer's +express Statement of Purpose. + +4. Limitations and Disclaimers. + + a. No trademark or patent rights held by Affirmer are waived, abandoned, + surrendered, licensed or otherwise affected by this document. + b. Affirmer offers the Work as-is and makes no representations or + warranties of any kind concerning the Work, express, implied, + statutory or otherwise, including without limitation warranties of + title, merchantability, fitness for a particular purpose, non + infringement, or the absence of latent or other defects, accuracy, or + the present or absence of errors, whether or not discoverable, all to + the greatest extent permissible under applicable law. + c. Affirmer disclaims responsibility for clearing rights of other persons + that may apply to the Work or any use thereof, including without + limitation any person's Copyright and Related Rights in the Work. + Further, Affirmer disclaims responsibility for obtaining any necessary + consents, permissions or other rights required for any use of the + Work. + d. Affirmer understands and acknowledges that Creative Commons is not a + party to this document and has no duty or obligation with respect to + this CC0 or use of the Work. \ No newline at end of file diff --git a/python/user_packages/Python313/site-packages/numpy-2.4.4.dist-info/licenses/numpy/_core/src/multiarray/dragon4_LICENSE.txt b/python/user_packages/Python313/site-packages/numpy-2.4.4.dist-info/licenses/numpy/_core/src/multiarray/dragon4_LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..cb24e976e19f1146d0ca8ae8ad7f64d125b71e34 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy-2.4.4.dist-info/licenses/numpy/_core/src/multiarray/dragon4_LICENSE.txt @@ -0,0 +1,27 @@ +Copyright (c) 2014 Ryan Juckett + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. + +dragon4.c|h h contains a modified version of Ryan Juckett's Dragon4 +implementation, obtained from https://www.ryanjuckett.com, +which has been ported from C++ to C and which has +modifications specific to printing floats in numpy. + +Ryan Juckett's original code was under the Zlib license; he gave numpy +permission to include it under the MIT license instead. diff --git a/python/user_packages/Python313/site-packages/numpy-2.4.4.dist-info/licenses/numpy/_core/src/npysort/x86-simd-sort/LICENSE.md b/python/user_packages/Python313/site-packages/numpy-2.4.4.dist-info/licenses/numpy/_core/src/npysort/x86-simd-sort/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..99399cd4ec783c1c2af00c6e38357fb518d7b250 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy-2.4.4.dist-info/licenses/numpy/_core/src/npysort/x86-simd-sort/LICENSE.md @@ -0,0 +1,28 @@ +BSD 3-Clause License + +Copyright (c) 2022, Intel. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/python/user_packages/Python313/site-packages/numpy-2.4.4.dist-info/licenses/numpy/_core/src/umath/svml/LICENSE b/python/user_packages/Python313/site-packages/numpy-2.4.4.dist-info/licenses/numpy/_core/src/umath/svml/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..51b8406fa98999f72f20a5cc72d321188b660eb0 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy-2.4.4.dist-info/licenses/numpy/_core/src/umath/svml/LICENSE @@ -0,0 +1,30 @@ +Copyright (c) 2005-2021, NumPy Developers. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + + * Neither the name of the NumPy Developers nor the names of any + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/python/user_packages/Python313/site-packages/numpy-2.4.4.dist-info/licenses/numpy/fft/pocketfft/LICENSE.md b/python/user_packages/Python313/site-packages/numpy-2.4.4.dist-info/licenses/numpy/fft/pocketfft/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..79b818c5e05787714dfea4bb234c8b2b0ef0b064 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy-2.4.4.dist-info/licenses/numpy/fft/pocketfft/LICENSE.md @@ -0,0 +1,25 @@ +Copyright (C) 2010-2018 Max-Planck-Society +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright notice, this + list of conditions and the following disclaimer in the documentation and/or + other materials provided with the distribution. +* Neither the name of the copyright holder nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/python/user_packages/Python313/site-packages/numpy-2.4.4.dist-info/licenses/numpy/linalg/lapack_lite/LICENSE.txt b/python/user_packages/Python313/site-packages/numpy-2.4.4.dist-info/licenses/numpy/linalg/lapack_lite/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..4d23316b6739404951c27f97b9098612931d4247 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy-2.4.4.dist-info/licenses/numpy/linalg/lapack_lite/LICENSE.txt @@ -0,0 +1,48 @@ +Copyright (c) 1992-2013 The University of Tennessee and The University + of Tennessee Research Foundation. All rights + reserved. +Copyright (c) 2000-2013 The University of California Berkeley. All + rights reserved. +Copyright (c) 2006-2013 The University of Colorado Denver. All rights + reserved. + +$COPYRIGHT$ + +Additional copyrights may follow + +$HEADER$ + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +- Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +- Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer listed + in this license in the documentation and/or other materials + provided with the distribution. + +- Neither the name of the copyright holders nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +The copyright holders provide no reassurances that the source code +provided does not infringe any patent, copyright, or any other +intellectual property rights of third parties. The copyright holders +disclaim any liability to any recipient for claims brought against +recipient by any third party for infringement of that parties +intellectual property rights. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/python/user_packages/Python313/site-packages/numpy-2.4.4.dist-info/licenses/numpy/ma/LICENSE b/python/user_packages/Python313/site-packages/numpy-2.4.4.dist-info/licenses/numpy/ma/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..f165a0f6dbf57b89e2f6e23b9f042750dde3caab --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy-2.4.4.dist-info/licenses/numpy/ma/LICENSE @@ -0,0 +1,24 @@ +* Copyright (c) 2006, University of Georgia and Pierre G.F. Gerard-Marchant +* All rights reserved. +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the University of Georgia nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \ No newline at end of file diff --git a/python/user_packages/Python313/site-packages/numpy-2.4.4.dist-info/licenses/numpy/random/LICENSE.md b/python/user_packages/Python313/site-packages/numpy-2.4.4.dist-info/licenses/numpy/random/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..4f9513f1eddbc5aba61a8a1ef8f64869b2b4a917 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy-2.4.4.dist-info/licenses/numpy/random/LICENSE.md @@ -0,0 +1,71 @@ +**This software is dual-licensed under the The University of Illinois/NCSA +Open Source License (NCSA) and The 3-Clause BSD License** + +# NCSA Open Source License +**Copyright (c) 2019 Kevin Sheppard. All rights reserved.** + +Developed by: Kevin Sheppard (, +) +[http://www.kevinsheppard.com](http://www.kevinsheppard.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal with +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +Redistributions of source code must retain the above copyright notice, this +list of conditions and the following disclaimers. + +Redistributions in binary form must reproduce the above copyright notice, this +list of conditions and the following disclaimers in the documentation and/or +other materials provided with the distribution. + +Neither the names of Kevin Sheppard, nor the names of any contributors may be +used to endorse or promote products derived from this Software without specific +prior written permission. + +**THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH +THE SOFTWARE.** + + +# 3-Clause BSD License +**Copyright (c) 2019 Kevin Sheppard. All rights reserved.** + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +**THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF +THE POSSIBILITY OF SUCH DAMAGE.** + +# Components + +Many parts of this module have been derived from original sources, +often the algorithm's designer. Component licenses are located with +the component code. diff --git a/python/user_packages/Python313/site-packages/numpy-2.4.4.dist-info/licenses/numpy/random/src/distributions/LICENSE.md b/python/user_packages/Python313/site-packages/numpy-2.4.4.dist-info/licenses/numpy/random/src/distributions/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..3d693b8e9c756567fa50cc8b9ec2f6590396c0d6 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy-2.4.4.dist-info/licenses/numpy/random/src/distributions/LICENSE.md @@ -0,0 +1,61 @@ +## NumPy + +Copyright (c) 2005-2017, NumPy Developers. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +* Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + +* Neither the name of the NumPy Developers nor the names of any + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +## Julia + +The ziggurat methods were derived from Julia. + +Copyright (c) 2009-2019: Jeff Bezanson, Stefan Karpinski, Viral B. Shah, +and other contributors: + +https://github.com/JuliaLang/julia/contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/python/user_packages/Python313/site-packages/numpy-2.4.4.dist-info/licenses/numpy/random/src/mt19937/LICENSE.md b/python/user_packages/Python313/site-packages/numpy-2.4.4.dist-info/licenses/numpy/random/src/mt19937/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..364e728d996d5cf4ca5251560050f6246a435601 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy-2.4.4.dist-info/licenses/numpy/random/src/mt19937/LICENSE.md @@ -0,0 +1,61 @@ +# MT19937 + +Copyright (c) 2003-2005, Jean-Sebastien Roy (js@jeannot.org) + +The rk_random and rk_seed functions algorithms and the original design of +the Mersenne Twister RNG: + + Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura, + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + 3. The names of its contributors may not be used to endorse or promote + products derived from this software without specific prior written + permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER +OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +Original algorithm for the implementation of rk_interval function from +Richard J. Wagner's implementation of the Mersenne Twister RNG, optimised by +Magnus Jonsson. + +Constants used in the rk_double implementation by Isaku Wada. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/python/user_packages/Python313/site-packages/numpy-2.4.4.dist-info/licenses/numpy/random/src/pcg64/LICENSE.md b/python/user_packages/Python313/site-packages/numpy-2.4.4.dist-info/licenses/numpy/random/src/pcg64/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..da7487a3110780bd9bc1e682d2a0c4f8b5f1e9e1 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy-2.4.4.dist-info/licenses/numpy/random/src/pcg64/LICENSE.md @@ -0,0 +1,22 @@ +# PCG64 + +## The MIT License + +PCG Random Number Generation for C. + +Copyright 2014 Melissa O'Neill + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the "Software"), +to deal in the Software without restriction, including without limitation +the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/python/user_packages/Python313/site-packages/numpy-2.4.4.dist-info/licenses/numpy/random/src/philox/LICENSE.md b/python/user_packages/Python313/site-packages/numpy-2.4.4.dist-info/licenses/numpy/random/src/philox/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..c815ae29364457c0bdccf417d170c2dd8696e09a --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy-2.4.4.dist-info/licenses/numpy/random/src/philox/LICENSE.md @@ -0,0 +1,31 @@ +# PHILOX + +Copyright 2010-2012, D. E. Shaw Research. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +* Redistributions of source code must retain the above copyright + notice, this list of conditions, and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright + notice, this list of conditions, and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +* Neither the name of D. E. Shaw Research nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/python/user_packages/Python313/site-packages/numpy-2.4.4.dist-info/licenses/numpy/random/src/sfc64/LICENSE.md b/python/user_packages/Python313/site-packages/numpy-2.4.4.dist-info/licenses/numpy/random/src/sfc64/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..84707451a9f5c6432ef3a959f6c60d401327b981 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy-2.4.4.dist-info/licenses/numpy/random/src/sfc64/LICENSE.md @@ -0,0 +1,27 @@ +# SFC64 + +## The MIT License + +Adapted from a C++ implementation of Chris Doty-Humphrey's SFC PRNG. + +https://gist.github.com/imneme/f1f7821f07cf76504a97f6537c818083 + +Copyright (c) 2018 Melissa E. O'Neill + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the "Software"), +to deal in the Software without restriction, including without limitation +the rights to use, copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/python/user_packages/Python313/site-packages/numpy-2.4.4.dist-info/licenses/numpy/random/src/splitmix64/LICENSE.md b/python/user_packages/Python313/site-packages/numpy-2.4.4.dist-info/licenses/numpy/random/src/splitmix64/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..fb75aa5b380f24d69518397ed93da5317c9da113 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy-2.4.4.dist-info/licenses/numpy/random/src/splitmix64/LICENSE.md @@ -0,0 +1,9 @@ +# SPLITMIX64 + +Written in 2015 by Sebastiano Vigna (vigna@acm.org) + +To the extent possible under law, the author has dedicated all copyright +and related and neighboring rights to this software to the public domain +worldwide. This software is distributed without any warranty. + +See . \ No newline at end of file diff --git a/python/user_packages/Python313/site-packages/numpy/char/__init__.py b/python/user_packages/Python313/site-packages/numpy/char/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0a360f7f74cd0c9ce96997d659353af7fa2b1555 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/char/__init__.py @@ -0,0 +1,2 @@ +from numpy._core.defchararray import * +from numpy._core.defchararray import __all__, __doc__ diff --git a/python/user_packages/Python313/site-packages/numpy/char/__init__.pyi b/python/user_packages/Python313/site-packages/numpy/char/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..c736eb28b5638e9db16c58c466c5ec45fa081dca --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/char/__init__.pyi @@ -0,0 +1,111 @@ +from numpy._core.defchararray import ( + add, + array, + asarray, + capitalize, + center, + chararray, + compare_chararrays, + count, + decode, + encode, + endswith, + equal, + expandtabs, + find, + greater, + greater_equal, + index, + isalnum, + isalpha, + isdecimal, + isdigit, + islower, + isnumeric, + isspace, + istitle, + isupper, + join, + less, + less_equal, + ljust, + lower, + lstrip, + mod, + multiply, + not_equal, + partition, + replace, + rfind, + rindex, + rjust, + rpartition, + rsplit, + rstrip, + split, + splitlines, + startswith, + str_len, + strip, + swapcase, + title, + translate, + upper, + zfill, +) + +__all__ = [ + "equal", + "not_equal", + "greater_equal", + "less_equal", + "greater", + "less", + "str_len", + "add", + "multiply", + "mod", + "capitalize", + "center", + "count", + "decode", + "encode", + "endswith", + "expandtabs", + "find", + "index", + "isalnum", + "isalpha", + "isdigit", + "islower", + "isspace", + "istitle", + "isupper", + "join", + "ljust", + "lower", + "lstrip", + "partition", + "replace", + "rfind", + "rindex", + "rjust", + "rpartition", + "rsplit", + "rstrip", + "split", + "splitlines", + "startswith", + "strip", + "swapcase", + "title", + "translate", + "upper", + "zfill", + "isnumeric", + "isdecimal", + "array", + "asarray", + "compare_chararrays", + "chararray", +] diff --git a/python/user_packages/Python313/site-packages/numpy/core/__init__.py b/python/user_packages/Python313/site-packages/numpy/core/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bd55086d0f0e6d4b605a1217421d5a29ccf10b --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/core/__init__.py @@ -0,0 +1,33 @@ +""" +The `numpy.core` submodule exists solely for backward compatibility +purposes. The original `core` was renamed to `_core` and made private. +`numpy.core` will be removed in the future. +""" +from numpy import _core + +from ._utils import _raise_warning + + +# We used to use `np.core._ufunc_reconstruct` to unpickle. +# This is unnecessary, but old pickles saved before 1.20 will be using it, +# and there is no reason to break loading them. +def _ufunc_reconstruct(module, name): + # The `fromlist` kwarg is required to ensure that `mod` points to the + # inner-most module rather than the parent package when module name is + # nested. This makes it possible to pickle non-toplevel ufuncs such as + # scipy.special.expit for instance. + mod = __import__(module, fromlist=[name]) + return getattr(mod, name) + + +# force lazy-loading of submodules to ensure a warning is printed + +__all__ = ["arrayprint", "defchararray", "_dtype_ctypes", "_dtype", # noqa: F822 + "einsumfunc", "fromnumeric", "function_base", "getlimits", + "_internal", "multiarray", "_multiarray_umath", "numeric", + "numerictypes", "overrides", "records", "shape_base", "umath"] + +def __getattr__(attr_name): + attr = getattr(_core, attr_name) + _raise_warning(attr_name) + return attr diff --git a/python/user_packages/Python313/site-packages/numpy/core/__init__.pyi b/python/user_packages/Python313/site-packages/numpy/core/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/python/user_packages/Python313/site-packages/numpy/core/_dtype.py b/python/user_packages/Python313/site-packages/numpy/core/_dtype.py new file mode 100644 index 0000000000000000000000000000000000000000..9bda9108c55c3e34d06dc41ed6631848070655c0 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/core/_dtype.py @@ -0,0 +1,10 @@ +def __getattr__(attr_name): + from numpy._core import _dtype + + from ._utils import _raise_warning + ret = getattr(_dtype, attr_name, None) + if ret is None: + raise AttributeError( + f"module 'numpy.core._dtype' has no attribute {attr_name}") + _raise_warning(attr_name, "_dtype") + return ret diff --git a/python/user_packages/Python313/site-packages/numpy/core/_dtype.pyi b/python/user_packages/Python313/site-packages/numpy/core/_dtype.pyi new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/python/user_packages/Python313/site-packages/numpy/core/_dtype_ctypes.py b/python/user_packages/Python313/site-packages/numpy/core/_dtype_ctypes.py new file mode 100644 index 0000000000000000000000000000000000000000..4e82bed72241bc37b0744907036071ffe073172e --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/core/_dtype_ctypes.py @@ -0,0 +1,10 @@ +def __getattr__(attr_name): + from numpy._core import _dtype_ctypes + + from ._utils import _raise_warning + ret = getattr(_dtype_ctypes, attr_name, None) + if ret is None: + raise AttributeError( + f"module 'numpy.core._dtype_ctypes' has no attribute {attr_name}") + _raise_warning(attr_name, "_dtype_ctypes") + return ret diff --git a/python/user_packages/Python313/site-packages/numpy/core/_dtype_ctypes.pyi b/python/user_packages/Python313/site-packages/numpy/core/_dtype_ctypes.pyi new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/python/user_packages/Python313/site-packages/numpy/core/_internal.py b/python/user_packages/Python313/site-packages/numpy/core/_internal.py new file mode 100644 index 0000000000000000000000000000000000000000..f9c3d211d4344ac20f202f257f8b45ef5b009253 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/core/_internal.py @@ -0,0 +1,27 @@ +from numpy._core import _internal + + +# Build a new array from the information in a pickle. +# Note that the name numpy.core._internal._reconstruct is embedded in +# pickles of ndarrays made with NumPy before release 1.0 +# so don't remove the name here, or you'll +# break backward compatibility. +def _reconstruct(subtype, shape, dtype): + from numpy import ndarray + return ndarray.__new__(subtype, shape, dtype) + + +# Pybind11 (in versions <= 2.11.1) imports _dtype_from_pep3118 from the +# _internal submodule, therefore it must be importable without a warning. +_dtype_from_pep3118 = _internal._dtype_from_pep3118 + +def __getattr__(attr_name): + from numpy._core import _internal + + from ._utils import _raise_warning + ret = getattr(_internal, attr_name, None) + if ret is None: + raise AttributeError( + f"module 'numpy.core._internal' has no attribute {attr_name}") + _raise_warning(attr_name, "_internal") + return ret diff --git a/python/user_packages/Python313/site-packages/numpy/core/_multiarray_umath.py b/python/user_packages/Python313/site-packages/numpy/core/_multiarray_umath.py new file mode 100644 index 0000000000000000000000000000000000000000..7c188fd9158e88eae0dcf8b555c9364f8d4ccbd1 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/core/_multiarray_umath.py @@ -0,0 +1,57 @@ +from numpy import ufunc +from numpy._core import _multiarray_umath + +for item in _multiarray_umath.__dir__(): + # ufuncs appear in pickles with a path in numpy.core._multiarray_umath + # and so must import from this namespace without warning or error + attr = getattr(_multiarray_umath, item) + if isinstance(attr, ufunc): + globals()[item] = attr + + +def __getattr__(attr_name): + from numpy._core import _multiarray_umath + + from ._utils import _raise_warning + + if attr_name in {"_ARRAY_API", "_UFUNC_API"}: + import sys + import textwrap + import traceback + + from numpy.version import short_version + + msg = textwrap.dedent(f""" + A module that was compiled using NumPy 1.x cannot be run in + NumPy {short_version} as it may crash. To support both 1.x and 2.x + versions of NumPy, modules must be compiled with NumPy 2.0. + Some module may need to rebuild instead e.g. with 'pybind11>=2.12'. + + If you are a user of the module, the easiest solution will be to + downgrade to 'numpy<2' or try to upgrade the affected module. + We expect that some modules will need time to support NumPy 2. + + """) + tb_msg = "Traceback (most recent call last):" + for line in traceback.format_stack()[:-1]: + if "frozen importlib" in line: + continue + tb_msg += line + + # Also print the message (with traceback). This is because old versions + # of NumPy unfortunately set up the import to replace (and hide) the + # error. The traceback shouldn't be needed, but e.g. pytest plugins + # seem to swallow it and we should be failing anyway... + sys.stderr.write(msg + tb_msg) + raise ImportError(msg) + + ret = getattr(_multiarray_umath, attr_name, None) + if ret is None: + raise AttributeError( + "module 'numpy.core._multiarray_umath' has no attribute " + f"{attr_name}") + _raise_warning(attr_name, "_multiarray_umath") + return ret + + +del _multiarray_umath, ufunc diff --git a/python/user_packages/Python313/site-packages/numpy/core/_utils.py b/python/user_packages/Python313/site-packages/numpy/core/_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..d94f39bcb3cc155ce6534c8c81d06ef0e1ccf63e --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/core/_utils.py @@ -0,0 +1,21 @@ +import warnings + + +def _raise_warning(attr: str, submodule: str | None = None) -> None: + new_module = "numpy._core" + old_module = "numpy.core" + if submodule is not None: + new_module = f"{new_module}.{submodule}" + old_module = f"{old_module}.{submodule}" + warnings.warn( + f"{old_module} is deprecated and has been renamed to {new_module}. " + "The numpy._core namespace contains private NumPy internals and its " + "use is discouraged, as NumPy internals can change without warning in " + "any release. In practice, most real-world usage of numpy.core is to " + "access functionality in the public NumPy API. If that is the case, " + "use the public NumPy API. If not, you are using NumPy internals. " + "If you would still like to access an internal attribute, " + f"use {new_module}.{attr}.", + DeprecationWarning, + stacklevel=3 + ) diff --git a/python/user_packages/Python313/site-packages/numpy/core/arrayprint.py b/python/user_packages/Python313/site-packages/numpy/core/arrayprint.py new file mode 100644 index 0000000000000000000000000000000000000000..6f3bcf8acb1f10bf3c595e3ab7a886ac16ba31a1 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/core/arrayprint.py @@ -0,0 +1,10 @@ +def __getattr__(attr_name): + from numpy._core import arrayprint + + from ._utils import _raise_warning + ret = getattr(arrayprint, attr_name, None) + if ret is None: + raise AttributeError( + f"module 'numpy.core.arrayprint' has no attribute {attr_name}") + _raise_warning(attr_name, "arrayprint") + return ret diff --git a/python/user_packages/Python313/site-packages/numpy/core/defchararray.py b/python/user_packages/Python313/site-packages/numpy/core/defchararray.py new file mode 100644 index 0000000000000000000000000000000000000000..da288809e79a14a83709774404eec5281b05c9aa --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/core/defchararray.py @@ -0,0 +1,10 @@ +def __getattr__(attr_name): + from numpy._core import defchararray + + from ._utils import _raise_warning + ret = getattr(defchararray, attr_name, None) + if ret is None: + raise AttributeError( + f"module 'numpy.core.defchararray' has no attribute {attr_name}") + _raise_warning(attr_name, "defchararray") + return ret diff --git a/python/user_packages/Python313/site-packages/numpy/core/einsumfunc.py b/python/user_packages/Python313/site-packages/numpy/core/einsumfunc.py new file mode 100644 index 0000000000000000000000000000000000000000..d1e974e0b977a695423bcf2c469553b70b13f497 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/core/einsumfunc.py @@ -0,0 +1,10 @@ +def __getattr__(attr_name): + from numpy._core import einsumfunc + + from ._utils import _raise_warning + ret = getattr(einsumfunc, attr_name, None) + if ret is None: + raise AttributeError( + f"module 'numpy.core.einsumfunc' has no attribute {attr_name}") + _raise_warning(attr_name, "einsumfunc") + return ret diff --git a/python/user_packages/Python313/site-packages/numpy/core/fromnumeric.py b/python/user_packages/Python313/site-packages/numpy/core/fromnumeric.py new file mode 100644 index 0000000000000000000000000000000000000000..e50084f7f8cd5cc1be1bb49de57f9d189fcc7fe8 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/core/fromnumeric.py @@ -0,0 +1,10 @@ +def __getattr__(attr_name): + from numpy._core import fromnumeric + + from ._utils import _raise_warning + ret = getattr(fromnumeric, attr_name, None) + if ret is None: + raise AttributeError( + f"module 'numpy.core.fromnumeric' has no attribute {attr_name}") + _raise_warning(attr_name, "fromnumeric") + return ret diff --git a/python/user_packages/Python313/site-packages/numpy/core/function_base.py b/python/user_packages/Python313/site-packages/numpy/core/function_base.py new file mode 100644 index 0000000000000000000000000000000000000000..88fc2268b66064714fdd87efa17c1b2137c75c1b --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/core/function_base.py @@ -0,0 +1,10 @@ +def __getattr__(attr_name): + from numpy._core import function_base + + from ._utils import _raise_warning + ret = getattr(function_base, attr_name, None) + if ret is None: + raise AttributeError( + f"module 'numpy.core.function_base' has no attribute {attr_name}") + _raise_warning(attr_name, "function_base") + return ret diff --git a/python/user_packages/Python313/site-packages/numpy/core/getlimits.py b/python/user_packages/Python313/site-packages/numpy/core/getlimits.py new file mode 100644 index 0000000000000000000000000000000000000000..65c1107a349064278717f15f25206286d0645ef9 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/core/getlimits.py @@ -0,0 +1,10 @@ +def __getattr__(attr_name): + from numpy._core import getlimits + + from ._utils import _raise_warning + ret = getattr(getlimits, attr_name, None) + if ret is None: + raise AttributeError( + f"module 'numpy.core.getlimits' has no attribute {attr_name}") + _raise_warning(attr_name, "getlimits") + return ret diff --git a/python/user_packages/Python313/site-packages/numpy/core/multiarray.py b/python/user_packages/Python313/site-packages/numpy/core/multiarray.py new file mode 100644 index 0000000000000000000000000000000000000000..bb604a89dd0096040bf77e02302ce86a118e1082 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/core/multiarray.py @@ -0,0 +1,25 @@ +from numpy._core import multiarray + +# these must import without warning or error from numpy.core.multiarray to +# support old pickle files +for item in ["_reconstruct", "scalar"]: + globals()[item] = getattr(multiarray, item) + +# Pybind11 (in versions <= 2.11.1) imports _ARRAY_API from the multiarray +# submodule as a part of NumPy initialization, therefore it must be importable +# without a warning. +_ARRAY_API = multiarray._ARRAY_API + +def __getattr__(attr_name): + from numpy._core import multiarray + + from ._utils import _raise_warning + ret = getattr(multiarray, attr_name, None) + if ret is None: + raise AttributeError( + f"module 'numpy.core.multiarray' has no attribute {attr_name}") + _raise_warning(attr_name, "multiarray") + return ret + + +del multiarray diff --git a/python/user_packages/Python313/site-packages/numpy/core/numeric.py b/python/user_packages/Python313/site-packages/numpy/core/numeric.py new file mode 100644 index 0000000000000000000000000000000000000000..dcf0fd1696dd2e021cd9c196e3cef75fb69a4ef0 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/core/numeric.py @@ -0,0 +1,12 @@ +def __getattr__(attr_name): + from numpy._core import numeric + + from ._utils import _raise_warning + + sentinel = object() + ret = getattr(numeric, attr_name, sentinel) + if ret is sentinel: + raise AttributeError( + f"module 'numpy.core.numeric' has no attribute {attr_name}") + _raise_warning(attr_name, "numeric") + return ret diff --git a/python/user_packages/Python313/site-packages/numpy/core/numerictypes.py b/python/user_packages/Python313/site-packages/numpy/core/numerictypes.py new file mode 100644 index 0000000000000000000000000000000000000000..9ed72d613dfb362e2274f3222d7649715d206a4f --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/core/numerictypes.py @@ -0,0 +1,10 @@ +def __getattr__(attr_name): + from numpy._core import numerictypes + + from ._utils import _raise_warning + ret = getattr(numerictypes, attr_name, None) + if ret is None: + raise AttributeError( + f"module 'numpy.core.numerictypes' has no attribute {attr_name}") + _raise_warning(attr_name, "numerictypes") + return ret diff --git a/python/user_packages/Python313/site-packages/numpy/core/overrides.py b/python/user_packages/Python313/site-packages/numpy/core/overrides.py new file mode 100644 index 0000000000000000000000000000000000000000..eac0bb408b90aaf69fadd2fde2d432e733a851e8 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/core/overrides.py @@ -0,0 +1,10 @@ +def __getattr__(attr_name): + from numpy._core import overrides + + from ._utils import _raise_warning + ret = getattr(overrides, attr_name, None) + if ret is None: + raise AttributeError( + f"module 'numpy.core.overrides' has no attribute {attr_name}") + _raise_warning(attr_name, "overrides") + return ret diff --git a/python/user_packages/Python313/site-packages/numpy/core/overrides.pyi b/python/user_packages/Python313/site-packages/numpy/core/overrides.pyi new file mode 100644 index 0000000000000000000000000000000000000000..0d44e772b9f027a7dcfb6eab5274bd41a5fe8b1b --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/core/overrides.pyi @@ -0,0 +1,7 @@ +# NOTE: At runtime, this submodule dynamically re-exports any `numpy._core.overrides` +# member, and issues a `DeprecationWarning` when accessed. But since there is no +# `__dir__` or `__all__` present, these annotations would be unverifiable. Because +# this module is also deprecated in favor of `numpy._core`, and therefore not part of +# the public API, we omit the "re-exports", which in practice would require literal +# duplication of the stubs in order for the `@deprecated` decorator to be understood +# by type-checkers. diff --git a/python/user_packages/Python313/site-packages/numpy/core/records.py b/python/user_packages/Python313/site-packages/numpy/core/records.py new file mode 100644 index 0000000000000000000000000000000000000000..e3c84dd1fa86c11f92d56bc0ddcf23173f597624 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/core/records.py @@ -0,0 +1,10 @@ +def __getattr__(attr_name): + from numpy._core import records + + from ._utils import _raise_warning + ret = getattr(records, attr_name, None) + if ret is None: + raise AttributeError( + f"module 'numpy.core.records' has no attribute {attr_name}") + _raise_warning(attr_name, "records") + return ret diff --git a/python/user_packages/Python313/site-packages/numpy/core/shape_base.py b/python/user_packages/Python313/site-packages/numpy/core/shape_base.py new file mode 100644 index 0000000000000000000000000000000000000000..2372a66599c4033aa25eb21358f3c6201a3abf0a --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/core/shape_base.py @@ -0,0 +1,10 @@ +def __getattr__(attr_name): + from numpy._core import shape_base + + from ._utils import _raise_warning + ret = getattr(shape_base, attr_name, None) + if ret is None: + raise AttributeError( + f"module 'numpy.core.shape_base' has no attribute {attr_name}") + _raise_warning(attr_name, "shape_base") + return ret diff --git a/python/user_packages/Python313/site-packages/numpy/core/umath.py b/python/user_packages/Python313/site-packages/numpy/core/umath.py new file mode 100644 index 0000000000000000000000000000000000000000..836c0b3a81c9bc9c9feb187458f0ee624cc13106 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/core/umath.py @@ -0,0 +1,10 @@ +def __getattr__(attr_name): + from numpy._core import umath + + from ._utils import _raise_warning + ret = getattr(umath, attr_name, None) + if ret is None: + raise AttributeError( + f"module 'numpy.core.umath' has no attribute {attr_name}") + _raise_warning(attr_name, "umath") + return ret diff --git a/python/user_packages/Python313/site-packages/numpy/ctypeslib/__init__.py b/python/user_packages/Python313/site-packages/numpy/ctypeslib/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..35d2e3190715dea110ff2642d87bb307ee160b95 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/ctypeslib/__init__.py @@ -0,0 +1,13 @@ +from ._ctypeslib import ( + __all__, + __doc__, + _concrete_ndptr, + _ndptr, + as_array, + as_ctypes, + as_ctypes_type, + c_intp, + ctypes, + load_library, + ndpointer, +) diff --git a/python/user_packages/Python313/site-packages/numpy/ctypeslib/__init__.pyi b/python/user_packages/Python313/site-packages/numpy/ctypeslib/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..e9efaa421d0c40063bfbdf17ba4bc5647f218b43 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/ctypeslib/__init__.pyi @@ -0,0 +1,15 @@ +import ctypes +from ctypes import c_int64 as _c_intp + +from ._ctypeslib import ( + __all__ as __all__, + __doc__ as __doc__, + _concrete_ndptr as _concrete_ndptr, + _ndptr as _ndptr, + as_array as as_array, + as_ctypes as as_ctypes, + as_ctypes_type as as_ctypes_type, + c_intp as c_intp, + load_library as load_library, + ndpointer as ndpointer, +) diff --git a/python/user_packages/Python313/site-packages/numpy/ctypeslib/_ctypeslib.py b/python/user_packages/Python313/site-packages/numpy/ctypeslib/_ctypeslib.py new file mode 100644 index 0000000000000000000000000000000000000000..92a3c789bb7a4a43d444d2c243dd675a2d029982 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/ctypeslib/_ctypeslib.py @@ -0,0 +1,603 @@ +""" +============================ +``ctypes`` Utility Functions +============================ + +See Also +-------- +load_library : Load a C library. +ndpointer : Array restype/argtype with verification. +as_ctypes : Create a ctypes array from an ndarray. +as_array : Create an ndarray from a ctypes array. + +References +---------- +.. [1] "SciPy Cookbook: ctypes", https://scipy-cookbook.readthedocs.io/items/Ctypes.html + +Examples +-------- +Load the C library: + +>>> _lib = np.ctypeslib.load_library('libmystuff', '.') #doctest: +SKIP + +Our result type, an ndarray that must be of type double, be 1-dimensional +and is C-contiguous in memory: + +>>> array_1d_double = np.ctypeslib.ndpointer( +... dtype=np.double, +... ndim=1, flags='CONTIGUOUS') #doctest: +SKIP + +Our C-function typically takes an array and updates its values +in-place. For example:: + + void foo_func(double* x, int length) + { + int i; + for (i = 0; i < length; i++) { + x[i] = i*i; + } + } + +We wrap it using: + +>>> _lib.foo_func.restype = None #doctest: +SKIP +>>> _lib.foo_func.argtypes = [array_1d_double, c_int] #doctest: +SKIP + +Then, we're ready to call ``foo_func``: + +>>> out = np.empty(15, dtype=np.double) +>>> _lib.foo_func(out, len(out)) #doctest: +SKIP + +""" +__all__ = ['load_library', 'ndpointer', 'c_intp', 'as_ctypes', 'as_array', + 'as_ctypes_type'] + +import os + +import numpy as np +import numpy._core.multiarray as mu +from numpy._utils import set_module + +try: + import ctypes +except ImportError: + ctypes = None + +if ctypes is None: + @set_module("numpy.ctypeslib") + def _dummy(*args, **kwds): + """ + Dummy object that raises an ImportError if ctypes is not available. + + Raises + ------ + ImportError + If ctypes is not available. + + """ + raise ImportError("ctypes is not available.") + load_library = _dummy + as_ctypes = _dummy + as_ctypes_type = _dummy + as_array = _dummy + ndpointer = _dummy + from numpy import intp as c_intp + _ndptr_base = object +else: + import numpy._core._internal as nic + c_intp = nic._getintp_ctype() + del nic + _ndptr_base = ctypes.c_void_p + + # Adapted from Albert Strasheim + @set_module("numpy.ctypeslib") + def load_library(libname, loader_path): + """ + It is possible to load a library using + + >>> lib = ctypes.cdll[] # doctest: +SKIP + + But there are cross-platform considerations, such as library file extensions, + plus the fact Windows will just load the first library it finds with that name. + NumPy supplies the load_library function as a convenience. + + .. versionchanged:: 1.20.0 + Allow libname and loader_path to take any + :term:`python:path-like object`. + + Parameters + ---------- + libname : path-like + Name of the library, which can have 'lib' as a prefix, + but without an extension. + loader_path : path-like + Where the library can be found. + + Returns + ------- + ctypes.cdll[libpath] : library object + A ctypes library object + + Raises + ------ + OSError + If there is no library with the expected extension, or the + library is defective and cannot be loaded. + """ + # Convert path-like objects into strings + libname = os.fsdecode(libname) + loader_path = os.fsdecode(loader_path) + + ext = os.path.splitext(libname)[1] + if not ext: + import sys + import sysconfig + # Try to load library with platform-specific name, otherwise + # default to libname.[so|dll|dylib]. Sometimes, these files are + # built erroneously on non-linux platforms. + base_ext = ".so" + if sys.platform.startswith("darwin"): + base_ext = ".dylib" + elif sys.platform.startswith("win"): + base_ext = ".dll" + libname_ext = [libname + base_ext] + so_ext = sysconfig.get_config_var("EXT_SUFFIX") + if not so_ext == base_ext: + libname_ext.insert(0, libname + so_ext) + else: + libname_ext = [libname] + + loader_path = os.path.abspath(loader_path) + if not os.path.isdir(loader_path): + libdir = os.path.dirname(loader_path) + else: + libdir = loader_path + + for ln in libname_ext: + libpath = os.path.join(libdir, ln) + if os.path.exists(libpath): + try: + return ctypes.cdll[libpath] + except OSError: + # defective lib file + raise + # if no successful return in the libname_ext loop: + raise OSError("no file with expected extension") + + +def _num_fromflags(flaglist): + num = 0 + for val in flaglist: + num += mu._flagdict[val] + return num + + +_flagnames = ['C_CONTIGUOUS', 'F_CONTIGUOUS', 'ALIGNED', 'WRITEABLE', + 'OWNDATA', 'WRITEBACKIFCOPY'] +def _flags_fromnum(num): + res = [] + for key in _flagnames: + value = mu._flagdict[key] + if (num & value): + res.append(key) + return res + + +class _ndptr(_ndptr_base): + @classmethod + def from_param(cls, obj): + if not isinstance(obj, np.ndarray): + raise TypeError("argument must be an ndarray") + if cls._dtype_ is not None \ + and obj.dtype != cls._dtype_: + raise TypeError(f"array must have data type {cls._dtype_}") + if cls._ndim_ is not None \ + and obj.ndim != cls._ndim_: + raise TypeError("array must have %d dimension(s)" % cls._ndim_) + if cls._shape_ is not None \ + and obj.shape != cls._shape_: + raise TypeError(f"array must have shape {str(cls._shape_)}") + if cls._flags_ is not None \ + and ((obj.flags.num & cls._flags_) != cls._flags_): + raise TypeError(f"array must have flags {_flags_fromnum(cls._flags_)}") + return obj.ctypes + + +class _concrete_ndptr(_ndptr): + """ + Like _ndptr, but with `_shape_` and `_dtype_` specified. + + Notably, this means the pointer has enough information to reconstruct + the array, which is not generally true. + """ + def _check_retval_(self): + """ + This method is called when this class is used as the .restype + attribute for a shared-library function, to automatically wrap the + pointer into an array. + """ + return self.contents + + @property + def contents(self): + """ + Get an ndarray viewing the data pointed to by this pointer. + + This mirrors the `contents` attribute of a normal ctypes pointer + """ + full_dtype = np.dtype((self._dtype_, self._shape_)) + full_ctype = ctypes.c_char * full_dtype.itemsize + buffer = ctypes.cast(self, ctypes.POINTER(full_ctype)).contents + return np.frombuffer(buffer, dtype=full_dtype).squeeze(axis=0) + + +# Factory for an array-checking class with from_param defined for +# use with ctypes argtypes mechanism +_pointer_type_cache = {} + +@set_module("numpy.ctypeslib") +def ndpointer(dtype=None, ndim=None, shape=None, flags=None): + """ + Array-checking restype/argtypes. + + An ndpointer instance is used to describe an ndarray in restypes + and argtypes specifications. This approach is more flexible than + using, for example, ``POINTER(c_double)``, since several restrictions + can be specified, which are verified upon calling the ctypes function. + These include data type, number of dimensions, shape and flags. If a + given array does not satisfy the specified restrictions, + a ``TypeError`` is raised. + + Parameters + ---------- + dtype : data-type, optional + Array data-type. + ndim : int, optional + Number of array dimensions. + shape : tuple of ints, optional + Array shape. + flags : str or tuple of str + Array flags; may be one or more of: + + - C_CONTIGUOUS / C / CONTIGUOUS + - F_CONTIGUOUS / F / FORTRAN + - OWNDATA / O + - WRITEABLE / W + - ALIGNED / A + - WRITEBACKIFCOPY / X + + Returns + ------- + klass : ndpointer type object + A type object, which is an ``_ndtpr`` instance containing + dtype, ndim, shape and flags information. + + Raises + ------ + TypeError + If a given array does not satisfy the specified restrictions. + + Examples + -------- + >>> clib.somefunc.argtypes = [np.ctypeslib.ndpointer(dtype=np.float64, + ... ndim=1, + ... flags='C_CONTIGUOUS')] + ... #doctest: +SKIP + >>> clib.somefunc(np.array([1, 2, 3], dtype=np.float64)) + ... #doctest: +SKIP + + """ + + # normalize dtype to dtype | None + if dtype is not None: + dtype = np.dtype(dtype) + + # normalize flags to int | None + num = None + if flags is not None: + if isinstance(flags, str): + flags = flags.split(',') + elif isinstance(flags, (int, np.integer)): + num = flags + flags = _flags_fromnum(num) + elif isinstance(flags, mu.flagsobj): + num = flags.num + flags = _flags_fromnum(num) + if num is None: + try: + flags = [x.strip().upper() for x in flags] + except Exception as e: + raise TypeError("invalid flags specification") from e + num = _num_fromflags(flags) + + # normalize shape to tuple | None + if shape is not None: + try: + shape = tuple(shape) + except TypeError: + # single integer -> 1-tuple + shape = (shape,) + + cache_key = (dtype, ndim, shape, num) + + try: + return _pointer_type_cache[cache_key] + except KeyError: + pass + + # produce a name for the new type + if dtype is None: + name = 'any' + elif dtype.names is not None: + name = str(id(dtype)) + else: + name = dtype.str + if ndim is not None: + name += "_%dd" % ndim + if shape is not None: + name += "_" + "x".join(str(x) for x in shape) + if flags is not None: + name += "_" + "_".join(flags) + + if dtype is not None and shape is not None: + base = _concrete_ndptr + else: + base = _ndptr + + klass = type(f"ndpointer_{name}", (base,), + {"_dtype_": dtype, + "_shape_": shape, + "_ndim_": ndim, + "_flags_": num}) + _pointer_type_cache[cache_key] = klass + return klass + + +if ctypes is not None: + def _ctype_ndarray(element_type, shape): + """ Create an ndarray of the given element type and shape """ + for dim in shape[::-1]: + element_type = dim * element_type + # prevent the type name include np.ctypeslib + element_type.__module__ = None + return element_type + + def _get_scalar_type_map(): + """ + Return a dictionary mapping native endian scalar dtype to ctypes types + """ + ct = ctypes + simple_types = [ + ct.c_byte, ct.c_short, ct.c_int, ct.c_long, ct.c_longlong, + ct.c_ubyte, ct.c_ushort, ct.c_uint, ct.c_ulong, ct.c_ulonglong, + ct.c_float, ct.c_double, + ct.c_bool, + ] + return {np.dtype(ctype): ctype for ctype in simple_types} + + _scalar_type_map = _get_scalar_type_map() + + def _ctype_from_dtype_scalar(dtype): + # swapping twice ensure that `=` is promoted to <, >, or | + dtype_with_endian = dtype.newbyteorder('S').newbyteorder('S') + dtype_native = dtype.newbyteorder('=') + try: + ctype = _scalar_type_map[dtype_native] + except KeyError as e: + raise NotImplementedError( + f"Converting {dtype!r} to a ctypes type" + ) from None + + if dtype_with_endian.byteorder == '>': + ctype = ctype.__ctype_be__ + elif dtype_with_endian.byteorder == '<': + ctype = ctype.__ctype_le__ + + return ctype + + def _ctype_from_dtype_subarray(dtype): + element_dtype, shape = dtype.subdtype + ctype = _ctype_from_dtype(element_dtype) + return _ctype_ndarray(ctype, shape) + + def _ctype_from_dtype_structured(dtype): + # extract offsets of each field + field_data = [] + for name in dtype.names: + field_dtype, offset = dtype.fields[name][:2] + field_data.append((offset, name, _ctype_from_dtype(field_dtype))) + + # ctypes doesn't care about field order + field_data = sorted(field_data, key=lambda f: f[0]) + + if len(field_data) > 1 and all(offset == 0 for offset, _, _ in field_data): + # union, if multiple fields all at address 0 + size = 0 + _fields_ = [] + for offset, name, ctype in field_data: + _fields_.append((name, ctype)) + size = max(size, ctypes.sizeof(ctype)) + + # pad to the right size + if dtype.itemsize != size: + _fields_.append(('', ctypes.c_char * dtype.itemsize)) + + # we inserted manual padding, so always `_pack_` + return type('union', (ctypes.Union,), { + '_fields_': _fields_, + '_pack_': 1, + '__module__': None, + }) + else: + last_offset = 0 + _fields_ = [] + for offset, name, ctype in field_data: + padding = offset - last_offset + if padding < 0: + raise NotImplementedError("Overlapping fields") + if padding > 0: + _fields_.append(('', ctypes.c_char * padding)) + + _fields_.append((name, ctype)) + last_offset = offset + ctypes.sizeof(ctype) + + padding = dtype.itemsize - last_offset + if padding > 0: + _fields_.append(('', ctypes.c_char * padding)) + + # we inserted manual padding, so always `_pack_` + return type('struct', (ctypes.Structure,), { + '_fields_': _fields_, + '_pack_': 1, + '__module__': None, + }) + + def _ctype_from_dtype(dtype): + if dtype.fields is not None: + return _ctype_from_dtype_structured(dtype) + elif dtype.subdtype is not None: + return _ctype_from_dtype_subarray(dtype) + else: + return _ctype_from_dtype_scalar(dtype) + + @set_module("numpy.ctypeslib") + def as_ctypes_type(dtype): + r""" + Convert a dtype into a ctypes type. + + Parameters + ---------- + dtype : dtype + The dtype to convert + + Returns + ------- + ctype + A ctype scalar, union, array, or struct + + Raises + ------ + NotImplementedError + If the conversion is not possible + + Notes + ----- + This function does not losslessly round-trip in either direction. + + ``np.dtype(as_ctypes_type(dt))`` will: + + - insert padding fields + - reorder fields to be sorted by offset + - discard field titles + + ``as_ctypes_type(np.dtype(ctype))`` will: + + - discard the class names of `ctypes.Structure`\ s and + `ctypes.Union`\ s + - convert single-element `ctypes.Union`\ s into single-element + `ctypes.Structure`\ s + - insert padding fields + + Examples + -------- + Converting a simple dtype: + + >>> dt = np.dtype('int8') + >>> ctype = np.ctypeslib.as_ctypes_type(dt) + >>> ctype + + + Converting a structured dtype: + + >>> dt = np.dtype([('x', 'i4'), ('y', 'f4')]) + >>> ctype = np.ctypeslib.as_ctypes_type(dt) + >>> ctype + + + """ + return _ctype_from_dtype(np.dtype(dtype)) + + @set_module("numpy.ctypeslib") + def as_array(obj, shape=None): + """ + Create a numpy array from a ctypes array or POINTER. + + The numpy array shares the memory with the ctypes object. + + The shape parameter must be given if converting from a ctypes POINTER. + The shape parameter is ignored if converting from a ctypes array + + Examples + -------- + Converting a ctypes integer array: + + >>> import ctypes + >>> ctypes_array = (ctypes.c_int * 5)(0, 1, 2, 3, 4) + >>> np_array = np.ctypeslib.as_array(ctypes_array) + >>> np_array + array([0, 1, 2, 3, 4], dtype=int32) + + Converting a ctypes POINTER: + + >>> import ctypes + >>> buffer = (ctypes.c_int * 5)(0, 1, 2, 3, 4) + >>> pointer = ctypes.cast(buffer, ctypes.POINTER(ctypes.c_int)) + >>> np_array = np.ctypeslib.as_array(pointer, (5,)) + >>> np_array + array([0, 1, 2, 3, 4], dtype=int32) + + """ + if isinstance(obj, ctypes._Pointer): + # convert pointers to an array of the desired shape + if shape is None: + raise TypeError( + 'as_array() requires a shape argument when called on a ' + 'pointer') + p_arr_type = ctypes.POINTER(_ctype_ndarray(obj._type_, shape)) + obj = ctypes.cast(obj, p_arr_type).contents + + return np.asarray(obj) + + @set_module("numpy.ctypeslib") + def as_ctypes(obj): + """ + Create and return a ctypes object from a numpy array. Actually + anything that exposes the __array_interface__ is accepted. + + Examples + -------- + Create ctypes object from inferred int ``np.array``: + + >>> inferred_int_array = np.array([1, 2, 3]) + >>> c_int_array = np.ctypeslib.as_ctypes(inferred_int_array) + >>> type(c_int_array) + + >>> c_int_array[:] + [1, 2, 3] + + Create ctypes object from explicit 8 bit unsigned int ``np.array`` : + + >>> exp_int_array = np.array([1, 2, 3], dtype=np.uint8) + >>> c_int_array = np.ctypeslib.as_ctypes(exp_int_array) + >>> type(c_int_array) + + >>> c_int_array[:] + [1, 2, 3] + + """ + ai = obj.__array_interface__ + if ai["strides"]: + raise TypeError("strided arrays not supported") + if ai["version"] != 3: + raise TypeError("only __array_interface__ version 3 supported") + addr, readonly = ai["data"] + if readonly: + raise TypeError("readonly arrays unsupported") + + # can't use `_dtype((ai["typestr"], ai["shape"]))` here, as it overflows + # dtype.itemsize (gh-14214) + ctype_scalar = as_ctypes_type(ai["typestr"]) + result_type = _ctype_ndarray(ctype_scalar, ai["shape"]) + result = result_type.from_address(addr) + result.__keep = obj + return result diff --git a/python/user_packages/Python313/site-packages/numpy/ctypeslib/_ctypeslib.pyi b/python/user_packages/Python313/site-packages/numpy/ctypeslib/_ctypeslib.pyi new file mode 100644 index 0000000000000000000000000000000000000000..90627278fd6fbaf680a858718126f94d9aff3d83 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/ctypeslib/_ctypeslib.pyi @@ -0,0 +1,236 @@ +# NOTE: Numpy's mypy plugin is used for importing the correct +# platform-specific `ctypes._SimpleCData[int]` sub-type +import ctypes +from _typeshed import StrOrBytesPath +from collections.abc import Iterable, Sequence +from ctypes import c_int64 as _c_intp +from typing import Any, ClassVar, Generic, Literal as L, TypeAlias, TypeVar, overload + +import numpy as np +from numpy import ( + byte, + double, + dtype, + generic, + intc, + long, + longdouble, + longlong, + ndarray, + short, + single, + ubyte, + uintc, + ulong, + ulonglong, + ushort, + void, +) +from numpy._core._internal import _ctypes +from numpy._core.multiarray import flagsobj +from numpy._typing import ( + DTypeLike, + NDArray, + _AnyShape, + _ArrayLike, + _BoolCodes, + _ByteCodes, + _DoubleCodes, + _DTypeLike, + _IntCCodes, + _LongCodes, + _LongDoubleCodes, + _LongLongCodes, + _ShapeLike, + _ShortCodes, + _SingleCodes, + _UByteCodes, + _UIntCCodes, + _ULongCodes, + _ULongLongCodes, + _UShortCodes, + _VoidDTypeLike, +) + +__all__ = ["load_library", "ndpointer", "c_intp", "as_ctypes", "as_array", "as_ctypes_type"] + +# TODO: Add a proper `_Shape` bound once we've got variadic typevars +_DTypeT = TypeVar("_DTypeT", bound=dtype) +_DTypeOptionalT = TypeVar("_DTypeOptionalT", bound=dtype | None) +_ScalarT = TypeVar("_ScalarT", bound=generic) + +_FlagsKind: TypeAlias = L[ + "C_CONTIGUOUS", "CONTIGUOUS", "C", + "F_CONTIGUOUS", "FORTRAN", "F", + "ALIGNED", "A", + "WRITEABLE", "W", + "OWNDATA", "O", + "WRITEBACKIFCOPY", "X", +] + +# TODO: Add a shape typevar once we have variadic typevars (PEP 646) +class _ndptr(ctypes.c_void_p, Generic[_DTypeOptionalT]): + # In practice these 4 classvars are defined in the dynamic class + # returned by `ndpointer` + _dtype_: ClassVar[_DTypeOptionalT] + _shape_: ClassVar[_AnyShape | None] + _ndim_: ClassVar[int | None] + _flags_: ClassVar[list[_FlagsKind] | None] + + @overload # type: ignore[override] + @classmethod + def from_param(cls: type[_ndptr[None]], obj: NDArray[Any]) -> _ctypes[Any]: ... + @overload + @classmethod + def from_param(cls: type[_ndptr[_DTypeT]], obj: ndarray[Any, _DTypeT]) -> _ctypes[Any]: ... + +class _concrete_ndptr(_ndptr[_DTypeT]): + _dtype_: ClassVar[_DTypeT] + _shape_: ClassVar[_AnyShape] + @property + def contents(self) -> ndarray[_AnyShape, _DTypeT]: ... + +def load_library(libname: StrOrBytesPath, loader_path: StrOrBytesPath) -> ctypes.CDLL: ... + +c_intp = _c_intp + +@overload +def ndpointer( + dtype: None = None, + ndim: int | None = None, + shape: _ShapeLike | None = None, + flags: _FlagsKind | Iterable[_FlagsKind] | int | flagsobj | None = None, +) -> type[_ndptr[None]]: ... +@overload +def ndpointer( + dtype: _DTypeLike[_ScalarT], + ndim: int | None = None, + *, + shape: _ShapeLike, + flags: _FlagsKind | Iterable[_FlagsKind] | int | flagsobj | None = None, +) -> type[_concrete_ndptr[dtype[_ScalarT]]]: ... +@overload +def ndpointer( + dtype: DTypeLike | None, + ndim: int | None = None, + *, + shape: _ShapeLike, + flags: _FlagsKind | Iterable[_FlagsKind] | int | flagsobj | None = None, +) -> type[_concrete_ndptr[dtype]]: ... +@overload +def ndpointer( + dtype: _DTypeLike[_ScalarT], + ndim: int | None = None, + shape: None = None, + flags: _FlagsKind | Iterable[_FlagsKind] | int | flagsobj | None = None, +) -> type[_ndptr[dtype[_ScalarT]]]: ... +@overload +def ndpointer( + dtype: DTypeLike | None, + ndim: int | None = None, + shape: None = None, + flags: _FlagsKind | Iterable[_FlagsKind] | int | flagsobj | None = None, +) -> type[_ndptr[dtype]]: ... + +@overload +def as_ctypes_type(dtype: _BoolCodes | _DTypeLike[np.bool] | type[ctypes.c_bool]) -> type[ctypes.c_bool]: ... +@overload +def as_ctypes_type(dtype: _ByteCodes | _DTypeLike[byte] | type[ctypes.c_byte]) -> type[ctypes.c_byte]: ... +@overload +def as_ctypes_type(dtype: _ShortCodes | _DTypeLike[short] | type[ctypes.c_short]) -> type[ctypes.c_short]: ... +@overload +def as_ctypes_type(dtype: _IntCCodes | _DTypeLike[intc] | type[ctypes.c_int]) -> type[ctypes.c_int]: ... +@overload +def as_ctypes_type(dtype: _LongCodes | _DTypeLike[long] | type[ctypes.c_long]) -> type[ctypes.c_long]: ... +@overload +def as_ctypes_type(dtype: type[int]) -> type[c_intp]: ... +@overload +def as_ctypes_type(dtype: _LongLongCodes | _DTypeLike[longlong] | type[ctypes.c_longlong]) -> type[ctypes.c_longlong]: ... +@overload +def as_ctypes_type(dtype: _UByteCodes | _DTypeLike[ubyte] | type[ctypes.c_ubyte]) -> type[ctypes.c_ubyte]: ... +@overload +def as_ctypes_type(dtype: _UShortCodes | _DTypeLike[ushort] | type[ctypes.c_ushort]) -> type[ctypes.c_ushort]: ... +@overload +def as_ctypes_type(dtype: _UIntCCodes | _DTypeLike[uintc] | type[ctypes.c_uint]) -> type[ctypes.c_uint]: ... +@overload +def as_ctypes_type(dtype: _ULongCodes | _DTypeLike[ulong] | type[ctypes.c_ulong]) -> type[ctypes.c_ulong]: ... +@overload +def as_ctypes_type(dtype: _ULongLongCodes | _DTypeLike[ulonglong] | type[ctypes.c_ulonglong]) -> type[ctypes.c_ulonglong]: ... +@overload +def as_ctypes_type(dtype: _SingleCodes | _DTypeLike[single] | type[ctypes.c_float]) -> type[ctypes.c_float]: ... +@overload +def as_ctypes_type(dtype: _DoubleCodes | _DTypeLike[double] | type[float | ctypes.c_double]) -> type[ctypes.c_double]: ... +@overload +def as_ctypes_type(dtype: _LongDoubleCodes | _DTypeLike[longdouble] | type[ctypes.c_longdouble]) -> type[ctypes.c_longdouble]: ... +@overload +def as_ctypes_type(dtype: _VoidDTypeLike) -> type[Any]: ... # `ctypes.Union` or `ctypes.Structure` +@overload +def as_ctypes_type(dtype: str) -> type[Any]: ... + +@overload +def as_array(obj: ctypes._PointerLike, shape: Sequence[int]) -> NDArray[Any]: ... +@overload +def as_array(obj: _ArrayLike[_ScalarT], shape: _ShapeLike | None = None) -> NDArray[_ScalarT]: ... +@overload +def as_array(obj: object, shape: _ShapeLike | None = None) -> NDArray[Any]: ... + +@overload +def as_ctypes(obj: np.bool) -> ctypes.c_bool: ... +@overload +def as_ctypes(obj: byte) -> ctypes.c_byte: ... +@overload +def as_ctypes(obj: short) -> ctypes.c_short: ... +@overload +def as_ctypes(obj: intc) -> ctypes.c_int: ... +@overload +def as_ctypes(obj: long) -> ctypes.c_long: ... +@overload +def as_ctypes(obj: longlong) -> ctypes.c_longlong: ... # type: ignore[overload-cannot-match] +@overload +def as_ctypes(obj: ubyte) -> ctypes.c_ubyte: ... +@overload +def as_ctypes(obj: ushort) -> ctypes.c_ushort: ... +@overload +def as_ctypes(obj: uintc) -> ctypes.c_uint: ... +@overload +def as_ctypes(obj: ulong) -> ctypes.c_ulong: ... +@overload +def as_ctypes(obj: ulonglong) -> ctypes.c_ulonglong: ... # type: ignore[overload-cannot-match] +@overload +def as_ctypes(obj: single) -> ctypes.c_float: ... +@overload +def as_ctypes(obj: double) -> ctypes.c_double: ... +@overload +def as_ctypes(obj: longdouble) -> ctypes.c_longdouble: ... +@overload +def as_ctypes(obj: void) -> Any: ... # `ctypes.Union` or `ctypes.Structure` +@overload +def as_ctypes(obj: NDArray[np.bool]) -> ctypes.Array[ctypes.c_bool]: ... +@overload +def as_ctypes(obj: NDArray[byte]) -> ctypes.Array[ctypes.c_byte]: ... +@overload +def as_ctypes(obj: NDArray[short]) -> ctypes.Array[ctypes.c_short]: ... +@overload +def as_ctypes(obj: NDArray[intc]) -> ctypes.Array[ctypes.c_int]: ... +@overload +def as_ctypes(obj: NDArray[long]) -> ctypes.Array[ctypes.c_long]: ... +@overload +def as_ctypes(obj: NDArray[longlong]) -> ctypes.Array[ctypes.c_longlong]: ... # type: ignore[overload-cannot-match] +@overload +def as_ctypes(obj: NDArray[ubyte]) -> ctypes.Array[ctypes.c_ubyte]: ... +@overload +def as_ctypes(obj: NDArray[ushort]) -> ctypes.Array[ctypes.c_ushort]: ... +@overload +def as_ctypes(obj: NDArray[uintc]) -> ctypes.Array[ctypes.c_uint]: ... +@overload +def as_ctypes(obj: NDArray[ulong]) -> ctypes.Array[ctypes.c_ulong]: ... +@overload +def as_ctypes(obj: NDArray[ulonglong]) -> ctypes.Array[ctypes.c_ulonglong]: ... # type: ignore[overload-cannot-match] +@overload +def as_ctypes(obj: NDArray[single]) -> ctypes.Array[ctypes.c_float]: ... +@overload +def as_ctypes(obj: NDArray[double]) -> ctypes.Array[ctypes.c_double]: ... +@overload +def as_ctypes(obj: NDArray[longdouble]) -> ctypes.Array[ctypes.c_longdouble]: ... +@overload +def as_ctypes(obj: NDArray[void]) -> ctypes.Array[Any]: ... # `ctypes.Union` or `ctypes.Structure` diff --git a/python/user_packages/Python313/site-packages/numpy/doc/ufuncs.py b/python/user_packages/Python313/site-packages/numpy/doc/ufuncs.py new file mode 100644 index 0000000000000000000000000000000000000000..398e5e7975e0a27e6a2eae5444404b8bdec20571 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/doc/ufuncs.py @@ -0,0 +1,138 @@ +""" +=================== +Universal Functions +=================== + +Ufuncs are, generally speaking, mathematical functions or operations that are +applied element-by-element to the contents of an array. That is, the result +in each output array element only depends on the value in the corresponding +input array (or arrays) and on no other array elements. NumPy comes with a +large suite of ufuncs, and scipy extends that suite substantially. The simplest +example is the addition operator: :: + + >>> np.array([0,2,3,4]) + np.array([1,1,-1,2]) + array([1, 3, 2, 6]) + +The ufunc module lists all the available ufuncs in numpy. Documentation on +the specific ufuncs may be found in those modules. This documentation is +intended to address the more general aspects of ufuncs common to most of +them. All of the ufuncs that make use of Python operators (e.g., +, -, etc.) +have equivalent functions defined (e.g. add() for +) + +Type coercion +============= + +What happens when a binary operator (e.g., +,-,\\*,/, etc) deals with arrays of +two different types? What is the type of the result? Typically, the result is +the higher of the two types. For example: :: + + float32 + float64 -> float64 + int8 + int32 -> int32 + int16 + float32 -> float32 + float32 + complex64 -> complex64 + +There are some less obvious cases generally involving mixes of types +(e.g. uints, ints and floats) where equal bit sizes for each are not +capable of saving all the information in a different type of equivalent +bit size. Some examples are int32 vs float32 or uint32 vs int32. +Generally, the result is the higher type of larger size than both +(if available). So: :: + + int32 + float32 -> float64 + uint32 + int32 -> int64 + +Finally, the type coercion behavior when expressions involve Python +scalars is different than that seen for arrays. Since Python has a +limited number of types, combining a Python int with a dtype=np.int8 +array does not coerce to the higher type but instead, the type of the +array prevails. So the rules for Python scalars combined with arrays is +that the result will be that of the array equivalent the Python scalar +if the Python scalar is of a higher 'kind' than the array (e.g., float +vs. int), otherwise the resultant type will be that of the array. +For example: :: + + Python int + int8 -> int8 + Python float + int8 -> float64 + +ufunc methods +============= + +Binary ufuncs support 4 methods. + +**.reduce(arr)** applies the binary operator to elements of the array in + sequence. For example: :: + + >>> np.add.reduce(np.arange(10)) # adds all elements of array + 45 + +For multidimensional arrays, the first dimension is reduced by default: :: + + >>> np.add.reduce(np.arange(10).reshape(2,5)) + array([ 5, 7, 9, 11, 13]) + +The axis keyword can be used to specify different axes to reduce: :: + + >>> np.add.reduce(np.arange(10).reshape(2,5),axis=1) + array([10, 35]) + +**.accumulate(arr)** applies the binary operator and generates an +equivalently shaped array that includes the accumulated amount for each +element of the array. A couple examples: :: + + >>> np.add.accumulate(np.arange(10)) + array([ 0, 1, 3, 6, 10, 15, 21, 28, 36, 45]) + >>> np.multiply.accumulate(np.arange(1,9)) + array([ 1, 2, 6, 24, 120, 720, 5040, 40320]) + +The behavior for multidimensional arrays is the same as for .reduce(), +as is the use of the axis keyword). + +**.reduceat(arr,indices)** allows one to apply reduce to selected parts + of an array. It is a difficult method to understand. See the documentation + at: + +**.outer(arr1,arr2)** generates an outer operation on the two arrays arr1 and + arr2. It will work on multidimensional arrays (the shape of the result is + the concatenation of the two input shapes.: :: + + >>> np.multiply.outer(np.arange(3),np.arange(4)) + array([[0, 0, 0, 0], + [0, 1, 2, 3], + [0, 2, 4, 6]]) + +Output arguments +================ + +All ufuncs accept an optional output array. The array must be of the expected +output shape. Beware that if the type of the output array is of a different +(and lower) type than the output result, the results may be silently truncated +or otherwise corrupted in the downcast to the lower type. This usage is useful +when one wants to avoid creating large temporary arrays and instead allows one +to reuse the same array memory repeatedly (at the expense of not being able to +use more convenient operator notation in expressions). Note that when the +output argument is used, the ufunc still returns a reference to the result. + + >>> x = np.arange(2) + >>> np.add(np.arange(2, dtype=float), np.arange(2, dtype=float), x, + ... casting='unsafe') + array([0, 2]) + >>> x + array([0, 2]) + +and & or as ufuncs +================== + +Invariably people try to use the python 'and' and 'or' as logical operators +(and quite understandably). But these operators do not behave as normal +operators since Python treats these quite differently. They cannot be +overloaded with array equivalents. Thus using 'and' or 'or' with an array +results in an error. There are two alternatives: + + 1) use the ufunc functions logical_and() and logical_or(). + 2) use the bitwise operators & and \\|. The drawback of these is that if + the arguments to these operators are not boolean arrays, the result is + likely incorrect. On the other hand, most usages of logical_and and + logical_or are with boolean arrays. As long as one is careful, this is + a convenient way to apply these operators. + +""" diff --git a/python/user_packages/Python313/site-packages/numpy/f2py/__init__.py b/python/user_packages/Python313/site-packages/numpy/f2py/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..151193af21b0c4587c9c5c785ff5bc8c7d605e8d --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/f2py/__init__.py @@ -0,0 +1,86 @@ +"""Fortran to Python Interface Generator. + +Copyright 1999 -- 2011 Pearu Peterson all rights reserved. +Copyright 2011 -- present NumPy Developers. +Permission to use, modify, and distribute this software is given under the terms +of the NumPy License. + +NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. +""" +__all__ = ['run_main', 'get_include'] + +import os +import subprocess +import sys +import warnings + +from numpy.exceptions import VisibleDeprecationWarning + +from . import diagnose, f2py2e + +run_main = f2py2e.run_main +main = f2py2e.main + + +def get_include(): + """ + Return the directory that contains the ``fortranobject.c`` and ``.h`` files. + + .. note:: + + This function is not needed when building an extension with + `numpy.distutils` directly from ``.f`` and/or ``.pyf`` files + in one go. + + Python extension modules built with f2py-generated code need to use + ``fortranobject.c`` as a source file, and include the ``fortranobject.h`` + header. This function can be used to obtain the directory containing + both of these files. + + Returns + ------- + include_path : str + Absolute path to the directory containing ``fortranobject.c`` and + ``fortranobject.h``. + + Notes + ----- + .. versionadded:: 1.21.1 + + Unless the build system you are using has specific support for f2py, + building a Python extension using a ``.pyf`` signature file is a two-step + process. For a module ``mymod``: + + * Step 1: run ``python -m numpy.f2py mymod.pyf --quiet``. This + generates ``mymodmodule.c`` and (if needed) + ``mymod-f2pywrappers.f`` files next to ``mymod.pyf``. + * Step 2: build your Python extension module. This requires the + following source files: + + * ``mymodmodule.c`` + * ``mymod-f2pywrappers.f`` (if it was generated in Step 1) + * ``fortranobject.c`` + + See Also + -------- + numpy.get_include : function that returns the numpy include directory + + """ + return os.path.join(os.path.dirname(__file__), 'src') + + +def __getattr__(attr): + + # Avoid importing things that aren't needed for building + # which might import the main numpy module + if attr == "test": + from numpy._pytesttester import PytestTester + test = PytestTester(__name__) + return test + + else: + raise AttributeError(f"module {__name__!r} has no attribute {attr!r}") + + +def __dir__(): + return list(globals().keys() | {"test"}) diff --git a/python/user_packages/Python313/site-packages/numpy/f2py/__init__.pyi b/python/user_packages/Python313/site-packages/numpy/f2py/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..64540d3f4034c4e77bc24aaa6b29173977f033b3 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/f2py/__init__.pyi @@ -0,0 +1,5 @@ +from .f2py2e import main as main, run_main + +__all__ = ["get_include", "run_main"] + +def get_include() -> str: ... diff --git a/python/user_packages/Python313/site-packages/numpy/f2py/__main__.py b/python/user_packages/Python313/site-packages/numpy/f2py/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..19ced88500139d62fc99f027bc467b07ee59bb26 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/f2py/__main__.py @@ -0,0 +1,5 @@ +# See: +# https://web.archive.org/web/20140822061353/http://cens.ioc.ee/projects/f2py2e +from numpy.f2py.f2py2e import main + +main() diff --git a/python/user_packages/Python313/site-packages/numpy/f2py/__version__.py b/python/user_packages/Python313/site-packages/numpy/f2py/__version__.py new file mode 100644 index 0000000000000000000000000000000000000000..3cf646f74e56c68a2f781b76bae9f145fc0ea4b9 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/f2py/__version__.py @@ -0,0 +1 @@ +from numpy.version import version # noqa: F401 diff --git a/python/user_packages/Python313/site-packages/numpy/f2py/__version__.pyi b/python/user_packages/Python313/site-packages/numpy/f2py/__version__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..6fd876a2e48078e05b8ad8b06ed19018d6cb5e1b --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/f2py/__version__.pyi @@ -0,0 +1 @@ +from numpy.version import version as version diff --git a/python/user_packages/Python313/site-packages/numpy/f2py/_isocbind.py b/python/user_packages/Python313/site-packages/numpy/f2py/_isocbind.py new file mode 100644 index 0000000000000000000000000000000000000000..4a1399588bc9386219acff9ad7a483e27ea153f9 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/f2py/_isocbind.py @@ -0,0 +1,62 @@ +""" +ISO_C_BINDING maps for f2py2e. +Only required declarations/macros/functions will be used. + +Copyright 1999 -- 2011 Pearu Peterson all rights reserved. +Copyright 2011 -- present NumPy Developers. +Permission to use, modify, and distribute this software is given under the +terms of the NumPy License. + +NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. +""" +# These map to keys in c2py_map, via forced casting for now, see gh-25229 +iso_c_binding_map = { + 'integer': { + 'c_int': 'int', + 'c_short': 'short', # 'short' <=> 'int' for now + 'c_long': 'long', # 'long' <=> 'int' for now + 'c_long_long': 'long_long', + 'c_signed_char': 'signed_char', + 'c_size_t': 'unsigned', # size_t <=> 'unsigned' for now + 'c_int8_t': 'signed_char', # int8_t <=> 'signed_char' for now + 'c_int16_t': 'short', # int16_t <=> 'short' for now + 'c_int32_t': 'int', # int32_t <=> 'int' for now + 'c_int64_t': 'long_long', + 'c_int_least8_t': 'signed_char', # int_least8_t <=> 'signed_char' for now + 'c_int_least16_t': 'short', # int_least16_t <=> 'short' for now + 'c_int_least32_t': 'int', # int_least32_t <=> 'int' for now + 'c_int_least64_t': 'long_long', + 'c_int_fast8_t': 'signed_char', # int_fast8_t <=> 'signed_char' for now + 'c_int_fast16_t': 'short', # int_fast16_t <=> 'short' for now + 'c_int_fast32_t': 'int', # int_fast32_t <=> 'int' for now + 'c_int_fast64_t': 'long_long', + 'c_intmax_t': 'long_long', # intmax_t <=> 'long_long' for now + 'c_intptr_t': 'long', # intptr_t <=> 'long' for now + 'c_ptrdiff_t': 'long', # ptrdiff_t <=> 'long' for now + }, + 'real': { + 'c_float': 'float', + 'c_double': 'double', + 'c_long_double': 'long_double' + }, + 'complex': { + 'c_float_complex': 'complex_float', + 'c_double_complex': 'complex_double', + 'c_long_double_complex': 'complex_long_double' + }, + 'logical': { + 'c_bool': 'unsigned_char' # _Bool <=> 'unsigned_char' for now + }, + 'character': { + 'c_char': 'char' + } +} + +# TODO: See gh-25229 +isoc_c2pycode_map = {} +iso_c2py_map = {} + +isoc_kindmap = {} +for fortran_type, c_type_dict in iso_c_binding_map.items(): + for c_type in c_type_dict.keys(): + isoc_kindmap[c_type] = fortran_type diff --git a/python/user_packages/Python313/site-packages/numpy/f2py/_isocbind.pyi b/python/user_packages/Python313/site-packages/numpy/f2py/_isocbind.pyi new file mode 100644 index 0000000000000000000000000000000000000000..4a4b2ce2b633c3ad2bba4d78ce873fcc4b29bbbb --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/f2py/_isocbind.pyi @@ -0,0 +1,13 @@ +from typing import Any, Final + +iso_c_binding_map: Final[dict[str, dict[str, str]]] = ... + +isoc_c2pycode_map: Final[dict[str, Any]] = {} # not implemented +iso_c2py_map: Final[dict[str, Any]] = {} # not implemented + +isoc_kindmap: Final[dict[str, str]] = ... + +# namespace pollution +c_type: str +c_type_dict: dict[str, str] +fortran_type: str diff --git a/python/user_packages/Python313/site-packages/numpy/f2py/_src_pyf.py b/python/user_packages/Python313/site-packages/numpy/f2py/_src_pyf.py new file mode 100644 index 0000000000000000000000000000000000000000..6f270807b350e2322481f153e52a53fd305e6111 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/f2py/_src_pyf.py @@ -0,0 +1,247 @@ +import os +import re + +# START OF CODE VENDORED FROM `numpy.distutils.from_template` +############################################################# +""" +process_file(filename) + + takes templated file .xxx.src and produces .xxx file where .xxx + is .pyf .f90 or .f using the following template rules: + + '<..>' denotes a template. + + All function and subroutine blocks in a source file with names that + contain '<..>' will be replicated according to the rules in '<..>'. + + The number of comma-separated words in '<..>' will determine the number of + replicates. + + '<..>' may have two different forms, named and short. For example, + + named: + where anywhere inside a block '

' will be replaced with + 'd', 's', 'z', and 'c' for each replicate of the block. + + <_c> is already defined: <_c=s,d,c,z> + <_t> is already defined: <_t=real,double precision,complex,double complex> + + short: + , a short form of the named, useful when no

appears inside + a block. + + In general, '<..>' contains a comma separated list of arbitrary + expressions. If these expression must contain a comma|leftarrow|rightarrow, + then prepend the comma|leftarrow|rightarrow with a backslash. + + If an expression matches '\\' then it will be replaced + by -th expression. + + Note that all '<..>' forms in a block must have the same number of + comma-separated entries. + + Predefined named template rules: + + + + + +""" + +routine_start_re = re.compile(r'(\n|\A)(( (\$|\*))|)\s*(subroutine|function)\b', re.I) +routine_end_re = re.compile(r'\n\s*end\s*(subroutine|function)\b.*(\n|\Z)', re.I) +function_start_re = re.compile(r'\n (\$|\*)\s*function\b', re.I) + +def parse_structure(astr): + """ Return a list of tuples for each function or subroutine each + tuple is the start and end of a subroutine or function to be + expanded. + """ + + spanlist = [] + ind = 0 + while True: + m = routine_start_re.search(astr, ind) + if m is None: + break + start = m.start() + if function_start_re.match(astr, start, m.end()): + while True: + i = astr.rfind('\n', ind, start) + if i == -1: + break + start = i + if astr[i:i + 7] != '\n $': + break + start += 1 + m = routine_end_re.search(astr, m.end()) + ind = end = (m and m.end() - 1) or len(astr) + spanlist.append((start, end)) + return spanlist + + +template_re = re.compile(r"<\s*(\w[\w\d]*)\s*>") +named_re = re.compile(r"<\s*(\w[\w\d]*)\s*=\s*(.*?)\s*>") +list_re = re.compile(r"<\s*((.*?))\s*>") + +def find_repl_patterns(astr): + reps = named_re.findall(astr) + names = {} + for rep in reps: + name = rep[0].strip() or unique_key(names) + repl = rep[1].replace(r'\,', '@comma@') + thelist = conv(repl) + names[name] = thelist + return names + +def find_and_remove_repl_patterns(astr): + names = find_repl_patterns(astr) + astr = re.subn(named_re, '', astr)[0] + return astr, names + + +item_re = re.compile(r"\A\\(?P\d+)\Z") +def conv(astr): + b = astr.split(',') + l = [x.strip() for x in b] + for i in range(len(l)): + m = item_re.match(l[i]) + if m: + j = int(m.group('index')) + l[i] = l[j] + return ','.join(l) + +def unique_key(adict): + """ Obtain a unique key given a dictionary.""" + allkeys = list(adict.keys()) + done = False + n = 1 + while not done: + newkey = f'__l{n}' + if newkey in allkeys: + n += 1 + else: + done = True + return newkey + + +template_name_re = re.compile(r'\A\s*(\w[\w\d]*)\s*\Z') +def expand_sub(substr, names): + substr = substr.replace(r'\>', '@rightarrow@') + substr = substr.replace(r'\<', '@leftarrow@') + lnames = find_repl_patterns(substr) + substr = named_re.sub(r"<\1>", substr) # get rid of definition templates + + def listrepl(mobj): + thelist = conv(mobj.group(1).replace(r'\,', '@comma@')) + if template_name_re.match(thelist): + return f"<{thelist}>" + name = None + for key in lnames.keys(): # see if list is already in dictionary + if lnames[key] == thelist: + name = key + if name is None: # this list is not in the dictionary yet + name = unique_key(lnames) + lnames[name] = thelist + return f"<{name}>" + + # convert all lists to named templates + # new names are constructed as needed + substr = list_re.sub(listrepl, substr) + + numsubs = None + base_rule = None + rules = {} + for r in template_re.findall(substr): + if r not in rules: + thelist = lnames.get(r, names.get(r, None)) + if thelist is None: + raise ValueError(f'No replicates found for <{r}>') + if r not in names and not thelist.startswith('_'): + names[r] = thelist + rule = [i.replace('@comma@', ',') for i in thelist.split(',')] + num = len(rule) + + if numsubs is None: + numsubs = num + rules[r] = rule + base_rule = r + elif num == numsubs: + rules[r] = rule + else: + rules_base_rule = ','.join(rules[base_rule]) + print("Mismatch in number of replacements " + f"(base <{base_rule}={rules_base_rule}>) " + f"for <{r}={thelist}>. Ignoring.") + if not rules: + return substr + + def namerepl(mobj): + name = mobj.group(1) + return rules.get(name, (k + 1) * [name])[k] + + newstr = '' + for k in range(numsubs): + newstr += template_re.sub(namerepl, substr) + '\n\n' + + newstr = newstr.replace('@rightarrow@', '>') + newstr = newstr.replace('@leftarrow@', '<') + return newstr + +def process_str(allstr): + newstr = allstr + writestr = '' + + struct = parse_structure(newstr) + + oldend = 0 + names = {} + names.update(_special_names) + for sub in struct: + cleanedstr, defs = find_and_remove_repl_patterns(newstr[oldend:sub[0]]) + writestr += cleanedstr + names.update(defs) + writestr += expand_sub(newstr[sub[0]:sub[1]], names) + oldend = sub[1] + writestr += newstr[oldend:] + + return writestr + + +include_src_re = re.compile(r"(\n|\A)\s*include\s*['\"](?P[\w\d./\\]+\.src)['\"]", re.I) + +def resolve_includes(source): + d = os.path.dirname(source) + with open(source) as fid: + lines = [] + for line in fid: + m = include_src_re.match(line) + if m: + fn = m.group('name') + if not os.path.isabs(fn): + fn = os.path.join(d, fn) + if os.path.isfile(fn): + lines.extend(resolve_includes(fn)) + else: + lines.append(line) + else: + lines.append(line) + return lines + +def process_file(source): + lines = resolve_includes(source) + return process_str(''.join(lines)) + + +_special_names = find_repl_patterns(''' +<_c=s,d,c,z> +<_t=real,double precision,complex,double complex> + + + + + +''') + +# END OF CODE VENDORED FROM `numpy.distutils.from_template` +########################################################### diff --git a/python/user_packages/Python313/site-packages/numpy/f2py/_src_pyf.pyi b/python/user_packages/Python313/site-packages/numpy/f2py/_src_pyf.pyi new file mode 100644 index 0000000000000000000000000000000000000000..99e84604c82efa71f19cb146a4c8c215ac44bf64 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/f2py/_src_pyf.pyi @@ -0,0 +1,28 @@ +import re +from _typeshed import StrOrBytesPath +from collections.abc import Mapping +from typing import Final + +routine_start_re: Final[re.Pattern[str]] = ... +routine_end_re: Final[re.Pattern[str]] = ... +function_start_re: Final[re.Pattern[str]] = ... +template_re: Final[re.Pattern[str]] = ... +named_re: Final[re.Pattern[str]] = ... +list_re: Final[re.Pattern[str]] = ... +item_re: Final[re.Pattern[str]] = ... +template_name_re: Final[re.Pattern[str]] = ... +include_src_re: Final[re.Pattern[str]] = ... + +def parse_structure(astr: str) -> list[tuple[int, int]]: ... +def find_repl_patterns(astr: str) -> dict[str, str]: ... +def find_and_remove_repl_patterns(astr: str) -> tuple[str, dict[str, str]]: ... +def conv(astr: str) -> str: ... + +# +def unique_key(adict: Mapping[str, object]) -> str: ... +def expand_sub(substr: str, names: dict[str, str]) -> str: ... +def process_str(allstr: str) -> str: ... + +# +def resolve_includes(source: StrOrBytesPath) -> list[str]: ... +def process_file(source: StrOrBytesPath) -> str: ... diff --git a/python/user_packages/Python313/site-packages/numpy/f2py/auxfuncs.py b/python/user_packages/Python313/site-packages/numpy/f2py/auxfuncs.py new file mode 100644 index 0000000000000000000000000000000000000000..5e9fae4c08ff8db62659fe4423d7be23a9cc7b82 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/f2py/auxfuncs.py @@ -0,0 +1,1004 @@ +""" +Auxiliary functions for f2py2e. + +Copyright 1999 -- 2011 Pearu Peterson all rights reserved. +Copyright 2011 -- present NumPy Developers. +Permission to use, modify, and distribute this software is given under the +terms of the NumPy (BSD style) LICENSE. + +NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. +""" +import pprint +import re +import sys +import types +from functools import reduce + +from . import __version__, cfuncs +from .cfuncs import errmess + +__all__ = [ + 'applyrules', 'debugcapi', 'dictappend', 'errmess', 'gentitle', + 'getargs2', 'getcallprotoargument', 'getcallstatement', + 'getfortranname', 'getpymethoddef', 'getrestdoc', 'getusercode', + 'getusercode1', 'getdimension', 'hasbody', 'hascallstatement', 'hascommon', + 'hasexternals', 'hasinitvalue', 'hasnote', 'hasresultnote', + 'isallocatable', 'isarray', 'isarrayofstrings', + 'ischaracter', 'ischaracterarray', 'ischaracter_or_characterarray', + 'iscomplex', 'iscstyledirective', + 'iscomplexarray', 'iscomplexfunction', 'iscomplexfunction_warn', + 'isdouble', 'isdummyroutine', 'isexternal', 'isfunction', + 'isfunction_wrap', 'isint1', 'isint1array', 'isinteger', 'isintent_aux', + 'isintent_c', 'isintent_callback', 'isintent_copy', 'isintent_dict', + 'isintent_hide', 'isintent_in', 'isintent_inout', 'isintent_inplace', + 'isintent_nothide', 'isintent_out', 'isintent_overwrite', 'islogical', + 'islogicalfunction', 'islong_complex', 'islong_double', + 'islong_doublefunction', 'islong_long', 'islong_longfunction', + 'ismodule', 'ismoduleroutine', 'isoptional', 'isprivate', 'isvariable', + 'isrequired', 'isroutine', 'isscalar', 'issigned_long_longarray', + 'isstring', 'isstringarray', 'isstring_or_stringarray', 'isstringfunction', + 'issubroutine', 'get_f2py_modulename', 'issubroutine_wrap', 'isthreadsafe', + 'isunsigned', 'isunsigned_char', 'isunsigned_chararray', + 'isunsigned_long_long', 'isunsigned_long_longarray', 'isunsigned_short', + 'isunsigned_shortarray', 'l_and', 'l_not', 'l_or', 'outmess', 'replace', + 'show', 'stripcomma', 'throw_error', 'isattr_value', 'getuseblocks', + 'process_f2cmap_dict', 'containscommon', 'containsderivedtypes' +] + + +f2py_version = __version__.version + + +show = pprint.pprint + +options = {} +debugoptions = [] +wrapfuncs = 1 + + +def outmess(t): + if options.get('verbose', 1): + sys.stdout.write(t) + + +def debugcapi(var): + return 'capi' in debugoptions + + +def _ischaracter(var): + return 'typespec' in var and var['typespec'] == 'character' and \ + not isexternal(var) + + +def _isstring(var): + return 'typespec' in var and var['typespec'] == 'character' and \ + not isexternal(var) + + +def ischaracter_or_characterarray(var): + return _ischaracter(var) and 'charselector' not in var + + +def ischaracter(var): + return ischaracter_or_characterarray(var) and not isarray(var) + + +def ischaracterarray(var): + return ischaracter_or_characterarray(var) and isarray(var) + + +def isstring_or_stringarray(var): + return _ischaracter(var) and 'charselector' in var + + +def isstring(var): + return isstring_or_stringarray(var) and not isarray(var) + + +def isstringarray(var): + return isstring_or_stringarray(var) and isarray(var) + + +def isarrayofstrings(var): # obsolete? + # leaving out '*' for now so that `character*(*) a(m)` and `character + # a(m,*)` are treated differently. Luckily `character**` is illegal. + return isstringarray(var) and var['dimension'][-1] == '(*)' + + +def isarray(var): + return 'dimension' in var and not isexternal(var) + + +def isscalar(var): + return not (isarray(var) or isstring(var) or isexternal(var)) + + +def iscomplex(var): + return isscalar(var) and \ + var.get('typespec') in ['complex', 'double complex'] + + +def islogical(var): + return isscalar(var) and var.get('typespec') == 'logical' + + +def isinteger(var): + return isscalar(var) and var.get('typespec') == 'integer' + + +def isreal(var): + return isscalar(var) and var.get('typespec') == 'real' + + +def get_kind(var): + try: + return var['kindselector']['*'] + except KeyError: + try: + return var['kindselector']['kind'] + except KeyError: + pass + + +def isint1(var): + return var.get('typespec') == 'integer' \ + and get_kind(var) == '1' and not isarray(var) + + +def islong_long(var): + if not isscalar(var): + return 0 + if var.get('typespec') not in ['integer', 'logical']: + return 0 + return get_kind(var) == '8' + + +def isunsigned_char(var): + if not isscalar(var): + return 0 + if var.get('typespec') != 'integer': + return 0 + return get_kind(var) == '-1' + + +def isunsigned_short(var): + if not isscalar(var): + return 0 + if var.get('typespec') != 'integer': + return 0 + return get_kind(var) == '-2' + + +def isunsigned(var): + if not isscalar(var): + return 0 + if var.get('typespec') != 'integer': + return 0 + return get_kind(var) == '-4' + + +def isunsigned_long_long(var): + if not isscalar(var): + return 0 + if var.get('typespec') != 'integer': + return 0 + return get_kind(var) == '-8' + + +def isdouble(var): + if not isscalar(var): + return 0 + if not var.get('typespec') == 'real': + return 0 + return get_kind(var) == '8' + + +def islong_double(var): + if not isscalar(var): + return 0 + if not var.get('typespec') == 'real': + return 0 + return get_kind(var) == '16' + + +def islong_complex(var): + if not iscomplex(var): + return 0 + return get_kind(var) == '32' + + +def iscomplexarray(var): + return isarray(var) and \ + var.get('typespec') in ['complex', 'double complex'] + + +def isint1array(var): + return isarray(var) and var.get('typespec') == 'integer' \ + and get_kind(var) == '1' + + +def isunsigned_chararray(var): + return isarray(var) and var.get('typespec') in ['integer', 'logical']\ + and get_kind(var) == '-1' + + +def isunsigned_shortarray(var): + return isarray(var) and var.get('typespec') in ['integer', 'logical']\ + and get_kind(var) == '-2' + + +def isunsignedarray(var): + return isarray(var) and var.get('typespec') in ['integer', 'logical']\ + and get_kind(var) == '-4' + + +def isunsigned_long_longarray(var): + return isarray(var) and var.get('typespec') in ['integer', 'logical']\ + and get_kind(var) == '-8' + + +def issigned_chararray(var): + return isarray(var) and var.get('typespec') in ['integer', 'logical']\ + and get_kind(var) == '1' + + +def issigned_shortarray(var): + return isarray(var) and var.get('typespec') in ['integer', 'logical']\ + and get_kind(var) == '2' + + +def issigned_array(var): + return isarray(var) and var.get('typespec') in ['integer', 'logical']\ + and get_kind(var) == '4' + + +def issigned_long_longarray(var): + return isarray(var) and var.get('typespec') in ['integer', 'logical']\ + and get_kind(var) == '8' + + +def isallocatable(var): + return 'attrspec' in var and 'allocatable' in var['attrspec'] + + +def ismutable(var): + return not ('dimension' not in var or isstring(var)) + + +def ismoduleroutine(rout): + return 'modulename' in rout + + +def ismodule(rout): + return 'block' in rout and 'module' == rout['block'] + + +def isfunction(rout): + return 'block' in rout and 'function' == rout['block'] + + +def isfunction_wrap(rout): + if isintent_c(rout): + return 0 + return wrapfuncs and isfunction(rout) and (not isexternal(rout)) + + +def issubroutine(rout): + return 'block' in rout and 'subroutine' == rout['block'] + + +def issubroutine_wrap(rout): + if isintent_c(rout): + return 0 + return issubroutine(rout) and hasassumedshape(rout) + +def isattr_value(var): + return 'value' in var.get('attrspec', []) + + +def hasassumedshape(rout): + if rout.get('hasassumedshape'): + return True + for a in rout['args']: + for d in rout['vars'].get(a, {}).get('dimension', []): + if d == ':': + rout['hasassumedshape'] = True + return True + return False + + +def requiresf90wrapper(rout): + return ismoduleroutine(rout) or hasassumedshape(rout) + + +def isroutine(rout): + return isfunction(rout) or issubroutine(rout) + + +def islogicalfunction(rout): + if not isfunction(rout): + return 0 + if 'result' in rout: + a = rout['result'] + else: + a = rout['name'] + if a in rout['vars']: + return islogical(rout['vars'][a]) + return 0 + + +def islong_longfunction(rout): + if not isfunction(rout): + return 0 + if 'result' in rout: + a = rout['result'] + else: + a = rout['name'] + if a in rout['vars']: + return islong_long(rout['vars'][a]) + return 0 + + +def islong_doublefunction(rout): + if not isfunction(rout): + return 0 + if 'result' in rout: + a = rout['result'] + else: + a = rout['name'] + if a in rout['vars']: + return islong_double(rout['vars'][a]) + return 0 + + +def iscomplexfunction(rout): + if not isfunction(rout): + return 0 + if 'result' in rout: + a = rout['result'] + else: + a = rout['name'] + if a in rout['vars']: + return iscomplex(rout['vars'][a]) + return 0 + + +def iscomplexfunction_warn(rout): + if iscomplexfunction(rout): + outmess("""\ + ************************************************************** + Warning: code with a function returning complex value + may not work correctly with your Fortran compiler. + When using GNU gcc/g77 compilers, codes should work + correctly for callbacks with: + f2py -c -DF2PY_CB_RETURNCOMPLEX + **************************************************************\n""") + return 1 + return 0 + + +def isstringfunction(rout): + if not isfunction(rout): + return 0 + if 'result' in rout: + a = rout['result'] + else: + a = rout['name'] + if a in rout['vars']: + return isstring(rout['vars'][a]) + return 0 + + +def hasexternals(rout): + return 'externals' in rout and rout['externals'] + + +def isthreadsafe(rout): + return 'f2pyenhancements' in rout and \ + 'threadsafe' in rout['f2pyenhancements'] + + +def hasvariables(rout): + return 'vars' in rout and rout['vars'] + + +def isoptional(var): + return ('attrspec' in var and 'optional' in var['attrspec'] and + 'required' not in var['attrspec']) and isintent_nothide(var) + + +def isexternal(var): + return 'attrspec' in var and 'external' in var['attrspec'] + + +def getdimension(var): + dimpattern = r"\((.*?)\)" + if 'attrspec' in var.keys(): + if any('dimension' in s for s in var['attrspec']): + return next(re.findall(dimpattern, v) for v in var['attrspec']) + + +def isrequired(var): + return not isoptional(var) and isintent_nothide(var) + + +def iscstyledirective(f2py_line): + directives = {"callstatement", "callprotoargument", "pymethoddef"} + return any(directive in f2py_line.lower() for directive in directives) + + +def isintent_in(var): + if 'intent' not in var: + return 1 + if 'hide' in var['intent']: + return 0 + if 'inplace' in var['intent']: + return 0 + if 'in' in var['intent']: + return 1 + if 'out' in var['intent']: + return 0 + if 'inout' in var['intent']: + return 0 + if 'outin' in var['intent']: + return 0 + return 1 + + +def isintent_inout(var): + return ('intent' in var and ('inout' in var['intent'] or + 'outin' in var['intent']) and 'in' not in var['intent'] and + 'hide' not in var['intent'] and 'inplace' not in var['intent']) + + +def isintent_out(var): + return 'out' in var.get('intent', []) + + +def isintent_hide(var): + return ('intent' in var and ('hide' in var['intent'] or + ('out' in var['intent'] and 'in' not in var['intent'] and + (not l_or(isintent_inout, isintent_inplace)(var))))) + + +def isintent_nothide(var): + return not isintent_hide(var) + + +def isintent_c(var): + return 'c' in var.get('intent', []) + + +def isintent_cache(var): + return 'cache' in var.get('intent', []) + + +def isintent_copy(var): + return 'copy' in var.get('intent', []) + + +def isintent_overwrite(var): + return 'overwrite' in var.get('intent', []) + + +def isintent_callback(var): + return 'callback' in var.get('intent', []) + + +def isintent_inplace(var): + return 'inplace' in var.get('intent', []) + + +def isintent_aux(var): + return 'aux' in var.get('intent', []) + + +def isintent_aligned4(var): + return 'aligned4' in var.get('intent', []) + + +def isintent_aligned8(var): + return 'aligned8' in var.get('intent', []) + + +def isintent_aligned16(var): + return 'aligned16' in var.get('intent', []) + + +isintent_dict = {isintent_in: 'INTENT_IN', isintent_inout: 'INTENT_INOUT', + isintent_out: 'INTENT_OUT', isintent_hide: 'INTENT_HIDE', + isintent_cache: 'INTENT_CACHE', + isintent_c: 'INTENT_C', isoptional: 'OPTIONAL', + isintent_inplace: 'INTENT_INPLACE', + isintent_aligned4: 'INTENT_ALIGNED4', + isintent_aligned8: 'INTENT_ALIGNED8', + isintent_aligned16: 'INTENT_ALIGNED16', + } + + +def isprivate(var): + return 'attrspec' in var and 'private' in var['attrspec'] + + +def isvariable(var): + # heuristic to find public/private declarations of filtered subroutines + if len(var) == 1 and 'attrspec' in var and \ + var['attrspec'][0] in ('public', 'private'): + is_var = False + else: + is_var = True + return is_var + +def hasinitvalue(var): + return '=' in var + + +def hasinitvalueasstring(var): + if not hasinitvalue(var): + return 0 + return var['='][0] in ['"', "'"] + + +def hasnote(var): + return 'note' in var + + +def hasresultnote(rout): + if not isfunction(rout): + return 0 + if 'result' in rout: + a = rout['result'] + else: + a = rout['name'] + if a in rout['vars']: + return hasnote(rout['vars'][a]) + return 0 + + +def hascommon(rout): + return 'common' in rout + + +def containscommon(rout): + if hascommon(rout): + return 1 + if hasbody(rout): + for b in rout['body']: + if containscommon(b): + return 1 + return 0 + + +def hasderivedtypes(rout): + return ('block' in rout) and rout['block'] == 'type' + + +def containsderivedtypes(rout): + if hasderivedtypes(rout): + return 1 + if hasbody(rout): + for b in rout['body']: + if hasderivedtypes(b): + return 1 + return 0 + + +def containsmodule(block): + if ismodule(block): + return 1 + if not hasbody(block): + return 0 + for b in block['body']: + if containsmodule(b): + return 1 + return 0 + + +def hasbody(rout): + return 'body' in rout + + +def hascallstatement(rout): + return getcallstatement(rout) is not None + + +def istrue(var): + return 1 + + +def isfalse(var): + return 0 + + +class F2PYError(Exception): + pass + + +class throw_error: + + def __init__(self, mess): + self.mess = mess + + def __call__(self, var): + mess = f'\n\n var = {var}\n Message: {self.mess}\n' + raise F2PYError(mess) + + +def l_and(*f): + l1, l2 = 'lambda v', [] + for i in range(len(f)): + l1 = '%s,f%d=f[%d]' % (l1, i, i) + l2.append('f%d(v)' % (i)) + return eval(f"{l1}:{' and '.join(l2)}") + + +def l_or(*f): + l1, l2 = 'lambda v', [] + for i in range(len(f)): + l1 = '%s,f%d=f[%d]' % (l1, i, i) + l2.append('f%d(v)' % (i)) + return eval(f"{l1}:{' or '.join(l2)}") + + +def l_not(f): + return eval('lambda v,f=f:not f(v)') + + +def isdummyroutine(rout): + try: + return rout['f2pyenhancements']['fortranname'] == '' + except KeyError: + return 0 + + +def getfortranname(rout): + try: + name = rout['f2pyenhancements']['fortranname'] + if name == '': + raise KeyError + if not name: + errmess(f"Failed to use fortranname from {rout['f2pyenhancements']}\n") + raise KeyError + except KeyError: + name = rout['name'] + return name + + +def getmultilineblock(rout, blockname, comment=1, counter=0): + try: + r = rout['f2pyenhancements'].get(blockname) + except KeyError: + return + if not r: + return + if counter > 0 and isinstance(r, str): + return + if isinstance(r, list): + if counter >= len(r): + return + r = r[counter] + if r[:3] == "'''": + if comment: + r = '\t/* start ' + blockname + \ + ' multiline (' + repr(counter) + ') */\n' + r[3:] + else: + r = r[3:] + if r[-3:] == "'''": + if comment: + r = r[:-3] + '\n\t/* end multiline (' + repr(counter) + ')*/' + else: + r = r[:-3] + else: + errmess(f"{blockname} multiline block should end with `'''`: {repr(r)}\n") + return r + + +def getcallstatement(rout): + return getmultilineblock(rout, 'callstatement') + + +def getcallprotoargument(rout, cb_map={}): + r = getmultilineblock(rout, 'callprotoargument', comment=0) + if r: + return r + if hascallstatement(rout): + outmess( + 'warning: callstatement is defined without callprotoargument\n') + return + from .capi_maps import getctype + arg_types, arg_types2 = [], [] + if l_and(isstringfunction, l_not(isfunction_wrap))(rout): + arg_types.extend(['char*', 'size_t']) + for n in rout['args']: + var = rout['vars'][n] + if isintent_callback(var): + continue + if n in cb_map: + ctype = cb_map[n] + '_typedef' + else: + ctype = getctype(var) + if l_and(isintent_c, l_or(isscalar, iscomplex))(var): + pass + elif isstring(var): + pass + elif not isattr_value(var): + ctype = ctype + '*' + if (isstring(var) + or isarrayofstrings(var) # obsolete? + or isstringarray(var)): + arg_types2.append('size_t') + arg_types.append(ctype) + + proto_args = ','.join(arg_types + arg_types2) + if not proto_args: + proto_args = 'void' + return proto_args + + +def getusercode(rout): + return getmultilineblock(rout, 'usercode') + + +def getusercode1(rout): + return getmultilineblock(rout, 'usercode', counter=1) + + +def getpymethoddef(rout): + return getmultilineblock(rout, 'pymethoddef') + + +def getargs(rout): + sortargs, args = [], [] + if 'args' in rout: + args = rout['args'] + if 'sortvars' in rout: + for a in rout['sortvars']: + if a in args: + sortargs.append(a) + for a in args: + if a not in sortargs: + sortargs.append(a) + else: + sortargs = rout['args'] + return args, sortargs + + +def getargs2(rout): + sortargs, args = [], rout.get('args', []) + auxvars = [a for a in rout['vars'].keys() if isintent_aux(rout['vars'][a]) + and a not in args] + args = auxvars + args + if 'sortvars' in rout: + for a in rout['sortvars']: + if a in args: + sortargs.append(a) + for a in args: + if a not in sortargs: + sortargs.append(a) + else: + sortargs = auxvars + rout['args'] + return args, sortargs + + +def getrestdoc(rout): + if 'f2pymultilines' not in rout: + return None + k = None + if rout['block'] == 'python module': + k = rout['block'], rout['name'] + return rout['f2pymultilines'].get(k, None) + + +def gentitle(name): + ln = (80 - len(name) - 6) // 2 + return f"/*{ln * '*'} {name} {ln * '*'}*/" + + +def flatlist(lst): + if isinstance(lst, list): + return reduce(lambda x, y, f=flatlist: x + f(y), lst, []) + return [lst] + + +def stripcomma(s): + if s and s[-1] == ',': + return s[:-1] + return s + + +def replace(str, d, defaultsep=''): + if isinstance(d, list): + return [replace(str, _m, defaultsep) for _m in d] + if isinstance(str, list): + return [replace(_m, d, defaultsep) for _m in str] + for k in 2 * list(d.keys()): + if k == 'separatorsfor': + continue + if 'separatorsfor' in d and k in d['separatorsfor']: + sep = d['separatorsfor'][k] + else: + sep = defaultsep + if isinstance(d[k], list): + str = str.replace(f'#{k}#', sep.join(flatlist(d[k]))) + else: + str = str.replace(f'#{k}#', d[k]) + return str + + +def dictappend(rd, ar): + if isinstance(ar, list): + for a in ar: + rd = dictappend(rd, a) + return rd + for k in ar.keys(): + if k[0] == '_': + continue + if k in rd: + if isinstance(rd[k], str): + rd[k] = [rd[k]] + if isinstance(rd[k], list): + if isinstance(ar[k], list): + rd[k] = rd[k] + ar[k] + else: + rd[k].append(ar[k]) + elif isinstance(rd[k], dict): + if isinstance(ar[k], dict): + if k == 'separatorsfor': + for k1 in ar[k].keys(): + if k1 not in rd[k]: + rd[k][k1] = ar[k][k1] + else: + rd[k] = dictappend(rd[k], ar[k]) + else: + rd[k] = ar[k] + return rd + + +def applyrules(rules, d, var={}): + ret = {} + if isinstance(rules, list): + for r in rules: + rr = applyrules(r, d, var) + ret = dictappend(ret, rr) + if '_break' in rr: + break + return ret + if '_check' in rules and (not rules['_check'](var)): + return ret + if 'need' in rules: + res = applyrules({'needs': rules['need']}, d, var) + if 'needs' in res: + cfuncs.append_needs(res['needs']) + + for k in rules.keys(): + if k == 'separatorsfor': + ret[k] = rules[k] + continue + if isinstance(rules[k], str): + ret[k] = replace(rules[k], d) + elif isinstance(rules[k], list): + ret[k] = [] + for i in rules[k]: + ar = applyrules({k: i}, d, var) + if k in ar: + ret[k].append(ar[k]) + elif k[0] == '_': + continue + elif isinstance(rules[k], dict): + ret[k] = [] + for k1 in rules[k].keys(): + if isinstance(k1, types.FunctionType) and k1(var): + if isinstance(rules[k][k1], list): + for i in rules[k][k1]: + if isinstance(i, dict): + res = applyrules({'supertext': i}, d, var) + i = res.get('supertext', '') + ret[k].append(replace(i, d)) + else: + i = rules[k][k1] + if isinstance(i, dict): + res = applyrules({'supertext': i}, d) + i = res.get('supertext', '') + ret[k].append(replace(i, d)) + else: + errmess(f'applyrules: ignoring rule {repr(rules[k])}.\n') + if isinstance(ret[k], list): + if len(ret[k]) == 1: + ret[k] = ret[k][0] + if ret[k] == []: + del ret[k] + return ret + + +_f2py_module_name_match = re.compile(r'\s*python\s*module\s*(?P[\w_]+)', + re.I).match +_f2py_user_module_name_match = re.compile(r'\s*python\s*module\s*(?P[\w_]*?' + r'__user__[\w_]*)', re.I).match + +def get_f2py_modulename(source): + name = None + with open(source) as f: + for line in f: + m = _f2py_module_name_match(line) + if m: + if _f2py_user_module_name_match(line): # skip *__user__* names + continue + name = m.group('name') + break + return name + +def getuseblocks(pymod): + all_uses = [] + for inner in pymod['body']: + for modblock in inner['body']: + if modblock.get('use'): + all_uses.extend([x for x in modblock.get("use").keys() if "__" not in x]) + return all_uses + +def process_f2cmap_dict(f2cmap_all, new_map, c2py_map, verbose=False): + """ + Update the Fortran-to-C type mapping dictionary with new mappings and + return a list of successfully mapped C types. + + This function integrates a new mapping dictionary into an existing + Fortran-to-C type mapping dictionary. It ensures that all keys are in + lowercase and validates new entries against a given C-to-Python mapping + dictionary. Redefinitions and invalid entries are reported with a warning. + + Parameters + ---------- + f2cmap_all : dict + The existing Fortran-to-C type mapping dictionary that will be updated. + It should be a dictionary of dictionaries where the main keys represent + Fortran types and the nested dictionaries map Fortran type specifiers + to corresponding C types. + + new_map : dict + A dictionary containing new type mappings to be added to `f2cmap_all`. + The structure should be similar to `f2cmap_all`, with keys representing + Fortran types and values being dictionaries of type specifiers and their + C type equivalents. + + c2py_map : dict + A dictionary used for validating the C types in `new_map`. It maps C + types to corresponding Python types and is used to ensure that the C + types specified in `new_map` are valid. + + verbose : boolean + A flag used to provide information about the types mapped + + Returns + ------- + tuple of (dict, list) + The updated Fortran-to-C type mapping dictionary and a list of + successfully mapped C types. + """ + f2cmap_mapped = [] + + new_map_lower = {} + for k, d1 in new_map.items(): + d1_lower = {k1.lower(): v1 for k1, v1 in d1.items()} + new_map_lower[k.lower()] = d1_lower + + for k, d1 in new_map_lower.items(): + if k not in f2cmap_all: + f2cmap_all[k] = {} + + for k1, v1 in d1.items(): + if v1 in c2py_map: + if k1 in f2cmap_all[k]: + outmess( + "\tWarning: redefinition of {'%s':{'%s':'%s'->'%s'}}\n" + % (k, k1, f2cmap_all[k][k1], v1) + ) + f2cmap_all[k][k1] = v1 + if verbose: + outmess(f'\tMapping "{k}(kind={k1})" to "{v1}\"\n') + f2cmap_mapped.append(v1) + elif verbose: + errmess( + "\tIgnoring map {'%s':{'%s':'%s'}}: '%s' must be in %s\n" + % (k, k1, v1, v1, list(c2py_map.keys())) + ) + + return f2cmap_all, f2cmap_mapped diff --git a/python/user_packages/Python313/site-packages/numpy/f2py/auxfuncs.pyi b/python/user_packages/Python313/site-packages/numpy/f2py/auxfuncs.pyi new file mode 100644 index 0000000000000000000000000000000000000000..174556a91222b9343fe45b48482e5d4270cd8c04 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/f2py/auxfuncs.pyi @@ -0,0 +1,262 @@ +from _typeshed import FileDescriptorOrPath +from collections.abc import Callable, Mapping +from pprint import pprint as show +from typing import Any, Final, Literal as L, Never, TypeAlias, TypeVar, overload + +from .cfuncs import errmess + +__all__ = [ + "applyrules", + "containscommon", + "containsderivedtypes", + "debugcapi", + "dictappend", + "errmess", + "gentitle", + "get_f2py_modulename", + "getargs2", + "getcallprotoargument", + "getcallstatement", + "getdimension", + "getfortranname", + "getpymethoddef", + "getrestdoc", + "getuseblocks", + "getusercode", + "getusercode1", + "hasbody", + "hascallstatement", + "hascommon", + "hasexternals", + "hasinitvalue", + "hasnote", + "hasresultnote", + "isallocatable", + "isarray", + "isarrayofstrings", + "isattr_value", + "ischaracter", + "ischaracter_or_characterarray", + "ischaracterarray", + "iscomplex", + "iscomplexarray", + "iscomplexfunction", + "iscomplexfunction_warn", + "iscstyledirective", + "isdouble", + "isdummyroutine", + "isexternal", + "isfunction", + "isfunction_wrap", + "isint1", + "isint1array", + "isinteger", + "isintent_aux", + "isintent_c", + "isintent_callback", + "isintent_copy", + "isintent_dict", + "isintent_hide", + "isintent_in", + "isintent_inout", + "isintent_inplace", + "isintent_nothide", + "isintent_out", + "isintent_overwrite", + "islogical", + "islogicalfunction", + "islong_complex", + "islong_double", + "islong_doublefunction", + "islong_long", + "islong_longfunction", + "ismodule", + "ismoduleroutine", + "isoptional", + "isprivate", + "isrequired", + "isroutine", + "isscalar", + "issigned_long_longarray", + "isstring", + "isstring_or_stringarray", + "isstringarray", + "isstringfunction", + "issubroutine", + "issubroutine_wrap", + "isthreadsafe", + "isunsigned", + "isunsigned_char", + "isunsigned_chararray", + "isunsigned_long_long", + "isunsigned_long_longarray", + "isunsigned_short", + "isunsigned_shortarray", + "isvariable", + "l_and", + "l_not", + "l_or", + "outmess", + "process_f2cmap_dict", + "replace", + "show", + "stripcomma", + "throw_error", +] + +### + +_VT = TypeVar("_VT") +_RT = TypeVar("_RT") + +_Var: TypeAlias = Mapping[str, list[str]] +_ROut: TypeAlias = Mapping[str, str] +_F2CMap: TypeAlias = Mapping[str, Mapping[str, str]] + +_Bool: TypeAlias = bool | L[0, 1] +_Intent: TypeAlias = L[ + "INTENT_IN", + "INTENT_OUT", + "INTENT_INOUT", + "INTENT_C", + "INTENT_CACHE", + "INTENT_HIDE", + "INTENT_INPLACE", + "INTENT_ALIGNED4", + "INTENT_ALIGNED8", + "INTENT_ALIGNED16", + "OPTIONAL", +] + +### + +isintent_dict: dict[Callable[[_Var], _Bool], _Intent] + +class F2PYError(Exception): ... + +class throw_error: + mess: Final[str] + def __init__(self, /, mess: str) -> None: ... + def __call__(self, /, var: _Var) -> Never: ... # raises F2PYError + +# +def l_and(*f: tuple[str, Callable[[_VT], _RT]]) -> Callable[[_VT], _RT]: ... +def l_or(*f: tuple[str, Callable[[_VT], _RT]]) -> Callable[[_VT], _RT]: ... +def l_not(f: tuple[str, Callable[[_VT], _RT]]) -> Callable[[_VT], _RT]: ... + +# +def outmess(t: str) -> None: ... +def debugcapi(var: _Var) -> bool: ... + +# +def hasinitvalue(var: _Var | str) -> bool: ... +def hasnote(var: _Var | str) -> bool: ... +def ischaracter(var: _Var) -> bool: ... +def ischaracterarray(var: _Var) -> bool: ... +def ischaracter_or_characterarray(var: _Var) -> bool: ... +def isstring(var: _Var) -> bool: ... +def isstringarray(var: _Var) -> bool: ... +def isstring_or_stringarray(var: _Var) -> bool: ... +def isarray(var: _Var) -> bool: ... +def isarrayofstrings(var: _Var) -> bool: ... +def isscalar(var: _Var) -> bool: ... +def iscomplex(var: _Var) -> bool: ... +def islogical(var: _Var) -> bool: ... +def isinteger(var: _Var) -> bool: ... +def isint1(var: _Var) -> bool: ... +def isint1array(var: _Var) -> bool: ... +def islong_long(var: _Var) -> _Bool: ... +def isunsigned(var: _Var) -> _Bool: ... +def isunsigned_char(var: _Var) -> _Bool: ... +def isunsigned_chararray(var: _Var) -> bool: ... +def isunsigned_short(var: _Var) -> _Bool: ... +def isunsigned_shortarray(var: _Var) -> bool: ... +def isunsigned_long_long(var: _Var) -> _Bool: ... +def isunsigned_long_longarray(var: _Var) -> bool: ... +def issigned_long_longarray(var: _Var) -> bool: ... +def isdouble(var: _Var) -> _Bool: ... +def islong_double(var: _Var) -> _Bool: ... +def islong_complex(var: _Var) -> _Bool: ... +def iscomplexarray(var: _Var) -> bool: ... +def isallocatable(var: _Var) -> bool: ... +def isattr_value(var: _Var) -> bool: ... +def isoptional(var: _Var) -> bool: ... +def isexternal(var: _Var) -> bool: ... +def isrequired(var: _Var) -> bool: ... +def isprivate(var: _Var) -> bool: ... +def isvariable(var: _Var) -> bool: ... +def isintent_in(var: _Var) -> _Bool: ... +def isintent_inout(var: _Var) -> bool: ... +def isintent_out(var: _Var) -> bool: ... +def isintent_hide(var: _Var) -> bool: ... +def isintent_nothide(var: _Var) -> bool: ... +def isintent_c(var: _Var) -> bool: ... +def isintent_cache(var: _Var) -> bool: ... +def isintent_copy(var: _Var) -> bool: ... +def isintent_overwrite(var: _Var) -> bool: ... +def isintent_callback(var: _Var) -> bool: ... +def isintent_inplace(var: _Var) -> bool: ... +def isintent_aux(var: _Var) -> bool: ... + +# +def containsderivedtypes(rout: _ROut) -> L[0, 1]: ... +def containscommon(rout: _ROut) -> _Bool: ... +def hasexternals(rout: _ROut) -> bool: ... +def hasresultnote(rout: _ROut) -> _Bool: ... +def hasbody(rout: _ROut) -> _Bool: ... +def hascommon(rout: _ROut) -> bool: ... +def hasderivedtypes(rout: _ROut) -> bool: ... +def hascallstatement(rout: _ROut) -> bool: ... +def isroutine(rout: _ROut) -> bool: ... +def ismodule(rout: _ROut) -> bool: ... +def ismoduleroutine(rout: _ROut) -> bool: ... +def issubroutine(rout: _ROut) -> bool: ... +def issubroutine_wrap(rout: _ROut) -> _Bool: ... +def isfunction(rout: _ROut) -> bool: ... +def isfunction_wrap(rout: _ROut) -> _Bool: ... +def islogicalfunction(rout: _ROut) -> _Bool: ... +def islong_longfunction(rout: _ROut) -> _Bool: ... +def islong_doublefunction(rout: _ROut) -> _Bool: ... +def iscomplexfunction(rout: _ROut) -> _Bool: ... +def iscomplexfunction_warn(rout: _ROut) -> _Bool: ... +def isstringfunction(rout: _ROut) -> _Bool: ... +def isthreadsafe(rout: _ROut) -> bool: ... +def isdummyroutine(rout: _ROut) -> _Bool: ... +def iscstyledirective(f2py_line: str) -> bool: ... + +# . +def getdimension(var: _Var) -> list[Any] | None: ... +def getfortranname(rout: _ROut) -> str: ... +def getmultilineblock(rout: _ROut, blockname: str, comment: _Bool = 1, counter: int = 0) -> str | None: ... +def getcallstatement(rout: _ROut) -> str | None: ... +def getcallprotoargument(rout: _ROut, cb_map: dict[str, str] = {}) -> str: ... +def getusercode(rout: _ROut) -> str | None: ... +def getusercode1(rout: _ROut) -> str | None: ... +def getpymethoddef(rout: _ROut) -> str | None: ... +def getargs(rout: _ROut) -> tuple[list[str], list[str]]: ... +def getargs2(rout: _ROut) -> tuple[list[str], list[str]]: ... +def getrestdoc(rout: _ROut) -> str | None: ... + +# +def gentitle(name: str) -> str: ... +def stripcomma(s: str) -> str: ... +@overload +def replace(str: str, d: list[str], defaultsep: str = "") -> list[str]: ... +@overload +def replace(str: list[str], d: str, defaultsep: str = "") -> list[str]: ... +@overload +def replace(str: str, d: str, defaultsep: str = "") -> str: ... + +# +def dictappend(rd: Mapping[str, object], ar: Mapping[str, object] | list[Mapping[str, object]]) -> dict[str, Any]: ... +def applyrules(rules: Mapping[str, object], d: Mapping[str, object], var: _Var = {}) -> dict[str, Any]: ... + +# +def get_f2py_modulename(source: FileDescriptorOrPath) -> str: ... +def getuseblocks(pymod: Mapping[str, Mapping[str, Mapping[str, str]]]) -> list[str]: ... +def process_f2cmap_dict( + f2cmap_all: _F2CMap, + new_map: _F2CMap, + c2py_map: _F2CMap, + verbose: bool = False, +) -> tuple[dict[str, dict[str, str]], list[str]]: ... diff --git a/python/user_packages/Python313/site-packages/numpy/f2py/capi_maps.py b/python/user_packages/Python313/site-packages/numpy/f2py/capi_maps.py new file mode 100644 index 0000000000000000000000000000000000000000..2ab9e4067b7d5d016823545399060569414c5331 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/f2py/capi_maps.py @@ -0,0 +1,811 @@ +""" +Copyright 1999 -- 2011 Pearu Peterson all rights reserved. +Copyright 2011 -- present NumPy Developers. +Permission to use, modify, and distribute this software is given under the +terms of the NumPy License. + +NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. +""" +from . import __version__ + +f2py_version = __version__.version + +import copy +import os +import re + +from . import cb_rules +from ._isocbind import iso_c2py_map, iso_c_binding_map, isoc_c2pycode_map + +# The environment provided by auxfuncs.py is needed for some calls to eval. +# As the needed functions cannot be determined by static inspection of the +# code, it is safest to use import * pending a major refactoring of f2py. +from .auxfuncs import * +from .crackfortran import markoutercomma + +__all__ = [ + 'getctype', 'getstrlength', 'getarrdims', 'getpydocsign', + 'getarrdocsign', 'getinit', 'sign2map', 'routsign2map', 'modsign2map', + 'cb_sign2map', 'cb_routsign2map', 'common_sign2map', 'process_f2cmap_dict' +] + + +depargs = [] +lcb_map = {} +lcb2_map = {} +# forced casting: mainly caused by the fact that Python or Numeric +# C/APIs do not support the corresponding C types. +c2py_map = {'double': 'float', + 'float': 'float', # forced casting + 'long_double': 'float', # forced casting + 'char': 'int', # forced casting + 'signed_char': 'int', # forced casting + 'unsigned_char': 'int', # forced casting + 'short': 'int', # forced casting + 'unsigned_short': 'int', # forced casting + 'int': 'int', # forced casting + 'long': 'int', + 'long_long': 'long', + 'unsigned': 'int', # forced casting + 'complex_float': 'complex', # forced casting + 'complex_double': 'complex', + 'complex_long_double': 'complex', # forced casting + 'string': 'string', + 'character': 'bytes', + } + +c2capi_map = {'double': 'NPY_DOUBLE', + 'float': 'NPY_FLOAT', + 'long_double': 'NPY_LONGDOUBLE', + 'char': 'NPY_BYTE', + 'unsigned_char': 'NPY_UBYTE', + 'signed_char': 'NPY_BYTE', + 'short': 'NPY_SHORT', + 'unsigned_short': 'NPY_USHORT', + 'int': 'NPY_INT', + 'unsigned': 'NPY_UINT', + 'long': 'NPY_LONG', + 'unsigned_long': 'NPY_ULONG', + 'long_long': 'NPY_LONGLONG', + 'unsigned_long_long': 'NPY_ULONGLONG', + 'complex_float': 'NPY_CFLOAT', + 'complex_double': 'NPY_CDOUBLE', + 'complex_long_double': 'NPY_CDOUBLE', + 'string': 'NPY_STRING', + 'character': 'NPY_STRING'} + +c2pycode_map = {'double': 'd', + 'float': 'f', + 'long_double': 'g', + 'char': 'b', + 'unsigned_char': 'B', + 'signed_char': 'b', + 'short': 'h', + 'unsigned_short': 'H', + 'int': 'i', + 'unsigned': 'I', + 'long': 'l', + 'unsigned_long': 'L', + 'long_long': 'q', + 'unsigned_long_long': 'Q', + 'complex_float': 'F', + 'complex_double': 'D', + 'complex_long_double': 'G', + 'string': 'S', + 'character': 'c'} + +# https://docs.python.org/3/c-api/arg.html#building-values +c2buildvalue_map = {'double': 'd', + 'float': 'f', + 'char': 'b', + 'signed_char': 'b', + 'short': 'h', + 'int': 'i', + 'long': 'l', + 'long_long': 'L', + 'complex_float': 'N', + 'complex_double': 'N', + 'complex_long_double': 'N', + 'string': 'y', + 'character': 'c'} + +f2cmap_all = {'real': {'': 'float', '4': 'float', '8': 'double', + '12': 'long_double', '16': 'long_double'}, + 'integer': {'': 'int', '1': 'signed_char', '2': 'short', + '4': 'int', '8': 'long_long', + '-1': 'unsigned_char', '-2': 'unsigned_short', + '-4': 'unsigned', '-8': 'unsigned_long_long'}, + 'complex': {'': 'complex_float', '8': 'complex_float', + '16': 'complex_double', '24': 'complex_long_double', + '32': 'complex_long_double'}, + 'complexkind': {'': 'complex_float', '4': 'complex_float', + '8': 'complex_double', '12': 'complex_long_double', + '16': 'complex_long_double'}, + 'logical': {'': 'int', '1': 'char', '2': 'short', '4': 'int', + '8': 'long_long'}, + 'double complex': {'': 'complex_double'}, + 'double precision': {'': 'double'}, + 'byte': {'': 'char'}, + } + +# Add ISO_C handling +c2pycode_map.update(isoc_c2pycode_map) +c2py_map.update(iso_c2py_map) +f2cmap_all, _ = process_f2cmap_dict(f2cmap_all, iso_c_binding_map, c2py_map) +# End ISO_C handling +f2cmap_default = copy.deepcopy(f2cmap_all) + +f2cmap_mapped = [] + +def load_f2cmap_file(f2cmap_file): + global f2cmap_all, f2cmap_mapped + + f2cmap_all = copy.deepcopy(f2cmap_default) + + if f2cmap_file is None: + # Default value + f2cmap_file = '.f2py_f2cmap' + if not os.path.isfile(f2cmap_file): + return + + # User defined additions to f2cmap_all. + # f2cmap_file must contain a dictionary of dictionaries, only. For + # example, {'real':{'low':'float'}} means that Fortran 'real(low)' is + # interpreted as C 'float'. This feature is useful for F90/95 users if + # they use PARAMETERS in type specifications. + try: + outmess(f'Reading f2cmap from {f2cmap_file!r} ...\n') + with open(f2cmap_file) as f: + d = eval(f.read().lower(), {}, {}) + f2cmap_all, f2cmap_mapped = process_f2cmap_dict(f2cmap_all, d, c2py_map, True) + outmess('Successfully applied user defined f2cmap changes\n') + except Exception as msg: + errmess(f'Failed to apply user defined f2cmap changes: {msg}. Skipping.\n') + + +cformat_map = {'double': '%g', + 'float': '%g', + 'long_double': '%Lg', + 'char': '%d', + 'signed_char': '%d', + 'unsigned_char': '%hhu', + 'short': '%hd', + 'unsigned_short': '%hu', + 'int': '%d', + 'unsigned': '%u', + 'long': '%ld', + 'unsigned_long': '%lu', + 'long_long': '%ld', + 'complex_float': '(%g,%g)', + 'complex_double': '(%g,%g)', + 'complex_long_double': '(%Lg,%Lg)', + 'string': '\\"%s\\"', + 'character': "'%c'", + } + +# Auxiliary functions + + +def getctype(var): + """ + Determines C type + """ + ctype = 'void' + if isfunction(var): + if 'result' in var: + a = var['result'] + else: + a = var['name'] + if a in var['vars']: + return getctype(var['vars'][a]) + else: + errmess(f'getctype: function {a} has no return value?!\n') + elif issubroutine(var): + return ctype + elif ischaracter_or_characterarray(var): + return 'character' + elif isstring_or_stringarray(var): + return 'string' + elif 'typespec' in var and var['typespec'].lower() in f2cmap_all: + typespec = var['typespec'].lower() + f2cmap = f2cmap_all[typespec] + ctype = f2cmap[''] # default type + if 'kindselector' in var: + if '*' in var['kindselector']: + try: + ctype = f2cmap[var['kindselector']['*']] + except KeyError: + errmess('getctype: "%s %s %s" not supported.\n' % + (var['typespec'], '*', var['kindselector']['*'])) + elif 'kind' in var['kindselector']: + if typespec + 'kind' in f2cmap_all: + f2cmap = f2cmap_all[typespec + 'kind'] + try: + ctype = f2cmap[var['kindselector']['kind']] + except KeyError: + if typespec in f2cmap_all: + f2cmap = f2cmap_all[typespec] + try: + ctype = f2cmap[str(var['kindselector']['kind'])] + except KeyError: + errmess('getctype: "%s(kind=%s)" is mapped to C "%s" (to override define dict(%s = dict(%s="")) in %s/.f2py_f2cmap file).\n' + % (typespec, var['kindselector']['kind'], ctype, + typespec, var['kindselector']['kind'], os.getcwd())) + elif not isexternal(var): + errmess(f'getctype: No C-type found in "{var}", assuming void.\n') + return ctype + + +def f2cexpr(expr): + """Rewrite Fortran expression as f2py supported C expression. + + Due to the lack of a proper expression parser in f2py, this + function uses a heuristic approach that assumes that Fortran + arithmetic expressions are valid C arithmetic expressions when + mapping Fortran function calls to the corresponding C function/CPP + macros calls. + + """ + # TODO: support Fortran `len` function with optional kind parameter + expr = re.sub(r'\blen\b', 'f2py_slen', expr) + return expr + + +def getstrlength(var): + if isstringfunction(var): + if 'result' in var: + a = var['result'] + else: + a = var['name'] + if a in var['vars']: + return getstrlength(var['vars'][a]) + else: + errmess(f'getstrlength: function {a} has no return value?!\n') + if not isstring(var): + errmess( + f'getstrlength: expected a signature of a string but got: {repr(var)}\n') + len = '1' + if 'charselector' in var: + a = var['charselector'] + if '*' in a: + len = a['*'] + elif 'len' in a: + len = f2cexpr(a['len']) + if re.match(r'\(\s*(\*|:)\s*\)', len) or re.match(r'(\*|:)', len): + if isintent_hide(var): + errmess('getstrlength:intent(hide): expected a string with defined length but got: %s\n' % ( + repr(var))) + len = '-1' + return len + + +def getarrdims(a, var, verbose=0): + ret = {} + if isstring(var) and not isarray(var): + ret['size'] = getstrlength(var) + ret['rank'] = '0' + ret['dims'] = '' + elif isscalar(var): + ret['size'] = '1' + ret['rank'] = '0' + ret['dims'] = '' + elif isarray(var): + dim = copy.copy(var['dimension']) + ret['size'] = '*'.join(dim) + try: + ret['size'] = repr(eval(ret['size'])) + except Exception: + pass + ret['dims'] = ','.join(dim) + ret['rank'] = repr(len(dim)) + ret['rank*[-1]'] = repr(len(dim) * [-1])[1:-1] + for i in range(len(dim)): # solve dim for dependencies + v = [] + if dim[i] in depargs: + v = [dim[i]] + else: + for va in depargs: + if re.match(r'.*?\b%s\b.*' % va, dim[i]): + v.append(va) + for va in v: + if depargs.index(va) > depargs.index(a): + dim[i] = '*' + break + ret['setdims'], i = '', -1 + for d in dim: + i = i + 1 + if d not in ['*', ':', '(*)', '(:)']: + ret['setdims'] = '%s#varname#_Dims[%d]=%s,' % ( + ret['setdims'], i, d) + if ret['setdims']: + ret['setdims'] = ret['setdims'][:-1] + ret['cbsetdims'], i = '', -1 + for d in var['dimension']: + i = i + 1 + if d not in ['*', ':', '(*)', '(:)']: + ret['cbsetdims'] = '%s#varname#_Dims[%d]=%s,' % ( + ret['cbsetdims'], i, d) + elif isintent_in(var): + outmess('getarrdims:warning: assumed shape array, using 0 instead of %r\n' + % (d)) + ret['cbsetdims'] = '%s#varname#_Dims[%d]=%s,' % ( + ret['cbsetdims'], i, 0) + elif verbose: + errmess( + f'getarrdims: If in call-back function: array argument {repr(a)} must have bounded dimensions: got {repr(d)}\n') + if ret['cbsetdims']: + ret['cbsetdims'] = ret['cbsetdims'][:-1] +# if not isintent_c(var): +# var['dimension'].reverse() + return ret + + +def getpydocsign(a, var): + global lcb_map + if isfunction(var): + if 'result' in var: + af = var['result'] + else: + af = var['name'] + if af in var['vars']: + return getpydocsign(af, var['vars'][af]) + else: + errmess(f'getctype: function {af} has no return value?!\n') + return '', '' + sig, sigout = a, a + opt = '' + if isintent_in(var): + opt = 'input' + elif isintent_inout(var): + opt = 'in/output' + out_a = a + if isintent_out(var): + for k in var['intent']: + if k[:4] == 'out=': + out_a = k[4:] + break + init = '' + ctype = getctype(var) + + if hasinitvalue(var): + init, showinit = getinit(a, var) + init = f', optional\\n Default: {showinit}' + if isscalar(var): + if isintent_inout(var): + sig = '%s : %s rank-0 array(%s,\'%s\')%s' % (a, opt, c2py_map[ctype], + c2pycode_map[ctype], init) + else: + sig = f'{a} : {opt} {c2py_map[ctype]}{init}' + sigout = f'{out_a} : {c2py_map[ctype]}' + elif isstring(var): + if isintent_inout(var): + sig = '%s : %s rank-0 array(string(len=%s),\'c\')%s' % ( + a, opt, getstrlength(var), init) + else: + sig = f'{a} : {opt} string(len={getstrlength(var)}){init}' + sigout = f'{out_a} : string(len={getstrlength(var)})' + elif isarray(var): + dim = var['dimension'] + rank = repr(len(dim)) + sig = '%s : %s rank-%s array(\'%s\') with bounds (%s)%s' % (a, opt, rank, + c2pycode_map[ + ctype], + ','.join(dim), init) + if a == out_a: + sigout = '%s : rank-%s array(\'%s\') with bounds (%s)'\ + % (a, rank, c2pycode_map[ctype], ','.join(dim)) + else: + sigout = '%s : rank-%s array(\'%s\') with bounds (%s) and %s storage'\ + % (out_a, rank, c2pycode_map[ctype], ','.join(dim), a) + elif isexternal(var): + ua = '' + if a in lcb_map and lcb_map[a] in lcb2_map and 'argname' in lcb2_map[lcb_map[a]]: + ua = lcb2_map[lcb_map[a]]['argname'] + if not ua == a: + ua = f' => {ua}' + else: + ua = '' + sig = f'{a} : call-back function{ua}' + sigout = sig + else: + errmess( + f'getpydocsign: Could not resolve docsignature for "{a}".\n') + return sig, sigout + + +def getarrdocsign(a, var): + ctype = getctype(var) + if isstring(var) and (not isarray(var)): + sig = f'{a} : rank-0 array(string(len={getstrlength(var)}),\'c\')' + elif isscalar(var): + sig = f'{a} : rank-0 array({c2py_map[ctype]},\'{c2pycode_map[ctype]}\')' + elif isarray(var): + dim = var['dimension'] + rank = repr(len(dim)) + sig = '%s : rank-%s array(\'%s\') with bounds (%s)' % (a, rank, + c2pycode_map[ + ctype], + ','.join(dim)) + return sig + + +def getinit(a, var): + if isstring(var): + init, showinit = '""', "''" + else: + init, showinit = '', '' + if hasinitvalue(var): + init = var['='] + showinit = init + if iscomplex(var) or iscomplexarray(var): + ret = {} + + try: + v = var["="] + if ',' in v: + ret['init.r'], ret['init.i'] = markoutercomma( + v[1:-1]).split('@,@') + else: + v = eval(v, {}, {}) + ret['init.r'], ret['init.i'] = str(v.real), str(v.imag) + except Exception: + raise ValueError( + f'getinit: expected complex number `(r,i)\' but got `{init}\' as initial value of {a!r}.') + if isarray(var): + init = f"(capi_c.r={ret['init.r']},capi_c.i={ret['init.i']},capi_c)" + elif isstring(var): + if not init: + init, showinit = '""', "''" + if init[0] == "'": + init = '"%s"' % (init[1:-1].replace('"', '\\"')) + if init[0] == '"': + showinit = f"'{init[1:-1]}'" + return init, showinit + + +def get_elsize(var): + if isstring(var) or isstringarray(var): + elsize = getstrlength(var) + # override with user-specified length when available: + elsize = var['charselector'].get('f2py_len', elsize) + return elsize + if ischaracter(var) or ischaracterarray(var): + return '1' + # for numerical types, PyArray_New* functions ignore specified + # elsize, so we just return 1 and let elsize be determined at + # runtime, see fortranobject.c + return '1' + + +def sign2map(a, var): + """ + varname,ctype,atype + init,init.r,init.i,pytype + vardebuginfo,vardebugshowvalue,varshowvalue + varrformat + + intent + """ + out_a = a + if isintent_out(var): + for k in var['intent']: + if k[:4] == 'out=': + out_a = k[4:] + break + ret = {'varname': a, 'outvarname': out_a, 'ctype': getctype(var)} + intent_flags = [] + for f, s in isintent_dict.items(): + if f(var): + intent_flags.append(f'F2PY_{s}') + if intent_flags: + # TODO: Evaluate intent_flags here. + ret['intent'] = '|'.join(intent_flags) + else: + ret['intent'] = 'F2PY_INTENT_IN' + if isarray(var): + ret['varrformat'] = 'N' + elif ret['ctype'] in c2buildvalue_map: + ret['varrformat'] = c2buildvalue_map[ret['ctype']] + else: + ret['varrformat'] = 'O' + ret['init'], ret['showinit'] = getinit(a, var) + if hasinitvalue(var) and iscomplex(var) and not isarray(var): + ret['init.r'], ret['init.i'] = markoutercomma( + ret['init'][1:-1]).split('@,@') + if isexternal(var): + ret['cbnamekey'] = a + if a in lcb_map: + ret['cbname'] = lcb_map[a] + ret['maxnofargs'] = lcb2_map[lcb_map[a]]['maxnofargs'] + ret['nofoptargs'] = lcb2_map[lcb_map[a]]['nofoptargs'] + ret['cbdocstr'] = lcb2_map[lcb_map[a]]['docstr'] + ret['cblatexdocstr'] = lcb2_map[lcb_map[a]]['latexdocstr'] + else: + ret['cbname'] = a + errmess('sign2map: Confused: external %s is not in lcb_map%s.\n' % ( + a, list(lcb_map.keys()))) + if isstring(var): + ret['length'] = getstrlength(var) + if isarray(var): + ret = dictappend(ret, getarrdims(a, var)) + dim = copy.copy(var['dimension']) + if ret['ctype'] in c2capi_map: + ret['atype'] = c2capi_map[ret['ctype']] + ret['elsize'] = get_elsize(var) + # Debug info + if debugcapi(var): + il = [isintent_in, 'input', isintent_out, 'output', + isintent_inout, 'inoutput', isrequired, 'required', + isoptional, 'optional', isintent_hide, 'hidden', + iscomplex, 'complex scalar', + l_and(isscalar, l_not(iscomplex)), 'scalar', + isstring, 'string', isarray, 'array', + iscomplexarray, 'complex array', isstringarray, 'string array', + iscomplexfunction, 'complex function', + l_and(isfunction, l_not(iscomplexfunction)), 'function', + isexternal, 'callback', + isintent_callback, 'callback', + isintent_aux, 'auxiliary', + ] + rl = [] + for i in range(0, len(il), 2): + if il[i](var): + rl.append(il[i + 1]) + if isstring(var): + rl.append(f"slen({a})={ret['length']}") + if isarray(var): + ddim = ','.join( + map(lambda x, y: f'{x}|{y}', var['dimension'], dim)) + rl.append(f'dims({ddim})') + if isexternal(var): + ret['vardebuginfo'] = f"debug-capi:{a}=>{ret['cbname']}:{','.join(rl)}" + else: + ret['vardebuginfo'] = 'debug-capi:%s %s=%s:%s' % ( + ret['ctype'], a, ret['showinit'], ','.join(rl)) + if isscalar(var): + if ret['ctype'] in cformat_map: + ret['vardebugshowvalue'] = f"debug-capi:{a}={cformat_map[ret['ctype']]}" + if isstring(var): + ret['vardebugshowvalue'] = 'debug-capi:slen(%s)=%%d %s=\\"%%s\\"' % ( + a, a) + if isexternal(var): + ret['vardebugshowvalue'] = f'debug-capi:{a}=%p' + if ret['ctype'] in cformat_map: + ret['varshowvalue'] = f"#name#:{a}={cformat_map[ret['ctype']]}" + ret['showvalueformat'] = f"{cformat_map[ret['ctype']]}" + if isstring(var): + ret['varshowvalue'] = '#name#:slen(%s)=%%d %s=\\"%%s\\"' % (a, a) + ret['pydocsign'], ret['pydocsignout'] = getpydocsign(a, var) + if hasnote(var): + ret['note'] = var['note'] + return ret + + +def routsign2map(rout): + """ + name,NAME,begintitle,endtitle + rname,ctype,rformat + routdebugshowvalue + """ + global lcb_map + name = rout['name'] + fname = getfortranname(rout) + ret = {'name': name, + 'texname': name.replace('_', '\\_'), + 'name_lower': name.lower(), + 'NAME': name.upper(), + 'begintitle': gentitle(name), + 'endtitle': gentitle(f'end of {name}'), + 'fortranname': fname, + 'FORTRANNAME': fname.upper(), + 'callstatement': getcallstatement(rout) or '', + 'usercode': getusercode(rout) or '', + 'usercode1': getusercode1(rout) or '', + } + if '_' in fname: + ret['F_FUNC'] = 'F_FUNC_US' + else: + ret['F_FUNC'] = 'F_FUNC' + if '_' in name: + ret['F_WRAPPEDFUNC'] = 'F_WRAPPEDFUNC_US' + else: + ret['F_WRAPPEDFUNC'] = 'F_WRAPPEDFUNC' + lcb_map = {} + if 'use' in rout: + for u in rout['use'].keys(): + if u in cb_rules.cb_map: + for un in cb_rules.cb_map[u]: + ln = un[0] + if 'map' in rout['use'][u]: + for k in rout['use'][u]['map'].keys(): + if rout['use'][u]['map'][k] == un[0]: + ln = k + break + lcb_map[ln] = un[1] + elif rout.get('externals'): + errmess('routsign2map: Confused: function %s has externals %s but no "use" statement.\n' % ( + ret['name'], repr(rout['externals']))) + ret['callprotoargument'] = getcallprotoargument(rout, lcb_map) or '' + if isfunction(rout): + if 'result' in rout: + a = rout['result'] + else: + a = rout['name'] + ret['rname'] = a + ret['pydocsign'], ret['pydocsignout'] = getpydocsign(a, rout) + ret['ctype'] = getctype(rout['vars'][a]) + if hasresultnote(rout): + ret['resultnote'] = rout['vars'][a]['note'] + rout['vars'][a]['note'] = ['See elsewhere.'] + if ret['ctype'] in c2buildvalue_map: + ret['rformat'] = c2buildvalue_map[ret['ctype']] + else: + ret['rformat'] = 'O' + errmess('routsign2map: no c2buildvalue key for type %s\n' % + (repr(ret['ctype']))) + if debugcapi(rout): + if ret['ctype'] in cformat_map: + ret['routdebugshowvalue'] = 'debug-capi:%s=%s' % ( + a, cformat_map[ret['ctype']]) + if isstringfunction(rout): + ret['routdebugshowvalue'] = 'debug-capi:slen(%s)=%%d %s=\\"%%s\\"' % ( + a, a) + if isstringfunction(rout): + ret['rlength'] = getstrlength(rout['vars'][a]) + if ret['rlength'] == '-1': + errmess('routsign2map: expected explicit specification of the length of the string returned by the fortran function %s; taking 10.\n' % ( + repr(rout['name']))) + ret['rlength'] = '10' + if hasnote(rout): + ret['note'] = rout['note'] + rout['note'] = ['See elsewhere.'] + return ret + + +def modsign2map(m): + """ + modulename + """ + if ismodule(m): + ret = {'f90modulename': m['name'], + 'F90MODULENAME': m['name'].upper(), + 'texf90modulename': m['name'].replace('_', '\\_')} + else: + ret = {'modulename': m['name'], + 'MODULENAME': m['name'].upper(), + 'texmodulename': m['name'].replace('_', '\\_')} + ret['restdoc'] = getrestdoc(m) or [] + if hasnote(m): + ret['note'] = m['note'] + ret['usercode'] = getusercode(m) or '' + ret['usercode1'] = getusercode1(m) or '' + if m['body']: + ret['interface_usercode'] = getusercode(m['body'][0]) or '' + else: + ret['interface_usercode'] = '' + ret['pymethoddef'] = getpymethoddef(m) or '' + if 'gil_used' in m: + ret['gil_used'] = m['gil_used'] + if 'coutput' in m: + ret['coutput'] = m['coutput'] + if 'f2py_wrapper_output' in m: + ret['f2py_wrapper_output'] = m['f2py_wrapper_output'] + return ret + + +def cb_sign2map(a, var, index=None): + ret = {'varname': a} + ret['varname_i'] = ret['varname'] + ret['ctype'] = getctype(var) + if ret['ctype'] in c2capi_map: + ret['atype'] = c2capi_map[ret['ctype']] + ret['elsize'] = get_elsize(var) + if ret['ctype'] in cformat_map: + ret['showvalueformat'] = f"{cformat_map[ret['ctype']]}" + if isarray(var): + ret = dictappend(ret, getarrdims(a, var)) + ret['pydocsign'], ret['pydocsignout'] = getpydocsign(a, var) + if hasnote(var): + ret['note'] = var['note'] + var['note'] = ['See elsewhere.'] + return ret + + +def cb_routsign2map(rout, um): + """ + name,begintitle,endtitle,argname + ctype,rctype,maxnofargs,nofoptargs,returncptr + """ + ret = {'name': f"cb_{rout['name']}_in_{um}", + 'returncptr': ''} + if isintent_callback(rout): + if '_' in rout['name']: + F_FUNC = 'F_FUNC_US' + else: + F_FUNC = 'F_FUNC' + ret['callbackname'] = f"{F_FUNC}({rout['name'].lower()},{rout['name'].upper()})" + ret['static'] = 'extern' + else: + ret['callbackname'] = ret['name'] + ret['static'] = 'static' + ret['argname'] = rout['name'] + ret['begintitle'] = gentitle(ret['name']) + ret['endtitle'] = gentitle(f"end of {ret['name']}") + ret['ctype'] = getctype(rout) + ret['rctype'] = 'void' + if ret['ctype'] == 'string': + ret['rctype'] = 'void' + else: + ret['rctype'] = ret['ctype'] + if ret['rctype'] != 'void': + if iscomplexfunction(rout): + ret['returncptr'] = """ +#ifdef F2PY_CB_RETURNCOMPLEX +return_value= +#endif +""" + else: + ret['returncptr'] = 'return_value=' + if ret['ctype'] in cformat_map: + ret['showvalueformat'] = f"{cformat_map[ret['ctype']]}" + if isstringfunction(rout): + ret['strlength'] = getstrlength(rout) + if isfunction(rout): + if 'result' in rout: + a = rout['result'] + else: + a = rout['name'] + if hasnote(rout['vars'][a]): + ret['note'] = rout['vars'][a]['note'] + rout['vars'][a]['note'] = ['See elsewhere.'] + ret['rname'] = a + ret['pydocsign'], ret['pydocsignout'] = getpydocsign(a, rout) + if iscomplexfunction(rout): + ret['rctype'] = """ +#ifdef F2PY_CB_RETURNCOMPLEX +#ctype# +#else +void +#endif +""" + elif hasnote(rout): + ret['note'] = rout['note'] + rout['note'] = ['See elsewhere.'] + nofargs = 0 + nofoptargs = 0 + if 'args' in rout and 'vars' in rout: + for a in rout['args']: + var = rout['vars'][a] + if l_or(isintent_in, isintent_inout)(var): + nofargs = nofargs + 1 + if isoptional(var): + nofoptargs = nofoptargs + 1 + ret['maxnofargs'] = repr(nofargs) + ret['nofoptargs'] = repr(nofoptargs) + if hasnote(rout) and isfunction(rout) and 'result' in rout: + ret['routnote'] = rout['note'] + rout['note'] = ['See elsewhere.'] + return ret + + +def common_sign2map(a, var): # obsolete + ret = {'varname': a, 'ctype': getctype(var)} + if isstringarray(var): + ret['ctype'] = 'char' + if ret['ctype'] in c2capi_map: + ret['atype'] = c2capi_map[ret['ctype']] + ret['elsize'] = get_elsize(var) + if ret['ctype'] in cformat_map: + ret['showvalueformat'] = f"{cformat_map[ret['ctype']]}" + if isarray(var): + ret = dictappend(ret, getarrdims(a, var)) + elif isstring(var): + ret['size'] = getstrlength(var) + ret['rank'] = '1' + ret['pydocsign'], ret['pydocsignout'] = getpydocsign(a, var) + if hasnote(var): + ret['note'] = var['note'] + var['note'] = ['See elsewhere.'] + # for strings this returns 0-rank but actually is 1-rank + ret['arrdocstr'] = getarrdocsign(a, var) + return ret diff --git a/python/user_packages/Python313/site-packages/numpy/f2py/capi_maps.pyi b/python/user_packages/Python313/site-packages/numpy/f2py/capi_maps.pyi new file mode 100644 index 0000000000000000000000000000000000000000..b01d64c861fa7d4c564dddae37da38838faf6576 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/f2py/capi_maps.pyi @@ -0,0 +1,33 @@ +from .auxfuncs import _ROut, _Var, process_f2cmap_dict + +__all__ = [ + "cb_routsign2map", + "cb_sign2map", + "common_sign2map", + "getarrdims", + "getarrdocsign", + "getctype", + "getinit", + "getpydocsign", + "getstrlength", + "modsign2map", + "process_f2cmap_dict", + "routsign2map", + "sign2map", +] + +### + +def getctype(var: _Var) -> str: ... +def f2cexpr(expr: str) -> str: ... +def getstrlength(var: _Var) -> str: ... +def getarrdims(a: str, var: _Var, verbose: int = 0) -> dict[str, str]: ... +def getpydocsign(a: str, var: _Var) -> tuple[str, str]: ... +def getarrdocsign(a: str, var: _Var) -> str: ... +def getinit(a: str, var: _Var) -> tuple[str, str]: ... +def sign2map(a: str, var: _Var) -> dict[str, str]: ... +def routsign2map(rout: _ROut) -> dict[str, str]: ... +def modsign2map(m: _ROut) -> dict[str, str]: ... +def cb_sign2map(a: str, var: _Var, index: object | None = None) -> dict[str, str]: ... +def cb_routsign2map(rout: _ROut, um: str) -> dict[str, str]: ... +def common_sign2map(a: str, var: _Var) -> dict[str, str]: ... # obsolete diff --git a/python/user_packages/Python313/site-packages/numpy/f2py/cb_rules.py b/python/user_packages/Python313/site-packages/numpy/f2py/cb_rules.py new file mode 100644 index 0000000000000000000000000000000000000000..9803e68ea16ca21d818c1d13ae4bb1e5bdbbcedd --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/f2py/cb_rules.py @@ -0,0 +1,665 @@ +""" +Build call-back mechanism for f2py2e. + +Copyright 1999 -- 2011 Pearu Peterson all rights reserved. +Copyright 2011 -- present NumPy Developers. +Permission to use, modify, and distribute this software is given under the +terms of the NumPy License. + +NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. +""" +from . import __version__, cfuncs +from .auxfuncs import ( + applyrules, + debugcapi, + dictappend, + errmess, + getargs, + hasnote, + isarray, + iscomplex, + iscomplexarray, + iscomplexfunction, + isfunction, + isintent_c, + isintent_hide, + isintent_in, + isintent_inout, + isintent_nothide, + isintent_out, + isoptional, + isrequired, + isscalar, + isstring, + isstringfunction, + issubroutine, + l_and, + l_not, + l_or, + outmess, + replace, + stripcomma, + throw_error, +) + +f2py_version = __version__.version + + +################## Rules for callback function ############## + +cb_routine_rules = { + 'cbtypedefs': 'typedef #rctype#(*#name#_typedef)(#optargs_td##args_td##strarglens_td##noargs#);', + 'body': """ +#begintitle# +typedef struct { + PyObject *capi; + PyTupleObject *args_capi; + int nofargs; + jmp_buf jmpbuf; +} #name#_t; + +#if defined(F2PY_THREAD_LOCAL_DECL) && !defined(F2PY_USE_PYTHON_TLS) + +static F2PY_THREAD_LOCAL_DECL #name#_t *_active_#name# = NULL; + +static #name#_t *swap_active_#name#(#name#_t *ptr) { + #name#_t *prev = _active_#name#; + _active_#name# = ptr; + return prev; +} + +static #name#_t *get_active_#name#(void) { + return _active_#name#; +} + +#else + +static #name#_t *swap_active_#name#(#name#_t *ptr) { + char *key = "__f2py_cb_#name#"; + return (#name#_t *)F2PySwapThreadLocalCallbackPtr(key, ptr); +} + +static #name#_t *get_active_#name#(void) { + char *key = "__f2py_cb_#name#"; + return (#name#_t *)F2PyGetThreadLocalCallbackPtr(key); +} + +#endif + +/*typedef #rctype#(*#name#_typedef)(#optargs_td##args_td##strarglens_td##noargs#);*/ +#static# #rctype# #callbackname# (#optargs##args##strarglens##noargs#) { + #name#_t cb_local = { NULL, NULL, 0 }; + #name#_t *cb = NULL; + PyTupleObject *capi_arglist = NULL; + PyObject *capi_return = NULL; + PyObject *capi_tmp = NULL; + PyObject *capi_arglist_list = NULL; + int capi_j,capi_i = 0; + int capi_longjmp_ok = 1; +#decl# +#ifdef F2PY_REPORT_ATEXIT +f2py_cb_start_clock(); +#endif + cb = get_active_#name#(); + if (cb == NULL) { + capi_longjmp_ok = 0; + cb = &cb_local; + } + capi_arglist = cb->args_capi; + CFUNCSMESS(\"cb:Call-back function #name# (maxnofargs=#maxnofargs#(-#nofoptargs#))\\n\"); + CFUNCSMESSPY(\"cb:#name#_capi=\",cb->capi); + if (cb->capi==NULL) { + capi_longjmp_ok = 0; + cb->capi = PyObject_GetAttrString(#modulename#_module,\"#argname#\"); + CFUNCSMESSPY(\"cb:#name#_capi=\",cb->capi); + } + if (cb->capi==NULL) { + PyErr_SetString(#modulename#_error,\"cb: Callback #argname# not defined (as an argument or module #modulename# attribute).\\n\"); + goto capi_fail; + } + if (F2PyCapsule_Check(cb->capi)) { + #name#_typedef #name#_cptr; + #name#_cptr = F2PyCapsule_AsVoidPtr(cb->capi); + #returncptr#(*#name#_cptr)(#optargs_nm##args_nm##strarglens_nm#); + #return# + } + if (capi_arglist==NULL) { + capi_longjmp_ok = 0; + capi_tmp = PyObject_GetAttrString(#modulename#_module,\"#argname#_extra_args\"); + if (capi_tmp) { + capi_arglist = (PyTupleObject *)PySequence_Tuple(capi_tmp); + Py_DECREF(capi_tmp); + if (capi_arglist==NULL) { + PyErr_SetString(#modulename#_error,\"Failed to convert #modulename#.#argname#_extra_args to tuple.\\n\"); + goto capi_fail; + } + } else { + PyErr_Clear(); + capi_arglist = (PyTupleObject *)Py_BuildValue(\"()\"); + } + } + if (capi_arglist == NULL) { + PyErr_SetString(#modulename#_error,\"Callback #argname# argument list is not set.\\n\"); + goto capi_fail; + } +#setdims# +#ifdef PYPY_VERSION +#define CAPI_ARGLIST_SETITEM(idx, value) PyList_SetItem((PyObject *)capi_arglist_list, idx, value) + capi_arglist_list = PySequence_List((PyObject *)capi_arglist); + if (capi_arglist_list == NULL) goto capi_fail; +#else +#define CAPI_ARGLIST_SETITEM(idx, value) PyTuple_SetItem((PyObject *)capi_arglist, idx, value) +#endif +#pyobjfrom# +#undef CAPI_ARGLIST_SETITEM +#ifdef PYPY_VERSION + CFUNCSMESSPY(\"cb:capi_arglist=\",capi_arglist_list); +#else + CFUNCSMESSPY(\"cb:capi_arglist=\",capi_arglist); +#endif + CFUNCSMESS(\"cb:Call-back calling Python function #argname#.\\n\"); +#ifdef F2PY_REPORT_ATEXIT +f2py_cb_start_call_clock(); +#endif +#ifdef PYPY_VERSION + capi_return = PyObject_CallObject(cb->capi,(PyObject *)capi_arglist_list); + Py_DECREF(capi_arglist_list); + capi_arglist_list = NULL; +#else + capi_return = PyObject_CallObject(cb->capi,(PyObject *)capi_arglist); +#endif +#ifdef F2PY_REPORT_ATEXIT +f2py_cb_stop_call_clock(); +#endif + CFUNCSMESSPY(\"cb:capi_return=\",capi_return); + if (capi_return == NULL) { + fprintf(stderr,\"capi_return is NULL\\n\"); + goto capi_fail; + } + if (capi_return == Py_None) { + Py_DECREF(capi_return); + capi_return = Py_BuildValue(\"()\"); + } + else if (!PyTuple_Check(capi_return)) { + capi_return = Py_BuildValue(\"(N)\",capi_return); + } + capi_j = PyTuple_Size(capi_return); + capi_i = 0; +#frompyobj# + CFUNCSMESS(\"cb:#name#:successful\\n\"); + Py_DECREF(capi_return); +#ifdef F2PY_REPORT_ATEXIT +f2py_cb_stop_clock(); +#endif + goto capi_return_pt; +capi_fail: + fprintf(stderr,\"Call-back #name# failed.\\n\"); + Py_XDECREF(capi_return); + Py_XDECREF(capi_arglist_list); + if (capi_longjmp_ok) { + longjmp(cb->jmpbuf,-1); + } +capi_return_pt: + ; +#return# +} +#endtitle# +""", + 'need': ['setjmp.h', 'CFUNCSMESS', 'F2PY_THREAD_LOCAL_DECL'], + 'maxnofargs': '#maxnofargs#', + 'nofoptargs': '#nofoptargs#', + 'docstr': """\ + def #argname#(#docsignature#): return #docreturn#\\n\\ +#docstrsigns#""", + 'latexdocstr': """ +{{}\\verb@def #argname#(#latexdocsignature#): return #docreturn#@{}} +#routnote# + +#latexdocstrsigns#""", + 'docstrshort': 'def #argname#(#docsignature#): return #docreturn#' +} +cb_rout_rules = [ + { # Init + 'separatorsfor': {'decl': '\n', + 'args': ',', 'optargs': '', 'pyobjfrom': '\n', 'freemem': '\n', + 'args_td': ',', 'optargs_td': '', + 'args_nm': ',', 'optargs_nm': '', + 'frompyobj': '\n', 'setdims': '\n', + 'docstrsigns': '\\n"\n"', + 'latexdocstrsigns': '\n', + 'latexdocstrreq': '\n', 'latexdocstropt': '\n', + 'latexdocstrout': '\n', 'latexdocstrcbs': '\n', + }, + 'decl': '/*decl*/', 'pyobjfrom': '/*pyobjfrom*/', 'frompyobj': '/*frompyobj*/', + 'args': [], 'optargs': '', 'return': '', 'strarglens': '', 'freemem': '/*freemem*/', + 'args_td': [], 'optargs_td': '', 'strarglens_td': '', + 'args_nm': [], 'optargs_nm': '', 'strarglens_nm': '', + 'noargs': '', + 'setdims': '/*setdims*/', + 'docstrsigns': '', 'latexdocstrsigns': '', + 'docstrreq': ' Required arguments:', + 'docstropt': ' Optional arguments:', + 'docstrout': ' Return objects:', + 'docstrcbs': ' Call-back functions:', + 'docreturn': '', 'docsign': '', 'docsignopt': '', + 'latexdocstrreq': '\\noindent Required arguments:', + 'latexdocstropt': '\\noindent Optional arguments:', + 'latexdocstrout': '\\noindent Return objects:', + 'latexdocstrcbs': '\\noindent Call-back functions:', + 'routnote': {hasnote: '--- #note#', l_not(hasnote): ''}, + }, { # Function + 'decl': ' #ctype# return_value = 0;', + 'frompyobj': [ + {debugcapi: ' CFUNCSMESS("cb:Getting return_value->");'}, + '''\ + if (capi_j>capi_i) { + GETSCALARFROMPYTUPLE(capi_return,capi_i++,&return_value,#ctype#, + "#ctype#_from_pyobj failed in converting return_value of" + " call-back function #name# to C #ctype#\\n"); + } else { + fprintf(stderr,"Warning: call-back function #name# did not provide" + " return value (index=%d, type=#ctype#)\\n",capi_i); + }''', + {debugcapi: + ' fprintf(stderr,"#showvalueformat#.\\n",return_value);'} + ], + 'need': ['#ctype#_from_pyobj', {debugcapi: 'CFUNCSMESS'}, 'GETSCALARFROMPYTUPLE'], + 'return': ' return return_value;', + '_check': l_and(isfunction, l_not(isstringfunction), l_not(iscomplexfunction)) + }, + { # String function + 'pyobjfrom': {debugcapi: ' fprintf(stderr,"debug-capi:cb:#name#:%d:\\n",return_value_len);'}, + 'args': '#ctype# return_value,int return_value_len', + 'args_nm': 'return_value,&return_value_len', + 'args_td': '#ctype# ,int', + 'frompyobj': [ + {debugcapi: ' CFUNCSMESS("cb:Getting return_value->\\"");'}, + """\ + if (capi_j>capi_i) { + GETSTRFROMPYTUPLE(capi_return,capi_i++,return_value,return_value_len); + } else { + fprintf(stderr,"Warning: call-back function #name# did not provide" + " return value (index=%d, type=#ctype#)\\n",capi_i); + }""", + {debugcapi: + ' fprintf(stderr,"#showvalueformat#\\".\\n",return_value);'} + ], + 'need': ['#ctype#_from_pyobj', {debugcapi: 'CFUNCSMESS'}, + 'string.h', 'GETSTRFROMPYTUPLE'], + 'return': 'return;', + '_check': isstringfunction + }, + { # Complex function + 'optargs': """ +#ifndef F2PY_CB_RETURNCOMPLEX +#ctype# *return_value +#endif +""", + 'optargs_nm': """ +#ifndef F2PY_CB_RETURNCOMPLEX +return_value +#endif +""", + 'optargs_td': """ +#ifndef F2PY_CB_RETURNCOMPLEX +#ctype# * +#endif +""", + 'decl': """ +#ifdef F2PY_CB_RETURNCOMPLEX + #ctype# return_value = {0, 0}; +#endif +""", + 'frompyobj': [ + {debugcapi: ' CFUNCSMESS("cb:Getting return_value->");'}, + """\ + if (capi_j>capi_i) { +#ifdef F2PY_CB_RETURNCOMPLEX + GETSCALARFROMPYTUPLE(capi_return,capi_i++,&return_value,#ctype#, + \"#ctype#_from_pyobj failed in converting return_value of call-back\" + \" function #name# to C #ctype#\\n\"); +#else + GETSCALARFROMPYTUPLE(capi_return,capi_i++,return_value,#ctype#, + \"#ctype#_from_pyobj failed in converting return_value of call-back\" + \" function #name# to C #ctype#\\n\"); +#endif + } else { + fprintf(stderr, + \"Warning: call-back function #name# did not provide\" + \" return value (index=%d, type=#ctype#)\\n\",capi_i); + }""", + {debugcapi: """\ +#ifdef F2PY_CB_RETURNCOMPLEX + fprintf(stderr,\"#showvalueformat#.\\n\",(return_value).r,(return_value).i); +#else + fprintf(stderr,\"#showvalueformat#.\\n\",(*return_value).r,(*return_value).i); +#endif +"""} + ], + 'return': """ +#ifdef F2PY_CB_RETURNCOMPLEX + return return_value; +#else + return; +#endif +""", + 'need': ['#ctype#_from_pyobj', {debugcapi: 'CFUNCSMESS'}, + 'string.h', 'GETSCALARFROMPYTUPLE', '#ctype#'], + '_check': iscomplexfunction + }, + {'docstrout': ' #pydocsignout#', + 'latexdocstrout': ['\\item[]{{}\\verb@#pydocsignout#@{}}', + {hasnote: '--- #note#'}], + 'docreturn': '#rname#,', + '_check': isfunction}, + {'_check': issubroutine, 'return': 'return;'} +] + +cb_arg_rules = [ + { # Doc + 'docstropt': {l_and(isoptional, isintent_nothide): ' #pydocsign#'}, + 'docstrreq': {l_and(isrequired, isintent_nothide): ' #pydocsign#'}, + 'docstrout': {isintent_out: ' #pydocsignout#'}, + 'latexdocstropt': {l_and(isoptional, isintent_nothide): ['\\item[]{{}\\verb@#pydocsign#@{}}', + {hasnote: '--- #note#'}]}, + 'latexdocstrreq': {l_and(isrequired, isintent_nothide): ['\\item[]{{}\\verb@#pydocsign#@{}}', + {hasnote: '--- #note#'}]}, + 'latexdocstrout': {isintent_out: ['\\item[]{{}\\verb@#pydocsignout#@{}}', + {l_and(hasnote, isintent_hide): '--- #note#', + l_and(hasnote, isintent_nothide): '--- See above.'}]}, + 'docsign': {l_and(isrequired, isintent_nothide): '#varname#,'}, + 'docsignopt': {l_and(isoptional, isintent_nothide): '#varname#,'}, + 'depend': '' + }, + { + 'args': { + l_and(isscalar, isintent_c): '#ctype# #varname_i#', + l_and(isscalar, l_not(isintent_c)): '#ctype# *#varname_i#_cb_capi', + isarray: '#ctype# *#varname_i#', + isstring: '#ctype# #varname_i#' + }, + 'args_nm': { + l_and(isscalar, isintent_c): '#varname_i#', + l_and(isscalar, l_not(isintent_c)): '#varname_i#_cb_capi', + isarray: '#varname_i#', + isstring: '#varname_i#' + }, + 'args_td': { + l_and(isscalar, isintent_c): '#ctype#', + l_and(isscalar, l_not(isintent_c)): '#ctype# *', + isarray: '#ctype# *', + isstring: '#ctype#' + }, + 'need': {l_or(isscalar, isarray, isstring): '#ctype#'}, + # untested with multiple args + 'strarglens': {isstring: ',int #varname_i#_cb_len'}, + 'strarglens_td': {isstring: ',int'}, # untested with multiple args + # untested with multiple args + 'strarglens_nm': {isstring: ',#varname_i#_cb_len'}, + }, + { # Scalars + 'decl': {l_not(isintent_c): ' #ctype# #varname_i#=(*#varname_i#_cb_capi);'}, + 'error': {l_and(isintent_c, isintent_out, + throw_error('intent(c,out) is forbidden for callback scalar arguments')): + ''}, + 'frompyobj': [{debugcapi: ' CFUNCSMESS("cb:Getting #varname#->");'}, + {isintent_out: + ' if (capi_j>capi_i)\n GETSCALARFROMPYTUPLE(capi_return,capi_i++,#varname_i#_cb_capi,#ctype#,"#ctype#_from_pyobj failed in converting argument #varname# of call-back function #name# to C #ctype#\\n");'}, + {l_and(debugcapi, l_and(l_not(iscomplex), isintent_c)): + ' fprintf(stderr,"#showvalueformat#.\\n",#varname_i#);'}, + {l_and(debugcapi, l_and(l_not(iscomplex), l_not(isintent_c))): + ' fprintf(stderr,"#showvalueformat#.\\n",*#varname_i#_cb_capi);'}, + {l_and(debugcapi, l_and(iscomplex, isintent_c)): + ' fprintf(stderr,"#showvalueformat#.\\n",(#varname_i#).r,(#varname_i#).i);'}, + {l_and(debugcapi, l_and(iscomplex, l_not(isintent_c))): + ' fprintf(stderr,"#showvalueformat#.\\n",(*#varname_i#_cb_capi).r,(*#varname_i#_cb_capi).i);'}, + ], + 'need': [{isintent_out: ['#ctype#_from_pyobj', 'GETSCALARFROMPYTUPLE']}, + {debugcapi: 'CFUNCSMESS'}], + '_check': isscalar + }, { + 'pyobjfrom': [{isintent_in: """\ + if (cb->nofargs>capi_i) + if (CAPI_ARGLIST_SETITEM(capi_i++,pyobj_from_#ctype#1(#varname_i#))) + goto capi_fail;"""}, + {isintent_inout: """\ + if (cb->nofargs>capi_i) + if (CAPI_ARGLIST_SETITEM(capi_i++,pyarr_from_p_#ctype#1(#varname_i#_cb_capi))) + goto capi_fail;"""}], + 'need': [{isintent_in: 'pyobj_from_#ctype#1'}, + {isintent_inout: 'pyarr_from_p_#ctype#1'}, + {iscomplex: '#ctype#'}], + '_check': l_and(isscalar, isintent_nothide), + '_optional': '' + }, { # String + 'frompyobj': [{debugcapi: ' CFUNCSMESS("cb:Getting #varname#->\\"");'}, + """ if (capi_j>capi_i) + GETSTRFROMPYTUPLE(capi_return,capi_i++,#varname_i#,#varname_i#_cb_len);""", + {debugcapi: + ' fprintf(stderr,"#showvalueformat#\\":%d:.\\n",#varname_i#,#varname_i#_cb_len);'}, + ], + 'need': ['#ctype#', 'GETSTRFROMPYTUPLE', + {debugcapi: 'CFUNCSMESS'}, 'string.h'], + '_check': l_and(isstring, isintent_out) + }, { + 'pyobjfrom': [ + {debugcapi: + (' fprintf(stderr,"debug-capi:cb:#varname#=#showvalueformat#:' + '%d:\\n",#varname_i#,#varname_i#_cb_len);')}, + {isintent_in: """\ + if (cb->nofargs>capi_i) + if (CAPI_ARGLIST_SETITEM(capi_i++,pyobj_from_#ctype#1size(#varname_i#,#varname_i#_cb_len))) + goto capi_fail;"""}, + {isintent_inout: """\ + if (cb->nofargs>capi_i) { + int #varname_i#_cb_dims[] = {#varname_i#_cb_len}; + if (CAPI_ARGLIST_SETITEM(capi_i++,pyarr_from_p_#ctype#1(#varname_i#,#varname_i#_cb_dims))) + goto capi_fail; + }"""}], + 'need': [{isintent_in: 'pyobj_from_#ctype#1size'}, + {isintent_inout: 'pyarr_from_p_#ctype#1'}], + '_check': l_and(isstring, isintent_nothide), + '_optional': '' + }, + # Array ... + { + 'decl': ' npy_intp #varname_i#_Dims[#rank#] = {#rank*[-1]#};', + 'setdims': ' #cbsetdims#;', + '_check': isarray, + '_depend': '' + }, + { + 'pyobjfrom': [{debugcapi: ' fprintf(stderr,"debug-capi:cb:#varname#\\n");'}, + {isintent_c: """\ + if (cb->nofargs>capi_i) { + /* tmp_arr will be inserted to capi_arglist_list that will be + destroyed when leaving callback function wrapper together + with tmp_arr. */ + PyArrayObject *tmp_arr = (PyArrayObject *)PyArray_New(&PyArray_Type, + #rank#,#varname_i#_Dims,#atype#,NULL,(char*)#varname_i#,#elsize#, + NPY_ARRAY_CARRAY,NULL); +""", + l_not(isintent_c): """\ + if (cb->nofargs>capi_i) { + /* tmp_arr will be inserted to capi_arglist_list that will be + destroyed when leaving callback function wrapper together + with tmp_arr. */ + PyArrayObject *tmp_arr = (PyArrayObject *)PyArray_New(&PyArray_Type, + #rank#,#varname_i#_Dims,#atype#,NULL,(char*)#varname_i#,#elsize#, + NPY_ARRAY_FARRAY,NULL); +""", + }, + """ + if (tmp_arr==NULL) + goto capi_fail; + if (CAPI_ARGLIST_SETITEM(capi_i++,(PyObject *)tmp_arr)) + goto capi_fail; +}"""], + '_check': l_and(isarray, isintent_nothide, l_or(isintent_in, isintent_inout)), + '_optional': '', + }, { + 'frompyobj': [{debugcapi: ' CFUNCSMESS("cb:Getting #varname#->");'}, + """ if (capi_j>capi_i) { + PyArrayObject *rv_cb_arr = NULL; + if ((capi_tmp = PyTuple_GetItem(capi_return,capi_i++))==NULL) goto capi_fail; + rv_cb_arr = array_from_pyobj(#atype#,#varname_i#_Dims,#rank#,F2PY_INTENT_IN""", + {isintent_c: '|F2PY_INTENT_C'}, + """,capi_tmp); + if (rv_cb_arr == NULL) { + fprintf(stderr,\"rv_cb_arr is NULL\\n\"); + goto capi_fail; + } + MEMCOPY(#varname_i#,PyArray_DATA(rv_cb_arr),PyArray_NBYTES(rv_cb_arr)); + if (capi_tmp != (PyObject *)rv_cb_arr) { + Py_DECREF(rv_cb_arr); + } + }""", + {debugcapi: ' fprintf(stderr,"<-.\\n");'}, + ], + 'need': ['MEMCOPY', {iscomplexarray: '#ctype#'}], + '_check': l_and(isarray, isintent_out) + }, { + 'docreturn': '#varname#,', + '_check': isintent_out + } +] + +################## Build call-back module ############# +cb_map = {} + + +def buildcallbacks(m): + cb_map[m['name']] = [] + for bi in m['body']: + if bi['block'] == 'interface': + for b in bi['body']: + if b: + buildcallback(b, m['name']) + else: + errmess(f"warning: empty body for {m['name']}\n") + + +def buildcallback(rout, um): + from . import capi_maps + + outmess(f" Constructing call-back function \"cb_{rout['name']}_in_{um}\"\n") + args, depargs = getargs(rout) + capi_maps.depargs = depargs + var = rout['vars'] + vrd = capi_maps.cb_routsign2map(rout, um) + rd = dictappend({}, vrd) + cb_map[um].append([rout['name'], rd['name']]) + for r in cb_rout_rules: + if ('_check' in r and r['_check'](rout)) or ('_check' not in r): + ar = applyrules(r, vrd, rout) + rd = dictappend(rd, ar) + savevrd = {} + for i, a in enumerate(args): + vrd = capi_maps.cb_sign2map(a, var[a], index=i) + savevrd[a] = vrd + for r in cb_arg_rules: + if '_depend' in r: + continue + if '_optional' in r and isoptional(var[a]): + continue + if ('_check' in r and r['_check'](var[a])) or ('_check' not in r): + ar = applyrules(r, vrd, var[a]) + rd = dictappend(rd, ar) + if '_break' in r: + break + for a in args: + vrd = savevrd[a] + for r in cb_arg_rules: + if '_depend' in r: + continue + if ('_optional' not in r) or ('_optional' in r and isrequired(var[a])): + continue + if ('_check' in r and r['_check'](var[a])) or ('_check' not in r): + ar = applyrules(r, vrd, var[a]) + rd = dictappend(rd, ar) + if '_break' in r: + break + for a in depargs: + vrd = savevrd[a] + for r in cb_arg_rules: + if '_depend' not in r: + continue + if '_optional' in r: + continue + if ('_check' in r and r['_check'](var[a])) or ('_check' not in r): + ar = applyrules(r, vrd, var[a]) + rd = dictappend(rd, ar) + if '_break' in r: + break + if 'args' in rd and 'optargs' in rd: + if isinstance(rd['optargs'], list): + rd['optargs'] = rd['optargs'] + [""" +#ifndef F2PY_CB_RETURNCOMPLEX +, +#endif +"""] + rd['optargs_nm'] = rd['optargs_nm'] + [""" +#ifndef F2PY_CB_RETURNCOMPLEX +, +#endif +"""] + rd['optargs_td'] = rd['optargs_td'] + [""" +#ifndef F2PY_CB_RETURNCOMPLEX +, +#endif +"""] + if isinstance(rd['docreturn'], list): + rd['docreturn'] = stripcomma( + replace('#docreturn#', {'docreturn': rd['docreturn']})) + optargs = stripcomma(replace('#docsignopt#', + {'docsignopt': rd['docsignopt']} + )) + if optargs == '': + rd['docsignature'] = stripcomma( + replace('#docsign#', {'docsign': rd['docsign']})) + else: + rd['docsignature'] = replace('#docsign#[#docsignopt#]', + {'docsign': rd['docsign'], + 'docsignopt': optargs, + }) + rd['latexdocsignature'] = rd['docsignature'].replace('_', '\\_') + rd['latexdocsignature'] = rd['latexdocsignature'].replace(',', ', ') + rd['docstrsigns'] = [] + rd['latexdocstrsigns'] = [] + for k in ['docstrreq', 'docstropt', 'docstrout', 'docstrcbs']: + if k in rd and isinstance(rd[k], list): + rd['docstrsigns'] = rd['docstrsigns'] + rd[k] + k = 'latex' + k + if k in rd and isinstance(rd[k], list): + rd['latexdocstrsigns'] = rd['latexdocstrsigns'] + rd[k][0:1] +\ + ['\\begin{description}'] + rd[k][1:] +\ + ['\\end{description}'] + if 'args' not in rd: + rd['args'] = '' + rd['args_td'] = '' + rd['args_nm'] = '' + if not (rd.get('args') or rd.get('optargs') or rd.get('strarglens')): + rd['noargs'] = 'void' + + ar = applyrules(cb_routine_rules, rd) + cfuncs.callbacks[rd['name']] = ar['body'] + if isinstance(ar['need'], str): + ar['need'] = [ar['need']] + + if 'need' in rd: + for t in cfuncs.typedefs.keys(): + if t in rd['need']: + ar['need'].append(t) + + cfuncs.typedefs_generated[rd['name'] + '_typedef'] = ar['cbtypedefs'] + ar['need'].append(rd['name'] + '_typedef') + cfuncs.needs[rd['name']] = ar['need'] + + capi_maps.lcb2_map[rd['name']] = {'maxnofargs': ar['maxnofargs'], + 'nofoptargs': ar['nofoptargs'], + 'docstr': ar['docstr'], + 'latexdocstr': ar['latexdocstr'], + 'argname': rd['argname'] + } + outmess(f" {ar['docstrshort']}\n") +################## Build call-back function ############# diff --git a/python/user_packages/Python313/site-packages/numpy/f2py/cb_rules.pyi b/python/user_packages/Python313/site-packages/numpy/f2py/cb_rules.pyi new file mode 100644 index 0000000000000000000000000000000000000000..67d3fd9b4e1b18cd5890da6fbfe51300c0806344 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/f2py/cb_rules.pyi @@ -0,0 +1,17 @@ +from collections.abc import Mapping +from typing import Any, Final + +from .__version__ import version + +## + +f2py_version: Final = version + +cb_routine_rules: Final[dict[str, str | list[str]]] = ... +cb_rout_rules: Final[list[dict[str, str | Any]]] = ... +cb_arg_rules: Final[list[dict[str, str | Any]]] = ... + +cb_map: Final[dict[str, list[list[str]]]] = ... + +def buildcallbacks(m: Mapping[str, object]) -> None: ... +def buildcallback(rout: Mapping[str, object], um: Mapping[str, object]) -> None: ... diff --git a/python/user_packages/Python313/site-packages/numpy/f2py/cfuncs.py b/python/user_packages/Python313/site-packages/numpy/f2py/cfuncs.py new file mode 100644 index 0000000000000000000000000000000000000000..c33a0d9ecbd825fd3bc4bffe64fc14c78e6f2343 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/f2py/cfuncs.py @@ -0,0 +1,1563 @@ +""" +C declarations, CPP macros, and C functions for f2py2e. +Only required declarations/macros/functions will be used. + +Copyright 1999 -- 2011 Pearu Peterson all rights reserved. +Copyright 2011 -- present NumPy Developers. +Permission to use, modify, and distribute this software is given under the +terms of the NumPy License. + +NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. +""" +import copy +import sys + +from . import __version__ + +f2py_version = __version__.version + + +def errmess(s: str) -> None: + """ + Write an error message to stderr. + + This indirection is needed because sys.stderr might not always be available (see #26862). + """ + if sys.stderr is not None: + sys.stderr.write(s) + +##################### Definitions ################## + + +outneeds = {'includes0': [], 'includes': [], 'typedefs': [], 'typedefs_generated': [], + 'userincludes': [], + 'cppmacros': [], 'cfuncs': [], 'callbacks': [], 'f90modhooks': [], + 'commonhooks': []} +needs = {} +includes0 = {'includes0': '/*need_includes0*/'} +includes = {'includes': '/*need_includes*/'} +userincludes = {'userincludes': '/*need_userincludes*/'} +typedefs = {'typedefs': '/*need_typedefs*/'} +typedefs_generated = {'typedefs_generated': '/*need_typedefs_generated*/'} +cppmacros = {'cppmacros': '/*need_cppmacros*/'} +cfuncs = {'cfuncs': '/*need_cfuncs*/'} +callbacks = {'callbacks': '/*need_callbacks*/'} +f90modhooks = {'f90modhooks': '/*need_f90modhooks*/', + 'initf90modhooksstatic': '/*initf90modhooksstatic*/', + 'initf90modhooksdynamic': '/*initf90modhooksdynamic*/', + } +commonhooks = {'commonhooks': '/*need_commonhooks*/', + 'initcommonhooks': '/*need_initcommonhooks*/', + } + +############ Includes ################### + +includes0['math.h'] = '#include ' +includes0['string.h'] = '#include ' +includes0['setjmp.h'] = '#include ' + +includes['arrayobject.h'] = '''#define PY_ARRAY_UNIQUE_SYMBOL PyArray_API +#include "arrayobject.h"''' +includes['npy_math.h'] = '#include "numpy/npy_math.h"' + +includes['arrayobject.h'] = '#include "fortranobject.h"' +includes['stdarg.h'] = '#include ' + +############# Type definitions ############### + +typedefs['unsigned_char'] = 'typedef unsigned char unsigned_char;' +typedefs['unsigned_short'] = 'typedef unsigned short unsigned_short;' +typedefs['unsigned_long'] = 'typedef unsigned long unsigned_long;' +typedefs['signed_char'] = 'typedef signed char signed_char;' +typedefs['long_long'] = """ +#if defined(NPY_OS_WIN32) +typedef __int64 long_long; +#else +typedef long long long_long; +typedef unsigned long long unsigned_long_long; +#endif +""" +typedefs['unsigned_long_long'] = """ +#if defined(NPY_OS_WIN32) +typedef __uint64 long_long; +#else +typedef unsigned long long unsigned_long_long; +#endif +""" +typedefs['long_double'] = """ +#ifndef _LONG_DOUBLE +typedef long double long_double; +#endif +""" +typedefs[ + 'complex_long_double'] = 'typedef struct {long double r,i;} complex_long_double;' +typedefs['complex_float'] = 'typedef struct {float r,i;} complex_float;' +typedefs['complex_double'] = 'typedef struct {double r,i;} complex_double;' +typedefs['string'] = """typedef char * string;""" +typedefs['character'] = """typedef char character;""" + + +############### CPP macros #################### +cppmacros['CFUNCSMESS'] = """ +#ifdef DEBUGCFUNCS +#define CFUNCSMESS(mess) fprintf(stderr,\"debug-capi:\"mess); +#define CFUNCSMESSPY(mess,obj) CFUNCSMESS(mess) \\ + PyObject_Print((PyObject *)obj,stderr,Py_PRINT_RAW);\\ + fprintf(stderr,\"\\n\"); +#else +#define CFUNCSMESS(mess) +#define CFUNCSMESSPY(mess,obj) +#endif +""" +cppmacros['F_FUNC'] = """ +#if defined(PREPEND_FORTRAN) +#if defined(NO_APPEND_FORTRAN) +#if defined(UPPERCASE_FORTRAN) +#define F_FUNC(f,F) _##F +#else +#define F_FUNC(f,F) _##f +#endif +#else +#if defined(UPPERCASE_FORTRAN) +#define F_FUNC(f,F) _##F##_ +#else +#define F_FUNC(f,F) _##f##_ +#endif +#endif +#else +#if defined(NO_APPEND_FORTRAN) +#if defined(UPPERCASE_FORTRAN) +#define F_FUNC(f,F) F +#else +#define F_FUNC(f,F) f +#endif +#else +#if defined(UPPERCASE_FORTRAN) +#define F_FUNC(f,F) F##_ +#else +#define F_FUNC(f,F) f##_ +#endif +#endif +#endif +#if defined(UNDERSCORE_G77) +#define F_FUNC_US(f,F) F_FUNC(f##_,F##_) +#else +#define F_FUNC_US(f,F) F_FUNC(f,F) +#endif +""" +cppmacros['F_WRAPPEDFUNC'] = """ +#if defined(PREPEND_FORTRAN) +#if defined(NO_APPEND_FORTRAN) +#if defined(UPPERCASE_FORTRAN) +#define F_WRAPPEDFUNC(f,F) _F2PYWRAP##F +#else +#define F_WRAPPEDFUNC(f,F) _f2pywrap##f +#endif +#else +#if defined(UPPERCASE_FORTRAN) +#define F_WRAPPEDFUNC(f,F) _F2PYWRAP##F##_ +#else +#define F_WRAPPEDFUNC(f,F) _f2pywrap##f##_ +#endif +#endif +#else +#if defined(NO_APPEND_FORTRAN) +#if defined(UPPERCASE_FORTRAN) +#define F_WRAPPEDFUNC(f,F) F2PYWRAP##F +#else +#define F_WRAPPEDFUNC(f,F) f2pywrap##f +#endif +#else +#if defined(UPPERCASE_FORTRAN) +#define F_WRAPPEDFUNC(f,F) F2PYWRAP##F##_ +#else +#define F_WRAPPEDFUNC(f,F) f2pywrap##f##_ +#endif +#endif +#endif +#if defined(UNDERSCORE_G77) +#define F_WRAPPEDFUNC_US(f,F) F_WRAPPEDFUNC(f##_,F##_) +#else +#define F_WRAPPEDFUNC_US(f,F) F_WRAPPEDFUNC(f,F) +#endif +""" +cppmacros['F_MODFUNC'] = """ +#if defined(F90MOD2CCONV1) /*E.g. Compaq Fortran */ +#if defined(NO_APPEND_FORTRAN) +#define F_MODFUNCNAME(m,f) $ ## m ## $ ## f +#else +#define F_MODFUNCNAME(m,f) $ ## m ## $ ## f ## _ +#endif +#endif + +#if defined(F90MOD2CCONV2) /*E.g. IBM XL Fortran, not tested though */ +#if defined(NO_APPEND_FORTRAN) +#define F_MODFUNCNAME(m,f) __ ## m ## _MOD_ ## f +#else +#define F_MODFUNCNAME(m,f) __ ## m ## _MOD_ ## f ## _ +#endif +#endif + +#if defined(F90MOD2CCONV3) /*E.g. MIPSPro Compilers */ +#if defined(NO_APPEND_FORTRAN) +#define F_MODFUNCNAME(m,f) f ## .in. ## m +#else +#define F_MODFUNCNAME(m,f) f ## .in. ## m ## _ +#endif +#endif +/* +#if defined(UPPERCASE_FORTRAN) +#define F_MODFUNC(m,M,f,F) F_MODFUNCNAME(M,F) +#else +#define F_MODFUNC(m,M,f,F) F_MODFUNCNAME(m,f) +#endif +*/ + +#define F_MODFUNC(m,f) (*(f2pymodstruct##m##.##f)) +""" +cppmacros['SWAPUNSAFE'] = """ +#define SWAP(a,b) (size_t)(a) = ((size_t)(a) ^ (size_t)(b));\\ + (size_t)(b) = ((size_t)(a) ^ (size_t)(b));\\ + (size_t)(a) = ((size_t)(a) ^ (size_t)(b)) +""" +cppmacros['SWAP'] = """ +#define SWAP(a,b,t) {\\ + t *c;\\ + c = a;\\ + a = b;\\ + b = c;} +""" +# cppmacros['ISCONTIGUOUS']='#define ISCONTIGUOUS(m) (PyArray_FLAGS(m) & +# NPY_ARRAY_C_CONTIGUOUS)' +cppmacros['PRINTPYOBJERR'] = """ +#define PRINTPYOBJERR(obj)\\ + fprintf(stderr,\"#modulename#.error is related to \");\\ + PyObject_Print((PyObject *)obj,stderr,Py_PRINT_RAW);\\ + fprintf(stderr,\"\\n\"); +""" +cppmacros['MINMAX'] = """ +#ifndef max +#define max(a,b) ((a > b) ? (a) : (b)) +#endif +#ifndef min +#define min(a,b) ((a < b) ? (a) : (b)) +#endif +#ifndef MAX +#define MAX(a,b) ((a > b) ? (a) : (b)) +#endif +#ifndef MIN +#define MIN(a,b) ((a < b) ? (a) : (b)) +#endif +""" +cppmacros['len..'] = """ +/* See fortranobject.h for definitions. The macros here are provided for BC. */ +#define rank f2py_rank +#define shape f2py_shape +#define fshape f2py_shape +#define len f2py_len +#define flen f2py_flen +#define slen f2py_slen +#define size f2py_size +""" +cppmacros['pyobj_from_char1'] = r""" +#define pyobj_from_char1(v) (PyLong_FromLong(v)) +""" +cppmacros['pyobj_from_short1'] = r""" +#define pyobj_from_short1(v) (PyLong_FromLong(v)) +""" +needs['pyobj_from_int1'] = ['signed_char'] +cppmacros['pyobj_from_int1'] = r""" +#define pyobj_from_int1(v) (PyLong_FromLong(v)) +""" +cppmacros['pyobj_from_long1'] = r""" +#define pyobj_from_long1(v) (PyLong_FromLong(v)) +""" +needs['pyobj_from_long_long1'] = ['long_long'] +cppmacros['pyobj_from_long_long1'] = """ +#ifdef HAVE_LONG_LONG +#define pyobj_from_long_long1(v) (PyLong_FromLongLong(v)) +#else +#warning HAVE_LONG_LONG is not available. Redefining pyobj_from_long_long. +#define pyobj_from_long_long1(v) (PyLong_FromLong(v)) +#endif +""" +needs['pyobj_from_long_double1'] = ['long_double'] +cppmacros['pyobj_from_long_double1'] = """ +#define pyobj_from_long_double1(v) (PyFloat_FromDouble(v))""" +cppmacros['pyobj_from_double1'] = """ +#define pyobj_from_double1(v) (PyFloat_FromDouble(v))""" +cppmacros['pyobj_from_float1'] = """ +#define pyobj_from_float1(v) (PyFloat_FromDouble(v))""" +needs['pyobj_from_complex_long_double1'] = ['complex_long_double'] +cppmacros['pyobj_from_complex_long_double1'] = """ +#define pyobj_from_complex_long_double1(v) (PyComplex_FromDoubles(v.r,v.i))""" +needs['pyobj_from_complex_double1'] = ['complex_double'] +cppmacros['pyobj_from_complex_double1'] = """ +#define pyobj_from_complex_double1(v) (PyComplex_FromDoubles(v.r,v.i))""" +needs['pyobj_from_complex_float1'] = ['complex_float'] +cppmacros['pyobj_from_complex_float1'] = """ +#define pyobj_from_complex_float1(v) (PyComplex_FromDoubles(v.r,v.i))""" +needs['pyobj_from_string1'] = ['string'] +cppmacros['pyobj_from_string1'] = """ +#define pyobj_from_string1(v) (PyUnicode_FromString((char *)v))""" +needs['pyobj_from_string1size'] = ['string'] +cppmacros['pyobj_from_string1size'] = """ +#define pyobj_from_string1size(v,len) (PyUnicode_FromStringAndSize((char *)v, len))""" +needs['TRYPYARRAYTEMPLATE'] = ['PRINTPYOBJERR'] +cppmacros['TRYPYARRAYTEMPLATE'] = """ +/* New SciPy */ +#define TRYPYARRAYTEMPLATECHAR case NPY_STRING: *(char *)(PyArray_DATA(arr))=*v; break; +#define TRYPYARRAYTEMPLATELONG case NPY_LONG: *(long *)(PyArray_DATA(arr))=*v; break; +#define TRYPYARRAYTEMPLATEOBJECT case NPY_OBJECT: PyArray_SETITEM(arr,PyArray_DATA(arr),pyobj_from_ ## ctype ## 1(*v)); break; + +#define TRYPYARRAYTEMPLATE(ctype,typecode) \\ + PyArrayObject *arr = NULL;\\ + if (!obj) return -2;\\ + if (!PyArray_Check(obj)) return -1;\\ + if (!(arr=(PyArrayObject *)obj)) {fprintf(stderr,\"TRYPYARRAYTEMPLATE:\");PRINTPYOBJERR(obj);return 0;}\\ + if (PyArray_DESCR(arr)->type==typecode) {*(ctype *)(PyArray_DATA(arr))=*v; return 1;}\\ + switch (PyArray_TYPE(arr)) {\\ + case NPY_DOUBLE: *(npy_double *)(PyArray_DATA(arr))=*v; break;\\ + case NPY_INT: *(npy_int *)(PyArray_DATA(arr))=*v; break;\\ + case NPY_LONG: *(npy_long *)(PyArray_DATA(arr))=*v; break;\\ + case NPY_FLOAT: *(npy_float *)(PyArray_DATA(arr))=*v; break;\\ + case NPY_CDOUBLE: *(npy_double *)(PyArray_DATA(arr))=*v; break;\\ + case NPY_CFLOAT: *(npy_float *)(PyArray_DATA(arr))=*v; break;\\ + case NPY_BOOL: *(npy_bool *)(PyArray_DATA(arr))=(*v!=0); break;\\ + case NPY_UBYTE: *(npy_ubyte *)(PyArray_DATA(arr))=*v; break;\\ + case NPY_BYTE: *(npy_byte *)(PyArray_DATA(arr))=*v; break;\\ + case NPY_SHORT: *(npy_short *)(PyArray_DATA(arr))=*v; break;\\ + case NPY_USHORT: *(npy_ushort *)(PyArray_DATA(arr))=*v; break;\\ + case NPY_UINT: *(npy_uint *)(PyArray_DATA(arr))=*v; break;\\ + case NPY_ULONG: *(npy_ulong *)(PyArray_DATA(arr))=*v; break;\\ + case NPY_LONGLONG: *(npy_longlong *)(PyArray_DATA(arr))=*v; break;\\ + case NPY_ULONGLONG: *(npy_ulonglong *)(PyArray_DATA(arr))=*v; break;\\ + case NPY_LONGDOUBLE: *(npy_longdouble *)(PyArray_DATA(arr))=*v; break;\\ + case NPY_CLONGDOUBLE: *(npy_longdouble *)(PyArray_DATA(arr))=*v; break;\\ + case NPY_OBJECT: PyArray_SETITEM(arr, PyArray_DATA(arr), pyobj_from_ ## ctype ## 1(*v)); break;\\ + default: return -2;\\ + };\\ + return 1 +""" + +needs['TRYCOMPLEXPYARRAYTEMPLATE'] = ['PRINTPYOBJERR'] +cppmacros['TRYCOMPLEXPYARRAYTEMPLATE'] = """ +#define TRYCOMPLEXPYARRAYTEMPLATEOBJECT case NPY_OBJECT: PyArray_SETITEM(arr, PyArray_DATA(arr), pyobj_from_complex_ ## ctype ## 1((*v))); break; +#define TRYCOMPLEXPYARRAYTEMPLATE(ctype,typecode)\\ + PyArrayObject *arr = NULL;\\ + if (!obj) return -2;\\ + if (!PyArray_Check(obj)) return -1;\\ + if (!(arr=(PyArrayObject *)obj)) {fprintf(stderr,\"TRYCOMPLEXPYARRAYTEMPLATE:\");PRINTPYOBJERR(obj);return 0;}\\ + if (PyArray_DESCR(arr)->type==typecode) {\\ + *(ctype *)(PyArray_DATA(arr))=(*v).r;\\ + *(ctype *)(PyArray_DATA(arr)+sizeof(ctype))=(*v).i;\\ + return 1;\\ + }\\ + switch (PyArray_TYPE(arr)) {\\ + case NPY_CDOUBLE: *(npy_double *)(PyArray_DATA(arr))=(*v).r;\\ + *(npy_double *)(PyArray_DATA(arr)+sizeof(npy_double))=(*v).i;\\ + break;\\ + case NPY_CFLOAT: *(npy_float *)(PyArray_DATA(arr))=(*v).r;\\ + *(npy_float *)(PyArray_DATA(arr)+sizeof(npy_float))=(*v).i;\\ + break;\\ + case NPY_DOUBLE: *(npy_double *)(PyArray_DATA(arr))=(*v).r; break;\\ + case NPY_LONG: *(npy_long *)(PyArray_DATA(arr))=(*v).r; break;\\ + case NPY_FLOAT: *(npy_float *)(PyArray_DATA(arr))=(*v).r; break;\\ + case NPY_INT: *(npy_int *)(PyArray_DATA(arr))=(*v).r; break;\\ + case NPY_SHORT: *(npy_short *)(PyArray_DATA(arr))=(*v).r; break;\\ + case NPY_UBYTE: *(npy_ubyte *)(PyArray_DATA(arr))=(*v).r; break;\\ + case NPY_BYTE: *(npy_byte *)(PyArray_DATA(arr))=(*v).r; break;\\ + case NPY_BOOL: *(npy_bool *)(PyArray_DATA(arr))=((*v).r!=0 && (*v).i!=0); break;\\ + case NPY_USHORT: *(npy_ushort *)(PyArray_DATA(arr))=(*v).r; break;\\ + case NPY_UINT: *(npy_uint *)(PyArray_DATA(arr))=(*v).r; break;\\ + case NPY_ULONG: *(npy_ulong *)(PyArray_DATA(arr))=(*v).r; break;\\ + case NPY_LONGLONG: *(npy_longlong *)(PyArray_DATA(arr))=(*v).r; break;\\ + case NPY_ULONGLONG: *(npy_ulonglong *)(PyArray_DATA(arr))=(*v).r; break;\\ + case NPY_LONGDOUBLE: *(npy_longdouble *)(PyArray_DATA(arr))=(*v).r; break;\\ + case NPY_CLONGDOUBLE: *(npy_longdouble *)(PyArray_DATA(arr))=(*v).r;\\ + *(npy_longdouble *)(PyArray_DATA(arr)+sizeof(npy_longdouble))=(*v).i;\\ + break;\\ + case NPY_OBJECT: PyArray_SETITEM(arr, PyArray_DATA(arr), pyobj_from_complex_ ## ctype ## 1((*v))); break;\\ + default: return -2;\\ + };\\ + return -1; +""" +# cppmacros['NUMFROMARROBJ']=""" +# define NUMFROMARROBJ(typenum,ctype) \\ +# if (PyArray_Check(obj)) arr = (PyArrayObject *)obj;\\ +# else arr = (PyArrayObject *)PyArray_ContiguousFromObject(obj,typenum,0,0);\\ +# if (arr) {\\ +# if (PyArray_TYPE(arr)==NPY_OBJECT) {\\ +# if (!ctype ## _from_pyobj(v,(PyArray_DESCR(arr)->getitem)(PyArray_DATA(arr)),\"\"))\\ +# goto capi_fail;\\ +# } else {\\ +# (PyArray_DESCR(arr)->cast[typenum])(PyArray_DATA(arr),1,(char*)v,1,1);\\ +# }\\ +# if ((PyObject *)arr != obj) { Py_DECREF(arr); }\\ +# return 1;\\ +# } +# """ +# XXX: Note that CNUMFROMARROBJ is identical with NUMFROMARROBJ +# cppmacros['CNUMFROMARROBJ']=""" +# define CNUMFROMARROBJ(typenum,ctype) \\ +# if (PyArray_Check(obj)) arr = (PyArrayObject *)obj;\\ +# else arr = (PyArrayObject *)PyArray_ContiguousFromObject(obj,typenum,0,0);\\ +# if (arr) {\\ +# if (PyArray_TYPE(arr)==NPY_OBJECT) {\\ +# if (!ctype ## _from_pyobj(v,(PyArray_DESCR(arr)->getitem)(PyArray_DATA(arr)),\"\"))\\ +# goto capi_fail;\\ +# } else {\\ +# (PyArray_DESCR(arr)->cast[typenum])((void *)(PyArray_DATA(arr)),1,(void *)(v),1,1);\\ +# }\\ +# if ((PyObject *)arr != obj) { Py_DECREF(arr); }\\ +# return 1;\\ +# } +# """ + + +needs['GETSTRFROMPYTUPLE'] = ['STRINGCOPYN', 'PRINTPYOBJERR'] +cppmacros['GETSTRFROMPYTUPLE'] = """ +#define GETSTRFROMPYTUPLE(tuple,index,str,len) {\\ + PyObject *rv_cb_str = PyTuple_GetItem((tuple),(index));\\ + if (rv_cb_str == NULL)\\ + goto capi_fail;\\ + if (PyBytes_Check(rv_cb_str)) {\\ + str[len-1]='\\0';\\ + STRINGCOPYN((str),PyBytes_AS_STRING((PyBytesObject*)rv_cb_str),(len));\\ + } else {\\ + PRINTPYOBJERR(rv_cb_str);\\ + PyErr_SetString(#modulename#_error,\"string object expected\");\\ + goto capi_fail;\\ + }\\ + } +""" +cppmacros['GETSCALARFROMPYTUPLE'] = """ +#define GETSCALARFROMPYTUPLE(tuple,index,var,ctype,mess) {\\ + if ((capi_tmp = PyTuple_GetItem((tuple),(index)))==NULL) goto capi_fail;\\ + if (!(ctype ## _from_pyobj((var),capi_tmp,mess)))\\ + goto capi_fail;\\ + } +""" + +cppmacros['FAILNULL'] = """\ +#define FAILNULL(p) do { \\ + if ((p) == NULL) { \\ + PyErr_SetString(PyExc_MemoryError, "NULL pointer found"); \\ + goto capi_fail; \\ + } \\ +} while (0) +""" +needs['MEMCOPY'] = ['string.h', 'FAILNULL'] +cppmacros['MEMCOPY'] = """ +#define MEMCOPY(to,from,n)\\ + do { FAILNULL(to); FAILNULL(from); (void)memcpy(to,from,n); } while (0) +""" +cppmacros['STRINGMALLOC'] = """ +#define STRINGMALLOC(str,len)\\ + if ((str = (string)malloc(len+1)) == NULL) {\\ + PyErr_SetString(PyExc_MemoryError, \"out of memory\");\\ + goto capi_fail;\\ + } else {\\ + (str)[len] = '\\0';\\ + } +""" +cppmacros['STRINGFREE'] = """ +#define STRINGFREE(str) do {if (!(str == NULL)) free(str);} while (0) +""" +needs['STRINGPADN'] = ['string.h'] +cppmacros['STRINGPADN'] = """ +/* +STRINGPADN replaces null values with padding values from the right. + +`to` must have size of at least N bytes. + +If the `to[N-1]` has null value, then replace it and all the +preceding, nulls with the given padding. + +STRINGPADN(to, N, PADDING, NULLVALUE) is an inverse operation. +*/ +#define STRINGPADN(to, N, NULLVALUE, PADDING) \\ + do { \\ + int _m = (N); \\ + char *_to = (to); \\ + for (_m -= 1; _m >= 0 && _to[_m] == NULLVALUE; _m--) { \\ + _to[_m] = PADDING; \\ + } \\ + } while (0) +""" +needs['STRINGCOPYN'] = ['string.h', 'FAILNULL'] +cppmacros['STRINGCOPYN'] = """ +/* +STRINGCOPYN copies N bytes. + +`to` and `from` buffers must have sizes of at least N bytes. +*/ +#define STRINGCOPYN(to,from,N) \\ + do { \\ + int _m = (N); \\ + char *_to = (to); \\ + char *_from = (from); \\ + FAILNULL(_to); FAILNULL(_from); \\ + (void)strncpy(_to, _from, _m); \\ + } while (0) +""" +needs['STRINGCOPY'] = ['string.h', 'FAILNULL'] +cppmacros['STRINGCOPY'] = """ +#define STRINGCOPY(to,from)\\ + do { FAILNULL(to); FAILNULL(from); (void)strcpy(to,from); } while (0) +""" +cppmacros['CHECKGENERIC'] = """ +#define CHECKGENERIC(check,tcheck,name) \\ + if (!(check)) {\\ + PyErr_SetString(#modulename#_error,\"(\"tcheck\") failed for \"name);\\ + /*goto capi_fail;*/\\ + } else """ +cppmacros['CHECKARRAY'] = """ +#define CHECKARRAY(check,tcheck,name) \\ + if (!(check)) {\\ + PyErr_SetString(#modulename#_error,\"(\"tcheck\") failed for \"name);\\ + /*goto capi_fail;*/\\ + } else """ +cppmacros['CHECKSTRING'] = """ +#define CHECKSTRING(check,tcheck,name,show,var)\\ + if (!(check)) {\\ + char errstring[256];\\ + sprintf(errstring, \"%s: \"show, \"(\"tcheck\") failed for \"name, slen(var), var);\\ + PyErr_SetString(#modulename#_error, errstring);\\ + /*goto capi_fail;*/\\ + } else """ +cppmacros['CHECKSCALAR'] = """ +#define CHECKSCALAR(check,tcheck,name,show,var)\\ + if (!(check)) {\\ + char errstring[256];\\ + sprintf(errstring, \"%s: \"show, \"(\"tcheck\") failed for \"name, var);\\ + PyErr_SetString(#modulename#_error,errstring);\\ + /*goto capi_fail;*/\\ + } else """ +# cppmacros['CHECKDIMS']=""" +# define CHECKDIMS(dims,rank) \\ +# for (int i=0;i<(rank);i++)\\ +# if (dims[i]<0) {\\ +# fprintf(stderr,\"Unspecified array argument requires a complete dimension specification.\\n\");\\ +# goto capi_fail;\\ +# } +# """ +cppmacros[ + 'ARRSIZE'] = '#define ARRSIZE(dims,rank) (_PyArray_multiply_list(dims,rank))' +cppmacros['OLDPYNUM'] = """ +#ifdef OLDPYNUM +#error You need to install NumPy version 0.13 or higher. See https://scipy.org/install.html +#endif +""" + +# Defining the correct value to indicate thread-local storage in C without +# running a compile-time check (which we have no control over in generated +# code used outside of NumPy) is hard. Therefore we support overriding this +# via an external define - the f2py-using package can then use the same +# compile-time checks as we use for `NPY_TLS` when building NumPy (see +# scipy#21860 for an example of that). +# +# __STDC_NO_THREADS__ should not be coupled to the availability of _Thread_local. +# In case we get a bug report, guard it with __STDC_NO_THREADS__ after all. +# +# `thread_local` has become a keyword in C23, but don't try to use that yet +# (too new, doing so while C23 support is preliminary will likely cause more +# problems than it solves). +# +# Note: do not try to use `threads.h`, its availability is very low +# *and* threads.h isn't actually used where `F2PY_THREAD_LOCAL_DECL` is +# in the generated code. See gh-27718 for more details. +cppmacros["F2PY_THREAD_LOCAL_DECL"] = """ +#ifndef F2PY_THREAD_LOCAL_DECL +#if defined(_MSC_VER) +#define F2PY_THREAD_LOCAL_DECL __declspec(thread) +#elif defined(NPY_OS_MINGW) +#define F2PY_THREAD_LOCAL_DECL __thread +#elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) +#define F2PY_THREAD_LOCAL_DECL _Thread_local +#elif defined(__GNUC__) \\ + && (__GNUC__ > 4 || (__GNUC__ == 4 && (__GNUC_MINOR__ >= 4))) +#define F2PY_THREAD_LOCAL_DECL __thread +#endif +#endif +""" +################# C functions ############### + +cfuncs['calcarrindex'] = """ +static int calcarrindex(int *i,PyArrayObject *arr) { + int k,ii = i[0]; + for (k=1; k < PyArray_NDIM(arr); k++) + ii += (ii*(PyArray_DIM(arr,k) - 1)+i[k]); /* assuming contiguous arr */ + return ii; +}""" +cfuncs['calcarrindextr'] = """ +static int calcarrindextr(int *i,PyArrayObject *arr) { + int k,ii = i[PyArray_NDIM(arr)-1]; + for (k=1; k < PyArray_NDIM(arr); k++) + ii += (ii*(PyArray_DIM(arr,PyArray_NDIM(arr)-k-1) - 1)+i[PyArray_NDIM(arr)-k-1]); /* assuming contiguous arr */ + return ii; +}""" +cfuncs['forcomb'] = """ +struct ForcombCache { int nd;npy_intp *d;int *i,*i_tr,tr; }; +static int initforcomb(struct ForcombCache *cache, npy_intp *dims,int nd,int tr) { + int k; + if (dims==NULL) return 0; + if (nd<0) return 0; + cache->nd = nd; + cache->d = dims; + cache->tr = tr; + + cache->i = (int *)malloc(sizeof(int)*nd); + if (cache->i==NULL) return 0; + cache->i_tr = (int *)malloc(sizeof(int)*nd); + if (cache->i_tr==NULL) {free(cache->i); return 0;}; + + for (k=1;ki[k] = cache->i_tr[nd-k-1] = 0; + } + cache->i[0] = cache->i_tr[nd-1] = -1; + return 1; +} +static int *nextforcomb(struct ForcombCache *cache) { + if (cache==NULL) return NULL; + int j,*i,*i_tr,k; + int nd=cache->nd; + if ((i=cache->i) == NULL) return NULL; + if ((i_tr=cache->i_tr) == NULL) return NULL; + if (cache->d == NULL) return NULL; + i[0]++; + if (i[0]==cache->d[0]) { + j=1; + while ((jd[j]-1)) j++; + if (j==nd) { + free(i); + free(i_tr); + return NULL; + } + for (k=0;ktr) return i_tr; + return i; +}""" +needs['try_pyarr_from_string'] = ['STRINGCOPYN', 'PRINTPYOBJERR', 'string'] +cfuncs['try_pyarr_from_string'] = """ +/* + try_pyarr_from_string copies str[:len(obj)] to the data of an `ndarray`. + + If obj is an `ndarray`, it is assumed to be contiguous. + + If the specified len==-1, str must be null-terminated. +*/ +static int try_pyarr_from_string(PyObject *obj, + const string str, const int len) { +#ifdef DEBUGCFUNCS +fprintf(stderr, "try_pyarr_from_string(str='%s', len=%d, obj=%p)\\n", + (char*)str,len, obj); +#endif + if (!obj) return -2; /* Object missing */ + if (obj == Py_None) return -1; /* None */ + if (!PyArray_Check(obj)) goto capi_fail; /* not an ndarray */ + if (PyArray_Check(obj)) { + PyArrayObject *arr = (PyArrayObject *)obj; + assert(ISCONTIGUOUS(arr)); + string buf = PyArray_DATA(arr); + npy_intp n = len; + if (n == -1) { + /* Assuming null-terminated str. */ + n = strlen(str); + } + if (n > PyArray_NBYTES(arr)) { + n = PyArray_NBYTES(arr); + } + STRINGCOPYN(buf, str, n); + return 1; + } +capi_fail: + PRINTPYOBJERR(obj); + PyErr_SetString(#modulename#_error, \"try_pyarr_from_string failed\"); + return 0; +} +""" +needs['string_from_pyobj'] = ['string', 'STRINGMALLOC', 'STRINGCOPYN'] +cfuncs['string_from_pyobj'] = """ +/* + Create a new string buffer `str` of at most length `len` from a + Python string-like object `obj`. + + The string buffer has given size (len) or the size of inistr when len==-1. + + The string buffer is padded with blanks: in Fortran, trailing blanks + are insignificant contrary to C nulls. + */ +static int +string_from_pyobj(string *str, int *len, const string inistr, PyObject *obj, + const char *errmess) +{ + PyObject *tmp = NULL; + string buf = NULL; + npy_intp n = -1; +#ifdef DEBUGCFUNCS +fprintf(stderr,\"string_from_pyobj(str='%s',len=%d,inistr='%s',obj=%p)\\n\", + (char*)str, *len, (char *)inistr, obj); +#endif + if (obj == Py_None) { + n = strlen(inistr); + buf = inistr; + } + else if (PyArray_Check(obj)) { + PyArrayObject *arr = (PyArrayObject *)obj; + if (!ISCONTIGUOUS(arr)) { + PyErr_SetString(PyExc_ValueError, + \"array object is non-contiguous.\"); + goto capi_fail; + } + n = PyArray_NBYTES(arr); + buf = PyArray_DATA(arr); + n = strnlen(buf, n); + } + else { + if (PyBytes_Check(obj)) { + tmp = obj; + Py_INCREF(tmp); + } + else if (PyUnicode_Check(obj)) { + tmp = PyUnicode_AsASCIIString(obj); + } + else { + PyObject *tmp2; + tmp2 = PyObject_Str(obj); + if (tmp2) { + tmp = PyUnicode_AsASCIIString(tmp2); + Py_DECREF(tmp2); + } + else { + tmp = NULL; + } + } + if (tmp == NULL) goto capi_fail; + n = PyBytes_GET_SIZE(tmp); + buf = PyBytes_AS_STRING(tmp); + } + if (*len == -1) { + /* TODO: change the type of `len` so that we can remove this */ + if (n > NPY_MAX_INT) { + PyErr_SetString(PyExc_OverflowError, + "object too large for a 32-bit int"); + goto capi_fail; + } + *len = n; + } + else if (*len < n) { + /* discard the last (len-n) bytes of input buf */ + n = *len; + } + if (n < 0 || *len < 0 || buf == NULL) { + goto capi_fail; + } + STRINGMALLOC(*str, *len); // *str is allocated with size (*len + 1) + if (n < *len) { + /* + Pad fixed-width string with nulls. The caller will replace + nulls with blanks when the corresponding argument is not + intent(c). + */ + memset(*str + n, '\\0', *len - n); + } + STRINGCOPYN(*str, buf, n); + Py_XDECREF(tmp); + return 1; +capi_fail: + Py_XDECREF(tmp); + { + PyObject* err = PyErr_Occurred(); + if (err == NULL) { + err = #modulename#_error; + } + PyErr_SetString(err, errmess); + } + return 0; +} +""" + +cfuncs['character_from_pyobj'] = """ +static int +character_from_pyobj(character* v, PyObject *obj, const char *errmess) { + if (PyBytes_Check(obj)) { + /* empty bytes has trailing null, so dereferencing is always safe */ + *v = PyBytes_AS_STRING(obj)[0]; + return 1; + } else if (PyUnicode_Check(obj)) { + PyObject* tmp = PyUnicode_AsASCIIString(obj); + if (tmp != NULL) { + *v = PyBytes_AS_STRING(tmp)[0]; + Py_DECREF(tmp); + return 1; + } + } else if (PyArray_Check(obj)) { + PyArrayObject* arr = (PyArrayObject*)obj; + if (F2PY_ARRAY_IS_CHARACTER_COMPATIBLE(arr)) { + *v = PyArray_BYTES(arr)[0]; + return 1; + } else if (F2PY_IS_UNICODE_ARRAY(arr)) { + // TODO: update when numpy will support 1-byte and + // 2-byte unicode dtypes + PyObject* tmp = PyUnicode_FromKindAndData( + PyUnicode_4BYTE_KIND, + PyArray_BYTES(arr), + (PyArray_NBYTES(arr)>0?1:0)); + if (tmp != NULL) { + if (character_from_pyobj(v, tmp, errmess)) { + Py_DECREF(tmp); + return 1; + } + Py_DECREF(tmp); + } + } + } else if (PySequence_Check(obj)) { + PyObject* tmp = PySequence_GetItem(obj,0); + if (tmp != NULL) { + if (character_from_pyobj(v, tmp, errmess)) { + Py_DECREF(tmp); + return 1; + } + Py_DECREF(tmp); + } + } + { + /* TODO: This error (and most other) error handling needs cleaning. */ + char mess[F2PY_MESSAGE_BUFFER_SIZE]; + strcpy(mess, errmess); + PyObject* err = PyErr_Occurred(); + if (err == NULL) { + err = PyExc_TypeError; + Py_INCREF(err); + } + else { + Py_INCREF(err); + PyErr_Clear(); + } + sprintf(mess + strlen(mess), + " -- expected str|bytes|sequence-of-str-or-bytes, got "); + f2py_describe(obj, mess + strlen(mess)); + PyErr_SetString(err, mess); + Py_DECREF(err); + } + return 0; +} +""" + +# TODO: These should be dynamically generated, too many mapped to int things, +# see note in _isocbind.py +needs['char_from_pyobj'] = ['int_from_pyobj'] +cfuncs['char_from_pyobj'] = """ +static int +char_from_pyobj(char* v, PyObject *obj, const char *errmess) { + int i = 0; + if (int_from_pyobj(&i, obj, errmess)) { + *v = (char)i; + return 1; + } + return 0; +} +""" + + +needs['signed_char_from_pyobj'] = ['int_from_pyobj', 'signed_char'] +cfuncs['signed_char_from_pyobj'] = """ +static int +signed_char_from_pyobj(signed_char* v, PyObject *obj, const char *errmess) { + int i = 0; + if (int_from_pyobj(&i, obj, errmess)) { + *v = (signed_char)i; + return 1; + } + return 0; +} +""" + + +needs['short_from_pyobj'] = ['int_from_pyobj'] +cfuncs['short_from_pyobj'] = """ +static int +short_from_pyobj(short* v, PyObject *obj, const char *errmess) { + int i = 0; + if (int_from_pyobj(&i, obj, errmess)) { + *v = (short)i; + return 1; + } + return 0; +} +""" + + +cfuncs['int_from_pyobj'] = """ +static int +int_from_pyobj(int* v, PyObject *obj, const char *errmess) +{ + PyObject* tmp = NULL; + + if (PyLong_Check(obj)) { + *v = Npy__PyLong_AsInt(obj); + return !(*v == -1 && PyErr_Occurred()); + } + + tmp = PyNumber_Long(obj); + if (tmp) { + *v = Npy__PyLong_AsInt(tmp); + Py_DECREF(tmp); + return !(*v == -1 && PyErr_Occurred()); + } + + if (PyComplex_Check(obj)) { + PyErr_Clear(); + tmp = PyObject_GetAttrString(obj,\"real\"); + } + else if (PyBytes_Check(obj) || PyUnicode_Check(obj)) { + /*pass*/; + } + else if (PySequence_Check(obj)) { + PyErr_Clear(); + tmp = PySequence_GetItem(obj, 0); + } + + if (tmp) { + if (int_from_pyobj(v, tmp, errmess)) { + Py_DECREF(tmp); + return 1; + } + Py_DECREF(tmp); + } + + { + PyObject* err = PyErr_Occurred(); + if (err == NULL) { + err = #modulename#_error; + } + PyErr_SetString(err, errmess); + } + return 0; +} +""" + + +cfuncs['long_from_pyobj'] = """ +static int +long_from_pyobj(long* v, PyObject *obj, const char *errmess) { + PyObject* tmp = NULL; + + if (PyLong_Check(obj)) { + *v = PyLong_AsLong(obj); + return !(*v == -1 && PyErr_Occurred()); + } + + tmp = PyNumber_Long(obj); + if (tmp) { + *v = PyLong_AsLong(tmp); + Py_DECREF(tmp); + return !(*v == -1 && PyErr_Occurred()); + } + + if (PyComplex_Check(obj)) { + PyErr_Clear(); + tmp = PyObject_GetAttrString(obj,\"real\"); + } + else if (PyBytes_Check(obj) || PyUnicode_Check(obj)) { + /*pass*/; + } + else if (PySequence_Check(obj)) { + PyErr_Clear(); + tmp = PySequence_GetItem(obj, 0); + } + + if (tmp) { + if (long_from_pyobj(v, tmp, errmess)) { + Py_DECREF(tmp); + return 1; + } + Py_DECREF(tmp); + } + { + PyObject* err = PyErr_Occurred(); + if (err == NULL) { + err = #modulename#_error; + } + PyErr_SetString(err, errmess); + } + return 0; +} +""" + + +needs['long_long_from_pyobj'] = ['long_long'] +cfuncs['long_long_from_pyobj'] = """ +static int +long_long_from_pyobj(long_long* v, PyObject *obj, const char *errmess) +{ + PyObject* tmp = NULL; + + if (PyLong_Check(obj)) { + *v = PyLong_AsLongLong(obj); + return !(*v == -1 && PyErr_Occurred()); + } + + tmp = PyNumber_Long(obj); + if (tmp) { + *v = PyLong_AsLongLong(tmp); + Py_DECREF(tmp); + return !(*v == -1 && PyErr_Occurred()); + } + + if (PyComplex_Check(obj)) { + PyErr_Clear(); + tmp = PyObject_GetAttrString(obj,\"real\"); + } + else if (PyBytes_Check(obj) || PyUnicode_Check(obj)) { + /*pass*/; + } + else if (PySequence_Check(obj)) { + PyErr_Clear(); + tmp = PySequence_GetItem(obj, 0); + } + + if (tmp) { + if (long_long_from_pyobj(v, tmp, errmess)) { + Py_DECREF(tmp); + return 1; + } + Py_DECREF(tmp); + } + { + PyObject* err = PyErr_Occurred(); + if (err == NULL) { + err = #modulename#_error; + } + PyErr_SetString(err,errmess); + } + return 0; +} +""" + + +needs['long_double_from_pyobj'] = ['double_from_pyobj', 'long_double'] +cfuncs['long_double_from_pyobj'] = """ +static int +long_double_from_pyobj(long_double* v, PyObject *obj, const char *errmess) +{ + double d=0; + if (PyArray_CheckScalar(obj)){ + if PyArray_IsScalar(obj, LongDouble) { + PyArray_ScalarAsCtype(obj, v); + return 1; + } + else if (PyArray_Check(obj)) { + PyArrayObject *arr = (PyArrayObject *)obj; + if (PyArray_TYPE(arr) == NPY_LONGDOUBLE) { + (*v) = *((npy_longdouble *)PyArray_DATA(arr)); + return 1; + } + } + } + if (double_from_pyobj(&d, obj, errmess)) { + *v = (long_double)d; + return 1; + } + return 0; +} +""" + + +cfuncs['double_from_pyobj'] = """ +static int +double_from_pyobj(double* v, PyObject *obj, const char *errmess) +{ + PyObject* tmp = NULL; + if (PyFloat_Check(obj)) { + *v = PyFloat_AsDouble(obj); + return !(*v == -1.0 && PyErr_Occurred()); + } + + tmp = PyNumber_Float(obj); + if (tmp) { + *v = PyFloat_AsDouble(tmp); + Py_DECREF(tmp); + return !(*v == -1.0 && PyErr_Occurred()); + } + + if (PyComplex_Check(obj)) { + PyErr_Clear(); + tmp = PyObject_GetAttrString(obj,\"real\"); + } + else if (PyBytes_Check(obj) || PyUnicode_Check(obj)) { + /*pass*/; + } + else if (PySequence_Check(obj)) { + PyErr_Clear(); + tmp = PySequence_GetItem(obj, 0); + } + + if (tmp) { + if (double_from_pyobj(v,tmp,errmess)) {Py_DECREF(tmp); return 1;} + Py_DECREF(tmp); + } + { + PyObject* err = PyErr_Occurred(); + if (err==NULL) err = #modulename#_error; + PyErr_SetString(err,errmess); + } + return 0; +} +""" + + +needs['float_from_pyobj'] = ['double_from_pyobj'] +cfuncs['float_from_pyobj'] = """ +static int +float_from_pyobj(float* v, PyObject *obj, const char *errmess) +{ + double d=0.0; + if (double_from_pyobj(&d,obj,errmess)) { + *v = (float)d; + return 1; + } + return 0; +} +""" + + +needs['complex_long_double_from_pyobj'] = ['complex_long_double', 'long_double', + 'complex_double_from_pyobj', 'npy_math.h'] +cfuncs['complex_long_double_from_pyobj'] = """ +static int +complex_long_double_from_pyobj(complex_long_double* v, PyObject *obj, const char *errmess) +{ + complex_double cd = {0.0,0.0}; + if (PyArray_CheckScalar(obj)){ + if PyArray_IsScalar(obj, CLongDouble) { + PyArray_ScalarAsCtype(obj, v); + return 1; + } + else if (PyArray_Check(obj)) { + PyArrayObject *arr = (PyArrayObject *)obj; + if (PyArray_TYPE(arr)==NPY_CLONGDOUBLE) { + (*v).r = npy_creall(*(((npy_clongdouble *)PyArray_DATA(arr)))); + (*v).i = npy_cimagl(*(((npy_clongdouble *)PyArray_DATA(arr)))); + return 1; + } + } + } + if (complex_double_from_pyobj(&cd,obj,errmess)) { + (*v).r = (long_double)cd.r; + (*v).i = (long_double)cd.i; + return 1; + } + return 0; +} +""" + + +needs['complex_double_from_pyobj'] = ['complex_double', 'npy_math.h'] +cfuncs['complex_double_from_pyobj'] = """ +static int +complex_double_from_pyobj(complex_double* v, PyObject *obj, const char *errmess) { + Py_complex c; + if (PyComplex_Check(obj)) { + c = PyComplex_AsCComplex(obj); + (*v).r = c.real; + (*v).i = c.imag; + return 1; + } + if (PyArray_IsScalar(obj, ComplexFloating)) { + if (PyArray_IsScalar(obj, CFloat)) { + npy_cfloat new; + PyArray_ScalarAsCtype(obj, &new); + (*v).r = (double)npy_crealf(new); + (*v).i = (double)npy_cimagf(new); + } + else if (PyArray_IsScalar(obj, CLongDouble)) { + npy_clongdouble new; + PyArray_ScalarAsCtype(obj, &new); + (*v).r = (double)npy_creall(new); + (*v).i = (double)npy_cimagl(new); + } + else { /* if (PyArray_IsScalar(obj, CDouble)) */ + PyArray_ScalarAsCtype(obj, v); + } + return 1; + } + if (PyArray_CheckScalar(obj)) { /* 0-dim array or still array scalar */ + PyArrayObject *arr; + if (PyArray_Check(obj)) { + arr = (PyArrayObject *)PyArray_Cast((PyArrayObject *)obj, NPY_CDOUBLE); + } + else { + arr = (PyArrayObject *)PyArray_FromScalar(obj, PyArray_DescrFromType(NPY_CDOUBLE)); + } + if (arr == NULL) { + return 0; + } + (*v).r = npy_creal(*(((npy_cdouble *)PyArray_DATA(arr)))); + (*v).i = npy_cimag(*(((npy_cdouble *)PyArray_DATA(arr)))); + Py_DECREF(arr); + return 1; + } + /* Python does not provide PyNumber_Complex function :-( */ + (*v).i = 0.0; + if (PyFloat_Check(obj)) { + (*v).r = PyFloat_AsDouble(obj); + return !((*v).r == -1.0 && PyErr_Occurred()); + } + if (PyLong_Check(obj)) { + (*v).r = PyLong_AsDouble(obj); + return !((*v).r == -1.0 && PyErr_Occurred()); + } + if (PySequence_Check(obj) && !(PyBytes_Check(obj) || PyUnicode_Check(obj))) { + PyObject *tmp = PySequence_GetItem(obj,0); + if (tmp) { + if (complex_double_from_pyobj(v,tmp,errmess)) { + Py_DECREF(tmp); + return 1; + } + Py_DECREF(tmp); + } + } + { + PyObject* err = PyErr_Occurred(); + if (err==NULL) + err = PyExc_TypeError; + PyErr_SetString(err,errmess); + } + return 0; +} +""" + + +needs['complex_float_from_pyobj'] = [ + 'complex_float', 'complex_double_from_pyobj'] +cfuncs['complex_float_from_pyobj'] = """ +static int +complex_float_from_pyobj(complex_float* v,PyObject *obj,const char *errmess) +{ + complex_double cd={0.0,0.0}; + if (complex_double_from_pyobj(&cd,obj,errmess)) { + (*v).r = (float)cd.r; + (*v).i = (float)cd.i; + return 1; + } + return 0; +} +""" + + +cfuncs['try_pyarr_from_character'] = """ +static int try_pyarr_from_character(PyObject* obj, character* v) { + PyArrayObject *arr = (PyArrayObject*)obj; + if (!obj) return -2; + if (PyArray_Check(obj)) { + if (F2PY_ARRAY_IS_CHARACTER_COMPATIBLE(arr)) { + *(character *)(PyArray_DATA(arr)) = *v; + return 1; + } + } + { + char mess[F2PY_MESSAGE_BUFFER_SIZE]; + PyObject* err = PyErr_Occurred(); + if (err == NULL) { + err = PyExc_ValueError; + strcpy(mess, "try_pyarr_from_character failed" + " -- expected bytes array-scalar|array, got "); + f2py_describe(obj, mess + strlen(mess)); + PyErr_SetString(err, mess); + } + } + return 0; +} +""" + +needs['try_pyarr_from_char'] = ['pyobj_from_char1', 'TRYPYARRAYTEMPLATE'] +cfuncs[ + 'try_pyarr_from_char'] = 'static int try_pyarr_from_char(PyObject* obj,char* v) {\n TRYPYARRAYTEMPLATE(char,\'c\');\n}\n' +needs['try_pyarr_from_signed_char'] = ['TRYPYARRAYTEMPLATE', 'unsigned_char'] +cfuncs[ + 'try_pyarr_from_unsigned_char'] = 'static int try_pyarr_from_unsigned_char(PyObject* obj,unsigned_char* v) {\n TRYPYARRAYTEMPLATE(unsigned_char,\'b\');\n}\n' +needs['try_pyarr_from_signed_char'] = ['TRYPYARRAYTEMPLATE', 'signed_char'] +cfuncs[ + 'try_pyarr_from_signed_char'] = 'static int try_pyarr_from_signed_char(PyObject* obj,signed_char* v) {\n TRYPYARRAYTEMPLATE(signed_char,\'1\');\n}\n' +needs['try_pyarr_from_short'] = ['pyobj_from_short1', 'TRYPYARRAYTEMPLATE'] +cfuncs[ + 'try_pyarr_from_short'] = 'static int try_pyarr_from_short(PyObject* obj,short* v) {\n TRYPYARRAYTEMPLATE(short,\'s\');\n}\n' +needs['try_pyarr_from_int'] = ['pyobj_from_int1', 'TRYPYARRAYTEMPLATE'] +cfuncs[ + 'try_pyarr_from_int'] = 'static int try_pyarr_from_int(PyObject* obj,int* v) {\n TRYPYARRAYTEMPLATE(int,\'i\');\n}\n' +needs['try_pyarr_from_long'] = ['pyobj_from_long1', 'TRYPYARRAYTEMPLATE'] +cfuncs[ + 'try_pyarr_from_long'] = 'static int try_pyarr_from_long(PyObject* obj,long* v) {\n TRYPYARRAYTEMPLATE(long,\'l\');\n}\n' +needs['try_pyarr_from_long_long'] = [ + 'pyobj_from_long_long1', 'TRYPYARRAYTEMPLATE', 'long_long'] +cfuncs[ + 'try_pyarr_from_long_long'] = 'static int try_pyarr_from_long_long(PyObject* obj,long_long* v) {\n TRYPYARRAYTEMPLATE(long_long,\'L\');\n}\n' +needs['try_pyarr_from_float'] = ['pyobj_from_float1', 'TRYPYARRAYTEMPLATE'] +cfuncs[ + 'try_pyarr_from_float'] = 'static int try_pyarr_from_float(PyObject* obj,float* v) {\n TRYPYARRAYTEMPLATE(float,\'f\');\n}\n' +needs['try_pyarr_from_double'] = ['pyobj_from_double1', 'TRYPYARRAYTEMPLATE'] +cfuncs[ + 'try_pyarr_from_double'] = 'static int try_pyarr_from_double(PyObject* obj,double* v) {\n TRYPYARRAYTEMPLATE(double,\'d\');\n}\n' +needs['try_pyarr_from_complex_float'] = [ + 'pyobj_from_complex_float1', 'TRYCOMPLEXPYARRAYTEMPLATE', 'complex_float'] +cfuncs[ + 'try_pyarr_from_complex_float'] = 'static int try_pyarr_from_complex_float(PyObject* obj,complex_float* v) {\n TRYCOMPLEXPYARRAYTEMPLATE(float,\'F\');\n}\n' +needs['try_pyarr_from_complex_double'] = [ + 'pyobj_from_complex_double1', 'TRYCOMPLEXPYARRAYTEMPLATE', 'complex_double'] +cfuncs[ + 'try_pyarr_from_complex_double'] = 'static int try_pyarr_from_complex_double(PyObject* obj,complex_double* v) {\n TRYCOMPLEXPYARRAYTEMPLATE(double,\'D\');\n}\n' + + +needs['create_cb_arglist'] = ['CFUNCSMESS', 'PRINTPYOBJERR', 'MINMAX'] +# create the list of arguments to be used when calling back to python +cfuncs['create_cb_arglist'] = """ +static int +create_cb_arglist(PyObject* fun, PyTupleObject* xa , const int maxnofargs, + const int nofoptargs, int *nofargs, PyTupleObject **args, + const char *errmess) +{ + PyObject *tmp = NULL; + PyObject *tmp_fun = NULL; + Py_ssize_t tot, opt, ext, siz, i, di = 0; + CFUNCSMESS(\"create_cb_arglist\\n\"); + tot=opt=ext=siz=0; + /* Get the total number of arguments */ + if (PyFunction_Check(fun)) { + tmp_fun = fun; + Py_INCREF(tmp_fun); + } + else { + di = 1; + if (PyObject_HasAttrString(fun,\"im_func\")) { + tmp_fun = PyObject_GetAttrString(fun,\"im_func\"); + } + else if (PyObject_HasAttrString(fun,\"__call__\")) { + tmp = PyObject_GetAttrString(fun,\"__call__\"); + if (PyObject_HasAttrString(tmp,\"im_func\")) + tmp_fun = PyObject_GetAttrString(tmp,\"im_func\"); + else { + tmp_fun = fun; /* built-in function */ + Py_INCREF(tmp_fun); + tot = maxnofargs; + if (PyCFunction_Check(fun)) { + /* In case the function has a co_argcount (like on PyPy) */ + di = 0; + } + if (xa != NULL) + tot += PyTuple_Size((PyObject *)xa); + } + Py_XDECREF(tmp); + } + else if (PyFortran_Check(fun) || PyFortran_Check1(fun)) { + tot = maxnofargs; + if (xa != NULL) + tot += PyTuple_Size((PyObject *)xa); + tmp_fun = fun; + Py_INCREF(tmp_fun); + } + else if (F2PyCapsule_Check(fun)) { + tot = maxnofargs; + if (xa != NULL) + ext = PyTuple_Size((PyObject *)xa); + if(ext>0) { + fprintf(stderr,\"extra arguments tuple cannot be used with PyCapsule call-back\\n\"); + goto capi_fail; + } + tmp_fun = fun; + Py_INCREF(tmp_fun); + } + } + + if (tmp_fun == NULL) { + fprintf(stderr, + \"Call-back argument must be function|instance|instance.__call__|f2py-function \" + \"but got %s.\\n\", + ((fun == NULL) ? \"NULL\" : Py_TYPE(fun)->tp_name)); + goto capi_fail; + } + + if (PyObject_HasAttrString(tmp_fun,\"__code__\")) { + if (PyObject_HasAttrString(tmp = PyObject_GetAttrString(tmp_fun,\"__code__\"),\"co_argcount\")) { + PyObject *tmp_argcount = PyObject_GetAttrString(tmp,\"co_argcount\"); + Py_DECREF(tmp); + if (tmp_argcount == NULL) { + goto capi_fail; + } + tot = PyLong_AsSsize_t(tmp_argcount) - di; + Py_DECREF(tmp_argcount); + } + } + /* Get the number of optional arguments */ + if (PyObject_HasAttrString(tmp_fun,\"__defaults__\")) { + if (PyTuple_Check(tmp = PyObject_GetAttrString(tmp_fun,\"__defaults__\"))) + opt = PyTuple_Size(tmp); + Py_XDECREF(tmp); + } + /* Get the number of extra arguments */ + if (xa != NULL) + ext = PyTuple_Size((PyObject *)xa); + /* Calculate the size of call-backs argument list */ + siz = MIN(maxnofargs+ext,tot); + *nofargs = MAX(0,siz-ext); + +#ifdef DEBUGCFUNCS + fprintf(stderr, + \"debug-capi:create_cb_arglist:maxnofargs(-nofoptargs),\" + \"tot,opt,ext,siz,nofargs = %d(-%d), %zd, %zd, %zd, %zd, %d\\n\", + maxnofargs, nofoptargs, tot, opt, ext, siz, *nofargs); +#endif + + if (siz < tot-opt) { + fprintf(stderr, + \"create_cb_arglist: Failed to build argument list \" + \"(siz) with enough arguments (tot-opt) required by \" + \"user-supplied function (siz,tot,opt=%zd, %zd, %zd).\\n\", + siz, tot, opt); + goto capi_fail; + } + + /* Initialize argument list */ + *args = (PyTupleObject *)PyTuple_New(siz); + for (i=0;i<*nofargs;i++) { + Py_INCREF(Py_None); + PyTuple_SET_ITEM((PyObject *)(*args),i,Py_None); + } + if (xa != NULL) + for (i=(*nofargs);i 0: + if outneeds[n][0] not in needs: + out.append(outneeds[n][0]) + del outneeds[n][0] + else: + flag = 0 + for k in outneeds[n][1:]: + if k in needs[outneeds[n][0]]: + flag = 1 + break + if flag: + outneeds[n] = outneeds[n][1:] + [outneeds[n][0]] + else: + out.append(outneeds[n][0]) + del outneeds[n][0] + if saveout and (0 not in map(lambda x, y: x == y, saveout, outneeds[n])) \ + and outneeds[n] != []: + print(n, saveout) + errmess( + 'get_needs: no progress in sorting needs, probably circular dependence, skipping.\n') + out = out + saveout + break + saveout = copy.copy(outneeds[n]) + if out == []: + out = [n] + res[n] = out + return res diff --git a/python/user_packages/Python313/site-packages/numpy/f2py/cfuncs.pyi b/python/user_packages/Python313/site-packages/numpy/f2py/cfuncs.pyi new file mode 100644 index 0000000000000000000000000000000000000000..aad89073c656139d71ae2f4322081f14e2501cb4 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/f2py/cfuncs.pyi @@ -0,0 +1,31 @@ +from typing import Final, TypeAlias + +from .__version__ import version + +### + +_NeedListDict: TypeAlias = dict[str, list[str]] +_NeedDict: TypeAlias = dict[str, str] + +### + +f2py_version: Final = version + +outneeds: Final[_NeedListDict] = ... +needs: Final[_NeedListDict] = ... + +includes0: Final[_NeedDict] = ... +includes: Final[_NeedDict] = ... +userincludes: Final[_NeedDict] = ... +typedefs: Final[_NeedDict] = ... +typedefs_generated: Final[_NeedDict] = ... +cppmacros: Final[_NeedDict] = ... +cfuncs: Final[_NeedDict] = ... +callbacks: Final[_NeedDict] = ... +f90modhooks: Final[_NeedDict] = ... +commonhooks: Final[_NeedDict] = ... + +def errmess(s: str) -> None: ... +def buildcfuncs() -> None: ... +def get_needs() -> _NeedListDict: ... +def append_needs(need: str | list[str], flag: int = 1) -> _NeedListDict: ... diff --git a/python/user_packages/Python313/site-packages/numpy/f2py/common_rules.py b/python/user_packages/Python313/site-packages/numpy/f2py/common_rules.py new file mode 100644 index 0000000000000000000000000000000000000000..206928e9a02cc5c9204bd8ba858fd224173dde07 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/f2py/common_rules.py @@ -0,0 +1,143 @@ +""" +Build common block mechanism for f2py2e. + +Copyright 1999 -- 2011 Pearu Peterson all rights reserved. +Copyright 2011 -- present NumPy Developers. +Permission to use, modify, and distribute this software is given under the +terms of the NumPy License + +NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. +""" +from . import __version__ + +f2py_version = __version__.version + +from . import capi_maps, func2subr +from .auxfuncs import getuseblocks, hasbody, hascommon, hasnote, isintent_hide, outmess +from .crackfortran import rmbadname + + +def findcommonblocks(block, top=1): + ret = [] + if hascommon(block): + for key, value in block['common'].items(): + vars_ = {v: block['vars'][v] for v in value} + ret.append((key, value, vars_)) + elif hasbody(block): + for b in block['body']: + ret = ret + findcommonblocks(b, 0) + if top: + tret = [] + names = [] + for t in ret: + if t[0] not in names: + names.append(t[0]) + tret.append(t) + return tret + return ret + + +def buildhooks(m): + ret = {'commonhooks': [], 'initcommonhooks': [], + 'docs': ['"COMMON blocks:\\n"']} + fwrap = [''] + + def fadd(line, s=fwrap): + s[0] = f'{s[0]}\n {line}' + chooks = [''] + + def cadd(line, s=chooks): + s[0] = f'{s[0]}\n{line}' + ihooks = [''] + + def iadd(line, s=ihooks): + s[0] = f'{s[0]}\n{line}' + doc = [''] + + def dadd(line, s=doc): + s[0] = f'{s[0]}\n{line}' + for (name, vnames, vars) in findcommonblocks(m): + lower_name = name.lower() + hnames, inames = [], [] + for n in vnames: + if isintent_hide(vars[n]): + hnames.append(n) + else: + inames.append(n) + if hnames: + outmess('\t\tConstructing COMMON block support for "%s"...\n\t\t %s\n\t\t Hidden: %s\n' % ( + name, ','.join(inames), ','.join(hnames))) + else: + outmess('\t\tConstructing COMMON block support for "%s"...\n\t\t %s\n' % ( + name, ','.join(inames))) + fadd(f'subroutine f2pyinit{name}(setupfunc)') + for usename in getuseblocks(m): + fadd(f'use {usename}') + fadd('external setupfunc') + for n in vnames: + fadd(func2subr.var2fixfortran(vars, n)) + if name == '_BLNK_': + fadd(f"common {','.join(vnames)}") + else: + fadd(f"common /{name}/ {','.join(vnames)}") + fadd(f"call setupfunc({','.join(inames)})") + fadd('end\n') + cadd('static FortranDataDef f2py_%s_def[] = {' % (name)) + idims = [] + for n in inames: + ct = capi_maps.getctype(vars[n]) + elsize = capi_maps.get_elsize(vars[n]) + at = capi_maps.c2capi_map[ct] + dm = capi_maps.getarrdims(n, vars[n]) + if dm['dims']: + idims.append(f"({dm['dims']})") + else: + idims.append('') + dms = dm['dims'].strip() + if not dms: + dms = '-1' + cadd('\t{\"%s\",%s,{{%s}},%s, %s},' + % (n, dm['rank'], dms, at, elsize)) + cadd('\t{NULL}\n};') + inames1 = rmbadname(inames) + inames1_tps = ','.join(['char *' + s for s in inames1]) + cadd('static void f2py_setup_%s(%s) {' % (name, inames1_tps)) + cadd('\tint i_f2py=0;') + for n in inames1: + cadd(f'\tf2py_{name}_def[i_f2py++].data = {n};') + cadd('}') + if '_' in lower_name: + F_FUNC = 'F_FUNC_US' + else: + F_FUNC = 'F_FUNC' + cadd('extern void %s(f2pyinit%s,F2PYINIT%s)(void(*)(%s));' + % (F_FUNC, lower_name, name.upper(), + ','.join(['char*'] * len(inames1)))) + cadd('static void f2py_init_%s(void) {' % name) + cadd('\t%s(f2pyinit%s,F2PYINIT%s)(f2py_setup_%s);' + % (F_FUNC, lower_name, name.upper(), name)) + cadd('}\n') + iadd(f'\ttmp = PyFortranObject_New(f2py_{name}_def,f2py_init_{name});') + iadd('\tif (tmp == NULL) return NULL;') + iadd(f'\tif (F2PyDict_SetItemString(d, "{name}", tmp) == -1) return NULL;') + iadd('\tPy_DECREF(tmp);') + tname = name.replace('_', '\\_') + dadd('\\subsection{Common block \\texttt{%s}}\n' % (tname)) + dadd('\\begin{description}') + for n in inames: + dadd('\\item[]{{}\\verb@%s@{}}' % + (capi_maps.getarrdocsign(n, vars[n]))) + if hasnote(vars[n]): + note = vars[n]['note'] + if isinstance(note, list): + note = '\n'.join(note) + dadd(f'--- {note}') + dadd('\\end{description}') + ret['docs'].append( + f"\"\t/{name}/ {','.join(map(lambda v, d: v + d, inames, idims))}\\n\"") + ret['commonhooks'] = chooks + ret['initcommonhooks'] = ihooks + ret['latexdoc'] = doc[0] + if len(ret['docs']) <= 1: + ret['docs'] = '' + return ret, fwrap[0] diff --git a/python/user_packages/Python313/site-packages/numpy/f2py/common_rules.pyi b/python/user_packages/Python313/site-packages/numpy/f2py/common_rules.pyi new file mode 100644 index 0000000000000000000000000000000000000000..58fec3159753e292a9e18585c643f3416426060f --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/f2py/common_rules.pyi @@ -0,0 +1,9 @@ +from collections.abc import Mapping +from typing import Any, Final + +from .__version__ import version + +f2py_version: Final = version + +def findcommonblocks(block: Mapping[str, object], top: int = 1) -> list[tuple[str, list[str], dict[str, Any]]]: ... +def buildhooks(m: Mapping[str, object]) -> tuple[dict[str, Any], str]: ... diff --git a/python/user_packages/Python313/site-packages/numpy/f2py/crackfortran.py b/python/user_packages/Python313/site-packages/numpy/f2py/crackfortran.py new file mode 100644 index 0000000000000000000000000000000000000000..8befbded4b94b6b156638fce197554471345a747 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/f2py/crackfortran.py @@ -0,0 +1,3725 @@ +""" +crackfortran --- read fortran (77,90) code and extract declaration information. + +Copyright 1999 -- 2011 Pearu Peterson all rights reserved. +Copyright 2011 -- present NumPy Developers. +Permission to use, modify, and distribute this software is given under the +terms of the NumPy License. + +NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. + + +Usage of crackfortran: +====================== +Command line keys: -quiet,-verbose,-fix,-f77,-f90,-show,-h + -m ,--ignore-contains +Functions: crackfortran, crack2fortran +The following Fortran statements/constructions are supported +(or will be if needed): + block data,byte,call,character,common,complex,contains,data, + dimension,double complex,double precision,end,external,function, + implicit,integer,intent,interface,intrinsic, + logical,module,optional,parameter,private,public, + program,real,(sequence?),subroutine,type,use,virtual, + include,pythonmodule +Note: 'virtual' is mapped to 'dimension'. +Note: 'implicit integer (z) static (z)' is 'implicit static (z)' (this is minor bug). +Note: code after 'contains' will be ignored until its scope ends. +Note: 'common' statement is extended: dimensions are moved to variable definitions +Note: f2py directive: f2py is read as +Note: pythonmodule is introduced to represent Python module + +Usage: + `postlist=crackfortran(files)` + `postlist` contains declaration information read from the list of files `files`. + `crack2fortran(postlist)` returns a fortran code to be saved to pyf-file + + `postlist` has the following structure: + *** it is a list of dictionaries containing `blocks': + B = {'block','body','vars','parent_block'[,'name','prefix','args','result', + 'implicit','externals','interfaced','common','sortvars', + 'commonvars','note']} + B['block'] = 'interface' | 'function' | 'subroutine' | 'module' | + 'program' | 'block data' | 'type' | 'pythonmodule' | + 'abstract interface' + B['body'] --- list containing `subblocks' with the same structure as `blocks' + B['parent_block'] --- dictionary of a parent block: + C['body'][]['parent_block'] is C + B['vars'] --- dictionary of variable definitions + B['sortvars'] --- dictionary of variable definitions sorted by dependence (independent first) + B['name'] --- name of the block (not if B['block']=='interface') + B['prefix'] --- prefix string (only if B['block']=='function') + B['args'] --- list of argument names if B['block']== 'function' | 'subroutine' + B['result'] --- name of the return value (only if B['block']=='function') + B['implicit'] --- dictionary {'a':,'b':...} | None + B['externals'] --- list of variables being external + B['interfaced'] --- list of variables being external and defined + B['common'] --- dictionary of common blocks (list of objects) + B['commonvars'] --- list of variables used in common blocks (dimensions are moved to variable definitions) + B['from'] --- string showing the 'parents' of the current block + B['use'] --- dictionary of modules used in current block: + {:{['only':<0|1>],['map':{:,...}]}} + B['note'] --- list of LaTeX comments on the block + B['f2pyenhancements'] --- optional dictionary + {'threadsafe':'','fortranname':, + 'callstatement':|, + 'callprotoargument':, + 'usercode':|, + 'pymethoddef:' + } + B['entry'] --- dictionary {entryname:argslist,..} + B['varnames'] --- list of variable names given in the order of reading the + Fortran code, useful for derived types. + B['saved_interface'] --- a string of scanned routine signature, defines explicit interface + *** Variable definition is a dictionary + D = B['vars'][] = + {'typespec'[,'attrspec','kindselector','charselector','=','typename']} + D['typespec'] = 'byte' | 'character' | 'complex' | 'double complex' | + 'double precision' | 'integer' | 'logical' | 'real' | 'type' + D['attrspec'] --- list of attributes (e.g. 'dimension()', + 'external','intent(in|out|inout|hide|c|callback|cache|aligned4|aligned8|aligned16)', + 'optional','required', etc) + K = D['kindselector'] = {['*','kind']} (only if D['typespec'] = + 'complex' | 'integer' | 'logical' | 'real' ) + C = D['charselector'] = {['*','len','kind','f2py_len']} + (only if D['typespec']=='character') + D['='] --- initialization expression string + D['typename'] --- name of the type if D['typespec']=='type' + D['dimension'] --- list of dimension bounds + D['intent'] --- list of intent specifications + D['depend'] --- list of variable names on which current variable depends on + D['check'] --- list of C-expressions; if C-expr returns zero, exception is raised + D['note'] --- list of LaTeX comments on the variable + *** Meaning of kind/char selectors (few examples): + D['typespec>']*K['*'] + D['typespec'](kind=K['kind']) + character*C['*'] + character(len=C['len'],kind=C['kind'], f2py_len=C['f2py_len']) + (see also fortran type declaration statement formats below) + +Fortran 90 type declaration statement format (F77 is subset of F90) +==================================================================== +(Main source: IBM XL Fortran 5.1 Language Reference Manual) +type declaration = [[]::] + = byte | + character[] | + complex[] | + double complex | + double precision | + integer[] | + logical[] | + real[] | + type() + = * | + ([len=][,[kind=]]) | + (kind=[,len=]) + = * | + ([kind=]) + = comma separated list of attributes. + Only the following attributes are used in + building up the interface: + external + (parameter --- affects '=' key) + optional + intent + Other attributes are ignored. + = in | out | inout + = comma separated list of dimension bounds. + = [[*][()] | [()]*] + [// | =] [,] + +In addition, the following attributes are used: check,depend,note + +TODO: + * Apply 'parameter' attribute (e.g. 'integer parameter :: i=2' 'real x(i)' + -> 'real x(2)') + The above may be solved by creating appropriate preprocessor program, for example. + +""" +import codecs +import copy +import fileinput +import os +import platform +import re +import string +import sys +from pathlib import Path + +try: + import charset_normalizer +except ImportError: + charset_normalizer = None + +from . import __version__, symbolic + +# The environment provided by auxfuncs.py is needed for some calls to eval. +# As the needed functions cannot be determined by static inspection of the +# code, it is safest to use import * pending a major refactoring of f2py. +from .auxfuncs import * + +f2py_version = __version__.version + +# Global flags: +strictf77 = 1 # Ignore `!' comments unless line[0]=='!' +sourcecodeform = 'fix' # 'fix','free' +quiet = 0 # Be verbose if 0 (Obsolete: not used any more) +verbose = 1 # Be quiet if 0, extra verbose if > 1. +tabchar = 4 * ' ' +pyffilename = '' +f77modulename = '' +skipemptyends = 0 # for old F77 programs without 'program' statement +ignorecontains = 1 +dolowercase = 1 +debug = [] + +# Global variables +beginpattern = '' +currentfilename = '' +expectbegin = 1 +f90modulevars = {} +filepositiontext = '' +gotnextfile = 1 +groupcache = None +groupcounter = 0 +grouplist = {groupcounter: []} +groupname = '' +include_paths = [] +neededmodule = -1 +onlyfuncs = [] +previous_context = None +skipblocksuntil = -1 +skipfuncs = [] +skipfunctions = [] +usermodules = [] + + +def reset_global_f2py_vars(): + global groupcounter, grouplist, neededmodule, expectbegin + global skipblocksuntil, usermodules, f90modulevars, gotnextfile + global filepositiontext, currentfilename, skipfunctions, skipfuncs + global onlyfuncs, include_paths, previous_context + global strictf77, sourcecodeform, quiet, verbose, tabchar, pyffilename + global f77modulename, skipemptyends, ignorecontains, dolowercase, debug + + # flags + strictf77 = 1 + sourcecodeform = 'fix' + quiet = 0 + verbose = 1 + tabchar = 4 * ' ' + pyffilename = '' + f77modulename = '' + skipemptyends = 0 + ignorecontains = 1 + dolowercase = 1 + debug = [] + # variables + groupcounter = 0 + grouplist = {groupcounter: []} + neededmodule = -1 + expectbegin = 1 + skipblocksuntil = -1 + usermodules = [] + f90modulevars = {} + gotnextfile = 1 + filepositiontext = '' + currentfilename = '' + skipfunctions = [] + skipfuncs = [] + onlyfuncs = [] + include_paths = [] + previous_context = None + + +def outmess(line, flag=1): + global filepositiontext + + if not verbose: + return + if not quiet: + if flag: + sys.stdout.write(filepositiontext) + sys.stdout.write(line) + + +re._MAXCACHE = 50 +defaultimplicitrules = {} +for c in "abcdefghopqrstuvwxyz$_": + defaultimplicitrules[c] = {'typespec': 'real'} +for c in "ijklmn": + defaultimplicitrules[c] = {'typespec': 'integer'} +badnames = {} +invbadnames = {} +for n in ['int', 'double', 'float', 'char', 'short', 'long', 'void', 'case', 'while', + 'return', 'signed', 'unsigned', 'if', 'for', 'typedef', 'sizeof', 'union', + 'struct', 'static', 'register', 'new', 'break', 'do', 'goto', 'switch', + 'continue', 'else', 'inline', 'extern', 'delete', 'const', 'auto', + 'len', 'rank', 'shape', 'index', 'slen', 'size', '_i', + 'max', 'min', + 'flen', 'fshape', + 'string', 'complex_double', 'float_double', 'stdin', 'stderr', 'stdout', + 'type', 'default']: + badnames[n] = n + '_bn' + invbadnames[n + '_bn'] = n + + +def rmbadname1(name): + if name in badnames: + errmess(f'rmbadname1: Replacing "{name}" with "{badnames[name]}".\n') + return badnames[name] + return name + + +def rmbadname(names): + return [rmbadname1(_m) for _m in names] + + +def undo_rmbadname1(name): + if name in invbadnames: + errmess(f'undo_rmbadname1: Replacing "{name}" with "{invbadnames[name]}".\n') + return invbadnames[name] + return name + + +def undo_rmbadname(names): + return [undo_rmbadname1(_m) for _m in names] + + +_has_f_header = re.compile(r'-\*-\s*fortran\s*-\*-', re.I).search +_has_f90_header = re.compile(r'-\*-\s*f90\s*-\*-', re.I).search +_has_fix_header = re.compile(r'-\*-\s*fix\s*-\*-', re.I).search +_free_f90_start = re.compile(r'[^c*]\s*[^\s\d\t]', re.I).match + +# Extensions +COMMON_FREE_EXTENSIONS = ['.f90', '.f95', '.f03', '.f08'] +COMMON_FIXED_EXTENSIONS = ['.for', '.ftn', '.f77', '.f'] + + +def openhook(filename, mode): + """Ensures that filename is opened with correct encoding parameter. + + This function uses charset_normalizer package, when available, for + determining the encoding of the file to be opened. When charset_normalizer + is not available, the function detects only UTF encodings, otherwise, ASCII + encoding is used as fallback. + """ + # Reads in the entire file. Robust detection of encoding. + # Correctly handles comments or late stage unicode characters + # gh-22871 + if charset_normalizer is not None: + encoding = charset_normalizer.from_path(filename).best().encoding + else: + # hint: install charset_normalizer for correct encoding handling + # No need to read the whole file for trying with startswith + nbytes = min(32, os.path.getsize(filename)) + with open(filename, 'rb') as fhandle: + raw = fhandle.read(nbytes) + if raw.startswith(codecs.BOM_UTF8): + encoding = 'UTF-8-SIG' + elif raw.startswith((codecs.BOM_UTF32_LE, codecs.BOM_UTF32_BE)): + encoding = 'UTF-32' + elif raw.startswith((codecs.BOM_LE, codecs.BOM_BE)): + encoding = 'UTF-16' + else: + # Fallback, without charset_normalizer + encoding = 'ascii' + return open(filename, mode, encoding=encoding) + + +def is_free_format(fname): + """Check if file is in free format Fortran.""" + # f90 allows both fixed and free format, assuming fixed unless + # signs of free format are detected. + result = False + if Path(fname).suffix.lower() in COMMON_FREE_EXTENSIONS: + result = True + with openhook(fname, 'r') as fhandle: + line = fhandle.readline() + n = 15 # the number of non-comment lines to scan for hints + if _has_f_header(line): + n = 0 + elif _has_f90_header(line): + n = 0 + result = True + while n > 0 and line: + if line[0] != '!' and line.strip(): + n -= 1 + if (line[0] != '\t' and _free_f90_start(line[:5])) or line[-2:-1] == '&': + result = True + break + line = fhandle.readline() + return result + + +# Read fortran (77,90) code +def readfortrancode(ffile, dowithline=show, istop=1): + """ + Read fortran codes from files and + 1) Get rid of comments, line continuations, and empty lines; lower cases. + 2) Call dowithline(line) on every line. + 3) Recursively call itself when statement \"include ''\" is met. + """ + global gotnextfile, filepositiontext, currentfilename, sourcecodeform, strictf77 + global beginpattern, quiet, verbose, dolowercase, include_paths + + if not istop: + saveglobals = gotnextfile, filepositiontext, currentfilename, sourcecodeform, strictf77,\ + beginpattern, quiet, verbose, dolowercase + if ffile == []: + return + localdolowercase = dolowercase + # cont: set to True when the content of the last line read + # indicates statement continuation + cont = False + finalline = '' + ll = '' + includeline = re.compile( + r'\s*include\s*(\'|")(?P[^\'"]*)(\'|")', re.I) + cont1 = re.compile(r'(?P.*)&\s*\Z') + cont2 = re.compile(r'(\s*&|)(?P.*)') + mline_mark = re.compile(r".*?'''") + if istop: + dowithline('', -1) + ll, l1 = '', '' + spacedigits = [' '] + [str(_m) for _m in range(10)] + filepositiontext = '' + fin = fileinput.FileInput(ffile, openhook=openhook) + while True: + try: + l = fin.readline() + except UnicodeDecodeError as msg: + raise Exception( + f'readfortrancode: reading {fin.filename()}#{fin.lineno()}' + f' failed with\n{msg}.\nIt is likely that installing charset_normalizer' + ' package will help f2py determine the input file encoding' + ' correctly.') + if not l: + break + if fin.isfirstline(): + filepositiontext = '' + currentfilename = fin.filename() + gotnextfile = 1 + l1 = l + strictf77 = 0 + sourcecodeform = 'fix' + ext = os.path.splitext(currentfilename)[1] + if Path(currentfilename).suffix.lower() in COMMON_FIXED_EXTENSIONS and \ + not (_has_f90_header(l) or _has_fix_header(l)): + strictf77 = 1 + elif is_free_format(currentfilename) and not _has_fix_header(l): + sourcecodeform = 'free' + if strictf77: + beginpattern = beginpattern77 + else: + beginpattern = beginpattern90 + outmess('\tReading file %s (format:%s%s)\n' + % (repr(currentfilename), sourcecodeform, + (strictf77 and ',strict') or '')) + + l = l.expandtabs().replace('\xa0', ' ') + # Get rid of newline characters + while not l == '': + if l[-1] not in "\n\r\f": + break + l = l[:-1] + # Do not lower for directives, gh-2547, gh-27697, gh-26681 + is_f2py_directive = False + # Unconditionally remove comments + (l, rl) = split_by_unquoted(l, '!') + l += ' ' + if rl[:5].lower() == '!f2py': # f2py directive + l, _ = split_by_unquoted(l + 4 * ' ' + rl[5:], '!') + is_f2py_directive = True + if l.strip() == '': # Skip empty line + if sourcecodeform == 'free': + # In free form, a statement continues in the next line + # that is not a comment line [3.3.2.4^1], lines with + # blanks are comment lines [3.3.2.3^1]. Hence, the + # line continuation flag must retain its state. + pass + else: + # In fixed form, statement continuation is determined + # by a non-blank character at the 6-th position. Empty + # line indicates a start of a new statement + # [3.3.3.3^1]. Hence, the line continuation flag must + # be reset. + cont = False + continue + if sourcecodeform == 'fix': + if l[0] in ['*', 'c', '!', 'C', '#']: + if l[1:5].lower() == 'f2py': # f2py directive + l = ' ' + l[5:] + is_f2py_directive = True + else: # Skip comment line + cont = False + is_f2py_directive = False + continue + elif strictf77: + if len(l) > 72: + l = l[:72] + if l[0] not in spacedigits: + raise Exception('readfortrancode: Found non-(space,digit) char ' + 'in the first column.\n\tAre you sure that ' + 'this code is in fix form?\n\tline=%s' % repr(l)) + + if (not cont or strictf77) and (len(l) > 5 and not l[5] == ' '): + # Continuation of a previous line + ll = ll + l[6:] + finalline = '' + origfinalline = '' + else: + r = cont1.match(l) + if r: + l = r.group('line') # Continuation follows .. + if cont: + ll = ll + cont2.match(l).group('line') + finalline = '' + origfinalline = '' + else: + # clean up line beginning from possible digits. + l = ' ' + l[5:] + # f2py directives are already stripped by this point + if localdolowercase: + finalline = ll.lower() + else: + finalline = ll + origfinalline = ll + ll = l + + elif sourcecodeform == 'free': + if not cont and ext == '.pyf' and mline_mark.match(l): + l = l + '\n' + while True: + lc = fin.readline() + if not lc: + errmess( + 'Unexpected end of file when reading multiline\n') + break + l = l + lc + if mline_mark.match(lc): + break + l = l.rstrip() + r = cont1.match(l) + if r: + l = r.group('line') # Continuation follows .. + if cont: + ll = ll + cont2.match(l).group('line') + finalline = '' + origfinalline = '' + else: + if localdolowercase: + # only skip lowering for C style constructs + # gh-2547, gh-27697, gh-26681, gh-28014 + finalline = ll.lower() if not (is_f2py_directive and iscstyledirective(ll)) else ll + else: + finalline = ll + origfinalline = ll + ll = l + cont = (r is not None) + else: + raise ValueError( + f"Flag sourcecodeform must be either 'fix' or 'free': {repr(sourcecodeform)}") + filepositiontext = 'Line #%d in %s:"%s"\n\t' % ( + fin.filelineno() - 1, currentfilename, l1) + m = includeline.match(origfinalline) + if m: + fn = m.group('name') + if os.path.isfile(fn): + readfortrancode(fn, dowithline=dowithline, istop=0) + else: + include_dirs = [ + os.path.dirname(currentfilename)] + include_paths + foundfile = 0 + for inc_dir in include_dirs: + fn1 = os.path.join(inc_dir, fn) + if os.path.isfile(fn1): + foundfile = 1 + readfortrancode(fn1, dowithline=dowithline, istop=0) + break + if not foundfile: + outmess('readfortrancode: could not find include file %s in %s. Ignoring.\n' % ( + repr(fn), os.pathsep.join(include_dirs))) + else: + dowithline(finalline) + l1 = ll + # Last line should never have an f2py directive anyway + if localdolowercase: + finalline = ll.lower() + else: + finalline = ll + origfinalline = ll + filepositiontext = 'Line #%d in %s:"%s"\n\t' % ( + fin.filelineno() - 1, currentfilename, l1) + m = includeline.match(origfinalline) + if m: + fn = m.group('name') + if os.path.isfile(fn): + readfortrancode(fn, dowithline=dowithline, istop=0) + else: + include_dirs = [os.path.dirname(currentfilename)] + include_paths + foundfile = 0 + for inc_dir in include_dirs: + fn1 = os.path.join(inc_dir, fn) + if os.path.isfile(fn1): + foundfile = 1 + readfortrancode(fn1, dowithline=dowithline, istop=0) + break + if not foundfile: + outmess('readfortrancode: could not find include file %s in %s. Ignoring.\n' % ( + repr(fn), os.pathsep.join(include_dirs))) + else: + dowithline(finalline) + filepositiontext = '' + fin.close() + if istop: + dowithline('', 1) + else: + gotnextfile, filepositiontext, currentfilename, sourcecodeform, strictf77,\ + beginpattern, quiet, verbose, dolowercase = saveglobals + + +# Crack line +beforethisafter = r'\s*(?P%s(?=\s*(\b(%s)\b)))'\ + r'\s*(?P(\b(%s)\b))'\ + r'\s*(?P%s)\s*\Z' +## +fortrantypes = r'character|logical|integer|real|complex|double\s*(precision\s*(complex|)|complex)|type(?=\s*\([\w\s,=(*)]*\))|byte' +typespattern = re.compile( + beforethisafter % ('', fortrantypes, fortrantypes, '.*'), re.I), 'type' +typespattern4implicit = re.compile(beforethisafter % ( + '', fortrantypes + '|static|automatic|undefined', fortrantypes + '|static|automatic|undefined', '.*'), re.I) +# +functionpattern = re.compile(beforethisafter % ( + r'([a-z]+[\w\s(=*+-/)]*?|)', 'function', 'function', '.*'), re.I), 'begin' +subroutinepattern = re.compile(beforethisafter % ( + r'[a-z\s]*?', 'subroutine', 'subroutine', '.*'), re.I), 'begin' +# modulepattern=re.compile(beforethisafter%('[a-z\s]*?','module','module','.*'),re.I),'begin' +# +groupbegins77 = r'program|block\s*data' +beginpattern77 = re.compile( + beforethisafter % ('', groupbegins77, groupbegins77, '.*'), re.I), 'begin' +groupbegins90 = groupbegins77 + \ + r'|module(?!\s*procedure)|python\s*module|(abstract|)\s*interface|'\ + r'type(?!\s*\()' +beginpattern90 = re.compile( + beforethisafter % ('', groupbegins90, groupbegins90, '.*'), re.I), 'begin' +groupends = (r'end|endprogram|endblockdata|endmodule|endpythonmodule|' + r'endinterface|endsubroutine|endfunction') +endpattern = re.compile( + beforethisafter % ('', groupends, groupends, '.*'), re.I), 'end' +# block, the Fortran 2008 construct needs special handling in the rest of the file +endifs = r'end\s*(if|do|where|select|while|forall|associate|'\ + r'critical|enum|team)' +endifpattern = re.compile( + beforethisafter % (r'[\w]*?', endifs, endifs, '.*'), re.I), 'endif' +# +moduleprocedures = r'module\s*procedure' +moduleprocedurepattern = re.compile( + beforethisafter % ('', moduleprocedures, moduleprocedures, '.*'), re.I), \ + 'moduleprocedure' +implicitpattern = re.compile( + beforethisafter % ('', 'implicit', 'implicit', '.*'), re.I), 'implicit' +dimensionpattern = re.compile(beforethisafter % ( + '', 'dimension|virtual', 'dimension|virtual', '.*'), re.I), 'dimension' +externalpattern = re.compile( + beforethisafter % ('', 'external', 'external', '.*'), re.I), 'external' +optionalpattern = re.compile( + beforethisafter % ('', 'optional', 'optional', '.*'), re.I), 'optional' +requiredpattern = re.compile( + beforethisafter % ('', 'required', 'required', '.*'), re.I), 'required' +publicpattern = re.compile( + beforethisafter % ('', 'public', 'public', '.*'), re.I), 'public' +privatepattern = re.compile( + beforethisafter % ('', 'private', 'private', '.*'), re.I), 'private' +intrinsicpattern = re.compile( + beforethisafter % ('', 'intrinsic', 'intrinsic', '.*'), re.I), 'intrinsic' +intentpattern = re.compile(beforethisafter % ( + '', 'intent|depend|note|check', 'intent|depend|note|check', r'\s*\(.*?\).*'), re.I), 'intent' +parameterpattern = re.compile( + beforethisafter % ('', 'parameter', 'parameter', r'\s*\(.*'), re.I), 'parameter' +datapattern = re.compile( + beforethisafter % ('', 'data', 'data', '.*'), re.I), 'data' +callpattern = re.compile( + beforethisafter % ('', 'call', 'call', '.*'), re.I), 'call' +entrypattern = re.compile( + beforethisafter % ('', 'entry', 'entry', '.*'), re.I), 'entry' +callfunpattern = re.compile( + beforethisafter % ('', 'callfun', 'callfun', '.*'), re.I), 'callfun' +commonpattern = re.compile( + beforethisafter % ('', 'common', 'common', '.*'), re.I), 'common' +usepattern = re.compile( + beforethisafter % ('', 'use', 'use', '.*'), re.I), 'use' +containspattern = re.compile( + beforethisafter % ('', 'contains', 'contains', ''), re.I), 'contains' +formatpattern = re.compile( + beforethisafter % ('', 'format', 'format', '.*'), re.I), 'format' +# Non-fortran and f2py-specific statements +f2pyenhancementspattern = re.compile(beforethisafter % ('', 'threadsafe|fortranname|callstatement|callprotoargument|usercode|pymethoddef', + 'threadsafe|fortranname|callstatement|callprotoargument|usercode|pymethoddef', '.*'), re.I | re.S), 'f2pyenhancements' +multilinepattern = re.compile( + r"\s*(?P''')(?P.*?)(?P''')\s*\Z", re.S), 'multiline' +## + +def split_by_unquoted(line, characters): + """ + Splits the line into (line[:i], line[i:]), + where i is the index of first occurrence of one of the characters + not within quotes, or len(line) if no such index exists + """ + assert not (set('"\'') & set(characters)), "cannot split by unquoted quotes" + r = re.compile( + r"\A(?P({single_quoted}|{double_quoted}|{not_quoted})*)" + r"(?P{char}.*)\Z".format( + not_quoted=f"[^\"'{re.escape(characters)}]", + char=f"[{re.escape(characters)}]", + single_quoted=r"('([^'\\]|(\\.))*')", + double_quoted=r'("([^"\\]|(\\.))*")')) + m = r.match(line) + if m: + d = m.groupdict() + return (d["before"], d["after"]) + return (line, "") + +def _simplifyargs(argsline): + a = [] + for n in markoutercomma(argsline).split('@,@'): + for r in '(),': + n = n.replace(r, '_') + a.append(n) + return ','.join(a) + + +crackline_re_1 = re.compile(r'\s*(?P\b[a-z]+\w*\b)\s*=.*', re.I) +crackline_bind_1 = re.compile(r'\s*(?P\b[a-z]+\w*\b)\s*=.*', re.I) +crackline_bindlang = re.compile(r'\s*bind\(\s*(?P[^,]+)\s*,\s*name\s*=\s*"(?P[^"]+)"\s*\)', re.I) + +def crackline(line, reset=0): + """ + reset=-1 --- initialize + reset=0 --- crack the line + reset=1 --- final check if mismatch of blocks occurred + + Cracked data is saved in grouplist[0]. + """ + global beginpattern, groupcounter, groupname, groupcache, grouplist + global filepositiontext, currentfilename, neededmodule, expectbegin + global skipblocksuntil, skipemptyends, previous_context, gotnextfile + + _, has_semicolon = split_by_unquoted(line, ";") + if has_semicolon and not (f2pyenhancementspattern[0].match(line) or + multilinepattern[0].match(line)): + # XXX: non-zero reset values need testing + assert reset == 0, repr(reset) + # split line on unquoted semicolons + line, semicolon_line = split_by_unquoted(line, ";") + while semicolon_line: + crackline(line, reset) + line, semicolon_line = split_by_unquoted(semicolon_line[1:], ";") + crackline(line, reset) + return + if reset < 0: + groupcounter = 0 + groupname = {groupcounter: ''} + groupcache = {groupcounter: {}} + grouplist = {groupcounter: []} + groupcache[groupcounter]['body'] = [] + groupcache[groupcounter]['vars'] = {} + groupcache[groupcounter]['block'] = '' + groupcache[groupcounter]['name'] = '' + neededmodule = -1 + skipblocksuntil = -1 + return + if reset > 0: + fl = 0 + if f77modulename and neededmodule == groupcounter: + fl = 2 + while groupcounter > fl: + outmess('crackline: groupcounter=%s groupname=%s\n' % + (repr(groupcounter), repr(groupname))) + outmess( + 'crackline: Mismatch of blocks encountered. Trying to fix it by assuming "end" statement.\n') + grouplist[groupcounter - 1].append(groupcache[groupcounter]) + grouplist[groupcounter - 1][-1]['body'] = grouplist[groupcounter] + del grouplist[groupcounter] + groupcounter = groupcounter - 1 + if f77modulename and neededmodule == groupcounter: + grouplist[groupcounter - 1].append(groupcache[groupcounter]) + grouplist[groupcounter - 1][-1]['body'] = grouplist[groupcounter] + del grouplist[groupcounter] + groupcounter = groupcounter - 1 # end interface + grouplist[groupcounter - 1].append(groupcache[groupcounter]) + grouplist[groupcounter - 1][-1]['body'] = grouplist[groupcounter] + del grouplist[groupcounter] + groupcounter = groupcounter - 1 # end module + neededmodule = -1 + return + if line == '': + return + flag = 0 + for pat in [dimensionpattern, externalpattern, intentpattern, optionalpattern, + requiredpattern, + parameterpattern, datapattern, publicpattern, privatepattern, + intrinsicpattern, + endifpattern, endpattern, + formatpattern, + beginpattern, functionpattern, subroutinepattern, + implicitpattern, typespattern, commonpattern, + callpattern, usepattern, containspattern, + entrypattern, + f2pyenhancementspattern, + multilinepattern, + moduleprocedurepattern + ]: + m = pat[0].match(line) + if m: + break + flag = flag + 1 + if not m: + re_1 = crackline_re_1 + if 0 <= skipblocksuntil <= groupcounter: + return + if 'externals' in groupcache[groupcounter]: + for name in groupcache[groupcounter]['externals']: + if name in invbadnames: + name = invbadnames[name] + if 'interfaced' in groupcache[groupcounter] and name in groupcache[groupcounter]['interfaced']: + continue + m1 = re.match( + r'(?P[^"]*)\b%s\b\s*@\(@(?P[^@]*)@\)@.*\Z' % name, markouterparen(line), re.I) + if m1: + m2 = re_1.match(m1.group('before')) + a = _simplifyargs(m1.group('args')) + if m2: + line = f"callfun {name}({a}) result ({m2.group('result')})" + else: + line = f'callfun {name}({a})' + m = callfunpattern[0].match(line) + if not m: + outmess( + f'crackline: could not resolve function call for line={repr(line)}.\n') + return + analyzeline(m, 'callfun', line) + return + if verbose > 1 or (verbose == 1 and currentfilename.lower().endswith('.pyf')): + previous_context = None + outmess('crackline:%d: No pattern for line\n' % (groupcounter)) + return + elif pat[1] == 'end': + if 0 <= skipblocksuntil < groupcounter: + groupcounter = groupcounter - 1 + if skipblocksuntil <= groupcounter: + return + if groupcounter <= 0: + raise Exception('crackline: groupcounter(=%s) is nonpositive. ' + 'Check the blocks.' + % (groupcounter)) + m1 = beginpattern[0].match(line) + if (m1) and (not m1.group('this') == groupname[groupcounter]): + raise Exception('crackline: End group %s does not match with ' + 'previous Begin group %s\n\t%s' % + (repr(m1.group('this')), repr(groupname[groupcounter]), + filepositiontext) + ) + if skipblocksuntil == groupcounter: + skipblocksuntil = -1 + grouplist[groupcounter - 1].append(groupcache[groupcounter]) + grouplist[groupcounter - 1][-1]['body'] = grouplist[groupcounter] + del grouplist[groupcounter] + groupcounter = groupcounter - 1 + if not skipemptyends: + expectbegin = 1 + elif pat[1] == 'begin': + if 0 <= skipblocksuntil <= groupcounter: + groupcounter = groupcounter + 1 + return + gotnextfile = 0 + analyzeline(m, pat[1], line) + expectbegin = 0 + elif pat[1] == 'endif': + pass + elif pat[1] == 'moduleprocedure': + analyzeline(m, pat[1], line) + elif pat[1] == 'contains': + if ignorecontains: + return + if 0 <= skipblocksuntil <= groupcounter: + return + skipblocksuntil = groupcounter + else: + if 0 <= skipblocksuntil <= groupcounter: + return + analyzeline(m, pat[1], line) + + +def markouterparen(line): + l = '' + f = 0 + for c in line: + if c == '(': + f = f + 1 + if f == 1: + l = l + '@(@' + continue + elif c == ')': + f = f - 1 + if f == 0: + l = l + '@)@' + continue + l = l + c + return l + + +def markoutercomma(line, comma=','): + l = '' + f = 0 + before, after = split_by_unquoted(line, comma + '()') + l += before + while after: + if (after[0] == comma) and (f == 0): + l += '@' + comma + '@' + else: + l += after[0] + if after[0] == '(': + f += 1 + elif after[0] == ')': + f -= 1 + before, after = split_by_unquoted(after[1:], comma + '()') + l += before + assert not f, repr((f, line, l)) + return l + +def unmarkouterparen(line): + r = line.replace('@(@', '(').replace('@)@', ')') + return r + + +def appenddecl(decl, decl2, force=1): + if not decl: + decl = {} + if not decl2: + return decl + if decl is decl2: + return decl + for k in list(decl2.keys()): + if k == 'typespec': + if force or k not in decl: + decl[k] = decl2[k] + elif k == 'attrspec': + for l in decl2[k]: + decl = setattrspec(decl, l, force) + elif k == 'kindselector': + decl = setkindselector(decl, decl2[k], force) + elif k == 'charselector': + decl = setcharselector(decl, decl2[k], force) + elif k in ['=', 'typename']: + if force or k not in decl: + decl[k] = decl2[k] + elif k == 'note': + pass + elif k in ['intent', 'check', 'dimension', 'optional', + 'required', 'depend']: + errmess(f'appenddecl: "{k}" not implemented.\n') + else: + raise Exception('appenddecl: Unknown variable definition key: ' + + str(k)) + return decl + + +selectpattern = re.compile( + r'\s*(?P(@\(@.*?@\)@|\*[\d*]+|\*\s*@\(@.*?@\)@|))(?P.*)\Z', re.I) +typedefpattern = re.compile( + r'(?:,(?P[\w(),]+))?(::)?(?P\b[a-z$_][\w$]*\b)' + r'(?:\((?P[\w,]*)\))?\Z', re.I) +nameargspattern = re.compile( + r'\s*(?P\b[\w$]+\b)\s*(@\(@\s*(?P[\w\s,]*)\s*@\)@|)\s*((result(\s*@\(@\s*(?P\b[\w$]+\b)\s*@\)@|))|(bind\s*@\(@\s*(?P(?:(?!@\)@).)*)\s*@\)@))*\s*\Z', re.I) +operatorpattern = re.compile( + r'\s*(?P(operator|assignment))' + r'@\(@\s*(?P[^)]+)\s*@\)@\s*\Z', re.I) +callnameargspattern = re.compile( + r'\s*(?P\b[\w$]+\b)\s*@\(@\s*(?P.*)\s*@\)@\s*\Z', re.I) +real16pattern = re.compile( + r'([-+]?(?:\d+(?:\.\d*)?|\d*\.\d+))[dD]((?:[-+]?\d+)?)') +real8pattern = re.compile( + r'([-+]?((?:\d+(?:\.\d*)?|\d*\.\d+))[eE]((?:[-+]?\d+)?)|(\d+\.\d*))') + +_intentcallbackpattern = re.compile(r'intent\s*\(.*?\bcallback\b', re.I) + + +def _is_intent_callback(vdecl): + for a in vdecl.get('attrspec', []): + if _intentcallbackpattern.match(a): + return 1 + return 0 + + +def _resolvetypedefpattern(line): + line = ''.join(line.split()) # removes whitespace + m1 = typedefpattern.match(line) + print(line, m1) + if m1: + attrs = m1.group('attributes') + attrs = [a.lower() for a in attrs.split(',')] if attrs else [] + return m1.group('name'), attrs, m1.group('params') + return None, [], None + +def parse_name_for_bind(line): + pattern = re.compile(r'bind\(\s*(?P[^,]+)(?:\s*,\s*name\s*=\s*["\'](?P[^"\']+)["\']\s*)?\)', re.I) + match = pattern.search(line) + bind_statement = None + if match: + bind_statement = match.group(0) + # Remove the 'bind' construct from the line. + line = line[:match.start()] + line[match.end():] + return line, bind_statement + +def _resolvenameargspattern(line): + line, bind_cname = parse_name_for_bind(line) + line = markouterparen(line) + m1 = nameargspattern.match(line) + if m1: + return m1.group('name'), m1.group('args'), m1.group('result'), bind_cname + m1 = operatorpattern.match(line) + if m1: + name = m1.group('scheme') + '(' + m1.group('name') + ')' + return name, [], None, None + m1 = callnameargspattern.match(line) + if m1: + return m1.group('name'), m1.group('args'), None, None + return None, [], None, None + + +def analyzeline(m, case, line): + """ + Reads each line in the input file in sequence and updates global vars. + + Effectively reads and collects information from the input file to the + global variable groupcache, a dictionary containing info about each part + of the fortran module. + + At the end of analyzeline, information is filtered into the correct dict + keys, but parameter values and dimensions are not yet interpreted. + """ + global groupcounter, groupname, groupcache, grouplist, filepositiontext + global currentfilename, f77modulename, neededinterface, neededmodule + global expectbegin, gotnextfile, previous_context + + block = m.group('this') + if case != 'multiline': + previous_context = None + if expectbegin and case not in ['begin', 'call', 'callfun', 'type'] \ + and not skipemptyends and groupcounter < 1: + newname = os.path.basename(currentfilename).split('.')[0] + outmess( + f'analyzeline: no group yet. Creating program group with name "{newname}".\n') + gotnextfile = 0 + groupcounter = groupcounter + 1 + groupname[groupcounter] = 'program' + groupcache[groupcounter] = {} + grouplist[groupcounter] = [] + groupcache[groupcounter]['body'] = [] + groupcache[groupcounter]['vars'] = {} + groupcache[groupcounter]['block'] = 'program' + groupcache[groupcounter]['name'] = newname + groupcache[groupcounter]['from'] = 'fromsky' + expectbegin = 0 + if case in ['begin', 'call', 'callfun']: + # Crack line => block,name,args,result + block = block.lower() + if re.match(r'block\s*data', block, re.I): + block = 'block data' + elif re.match(r'python\s*module', block, re.I): + block = 'python module' + elif re.match(r'abstract\s*interface', block, re.I): + block = 'abstract interface' + if block == 'type': + name, attrs, _ = _resolvetypedefpattern(m.group('after')) + groupcache[groupcounter]['vars'][name] = {'attrspec': attrs} + args = [] + result = None + else: + name, args, result, bindcline = _resolvenameargspattern(m.group('after')) + if name is None: + if block == 'block data': + name = '_BLOCK_DATA_' + else: + name = '' + if block not in ['interface', 'block data', 'abstract interface']: + outmess('analyzeline: No name/args pattern found for line.\n') + + previous_context = (block, name, groupcounter) + if args: + args = rmbadname([x.strip() + for x in markoutercomma(args).split('@,@')]) + else: + args = [] + if '' in args: + while '' in args: + args.remove('') + outmess( + 'analyzeline: argument list is malformed (missing argument).\n') + + # end of crack line => block,name,args,result + needmodule = 0 + needinterface = 0 + + if case in ['call', 'callfun']: + needinterface = 1 + if 'args' not in groupcache[groupcounter]: + return + if name not in groupcache[groupcounter]['args']: + return + for it in grouplist[groupcounter]: + if it['name'] == name: + return + if name in groupcache[groupcounter]['interfaced']: + return + block = {'call': 'subroutine', 'callfun': 'function'}[case] + if f77modulename and neededmodule == -1 and groupcounter <= 1: + neededmodule = groupcounter + 2 + needmodule = 1 + if block not in ['interface', 'abstract interface']: + needinterface = 1 + # Create new block(s) + groupcounter = groupcounter + 1 + groupcache[groupcounter] = {} + grouplist[groupcounter] = [] + if needmodule: + if verbose > 1: + outmess('analyzeline: Creating module block %s\n' % + repr(f77modulename), 0) + groupname[groupcounter] = 'module' + groupcache[groupcounter]['block'] = 'python module' + groupcache[groupcounter]['name'] = f77modulename + groupcache[groupcounter]['from'] = '' + groupcache[groupcounter]['body'] = [] + groupcache[groupcounter]['externals'] = [] + groupcache[groupcounter]['interfaced'] = [] + groupcache[groupcounter]['vars'] = {} + groupcounter = groupcounter + 1 + groupcache[groupcounter] = {} + grouplist[groupcounter] = [] + if needinterface: + if verbose > 1: + outmess('analyzeline: Creating additional interface block (groupcounter=%s).\n' % ( + groupcounter), 0) + groupname[groupcounter] = 'interface' + groupcache[groupcounter]['block'] = 'interface' + groupcache[groupcounter]['name'] = 'unknown_interface' + groupcache[groupcounter]['from'] = '%s:%s' % ( + groupcache[groupcounter - 1]['from'], groupcache[groupcounter - 1]['name']) + groupcache[groupcounter]['body'] = [] + groupcache[groupcounter]['externals'] = [] + groupcache[groupcounter]['interfaced'] = [] + groupcache[groupcounter]['vars'] = {} + groupcounter = groupcounter + 1 + groupcache[groupcounter] = {} + grouplist[groupcounter] = [] + groupname[groupcounter] = block + groupcache[groupcounter]['block'] = block + if not name: + name = 'unknown_' + block.replace(' ', '_') + groupcache[groupcounter]['prefix'] = m.group('before') + groupcache[groupcounter]['name'] = rmbadname1(name) + groupcache[groupcounter]['result'] = result + if groupcounter == 1: + groupcache[groupcounter]['from'] = currentfilename + elif f77modulename and groupcounter == 3: + groupcache[groupcounter]['from'] = '%s:%s' % ( + groupcache[groupcounter - 1]['from'], currentfilename) + else: + groupcache[groupcounter]['from'] = '%s:%s' % ( + groupcache[groupcounter - 1]['from'], groupcache[groupcounter - 1]['name']) + for k in list(groupcache[groupcounter].keys()): + if not groupcache[groupcounter][k]: + del groupcache[groupcounter][k] + + groupcache[groupcounter]['args'] = args + groupcache[groupcounter]['body'] = [] + groupcache[groupcounter]['externals'] = [] + groupcache[groupcounter]['interfaced'] = [] + groupcache[groupcounter]['vars'] = {} + groupcache[groupcounter]['entry'] = {} + # end of creation + if block == 'type': + groupcache[groupcounter]['varnames'] = [] + + if case in ['call', 'callfun']: # set parents variables + if name not in groupcache[groupcounter - 2]['externals']: + groupcache[groupcounter - 2]['externals'].append(name) + groupcache[groupcounter]['vars'] = copy.deepcopy( + groupcache[groupcounter - 2]['vars']) + try: + del groupcache[groupcounter]['vars'][name][ + groupcache[groupcounter]['vars'][name]['attrspec'].index('external')] + except Exception: + pass + if block in ['function', 'subroutine']: # set global attributes + # name is fortran name + if bindcline: + bindcdat = re.search(crackline_bindlang, bindcline) + if bindcdat: + groupcache[groupcounter]['bindlang'] = {name: {}} + groupcache[groupcounter]['bindlang'][name]["lang"] = bindcdat.group('lang') + if bindcdat.group('lang_name'): + groupcache[groupcounter]['bindlang'][name]["name"] = bindcdat.group('lang_name') + try: + groupcache[groupcounter]['vars'][name] = appenddecl( + groupcache[groupcounter]['vars'][name], groupcache[groupcounter - 2]['vars']['']) + except Exception: + pass + if case == 'callfun': # return type + if result and result in groupcache[groupcounter]['vars']: + if not name == result: + groupcache[groupcounter]['vars'][name] = appenddecl( + groupcache[groupcounter]['vars'][name], groupcache[groupcounter]['vars'][result]) + # if groupcounter>1: # name is interfaced + try: + groupcache[groupcounter - 2]['interfaced'].append(name) + except Exception: + pass + if block == 'function': + t = typespattern[0].match(m.group('before') + ' ' + name) + if t: + typespec, selector, attr, edecl = cracktypespec0( + t.group('this'), t.group('after')) + updatevars(typespec, selector, attr, edecl) + + if case in ['call', 'callfun']: + grouplist[groupcounter - 1].append(groupcache[groupcounter]) + grouplist[groupcounter - 1][-1]['body'] = grouplist[groupcounter] + del grouplist[groupcounter] + groupcounter = groupcounter - 1 # end routine + grouplist[groupcounter - 1].append(groupcache[groupcounter]) + grouplist[groupcounter - 1][-1]['body'] = grouplist[groupcounter] + del grouplist[groupcounter] + groupcounter = groupcounter - 1 # end interface + + elif case == 'entry': + name, args, result, _ = _resolvenameargspattern(m.group('after')) + if name is not None: + if args: + args = rmbadname([x.strip() + for x in markoutercomma(args).split('@,@')]) + else: + args = [] + assert result is None, repr(result) + groupcache[groupcounter]['entry'][name] = args + previous_context = ('entry', name, groupcounter) + elif case == 'type': + typespec, selector, attr, edecl = cracktypespec0( + block, m.group('after')) + last_name = updatevars(typespec, selector, attr, edecl) + if last_name is not None: + previous_context = ('variable', last_name, groupcounter) + elif case in ['dimension', 'intent', 'optional', 'required', 'external', 'public', 'private', 'intrinsic']: + edecl = groupcache[groupcounter]['vars'] + ll = m.group('after').strip() + i = ll.find('::') + if i < 0 and case == 'intent': + i = markouterparen(ll).find('@)@') - 2 + ll = ll[:i + 1] + '::' + ll[i + 1:] + i = ll.find('::') + if ll[i:] == '::' and 'args' in groupcache[groupcounter]: + outmess('All arguments will have attribute %s%s\n' % + (m.group('this'), ll[:i])) + ll = ll + ','.join(groupcache[groupcounter]['args']) + if i < 0: + i = 0 + pl = '' + else: + pl = ll[:i].strip() + ll = ll[i + 2:] + ch = markoutercomma(pl).split('@,@') + if len(ch) > 1: + pl = ch[0] + outmess('analyzeline: cannot handle multiple attributes without type specification. Ignoring %r.\n' % ( + ','.join(ch[1:]))) + last_name = None + + for e in [x.strip() for x in markoutercomma(ll).split('@,@')]: + m1 = namepattern.match(e) + if not m1: + if case in ['public', 'private']: + k = '' + else: + print(m.groupdict()) + outmess('analyzeline: no name pattern found in %s statement for %s. Skipping.\n' % ( + case, repr(e))) + continue + else: + k = rmbadname1(m1.group('name')) + if case in ['public', 'private'] and k in {'operator', 'assignment'}: + k += m1.group('after') + if k not in edecl: + edecl[k] = {} + if case == 'dimension': + ap = case + m1.group('after') + if case == 'intent': + ap = m.group('this') + pl + if _intentcallbackpattern.match(ap): + if k not in groupcache[groupcounter]['args']: + if groupcounter > 1: + if '__user__' not in groupcache[groupcounter - 2]['name']: + outmess( + 'analyzeline: missing __user__ module (could be nothing)\n') + # fixes ticket 1693 + if k != groupcache[groupcounter]['name']: + outmess('analyzeline: appending intent(callback) %s' + ' to %s arguments\n' % (k, groupcache[groupcounter]['name'])) + groupcache[groupcounter]['args'].append(k) + else: + errmess( + f'analyzeline: intent(callback) {k} is ignored\n') + else: + errmess('analyzeline: intent(callback) %s is already' + ' in argument list\n' % (k)) + if case in ['optional', 'required', 'public', 'external', 'private', 'intrinsic']: + ap = case + if 'attrspec' in edecl[k]: + edecl[k]['attrspec'].append(ap) + else: + edecl[k]['attrspec'] = [ap] + if case == 'external': + if groupcache[groupcounter]['block'] == 'program': + outmess('analyzeline: ignoring program arguments\n') + continue + if k not in groupcache[groupcounter]['args']: + continue + if 'externals' not in groupcache[groupcounter]: + groupcache[groupcounter]['externals'] = [] + groupcache[groupcounter]['externals'].append(k) + last_name = k + groupcache[groupcounter]['vars'] = edecl + if last_name is not None: + previous_context = ('variable', last_name, groupcounter) + elif case == 'moduleprocedure': + groupcache[groupcounter]['implementedby'] = \ + [x.strip() for x in m.group('after').split(',')] + elif case == 'parameter': + edecl = groupcache[groupcounter]['vars'] + ll = m.group('after').strip()[1:-1] + last_name = None + for e in markoutercomma(ll).split('@,@'): + try: + k, initexpr = [x.strip() for x in e.split('=')] + except Exception: + outmess( + f'analyzeline: could not extract name,expr in parameter statement "{e}" of "{ll}\"\n') + continue + params = get_parameters(edecl) + k = rmbadname1(k) + if k not in edecl: + edecl[k] = {} + if '=' in edecl[k] and (not edecl[k]['='] == initexpr): + outmess('analyzeline: Overwriting the value of parameter "%s" ("%s") with "%s".\n' % ( + k, edecl[k]['='], initexpr)) + t = determineexprtype(initexpr, params) + if t: + if t.get('typespec') == 'real': + tt = list(initexpr) + for m in real16pattern.finditer(initexpr): + tt[m.start():m.end()] = list( + initexpr[m.start():m.end()].lower().replace('d', 'e')) + initexpr = ''.join(tt) + elif t.get('typespec') == 'complex': + initexpr = initexpr[1:].lower().replace('d', 'e').\ + replace(',', '+1j*(') + try: + v = eval(initexpr, {}, params) + except (SyntaxError, NameError, TypeError) as msg: + errmess('analyzeline: Failed to evaluate %r. Ignoring: %s\n' + % (initexpr, msg)) + continue + edecl[k]['='] = repr(v) + if 'attrspec' in edecl[k]: + edecl[k]['attrspec'].append('parameter') + else: + edecl[k]['attrspec'] = ['parameter'] + last_name = k + groupcache[groupcounter]['vars'] = edecl + if last_name is not None: + previous_context = ('variable', last_name, groupcounter) + elif case == 'implicit': + if m.group('after').strip().lower() == 'none': + groupcache[groupcounter]['implicit'] = None + elif m.group('after'): + impl = groupcache[groupcounter].get('implicit', {}) + if impl is None: + outmess( + 'analyzeline: Overwriting earlier "implicit none" statement.\n') + impl = {} + for e in markoutercomma(m.group('after')).split('@,@'): + decl = {} + m1 = re.match( + r'\s*(?P.*?)\s*(\(\s*(?P[a-z-, ]+)\s*\)\s*|)\Z', e, re.I) + if not m1: + outmess( + f'analyzeline: could not extract info of implicit statement part "{e}\"\n') + continue + m2 = typespattern4implicit.match(m1.group('this')) + if not m2: + outmess( + f'analyzeline: could not extract types pattern of implicit statement part "{e}\"\n') + continue + typespec, selector, attr, edecl = cracktypespec0( + m2.group('this'), m2.group('after')) + kindselect, charselect, typename = cracktypespec( + typespec, selector) + decl['typespec'] = typespec + decl['kindselector'] = kindselect + decl['charselector'] = charselect + decl['typename'] = typename + for k in list(decl.keys()): + if not decl[k]: + del decl[k] + for r in markoutercomma(m1.group('after')).split('@,@'): + if '-' in r: + try: + begc, endc = [x.strip() for x in r.split('-')] + except Exception: + outmess( + f'analyzeline: expected "-" instead of "{r}" in range list of implicit statement\n') + continue + else: + begc = endc = r.strip() + if not len(begc) == len(endc) == 1: + outmess( + f'analyzeline: expected "-" instead of "{r}" in range list of implicit statement (2)\n') + continue + for o in range(ord(begc), ord(endc) + 1): + impl[chr(o)] = decl + groupcache[groupcounter]['implicit'] = impl + elif case == 'data': + ll = [] + dl = '' + il = '' + f = 0 + fc = 1 + inp = 0 + for c in m.group('after'): + if not inp: + if c == "'": + fc = not fc + if c == '/' and fc: + f = f + 1 + continue + if c == '(': + inp = inp + 1 + elif c == ')': + inp = inp - 1 + if f == 0: + dl = dl + c + elif f == 1: + il = il + c + elif f == 2: + dl = dl.strip() + if dl.startswith(','): + dl = dl[1:].strip() + ll.append([dl, il]) + dl = c + il = '' + f = 0 + if f == 2: + dl = dl.strip() + if dl.startswith(','): + dl = dl[1:].strip() + ll.append([dl, il]) + vars = groupcache[groupcounter].get('vars', {}) + last_name = None + for l in ll: + l[0], l[1] = l[0].strip().removeprefix(','), l[1].strip() + if l[0].startswith('('): + outmess(f'analyzeline: implied-DO list "{l[0]}" is not supported. Skipping.\n') + continue + for idx, v in enumerate(rmbadname([x.strip() for x in markoutercomma(l[0]).split('@,@')])): + if v.startswith('('): + outmess(f'analyzeline: implied-DO list "{v}" is not supported. Skipping.\n') + # XXX: subsequent init expressions may get wrong values. + # Ignoring since data statements are irrelevant for + # wrapping. + continue + if '!' in l[1]: + # Fixes gh-24746 pyf generation + # XXX: This essentially ignores the value for generating the pyf which is fine: + # integer dimension(3) :: mytab + # common /mycom/ mytab + # Since in any case it is initialized in the Fortran code + outmess(f'Comment line in declaration "{l[1]}" is not supported. Skipping.\n') + continue + vars.setdefault(v, {}) + vtype = vars[v].get('typespec') + vdim = getdimension(vars[v]) + matches = re.findall(r"\(.*?\)", l[1]) if vtype == 'complex' else l[1].split(',') + try: + new_val = f"(/{', '.join(matches)}/)" if vdim else matches[idx] + except IndexError: + # gh-24746 + # Runs only if above code fails. Fixes the line + # DATA IVAR1, IVAR2, IVAR3, IVAR4, EVAR5 /4*0,0.0D0/ + # by expanding to ['0', '0', '0', '0', '0.0d0'] + if any("*" in m for m in matches): + expanded_list = [] + for match in matches: + if "*" in match: + try: + multiplier, value = match.split("*") + expanded_list.extend([value.strip()] * int(multiplier)) + except ValueError: # if int(multiplier) fails + expanded_list.append(match.strip()) + else: + expanded_list.append(match.strip()) + matches = expanded_list + new_val = f"(/{', '.join(matches)}/)" if vdim else matches[idx] + current_val = vars[v].get('=') + if current_val and (current_val != new_val): + outmess(f'analyzeline: changing init expression of "{v}" ("{current_val}") to "{new_val}\"\n') + vars[v]['='] = new_val + last_name = v + groupcache[groupcounter]['vars'] = vars + if last_name: + previous_context = ('variable', last_name, groupcounter) + elif case == 'common': + line = m.group('after').strip() + if not line[0] == '/': + line = '//' + line + + cl = [] + [_, bn, ol] = re.split('/', line, maxsplit=2) # noqa: RUF039 + bn = bn.strip() + if not bn: + bn = '_BLNK_' + cl.append([bn, ol]) + commonkey = {} + if 'common' in groupcache[groupcounter]: + commonkey = groupcache[groupcounter]['common'] + for c in cl: + if c[0] not in commonkey: + commonkey[c[0]] = [] + for i in [x.strip() for x in markoutercomma(c[1]).split('@,@')]: + if i: + commonkey[c[0]].append(i) + groupcache[groupcounter]['common'] = commonkey + previous_context = ('common', bn, groupcounter) + elif case == 'use': + m1 = re.match( + r'\A\s*(?P\b\w+\b)\s*((,(\s*\bonly\b\s*:|(?P))\s*(?P.*))|)\s*\Z', m.group('after'), re.I) + if m1: + mm = m1.groupdict() + if 'use' not in groupcache[groupcounter]: + groupcache[groupcounter]['use'] = {} + name = m1.group('name') + groupcache[groupcounter]['use'][name] = {} + isonly = 0 + if 'list' in mm and mm['list'] is not None: + if 'notonly' in mm and mm['notonly'] is None: + isonly = 1 + groupcache[groupcounter]['use'][name]['only'] = isonly + ll = [x.strip() for x in mm['list'].split(',')] + rl = {} + for l in ll: + if '=' in l: + m2 = re.match( + r'\A\s*(?P\b\w+\b)\s*=\s*>\s*(?P\b\w+\b)\s*\Z', l, re.I) + if m2: + rl[m2.group('local').strip()] = m2.group( + 'use').strip() + else: + outmess( + f'analyzeline: Not local=>use pattern found in {repr(l)}\n') + else: + rl[l] = l + groupcache[groupcounter]['use'][name]['map'] = rl + else: + print(m.groupdict()) + outmess('analyzeline: Could not crack the use statement.\n') + elif case in ['f2pyenhancements']: + if 'f2pyenhancements' not in groupcache[groupcounter]: + groupcache[groupcounter]['f2pyenhancements'] = {} + d = groupcache[groupcounter]['f2pyenhancements'] + if m.group('this') == 'usercode' and 'usercode' in d: + if isinstance(d['usercode'], str): + d['usercode'] = [d['usercode']] + d['usercode'].append(m.group('after')) + else: + d[m.group('this')] = m.group('after') + elif case == 'multiline': + if previous_context is None: + if verbose: + outmess('analyzeline: No context for multiline block.\n') + return + gc = groupcounter + appendmultiline(groupcache[gc], + previous_context[:2], + m.group('this')) + elif verbose > 1: + print(m.groupdict()) + outmess('analyzeline: No code implemented for line.\n') + + +def appendmultiline(group, context_name, ml): + if 'f2pymultilines' not in group: + group['f2pymultilines'] = {} + d = group['f2pymultilines'] + if context_name not in d: + d[context_name] = [] + d[context_name].append(ml) + + +def cracktypespec0(typespec, ll): + selector = None + attr = None + if re.match(r'double\s*complex', typespec, re.I): + typespec = 'double complex' + elif re.match(r'double\s*precision', typespec, re.I): + typespec = 'double precision' + else: + typespec = typespec.strip().lower() + m1 = selectpattern.match(markouterparen(ll)) + if not m1: + outmess( + 'cracktypespec0: no kind/char_selector pattern found for line.\n') + return + d = m1.groupdict() + for k in list(d.keys()): + d[k] = unmarkouterparen(d[k]) + if typespec in ['complex', 'integer', 'logical', 'real', 'character', 'type']: + selector = d['this'] + ll = d['after'] + i = ll.find('::') + if i >= 0: + attr = ll[:i].strip() + ll = ll[i + 2:] + return typespec, selector, attr, ll + + +##### +namepattern = re.compile(r'\s*(?P\b\w+\b)\s*(?P.*)\s*\Z', re.I) +kindselector = re.compile( + r'\s*(\(\s*(kind\s*=)?\s*(?P.*)\s*\)|\*\s*(?P.*?))\s*\Z', re.I) +charselector = re.compile( + r'\s*(\((?P.*)\)|\*\s*(?P.*))\s*\Z', re.I) +lenkindpattern = re.compile( + r'\s*(kind\s*=\s*(?P.*?)\s*(@,@\s*len\s*=\s*(?P.*)|)' + r'|(len\s*=\s*|)(?P.*?)\s*(@,@\s*(kind\s*=\s*|)(?P.*)' + r'|(f2py_len\s*=\s*(?P.*))|))\s*\Z', re.I) +lenarraypattern = re.compile( + r'\s*(@\(@\s*(?!/)\s*(?P.*?)\s*@\)@\s*\*\s*(?P.*?)|(\*\s*(?P.*?)|)\s*(@\(@\s*(?!/)\s*(?P.*?)\s*@\)@|))\s*(=\s*(?P.*?)|(@\(@|)/\s*(?P.*?)\s*/(@\)@|)|)\s*\Z', re.I) + + +def removespaces(expr): + expr = expr.strip() + if len(expr) <= 1: + return expr + expr2 = expr[0] + for i in range(1, len(expr) - 1): + if (expr[i] == ' ' and + ((expr[i + 1] in "()[]{}=+-/* ") or + (expr[i - 1] in "()[]{}=+-/* "))): + continue + expr2 = expr2 + expr[i] + expr2 = expr2 + expr[-1] + return expr2 + + +def markinnerspaces(line): + """ + The function replace all spaces in the input variable line which are + surrounded with quotation marks, with the triplet "@_@". + + For instance, for the input "a 'b c'" the function returns "a 'b@_@c'" + + Parameters + ---------- + line : str + + Returns + ------- + str + + """ + fragment = '' + inside = False + current_quote = None + escaped = '' + for c in line: + if escaped == '\\' and c in ['\\', '\'', '"']: + fragment += c + escaped = c + continue + if not inside and c in ['\'', '"']: + current_quote = c + if c == current_quote: + inside = not inside + elif c == ' ' and inside: + fragment += '@_@' + continue + fragment += c + escaped = c # reset to non-backslash + return fragment + + +def updatevars(typespec, selector, attrspec, entitydecl): + """ + Returns last_name, the variable name without special chars, parenthesis + or dimension specifiers. + + Alters groupcache to add the name, typespec, attrspec (and possibly value) + of current variable. + """ + global groupcache, groupcounter + + last_name = None + kindselect, charselect, typename = cracktypespec(typespec, selector) + # Clean up outer commas, whitespace and undesired chars from attrspec + if attrspec: + attrspec = [x.strip() for x in markoutercomma(attrspec).split('@,@')] + l = [] + c = re.compile(r'(?P[a-zA-Z]+)') + for a in attrspec: + if not a: + continue + m = c.match(a) + if m: + s = m.group('start').lower() + a = s + a[len(s):] + l.append(a) + attrspec = l + el = [x.strip() for x in markoutercomma(entitydecl).split('@,@')] + el1 = [] + for e in el: + for e1 in [x.strip() for x in markoutercomma(removespaces(markinnerspaces(e)), comma=' ').split('@ @')]: + if e1: + el1.append(e1.replace('@_@', ' ')) + for e in el1: + m = namepattern.match(e) + if not m: + outmess( + f'updatevars: no name pattern found for entity={repr(e)}. Skipping.\n') + continue + ename = rmbadname1(m.group('name')) + edecl = {} + if ename in groupcache[groupcounter]['vars']: + edecl = groupcache[groupcounter]['vars'][ename].copy() + not_has_typespec = 'typespec' not in edecl + if not_has_typespec: + edecl['typespec'] = typespec + elif typespec and (not typespec == edecl['typespec']): + outmess('updatevars: attempt to change the type of "%s" ("%s") to "%s". Ignoring.\n' % ( + ename, edecl['typespec'], typespec)) + if 'kindselector' not in edecl: + edecl['kindselector'] = copy.copy(kindselect) + elif kindselect: + for k in list(kindselect.keys()): + if k in edecl['kindselector'] and (not kindselect[k] == edecl['kindselector'][k]): + outmess('updatevars: attempt to change the kindselector "%s" of "%s" ("%s") to "%s". Ignoring.\n' % ( + k, ename, edecl['kindselector'][k], kindselect[k])) + else: + edecl['kindselector'][k] = copy.copy(kindselect[k]) + if 'charselector' not in edecl and charselect: + if not_has_typespec: + edecl['charselector'] = charselect + else: + errmess('updatevars:%s: attempt to change empty charselector to %r. Ignoring.\n' + % (ename, charselect)) + elif charselect: + for k in list(charselect.keys()): + if k in edecl['charselector'] and (not charselect[k] == edecl['charselector'][k]): + outmess('updatevars: attempt to change the charselector "%s" of "%s" ("%s") to "%s". Ignoring.\n' % ( + k, ename, edecl['charselector'][k], charselect[k])) + else: + edecl['charselector'][k] = copy.copy(charselect[k]) + if 'typename' not in edecl: + edecl['typename'] = typename + elif typename and (not edecl['typename'] == typename): + outmess('updatevars: attempt to change the typename of "%s" ("%s") to "%s". Ignoring.\n' % ( + ename, edecl['typename'], typename)) + if 'attrspec' not in edecl: + edecl['attrspec'] = copy.copy(attrspec) + elif attrspec: + for a in attrspec: + if a not in edecl['attrspec']: + edecl['attrspec'].append(a) + else: + edecl['typespec'] = copy.copy(typespec) + edecl['kindselector'] = copy.copy(kindselect) + edecl['charselector'] = copy.copy(charselect) + edecl['typename'] = typename + edecl['attrspec'] = copy.copy(attrspec) + if 'external' in (edecl.get('attrspec') or []) and e in groupcache[groupcounter]['args']: + if 'externals' not in groupcache[groupcounter]: + groupcache[groupcounter]['externals'] = [] + groupcache[groupcounter]['externals'].append(e) + if m.group('after'): + m1 = lenarraypattern.match(markouterparen(m.group('after'))) + if m1: + d1 = m1.groupdict() + for lk in ['len', 'array', 'init']: + if d1[lk + '2'] is not None: + d1[lk] = d1[lk + '2'] + del d1[lk + '2'] + for k in list(d1.keys()): + if d1[k] is not None: + d1[k] = unmarkouterparen(d1[k]) + else: + del d1[k] + + if 'len' in d1 and 'array' in d1: + if d1['len'] == '': + d1['len'] = d1['array'] + del d1['array'] + elif typespec == 'character': + if ('charselector' not in edecl) or (not edecl['charselector']): + edecl['charselector'] = {} + if 'len' in edecl['charselector']: + del edecl['charselector']['len'] + edecl['charselector']['*'] = d1['len'] + del d1['len'] + else: + d1['array'] = d1['array'] + ',' + d1['len'] + del d1['len'] + errmess('updatevars: "%s %s" is mapped to "%s %s(%s)"\n' % ( + typespec, e, typespec, ename, d1['array'])) + + if 'len' in d1: + if typespec in ['complex', 'integer', 'logical', 'real']: + if ('kindselector' not in edecl) or (not edecl['kindselector']): + edecl['kindselector'] = {} + edecl['kindselector']['*'] = d1['len'] + del d1['len'] + elif typespec == 'character': + if ('charselector' not in edecl) or (not edecl['charselector']): + edecl['charselector'] = {} + if 'len' in edecl['charselector']: + del edecl['charselector']['len'] + edecl['charselector']['*'] = d1['len'] + del d1['len'] + + if 'init' in d1: + if '=' in edecl and (not edecl['='] == d1['init']): + outmess('updatevars: attempt to change the init expression of "%s" ("%s") to "%s". Ignoring.\n' % ( + ename, edecl['='], d1['init'])) + else: + edecl['='] = d1['init'] + + if 'array' in d1: + dm = f"dimension({d1['array']})" + if 'attrspec' not in edecl or (not edecl['attrspec']): + edecl['attrspec'] = [dm] + else: + edecl['attrspec'].append(dm) + for dm1 in edecl['attrspec']: + if dm1[:9] == 'dimension' and dm1 != dm: + del edecl['attrspec'][-1] + errmess('updatevars:%s: attempt to change %r to %r. Ignoring.\n' + % (ename, dm1, dm)) + break + + else: + outmess('updatevars: could not crack entity declaration "%s". Ignoring.\n' % ( + ename + m.group('after'))) + for k in list(edecl.keys()): + if not edecl[k]: + del edecl[k] + groupcache[groupcounter]['vars'][ename] = edecl + if 'varnames' in groupcache[groupcounter]: + groupcache[groupcounter]['varnames'].append(ename) + last_name = ename + return last_name + + +def cracktypespec(typespec, selector): + kindselect = None + charselect = None + typename = None + if selector: + if typespec in ['complex', 'integer', 'logical', 'real']: + kindselect = kindselector.match(selector) + if not kindselect: + outmess( + f'cracktypespec: no kindselector pattern found for {repr(selector)}\n') + return + kindselect = kindselect.groupdict() + kindselect['*'] = kindselect['kind2'] + del kindselect['kind2'] + for k in list(kindselect.keys()): + if not kindselect[k]: + del kindselect[k] + for k, i in list(kindselect.items()): + kindselect[k] = rmbadname1(i) + elif typespec == 'character': + charselect = charselector.match(selector) + if not charselect: + outmess( + f'cracktypespec: no charselector pattern found for {repr(selector)}\n') + return + charselect = charselect.groupdict() + charselect['*'] = charselect['charlen'] + del charselect['charlen'] + if charselect['lenkind']: + lenkind = lenkindpattern.match( + markoutercomma(charselect['lenkind'])) + lenkind = lenkind.groupdict() + for lk in ['len', 'kind']: + if lenkind[lk + '2']: + lenkind[lk] = lenkind[lk + '2'] + charselect[lk] = lenkind[lk] + del lenkind[lk + '2'] + if lenkind['f2py_len'] is not None: + # used to specify the length of assumed length strings + charselect['f2py_len'] = lenkind['f2py_len'] + del charselect['lenkind'] + for k in list(charselect.keys()): + if not charselect[k]: + del charselect[k] + for k, i in list(charselect.items()): + charselect[k] = rmbadname1(i) + elif typespec == 'type': + typename = re.match(r'\s*\(\s*(?P\w+)\s*\)', selector, re.I) + if typename: + typename = typename.group('name') + else: + outmess('cracktypespec: no typename found in %s\n' % + (repr(typespec + selector))) + else: + outmess(f'cracktypespec: no selector used for {repr(selector)}\n') + return kindselect, charselect, typename +###### + + +def setattrspec(decl, attr, force=0): + if not decl: + decl = {} + if not attr: + return decl + if 'attrspec' not in decl: + decl['attrspec'] = [attr] + return decl + if force: + decl['attrspec'].append(attr) + if attr in decl['attrspec']: + return decl + if attr == 'static' and 'automatic' not in decl['attrspec']: + decl['attrspec'].append(attr) + elif attr == 'automatic' and 'static' not in decl['attrspec']: + decl['attrspec'].append(attr) + elif attr == 'public': + if 'private' not in decl['attrspec']: + decl['attrspec'].append(attr) + elif attr == 'private': + if 'public' not in decl['attrspec']: + decl['attrspec'].append(attr) + else: + decl['attrspec'].append(attr) + return decl + + +def setkindselector(decl, sel, force=0): + if not decl: + decl = {} + if not sel: + return decl + if 'kindselector' not in decl: + decl['kindselector'] = sel + return decl + for k in list(sel.keys()): + if force or k not in decl['kindselector']: + decl['kindselector'][k] = sel[k] + return decl + + +def setcharselector(decl, sel, force=0): + if not decl: + decl = {} + if not sel: + return decl + if 'charselector' not in decl: + decl['charselector'] = sel + return decl + + for k in list(sel.keys()): + if force or k not in decl['charselector']: + decl['charselector'][k] = sel[k] + return decl + + +def getblockname(block, unknown='unknown'): + if 'name' in block: + return block['name'] + return unknown + +# post processing + + +def setmesstext(block): + global filepositiontext + + try: + filepositiontext = f"In: {block['from']}:{block['name']}\n" + except Exception: + pass + + +def get_usedict(block): + usedict = {} + if 'parent_block' in block: + usedict = get_usedict(block['parent_block']) + if 'use' in block: + usedict.update(block['use']) + return usedict + + +def get_useparameters(block, param_map=None): + global f90modulevars + + if param_map is None: + param_map = {} + usedict = get_usedict(block) + if not usedict: + return param_map + for usename, mapping in list(usedict.items()): + usename = usename.lower() + if usename not in f90modulevars: + outmess('get_useparameters: no module %s info used by %s\n' % + (usename, block.get('name'))) + continue + mvars = f90modulevars[usename] + params = get_parameters(mvars) + if not params: + continue + # XXX: apply mapping + if mapping: + errmess(f'get_useparameters: mapping for {mapping} not impl.\n') + for k, v in list(params.items()): + if k in param_map: + outmess('get_useparameters: overriding parameter %s with' + ' value from module %s\n' % (repr(k), repr(usename))) + param_map[k] = v + + return param_map + + +def postcrack2(block, tab='', param_map=None): + global f90modulevars + + if not f90modulevars: + return block + if isinstance(block, list): + ret = [postcrack2(g, tab=tab + '\t', param_map=param_map) + for g in block] + return ret + setmesstext(block) + outmess(f"{tab}Block: {block['name']}\n", 0) + + if param_map is None: + param_map = get_useparameters(block) + + if param_map is not None and 'vars' in block: + vars = block['vars'] + for n in list(vars.keys()): + var = vars[n] + if 'kindselector' in var: + kind = var['kindselector'] + if 'kind' in kind: + val = kind['kind'] + if val in param_map: + kind['kind'] = param_map[val] + new_body = [postcrack2(b, tab=tab + '\t', param_map=param_map) + for b in block['body']] + block['body'] = new_body + + return block + + +def postcrack(block, args=None, tab=''): + """ + TODO: + function return values + determine expression types if in argument list + """ + global usermodules, onlyfunctions + + if isinstance(block, list): + gret = [] + uret = [] + for g in block: + setmesstext(g) + g = postcrack(g, tab=tab + '\t') + # sort user routines to appear first + if 'name' in g and '__user__' in g['name']: + uret.append(g) + else: + gret.append(g) + return uret + gret + setmesstext(block) + if not isinstance(block, dict) and 'block' not in block: + raise Exception('postcrack: Expected block dictionary instead of ' + + str(block)) + if 'name' in block and not block['name'] == 'unknown_interface': + outmess(f"{tab}Block: {block['name']}\n", 0) + block = analyzeargs(block) + block = analyzecommon(block) + block['vars'] = analyzevars(block) + block['sortvars'] = sortvarnames(block['vars']) + if block.get('args'): + args = block['args'] + block['body'] = analyzebody(block, args, tab=tab) + + userisdefined = [] + if 'use' in block: + useblock = block['use'] + for k in list(useblock.keys()): + if '__user__' in k: + userisdefined.append(k) + else: + useblock = {} + name = '' + if 'name' in block: + name = block['name'] + # and not userisdefined: # Build a __user__ module + if block.get('externals'): + interfaced = [] + if 'interfaced' in block: + interfaced = block['interfaced'] + mvars = copy.copy(block['vars']) + if name: + mname = name + '__user__routines' + else: + mname = 'unknown__user__routines' + if mname in userisdefined: + i = 1 + while f"{mname}_{i}" in userisdefined: + i = i + 1 + mname = f"{mname}_{i}" + interface = {'block': 'interface', 'body': [], + 'vars': {}, 'name': name + '_user_interface'} + for e in block['externals']: + if e in interfaced: + edef = [] + j = -1 + for b in block['body']: + j = j + 1 + if b['block'] == 'interface': + i = -1 + for bb in b['body']: + i = i + 1 + if 'name' in bb and bb['name'] == e: + edef = copy.copy(bb) + del b['body'][i] + break + if edef: + if not b['body']: + del block['body'][j] + del interfaced[interfaced.index(e)] + break + interface['body'].append(edef) + elif e in mvars and not isexternal(mvars[e]): + interface['vars'][e] = mvars[e] + if interface['vars'] or interface['body']: + block['interfaced'] = interfaced + mblock = {'block': 'python module', 'body': [ + interface], 'vars': {}, 'name': mname, 'interfaced': block['externals']} + useblock[mname] = {} + usermodules.append(mblock) + if useblock: + block['use'] = useblock + return block + + +def sortvarnames(vars): + indep = [] + dep = [] + for v in list(vars.keys()): + if 'depend' in vars[v] and vars[v]['depend']: + dep.append(v) + else: + indep.append(v) + n = len(dep) + i = 0 + while dep: # XXX: How to catch dependence cycles correctly? + v = dep[0] + fl = 0 + for w in dep[1:]: + if w in vars[v]['depend']: + fl = 1 + break + if fl: + dep = dep[1:] + [v] + i = i + 1 + if i > n: + errmess('sortvarnames: failed to compute dependencies because' + ' of cyclic dependencies between ' + + ', '.join(dep) + '\n') + indep = indep + dep + break + else: + indep.append(v) + dep = dep[1:] + n = len(dep) + i = 0 + return indep + + +def analyzecommon(block): + if not hascommon(block): + return block + commonvars = [] + for k in list(block['common'].keys()): + comvars = [] + for e in block['common'][k]: + m = re.match( + r'\A\s*\b(?P.*?)\b\s*(\((?P.*?)\)|)\s*\Z', e, re.I) + if m: + dims = [] + if m.group('dims'): + dims = [x.strip() + for x in markoutercomma(m.group('dims')).split('@,@')] + n = rmbadname1(m.group('name').strip()) + if n in block['vars']: + if 'attrspec' in block['vars'][n]: + block['vars'][n]['attrspec'].append( + f"dimension({','.join(dims)})") + else: + block['vars'][n]['attrspec'] = [ + f"dimension({','.join(dims)})"] + elif dims: + block['vars'][n] = { + 'attrspec': [f"dimension({','.join(dims)})"]} + else: + block['vars'][n] = {} + if n not in commonvars: + commonvars.append(n) + else: + n = e + errmess( + f'analyzecommon: failed to extract "[()]" from "{e}" in common /{k}/.\n') + comvars.append(n) + block['common'][k] = comvars + if 'commonvars' not in block: + block['commonvars'] = commonvars + else: + block['commonvars'] = block['commonvars'] + commonvars + return block + + +def analyzebody(block, args, tab=''): + global usermodules, skipfuncs, onlyfuncs, f90modulevars + + setmesstext(block) + + maybe_private = { + key: value + for key, value in block['vars'].items() + if 'attrspec' not in value or 'public' not in value['attrspec'] + } + + body = [] + for b in block['body']: + b['parent_block'] = block + if b['block'] in ['function', 'subroutine']: + if args is not None and b['name'] not in args: + continue + else: + as_ = b['args'] + # Add private members to skipfuncs for gh-23879 + if b['name'] in maybe_private.keys(): + skipfuncs.append(b['name']) + if b['name'] in skipfuncs: + continue + if onlyfuncs and b['name'] not in onlyfuncs: + continue + b['saved_interface'] = crack2fortrangen( + b, '\n' + ' ' * 6, as_interface=True) + + else: + as_ = args + b = postcrack(b, as_, tab=tab + '\t') + if b['block'] in ['interface', 'abstract interface'] and \ + not b['body'] and not b.get('implementedby'): + if 'f2pyenhancements' not in b: + continue + if b['block'].replace(' ', '') == 'pythonmodule': + usermodules.append(b) + else: + if b['block'] == 'module': + f90modulevars[b['name']] = b['vars'] + body.append(b) + return body + + +def buildimplicitrules(block): + setmesstext(block) + implicitrules = defaultimplicitrules + attrrules = {} + if 'implicit' in block: + if block['implicit'] is None: + implicitrules = None + if verbose > 1: + outmess( + f"buildimplicitrules: no implicit rules for routine {repr(block['name'])}.\n") + else: + for k in list(block['implicit'].keys()): + if block['implicit'][k].get('typespec') not in ['static', 'automatic']: + implicitrules[k] = block['implicit'][k] + else: + attrrules[k] = block['implicit'][k]['typespec'] + return implicitrules, attrrules + + +def myeval(e, g=None, l=None): + """ Like `eval` but returns only integers and floats """ + r = eval(e, g, l) + if type(r) in [int, float]: + return r + raise ValueError(f'r={r!r}') + + +getlincoef_re_1 = re.compile(r'\A\b\w+\b\Z', re.I) + + +def getlincoef(e, xset): # e = a*x+b ; x in xset + """ + Obtain ``a`` and ``b`` when ``e == "a*x+b"``, where ``x`` is a symbol in + xset. + + >>> getlincoef('2*x + 1', {'x'}) + (2, 1, 'x') + >>> getlincoef('3*x + x*2 + 2 + 1', {'x'}) + (5, 3, 'x') + >>> getlincoef('0', {'x'}) + (0, 0, None) + >>> getlincoef('0*x', {'x'}) + (0, 0, 'x') + >>> getlincoef('x*x', {'x'}) + (None, None, None) + + This can be tricked by sufficiently complex expressions + + >>> getlincoef('(x - 0.5)*(x - 1.5)*(x - 1)*x + 2*x + 3', {'x'}) + (2.0, 3.0, 'x') + """ + try: + c = int(myeval(e, {}, {})) + return 0, c, None + except Exception: + pass + if getlincoef_re_1.match(e): + return 1, 0, e + len_e = len(e) + for x in xset: + if len(x) > len_e: + continue + if re.search(r'\w\s*\([^)]*\b' + x + r'\b', e): + # skip function calls having x as an argument, e.g max(1, x) + continue + re_1 = re.compile(r'(?P.*?)\b' + x + r'\b(?P.*)', re.I) + m = re_1.match(e) + if m: + try: + m1 = re_1.match(e) + while m1: + ee = f"{m1.group('before')}({0}){m1.group('after')}" + m1 = re_1.match(ee) + b = myeval(ee, {}, {}) + m1 = re_1.match(e) + while m1: + ee = f"{m1.group('before')}({1}){m1.group('after')}" + m1 = re_1.match(ee) + a = myeval(ee, {}, {}) - b + m1 = re_1.match(e) + while m1: + ee = f"{m1.group('before')}({0.5}){m1.group('after')}" + m1 = re_1.match(ee) + c = myeval(ee, {}, {}) + # computing another point to be sure that expression is linear + m1 = re_1.match(e) + while m1: + ee = f"{m1.group('before')}({1.5}){m1.group('after')}" + m1 = re_1.match(ee) + c2 = myeval(ee, {}, {}) + if (a * 0.5 + b == c and a * 1.5 + b == c2): + return a, b, x + except Exception: + pass + break + return None, None, None + + +word_pattern = re.compile(r'\b[a-z][\w$]*\b', re.I) + + +def _get_depend_dict(name, vars, deps): + if name in vars: + words = vars[name].get('depend', []) + + if '=' in vars[name] and not isstring(vars[name]): + for word in word_pattern.findall(vars[name]['=']): + # The word_pattern may return values that are not + # only variables, they can be string content for instance + if word not in words and word in vars and word != name: + words.append(word) + for word in words[:]: + for w in deps.get(word, []) \ + or _get_depend_dict(word, vars, deps): + if w not in words: + words.append(w) + else: + outmess(f'_get_depend_dict: no dependence info for {repr(name)}\n') + words = [] + deps[name] = words + return words + + +def _calc_depend_dict(vars): + names = list(vars.keys()) + depend_dict = {} + for n in names: + _get_depend_dict(n, vars, depend_dict) + return depend_dict + + +def get_sorted_names(vars): + depend_dict = _calc_depend_dict(vars) + names = [] + for name in list(depend_dict.keys()): + if not depend_dict[name]: + names.append(name) + del depend_dict[name] + while depend_dict: + for name, lst in list(depend_dict.items()): + new_lst = [n for n in lst if n in depend_dict] + if not new_lst: + names.append(name) + del depend_dict[name] + else: + depend_dict[name] = new_lst + return [name for name in names if name in vars] + + +def _kind_func(string): + # XXX: return something sensible. + if string[0] in "'\"": + string = string[1:-1] + if real16pattern.match(string): + return 8 + elif real8pattern.match(string): + return 4 + return 'kind(' + string + ')' + + +def _selected_int_kind_func(r): + # XXX: This should be processor dependent + m = 10 ** r + if m <= 2 ** 8: + return 1 + if m <= 2 ** 16: + return 2 + if m <= 2 ** 32: + return 4 + if m <= 2 ** 63: + return 8 + if m <= 2 ** 128: + return 16 + return -1 + + +def _selected_real_kind_func(p, r=0, radix=0): + # XXX: This should be processor dependent + # This is only verified for 0 <= p <= 20, possibly good for p <= 33 and above + if p < 7: + return 4 + if p < 16: + return 8 + machine = platform.machine().lower() + if machine.startswith(('aarch64', 'alpha', 'arm64', 'loongarch', 'mips', 'power', 'ppc', 'riscv', 's390x', 'sparc')): + if p <= 33: + return 16 + elif p < 19: + return 10 + elif p <= 33: + return 16 + return -1 + + +def get_parameters(vars, global_params={}): + params = copy.copy(global_params) + g_params = copy.copy(global_params) + for name, func in [('kind', _kind_func), + ('selected_int_kind', _selected_int_kind_func), + ('selected_real_kind', _selected_real_kind_func), ]: + if name not in g_params: + g_params[name] = func + param_names = [] + for n in get_sorted_names(vars): + if 'attrspec' in vars[n] and 'parameter' in vars[n]['attrspec']: + param_names.append(n) + kind_re = re.compile(r'\bkind\s*\(\s*(?P.*)\s*\)', re.I) + selected_int_kind_re = re.compile( + r'\bselected_int_kind\s*\(\s*(?P.*)\s*\)', re.I) + selected_kind_re = re.compile( + r'\bselected_(int|real)_kind\s*\(\s*(?P.*)\s*\)', re.I) + for n in param_names: + if '=' in vars[n]: + v = vars[n]['='] + if islogical(vars[n]): + v = v.lower() + for repl in [ + ('.false.', 'False'), + ('.true.', 'True'), + # TODO: test .eq., .neq., etc replacements. + ]: + v = v.replace(*repl) + + v = kind_re.sub(r'kind("\1")', v) + v = selected_int_kind_re.sub(r'selected_int_kind(\1)', v) + + # We need to act according to the data. + # The easy case is if the data has a kind-specifier, + # then we may easily remove those specifiers. + # However, it may be that the user uses other specifiers...(!) + is_replaced = False + + if 'kindselector' in vars[n]: + # Remove kind specifier (including those defined + # by parameters) + if 'kind' in vars[n]['kindselector']: + orig_v_len = len(v) + v = v.replace('_' + vars[n]['kindselector']['kind'], '') + # Again, this will be true if even a single specifier + # has been replaced, see comment above. + is_replaced = len(v) < orig_v_len + + if not is_replaced: + if not selected_kind_re.match(v): + v_ = v.split('_') + # In case there are additive parameters + if len(v_) > 1: + v = ''.join(v_[:-1]).lower().replace(v_[-1].lower(), '') + + # Currently this will not work for complex numbers. + # There is missing code for extracting a complex number, + # which may be defined in either of these: + # a) (Re, Im) + # b) cmplx(Re, Im) + # c) dcmplx(Re, Im) + # d) cmplx(Re, Im, ) + + if isdouble(vars[n]): + tt = list(v) + for m in real16pattern.finditer(v): + tt[m.start():m.end()] = list( + v[m.start():m.end()].lower().replace('d', 'e')) + v = ''.join(tt) + + elif iscomplex(vars[n]): + outmess(f'get_parameters[TODO]: ' + f'implement evaluation of complex expression {v}\n') + + dimspec = ([s.removeprefix('dimension').strip() + for s in vars[n]['attrspec'] + if s.startswith('dimension')] or [None])[0] + + # Handle _dp for gh-6624 + # Also fixes gh-20460 + if real16pattern.search(v): + v = 8 + elif real8pattern.search(v): + v = 4 + try: + params[n] = param_eval(v, g_params, params, dimspec=dimspec) + except Exception as msg: + params[n] = v + outmess(f'get_parameters: got "{msg}" on {n!r}\n') + + if isstring(vars[n]) and isinstance(params[n], int): + params[n] = chr(params[n]) + nl = n.lower() + if nl != n: + params[nl] = params[n] + else: + print(vars[n]) + outmess(f'get_parameters:parameter {n!r} does not have value?!\n') + return params + + +def _eval_length(length, params): + if length in ['(:)', '(*)', '*']: + return '(*)' + return _eval_scalar(length, params) + + +_is_kind_number = re.compile(r'\d+_').match + + +def _eval_scalar(value, params): + if _is_kind_number(value): + value = value.split('_')[0] + try: + # TODO: use symbolic from PR #19805 + value = eval(value, {}, params) + value = (repr if isinstance(value, str) else str)(value) + except (NameError, SyntaxError, TypeError): + return value + except Exception as msg: + errmess('"%s" in evaluating %r ' + '(available names: %s)\n' + % (msg, value, list(params.keys()))) + return value + + +def analyzevars(block): + """ + Sets correct dimension information for each variable/parameter + """ + + global f90modulevars + + setmesstext(block) + implicitrules, attrrules = buildimplicitrules(block) + vars = copy.copy(block['vars']) + if block['block'] == 'function' and block['name'] not in vars: + vars[block['name']] = {} + if '' in block['vars']: + del vars[''] + if 'attrspec' in block['vars']['']: + gen = block['vars']['']['attrspec'] + for n in set(vars) | {b['name'] for b in block['body']}: + for k in ['public', 'private']: + if k in gen: + vars[n] = setattrspec(vars.get(n, {}), k) + svars = [] + args = block['args'] + for a in args: + try: + vars[a] + svars.append(a) + except KeyError: + pass + for n in list(vars.keys()): + if n not in args: + svars.append(n) + + params = get_parameters(vars, get_useparameters(block)) + # At this point, params are read and interpreted, but + # the params used to define vars are not yet parsed + dep_matches = {} + name_match = re.compile(r'[A-Za-z][\w$]*').match + for v in list(vars.keys()): + m = name_match(v) + if m: + n = v[m.start():m.end()] + try: + dep_matches[n] + except KeyError: + dep_matches[n] = re.compile(r'.*\b%s\b' % (v), re.I).match + for n in svars: + if n[0] in list(attrrules.keys()): + vars[n] = setattrspec(vars[n], attrrules[n[0]]) + if 'typespec' not in vars[n]: + if not ('attrspec' in vars[n] and 'external' in vars[n]['attrspec']): + if implicitrules: + ln0 = n[0].lower() + for k in list(implicitrules[ln0].keys()): + if k == 'typespec' and implicitrules[ln0][k] == 'undefined': + continue + if k not in vars[n]: + vars[n][k] = implicitrules[ln0][k] + elif k == 'attrspec': + for l in implicitrules[ln0][k]: + vars[n] = setattrspec(vars[n], l) + elif n in block['args']: + outmess('analyzevars: typespec of variable %s is not defined in routine %s.\n' % ( + repr(n), block['name'])) + if 'charselector' in vars[n]: + if 'len' in vars[n]['charselector']: + l = vars[n]['charselector']['len'] + try: + l = str(eval(l, {}, params)) + except Exception: + pass + vars[n]['charselector']['len'] = l + + if 'kindselector' in vars[n]: + if 'kind' in vars[n]['kindselector']: + l = vars[n]['kindselector']['kind'] + try: + l = str(eval(l, {}, params)) + except Exception: + pass + vars[n]['kindselector']['kind'] = l + + dimension_exprs = {} + if 'attrspec' in vars[n]: + attr = vars[n]['attrspec'] + attr.reverse() + vars[n]['attrspec'] = [] + dim, intent, depend, check, note = None, None, None, None, None + for a in attr: + if a[:9] == 'dimension': + dim = (a[9:].strip())[1:-1] + elif a[:6] == 'intent': + intent = (a[6:].strip())[1:-1] + elif a[:6] == 'depend': + depend = (a[6:].strip())[1:-1] + elif a[:5] == 'check': + check = (a[5:].strip())[1:-1] + elif a[:4] == 'note': + note = (a[4:].strip())[1:-1] + else: + vars[n] = setattrspec(vars[n], a) + if intent: + if 'intent' not in vars[n]: + vars[n]['intent'] = [] + for c in [x.strip() for x in markoutercomma(intent).split('@,@')]: + # Remove spaces so that 'in out' becomes 'inout' + tmp = c.replace(' ', '') + if tmp not in vars[n]['intent']: + vars[n]['intent'].append(tmp) + intent = None + if note: + note = note.replace('\\n\\n', '\n\n') + note = note.replace('\\n ', '\n') + if 'note' not in vars[n]: + vars[n]['note'] = [note] + else: + vars[n]['note'].append(note) + note = None + if depend is not None: + if 'depend' not in vars[n]: + vars[n]['depend'] = [] + for c in rmbadname([x.strip() for x in markoutercomma(depend).split('@,@')]): + if c not in vars[n]['depend']: + vars[n]['depend'].append(c) + depend = None + if check is not None: + if 'check' not in vars[n]: + vars[n]['check'] = [] + for c in [x.strip() for x in markoutercomma(check).split('@,@')]: + if c not in vars[n]['check']: + vars[n]['check'].append(c) + check = None + if dim and 'dimension' not in vars[n]: + vars[n]['dimension'] = [] + for d in rmbadname( + [x.strip() for x in markoutercomma(dim).split('@,@')] + ): + # d is the expression inside the dimension declaration + # Evaluate `d` with respect to params + try: + # the dimension for this variable depends on a + # previously defined parameter + d = param_parse(d, params) + except (ValueError, IndexError, KeyError): + outmess( + 'analyzevars: could not parse dimension for ' + f'variable {d!r}\n' + ) + + dim_char = ':' if d == ':' else '*' + if d == dim_char: + dl = [dim_char] + else: + dl = markoutercomma(d, ':').split('@:@') + if len(dl) == 2 and '*' in dl: # e.g. dimension(5:*) + dl = ['*'] + d = '*' + if len(dl) == 1 and dl[0] != dim_char: + dl = ['1', dl[0]] + if len(dl) == 2: + d1, d2 = map(symbolic.Expr.parse, dl) + dsize = d2 - d1 + 1 + d = dsize.tostring(language=symbolic.Language.C) + # find variables v that define d as a linear + # function, `d == a * v + b`, and store + # coefficients a and b for further analysis. + solver_and_deps = {} + for v in block['vars']: + s = symbolic.as_symbol(v) + if dsize.contains(s): + try: + a, b = dsize.linear_solve(s) + + def solve_v(s, a=a, b=b): + return (s - b) / a + + all_symbols = set(a.symbols()) + all_symbols.update(b.symbols()) + except RuntimeError as msg: + # d is not a linear function of v, + # however, if v can be determined + # from d using other means, + # implement the corresponding + # solve_v function here. + solve_v = None + all_symbols = set(dsize.symbols()) + v_deps = { + s.data for s in all_symbols + if s.data in vars} + solver_and_deps[v] = solve_v, list(v_deps) + # Note that dsize may contain symbols that are + # not defined in block['vars']. Here we assume + # these correspond to Fortran/C intrinsic + # functions or that are defined by other + # means. We'll let the compiler validate the + # definiteness of such symbols. + dimension_exprs[d] = solver_and_deps + vars[n]['dimension'].append(d) + + if 'check' not in vars[n] and 'args' in block and n in block['args']: + # n is an argument that has no checks defined. Here we + # generate some consistency checks for n, and when n is an + # array, generate checks for its dimensions and construct + # initialization expressions. + n_deps = vars[n].get('depend', []) + n_checks = [] + n_is_input = l_or(isintent_in, isintent_inout, + isintent_inplace)(vars[n]) + if isarray(vars[n]): # n is array + for i, d in enumerate(vars[n]['dimension']): + coeffs_and_deps = dimension_exprs.get(d) + if coeffs_and_deps is None: + # d is `:` or `*` or a constant expression + pass + elif n_is_input: + # n is an input array argument and its shape + # may define variables used in dimension + # specifications. + for v, (solver, deps) in coeffs_and_deps.items(): + def compute_deps(v, deps): + for v1 in coeffs_and_deps.get(v, [None, []])[1]: + if v1 not in deps: + deps.add(v1) + compute_deps(v1, deps) + all_deps = set() + compute_deps(v, all_deps) + if (v in n_deps + or '=' in vars[v] + or 'depend' in vars[v]): + # Skip a variable that + # - n depends on + # - has user-defined initialization expression + # - has user-defined dependencies + continue + if solver is not None and v not in all_deps: + # v can be solved from d, hence, we + # make it an optional argument with + # initialization expression: + is_required = False + init = solver(symbolic.as_symbol( + f'shape({n}, {i})')) + init = init.tostring( + language=symbolic.Language.C) + vars[v]['='] = init + # n needs to be initialized before v. So, + # making v dependent on n and on any + # variables in solver or d. + vars[v]['depend'] = [n] + deps + if 'check' not in vars[v]: + # add check only when no + # user-specified checks exist + vars[v]['check'] = [ + f'shape({n}, {i}) == {d}'] + else: + # d is a non-linear function on v, + # hence, v must be a required input + # argument that n will depend on + is_required = True + if 'intent' not in vars[v]: + vars[v]['intent'] = [] + if 'in' not in vars[v]['intent']: + vars[v]['intent'].append('in') + # v needs to be initialized before n + n_deps.append(v) + n_checks.append( + f'shape({n}, {i}) == {d}') + v_attr = vars[v].get('attrspec', []) + if not ('optional' in v_attr + or 'required' in v_attr): + v_attr.append( + 'required' if is_required else 'optional') + if v_attr: + vars[v]['attrspec'] = v_attr + if coeffs_and_deps is not None: + # extend v dependencies with ones specified in attrspec + for v, (solver, deps) in coeffs_and_deps.items(): + v_deps = vars[v].get('depend', []) + for aa in vars[v].get('attrspec', []): + if aa.startswith('depend'): + aa = ''.join(aa.split()) + v_deps.extend(aa[7:-1].split(',')) + if v_deps: + vars[v]['depend'] = list(set(v_deps)) + if n not in v_deps: + n_deps.append(v) + elif isstring(vars[n]): + if 'charselector' in vars[n]: + if '*' in vars[n]['charselector']: + length = _eval_length(vars[n]['charselector']['*'], + params) + vars[n]['charselector']['*'] = length + elif 'len' in vars[n]['charselector']: + length = _eval_length(vars[n]['charselector']['len'], + params) + del vars[n]['charselector']['len'] + vars[n]['charselector']['*'] = length + if n_checks: + vars[n]['check'] = n_checks + if n_deps: + vars[n]['depend'] = list(set(n_deps)) + + if '=' in vars[n]: + if 'attrspec' not in vars[n]: + vars[n]['attrspec'] = [] + if ('optional' not in vars[n]['attrspec']) and \ + ('required' not in vars[n]['attrspec']): + vars[n]['attrspec'].append('optional') + if 'depend' not in vars[n]: + vars[n]['depend'] = [] + for v, m in list(dep_matches.items()): + if m(vars[n]['=']): + vars[n]['depend'].append(v) + if not vars[n]['depend']: + del vars[n]['depend'] + if isscalar(vars[n]): + vars[n]['='] = _eval_scalar(vars[n]['='], params) + + for n in list(vars.keys()): + if n == block['name']: # n is block name + if 'note' in vars[n]: + block['note'] = vars[n]['note'] + if block['block'] == 'function': + if 'result' in block and block['result'] in vars: + vars[n] = appenddecl(vars[n], vars[block['result']]) + if 'prefix' in block: + pr = block['prefix'] + pr1 = pr.replace('pure', '') + ispure = (not pr == pr1) + pr = pr1.replace('recursive', '') + isrec = (not pr == pr1) + m = typespattern[0].match(pr) + if m: + typespec, selector, attr, edecl = cracktypespec0( + m.group('this'), m.group('after')) + kindselect, charselect, typename = cracktypespec( + typespec, selector) + vars[n]['typespec'] = typespec + try: + if block['result']: + vars[block['result']]['typespec'] = typespec + except Exception: + pass + if kindselect: + if 'kind' in kindselect: + try: + kindselect['kind'] = eval( + kindselect['kind'], {}, params) + except Exception: + pass + vars[n]['kindselector'] = kindselect + if charselect: + vars[n]['charselector'] = charselect + if typename: + vars[n]['typename'] = typename + if ispure: + vars[n] = setattrspec(vars[n], 'pure') + if isrec: + vars[n] = setattrspec(vars[n], 'recursive') + else: + outmess( + f"analyzevars: prefix ({repr(block['prefix'])}) were not used\n") + if block['block'] not in ['module', 'pythonmodule', 'python module', 'block data']: + if 'commonvars' in block: + neededvars = copy.copy(block['args'] + block['commonvars']) + else: + neededvars = copy.copy(block['args']) + for n in list(vars.keys()): + if l_or(isintent_callback, isintent_aux)(vars[n]): + neededvars.append(n) + if 'entry' in block: + neededvars.extend(list(block['entry'].keys())) + for k in list(block['entry'].keys()): + for n in block['entry'][k]: + if n not in neededvars: + neededvars.append(n) + if block['block'] == 'function': + if 'result' in block: + neededvars.append(block['result']) + else: + neededvars.append(block['name']) + if block['block'] in ['subroutine', 'function']: + name = block['name'] + if name in vars and 'intent' in vars[name]: + block['intent'] = vars[name]['intent'] + if block['block'] == 'type': + neededvars.extend(list(vars.keys())) + for n in list(vars.keys()): + if n not in neededvars: + del vars[n] + return vars + + +analyzeargs_re_1 = re.compile(r'\A[a-z]+[\w$]*\Z', re.I) + + +def param_eval(v, g_params, params, dimspec=None): + """ + Creates a dictionary of indices and values for each parameter in a + parameter array to be evaluated later. + + WARNING: It is not possible to initialize multidimensional array + parameters e.g. dimension(-3:1, 4, 3:5) at this point. This is because in + Fortran initialization through array constructor requires the RESHAPE + intrinsic function. Since the right-hand side of the parameter declaration + is not executed in f2py, but rather at the compiled c/fortran extension, + later, it is not possible to execute a reshape of a parameter array. + One issue remains: if the user wants to access the array parameter from + python, we should either + 1) allow them to access the parameter array using python standard indexing + (which is often incompatible with the original fortran indexing) + 2) allow the parameter array to be accessed in python as a dictionary with + fortran indices as keys + We are choosing 2 for now. + """ + if dimspec is None: + try: + p = eval(v, g_params, params) + except Exception as msg: + p = v + outmess(f'param_eval: got "{msg}" on {v!r}\n') + return p + + # This is an array parameter. + # First, we parse the dimension information + if len(dimspec) < 2 or dimspec[::len(dimspec) - 1] != "()": + raise ValueError(f'param_eval: dimension {dimspec} can\'t be parsed') + dimrange = dimspec[1:-1].split(',') + if len(dimrange) == 1: + # e.g. dimension(2) or dimension(-1:1) + dimrange = dimrange[0].split(':') + # now, dimrange is a list of 1 or 2 elements + if len(dimrange) == 1: + bound = param_parse(dimrange[0], params) + dimrange = range(1, int(bound) + 1) + else: + lbound = param_parse(dimrange[0], params) + ubound = param_parse(dimrange[1], params) + dimrange = range(int(lbound), int(ubound) + 1) + else: + raise ValueError('param_eval: multidimensional array parameters ' + f'{dimspec} not supported') + + # Parse parameter value + v = (v[2:-2] if v.startswith('(/') else v).split(',') + v_eval = [] + for item in v: + try: + item = eval(item, g_params, params) + except Exception as msg: + outmess(f'param_eval: got "{msg}" on {item!r}\n') + v_eval.append(item) + + p = dict(zip(dimrange, v_eval)) + + return p + + +def param_parse(d, params): + """Recursively parse array dimensions. + + Parses the declaration of an array variable or parameter + `dimension` keyword, and is called recursively if the + dimension for this array is a previously defined parameter + (found in `params`). + + Parameters + ---------- + d : str + Fortran expression describing the dimension of an array. + params : dict + Previously parsed parameters declared in the Fortran source file. + + Returns + ------- + out : str + Parsed dimension expression. + + Examples + -------- + + * If the line being analyzed is + + `integer, parameter, dimension(2) :: pa = (/ 3, 5 /)` + + then `d = 2` and we return immediately, with + + >>> d = '2' + >>> param_parse(d, params) + 2 + + * If the line being analyzed is + + `integer, parameter, dimension(pa) :: pb = (/1, 2, 3/)` + + then `d = 'pa'`; since `pa` is a previously parsed parameter, + and `pa = 3`, we call `param_parse` recursively, to obtain + + >>> d = 'pa' + >>> params = {'pa': 3} + >>> param_parse(d, params) + 3 + + * If the line being analyzed is + + `integer, parameter, dimension(pa(1)) :: pb = (/1, 2, 3/)` + + then `d = 'pa(1)'`; since `pa` is a previously parsed parameter, + and `pa(1) = 3`, we call `param_parse` recursively, to obtain + + >>> d = 'pa(1)' + >>> params = dict(pa={1: 3, 2: 5}) + >>> param_parse(d, params) + 3 + """ + if "(" in d: + # this dimension expression is an array + dname = d[:d.find("(")] + ddims = d[d.find("(") + 1:d.rfind(")")] + # this dimension expression is also a parameter; + # parse it recursively + index = int(param_parse(ddims, params)) + return str(params[dname][index]) + elif d in params: + return str(params[d]) + else: + for p in params: + re_1 = re.compile( + r'(?P.*?)\b' + p + r'\b(?P.*)', re.I + ) + m = re_1.match(d) + while m: + d = m.group('before') + \ + str(params[p]) + m.group('after') + m = re_1.match(d) + return d + + +def expr2name(a, block, args=[]): + orig_a = a + a_is_expr = not analyzeargs_re_1.match(a) + if a_is_expr: # `a` is an expression + implicitrules, attrrules = buildimplicitrules(block) + at = determineexprtype(a, block['vars'], implicitrules) + na = 'e_' + for c in a: + c = c.lower() + if c not in string.ascii_lowercase + string.digits: + c = '_' + na = na + c + if na[-1] == '_': + na = na + 'e' + else: + na = na + '_e' + a = na + while a in block['vars'] or a in block['args']: + a = a + 'r' + if a in args: + k = 1 + while a + str(k) in args: + k = k + 1 + a = a + str(k) + if a_is_expr: + block['vars'][a] = at + else: + if a not in block['vars']: + block['vars'][a] = block['vars'].get(orig_a, {}) + if 'externals' in block and orig_a in block['externals'] + block['interfaced']: + block['vars'][a] = setattrspec(block['vars'][a], 'external') + return a + + +def analyzeargs(block): + setmesstext(block) + implicitrules, _ = buildimplicitrules(block) + if 'args' not in block: + block['args'] = [] + args = [] + for a in block['args']: + a = expr2name(a, block, args) + args.append(a) + block['args'] = args + if 'entry' in block: + for k, args1 in list(block['entry'].items()): + for a in args1: + if a not in block['vars']: + block['vars'][a] = {} + + for b in block['body']: + if b['name'] in args: + if 'externals' not in block: + block['externals'] = [] + if b['name'] not in block['externals']: + block['externals'].append(b['name']) + if 'result' in block and block['result'] not in block['vars']: + block['vars'][block['result']] = {} + return block + + +determineexprtype_re_1 = re.compile(r'\A\(.+?,.+?\)\Z', re.I) +determineexprtype_re_2 = re.compile(r'\A[+-]?\d+(_(?P\w+)|)\Z', re.I) +determineexprtype_re_3 = re.compile( + r'\A[+-]?[\d.]+[-\d+de.]*(_(?P\w+)|)\Z', re.I) +determineexprtype_re_4 = re.compile(r'\A\(.*\)\Z', re.I) +determineexprtype_re_5 = re.compile(r'\A(?P\w+)\s*\(.*?\)\s*\Z', re.I) + + +def _ensure_exprdict(r): + if isinstance(r, int): + return {'typespec': 'integer'} + if isinstance(r, float): + return {'typespec': 'real'} + if isinstance(r, complex): + return {'typespec': 'complex'} + if isinstance(r, dict): + return r + raise AssertionError(repr(r)) + + +def determineexprtype(expr, vars, rules={}): + if expr in vars: + return _ensure_exprdict(vars[expr]) + expr = expr.strip() + if determineexprtype_re_1.match(expr): + return {'typespec': 'complex'} + m = determineexprtype_re_2.match(expr) + if m: + if 'name' in m.groupdict() and m.group('name'): + outmess( + f'determineexprtype: selected kind types not supported ({repr(expr)})\n') + return {'typespec': 'integer'} + m = determineexprtype_re_3.match(expr) + if m: + if 'name' in m.groupdict() and m.group('name'): + outmess( + f'determineexprtype: selected kind types not supported ({repr(expr)})\n') + return {'typespec': 'real'} + for op in ['+', '-', '*', '/']: + for e in [x.strip() for x in markoutercomma(expr, comma=op).split('@' + op + '@')]: + if e in vars: + return _ensure_exprdict(vars[e]) + t = {} + if determineexprtype_re_4.match(expr): # in parenthesis + t = determineexprtype(expr[1:-1], vars, rules) + else: + m = determineexprtype_re_5.match(expr) + if m: + rn = m.group('name') + t = determineexprtype(m.group('name'), vars, rules) + if t and 'attrspec' in t: + del t['attrspec'] + if not t: + if rn[0] in rules: + return _ensure_exprdict(rules[rn[0]]) + if expr[0] in '\'"': + return {'typespec': 'character', 'charselector': {'*': '*'}} + if not t: + outmess( + f'determineexprtype: could not determine expressions ({repr(expr)}) type.\n') + return t + +###### + + +def crack2fortrangen(block, tab='\n', as_interface=False): + global skipfuncs, onlyfuncs + + setmesstext(block) + ret = '' + if isinstance(block, list): + for g in block: + if g and g['block'] in ['function', 'subroutine']: + if g['name'] in skipfuncs: + continue + if onlyfuncs and g['name'] not in onlyfuncs: + continue + ret = ret + crack2fortrangen(g, tab, as_interface=as_interface) + return ret + prefix = '' + name = '' + args = '' + blocktype = block['block'] + if blocktype == 'program': + return '' + argsl = [] + if 'name' in block: + name = block['name'] + if 'args' in block: + vars = block['vars'] + for a in block['args']: + a = expr2name(a, block, argsl) + if not isintent_callback(vars[a]): + argsl.append(a) + if block['block'] == 'function' or argsl: + args = f"({','.join(argsl)})" + f2pyenhancements = '' + if 'f2pyenhancements' in block: + for k in list(block['f2pyenhancements'].keys()): + f2pyenhancements = '%s%s%s %s' % ( + f2pyenhancements, tab + tabchar, k, block['f2pyenhancements'][k]) + intent_lst = block.get('intent', [])[:] + if blocktype == 'function' and 'callback' in intent_lst: + intent_lst.remove('callback') + if intent_lst: + f2pyenhancements = '%s%sintent(%s) %s' %\ + (f2pyenhancements, tab + tabchar, + ','.join(intent_lst), name) + use = '' + if 'use' in block: + use = use2fortran(block['use'], tab + tabchar) + common = '' + if 'common' in block: + common = common2fortran(block['common'], tab + tabchar) + if name == 'unknown_interface': + name = '' + result = '' + if 'result' in block: + result = f" result ({block['result']})" + if block['result'] not in argsl: + argsl.append(block['result']) + body = crack2fortrangen(block['body'], tab + tabchar, as_interface=as_interface) + vars = vars2fortran( + block, block['vars'], argsl, tab + tabchar, as_interface=as_interface) + mess = '' + if 'from' in block and not as_interface: + mess = f"! in {block['from']}" + if 'entry' in block: + entry_stmts = '' + for k, i in list(block['entry'].items()): + entry_stmts = f"{entry_stmts}{tab + tabchar}entry {k}({','.join(i)})" + body = body + entry_stmts + if blocktype == 'block data' and name == '_BLOCK_DATA_': + name = '' + ret = '%s%s%s %s%s%s %s%s%s%s%s%s%send %s %s' % ( + tab, prefix, blocktype, name, args, result, mess, f2pyenhancements, use, vars, common, body, tab, blocktype, name) + return ret + + +def common2fortran(common, tab=''): + ret = '' + for k in list(common.keys()): + if k == '_BLNK_': + ret = f"{ret}{tab}common {','.join(common[k])}" + else: + ret = f"{ret}{tab}common /{k}/ {','.join(common[k])}" + return ret + + +def use2fortran(use, tab=''): + ret = '' + for m in list(use.keys()): + ret = f'{ret}{tab}use {m},' + if use[m] == {}: + if ret and ret[-1] == ',': + ret = ret[:-1] + continue + if 'only' in use[m] and use[m]['only']: + ret = f'{ret} only:' + if 'map' in use[m] and use[m]['map']: + c = ' ' + for k in list(use[m]['map'].keys()): + if k == use[m]['map'][k]: + ret = f'{ret}{c}{k}' + c = ',' + else: + ret = f"{ret}{c}{k}=>{use[m]['map'][k]}" + c = ',' + if ret and ret[-1] == ',': + ret = ret[:-1] + return ret + + +def true_intent_list(var): + lst = var['intent'] + ret = [] + for intent in lst: + try: + f = globals()[f'isintent_{intent}'] + except KeyError: + pass + else: + if f(var): + ret.append(intent) + return ret + + +def vars2fortran(block, vars, args, tab='', as_interface=False): + setmesstext(block) + ret = '' + nout = [] + for a in args: + if a in block['vars']: + nout.append(a) + if 'commonvars' in block: + for a in block['commonvars']: + if a in vars: + if a not in nout: + nout.append(a) + else: + errmess( + f'vars2fortran: Confused?!: "{a}" is not defined in vars.\n') + if 'varnames' in block: + nout.extend(block['varnames']) + if not as_interface: + for a in list(vars.keys()): + if a not in nout: + nout.append(a) + for a in nout: + if 'depend' in vars[a]: + for d in vars[a]['depend']: + if d in vars and 'depend' in vars[d] and a in vars[d]['depend']: + errmess( + f'vars2fortran: Warning: cross-dependence between variables "{a}" and "{d}\"\n') + if 'externals' in block and a in block['externals']: + if isintent_callback(vars[a]): + ret = f'{ret}{tab}intent(callback) {a}' + ret = f'{ret}{tab}external {a}' + if isoptional(vars[a]): + ret = f'{ret}{tab}optional {a}' + if a in vars and 'typespec' not in vars[a]: + continue + cont = 1 + for b in block['body']: + if a == b['name'] and b['block'] == 'function': + cont = 0 + break + if cont: + continue + if a not in vars: + show(vars) + outmess(f'vars2fortran: No definition for argument "{a}".\n') + continue + if a == block['name']: + if block['block'] != 'function' or block.get('result'): + # 1) skip declaring a variable that name matches with + # subroutine name + # 2) skip declaring function when its type is + # declared via `result` construction + continue + if 'typespec' not in vars[a]: + if 'attrspec' in vars[a] and 'external' in vars[a]['attrspec']: + if a in args: + ret = f'{ret}{tab}external {a}' + continue + show(vars[a]) + outmess(f'vars2fortran: No typespec for argument "{a}".\n') + continue + vardef = vars[a]['typespec'] + if vardef == 'type' and 'typename' in vars[a]: + vardef = f"{vardef}({vars[a]['typename']})" + selector = {} + if 'kindselector' in vars[a]: + selector = vars[a]['kindselector'] + elif 'charselector' in vars[a]: + selector = vars[a]['charselector'] + if '*' in selector: + if selector['*'] in ['*', ':']: + vardef = f"{vardef}*({selector['*']})" + else: + vardef = f"{vardef}*{selector['*']}" + elif 'len' in selector: + vardef = f"{vardef}(len={selector['len']}" + if 'kind' in selector: + vardef = f"{vardef},kind={selector['kind']})" + else: + vardef = f'{vardef})' + elif 'kind' in selector: + vardef = f"{vardef}(kind={selector['kind']})" + c = ' ' + if 'attrspec' in vars[a]: + attr = [l for l in vars[a]['attrspec'] + if l not in ['external']] + if as_interface and 'intent(in)' in attr and 'intent(out)' in attr: + # In Fortran, intent(in, out) are conflicting while + # intent(in, out) can be specified only via + # `!f2py intent(out) ..`. + # So, for the Fortran interface, we'll drop + # intent(out) to resolve the conflict. + attr.remove('intent(out)') + if attr: + vardef = f"{vardef}, {','.join(attr)}" + c = ',' + if 'dimension' in vars[a]: + vardef = f"{vardef}{c}dimension({','.join(vars[a]['dimension'])})" + c = ',' + if 'intent' in vars[a]: + lst = true_intent_list(vars[a]) + if lst: + vardef = f"{vardef}{c}intent({','.join(lst)})" + c = ',' + if 'check' in vars[a]: + vardef = f"{vardef}{c}check({','.join(vars[a]['check'])})" + c = ',' + if 'depend' in vars[a]: + vardef = f"{vardef}{c}depend({','.join(vars[a]['depend'])})" + c = ',' + if '=' in vars[a]: + v = vars[a]['='] + if vars[a]['typespec'] in ['complex', 'double complex']: + try: + v = eval(v) + v = f'({v.real},{v.imag})' + except Exception: + pass + vardef = f'{vardef} :: {a}={v}' + else: + vardef = f'{vardef} :: {a}' + ret = f'{ret}{tab}{vardef}' + return ret +###### + + +# We expose post_processing_hooks as global variable so that +# user-libraries could register their own hooks to f2py. +post_processing_hooks = [] + + +def crackfortran(files): + global usermodules, post_processing_hooks + + outmess('Reading fortran codes...\n', 0) + readfortrancode(files, crackline) + outmess('Post-processing...\n', 0) + usermodules = [] + postlist = postcrack(grouplist[0]) + outmess('Applying post-processing hooks...\n', 0) + for hook in post_processing_hooks: + outmess(f' {hook.__name__}\n', 0) + postlist = traverse(postlist, hook) + outmess('Post-processing (stage 2)...\n', 0) + postlist = postcrack2(postlist) + return usermodules + postlist + + +def crack2fortran(block): + global f2py_version + + pyf = crack2fortrangen(block) + '\n' + header = """! -*- f90 -*- +! Note: the context of this file is case sensitive. +""" + footer = """ +! This file was auto-generated with f2py (version:%s). +! See: +! https://web.archive.org/web/20140822061353/http://cens.ioc.ee/projects/f2py2e +""" % (f2py_version) + return header + pyf + footer + + +def _is_visit_pair(obj): + return (isinstance(obj, tuple) + and len(obj) == 2 + and isinstance(obj[0], (int, str))) + + +def traverse(obj, visit, parents=[], result=None, *args, **kwargs): + '''Traverse f2py data structure with the following visit function: + + def visit(item, parents, result, *args, **kwargs): + """ + + parents is a list of key-"f2py data structure" pairs from which + items are taken from. + + result is a f2py data structure that is filled with the + return value of the visit function. + + item is 2-tuple (index, value) if parents[-1][1] is a list + item is 2-tuple (key, value) if parents[-1][1] is a dict + + The return value of visit must be None, or of the same kind as + item, that is, if parents[-1] is a list, the return value must + be 2-tuple (new_index, new_value), or if parents[-1] is a + dict, the return value must be 2-tuple (new_key, new_value). + + If new_index or new_value is None, the return value of visit + is ignored, that is, it will not be added to the result. + + If the return value is None, the content of obj will be + traversed, otherwise not. + """ + ''' + + if _is_visit_pair(obj): + if obj[0] == 'parent_block': + # avoid infinite recursion + return obj + new_result = visit(obj, parents, result, *args, **kwargs) + if new_result is not None: + assert _is_visit_pair(new_result) + return new_result + parent = obj + result_key, obj = obj + else: + parent = (None, obj) + result_key = None + + if isinstance(obj, list): + new_result = [] + for index, value in enumerate(obj): + new_index, new_item = traverse((index, value), visit, + parents + [parent], result, + *args, **kwargs) + if new_index is not None: + new_result.append(new_item) + elif isinstance(obj, dict): + new_result = {} + for key, value in obj.items(): + new_key, new_value = traverse((key, value), visit, + parents + [parent], result, + *args, **kwargs) + if new_key is not None: + new_result[new_key] = new_value + else: + new_result = obj + + if result_key is None: + return new_result + return result_key, new_result + + +def character_backward_compatibility_hook(item, parents, result, + *args, **kwargs): + """Previously, Fortran character was incorrectly treated as + character*1. This hook fixes the usage of the corresponding + variables in `check`, `dimension`, `=`, and `callstatement` + expressions. + + The usage of `char*` in `callprotoargument` expression can be left + unchanged because C `character` is C typedef of `char`, although, + new implementations should use `character*` in the corresponding + expressions. + + See https://github.com/numpy/numpy/pull/19388 for more information. + + """ + parent_key, parent_value = parents[-1] + key, value = item + + def fix_usage(varname, value): + value = re.sub(r'[*]\s*\b' + varname + r'\b', varname, value) + value = re.sub(r'\b' + varname + r'\b\s*[\[]\s*0\s*[\]]', + varname, value) + return value + + if parent_key in ['dimension', 'check']: + assert parents[-3][0] == 'vars' + vars_dict = parents[-3][1] + elif key == '=': + assert parents[-2][0] == 'vars' + vars_dict = parents[-2][1] + else: + vars_dict = None + + new_value = None + if vars_dict is not None: + new_value = value + for varname, vd in vars_dict.items(): + if ischaracter(vd): + new_value = fix_usage(varname, new_value) + elif key == 'callstatement': + vars_dict = parents[-2][1]['vars'] + new_value = value + for varname, vd in vars_dict.items(): + if ischaracter(vd): + # replace all occurrences of `` with + # `&` in argument passing + new_value = re.sub( + r'(? `{new_value}`\n', 1) + return (key, new_value) + + +post_processing_hooks.append(character_backward_compatibility_hook) + + +if __name__ == "__main__": + files = [] + funcs = [] + f = 1 + f2 = 0 + f3 = 0 + showblocklist = 0 + for l in sys.argv[1:]: + if l == '': + pass + elif l[0] == ':': + f = 0 + elif l == '-quiet': + quiet = 1 + verbose = 0 + elif l == '-verbose': + verbose = 2 + quiet = 0 + elif l == '-fix': + if strictf77: + outmess( + 'Use option -f90 before -fix if Fortran 90 code is in fix form.\n', 0) + skipemptyends = 1 + sourcecodeform = 'fix' + elif l == '-skipemptyends': + skipemptyends = 1 + elif l == '--ignore-contains': + ignorecontains = 1 + elif l == '-f77': + strictf77 = 1 + sourcecodeform = 'fix' + elif l == '-f90': + strictf77 = 0 + sourcecodeform = 'free' + skipemptyends = 1 + elif l == '-h': + f2 = 1 + elif l == '-show': + showblocklist = 1 + elif l == '-m': + f3 = 1 + elif l[0] == '-': + errmess(f'Unknown option {repr(l)}\n') + elif f2: + f2 = 0 + pyffilename = l + elif f3: + f3 = 0 + f77modulename = l + elif f: + try: + open(l).close() + files.append(l) + except OSError as detail: + errmess(f'OSError: {detail!s}\n') + else: + funcs.append(l) + if not strictf77 and f77modulename and not skipemptyends: + outmess("""\ + Warning: You have specified module name for non Fortran 77 code that + should not need one (expect if you are scanning F90 code for non + module blocks but then you should use flag -skipemptyends and also + be sure that the files do not contain programs without program + statement). +""", 0) + + postlist = crackfortran(files) + if pyffilename: + outmess(f'Writing fortran code to file {repr(pyffilename)}\n', 0) + pyf = crack2fortran(postlist) + with open(pyffilename, 'w') as f: + f.write(pyf) + if showblocklist: + show(postlist) diff --git a/python/user_packages/Python313/site-packages/numpy/f2py/crackfortran.pyi b/python/user_packages/Python313/site-packages/numpy/f2py/crackfortran.pyi new file mode 100644 index 0000000000000000000000000000000000000000..4d51a4d9594834ece7d12f2b5d8c2fdf33e0feba --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/f2py/crackfortran.pyi @@ -0,0 +1,266 @@ +import re +from _typeshed import StrOrBytesPath, StrPath +from collections.abc import Callable, Iterable, Mapping +from typing import ( + IO, + Any, + Concatenate, + Final, + Literal as L, + Never, + ParamSpec, + TypeAlias, + overload, +) + +from .__version__ import version +from .auxfuncs import isintent_dict as isintent_dict + +### + +_Tss = ParamSpec("_Tss") + +_VisitResult: TypeAlias = list[Any] | dict[str, Any] | None +_VisitItem: TypeAlias = tuple[str | None, _VisitResult] +_VisitFunc: TypeAlias = Callable[Concatenate[_VisitItem, list[_VisitItem], _VisitResult, _Tss], _VisitItem | None] + +### + +COMMON_FREE_EXTENSIONS: Final[list[str]] = ... +COMMON_FIXED_EXTENSIONS: Final[list[str]] = ... + +f2py_version: Final = version +tabchar: Final[str] = " " + +f77modulename: str +pyffilename: str +sourcecodeform: L["fix", "gree"] +strictf77: L[0, 1] +quiet: L[0, 1] +verbose: L[0, 1, 2] +skipemptyends: L[0, 1] +ignorecontains: L[1] +dolowercase: L[1] + +beginpattern: str | re.Pattern[str] +currentfilename: str +filepositiontext: str +expectbegin: L[0, 1] +gotnextfile: L[0, 1] +neededmodule: int +skipblocksuntil: int +groupcounter: int +groupname: dict[int, str] | str +groupcache: dict[int, dict[str, Any]] | None +grouplist: dict[int, list[dict[str, Any]]] | None +previous_context: tuple[str, str, int] | None + +f90modulevars: dict[str, dict[str, Any]] = {} +debug: list[Never] = [] +include_paths: list[str] = [] +onlyfuncs: list[str] = [] +skipfuncs: list[str] = [] +skipfunctions: Final[list[str]] = [] +usermodules: Final[list[dict[str, Any]]] = [] + +defaultimplicitrules: Final[dict[str, dict[str, str]]] = {} +badnames: Final[dict[str, str]] = {} +invbadnames: Final[dict[str, str]] = {} + +beforethisafter: Final[str] = ... +fortrantypes: Final[str] = ... +groupbegins77: Final[str] = ... +groupbegins90: Final[str] = ... +groupends: Final[str] = ... +endifs: Final[str] = ... +moduleprocedures: Final[str] = ... + +beginpattern77: Final[tuple[re.Pattern[str], L["begin"]]] = ... +beginpattern90: Final[tuple[re.Pattern[str], L["begin"]]] = ... +callpattern: Final[tuple[re.Pattern[str], L["call"]]] = ... +callfunpattern: Final[tuple[re.Pattern[str], L["callfun"]]] = ... +commonpattern: Final[tuple[re.Pattern[str], L["common"]]] = ... +containspattern: Final[tuple[re.Pattern[str], L["contains"]]] = ... +datapattern: Final[tuple[re.Pattern[str], L["data"]]] = ... +dimensionpattern: Final[tuple[re.Pattern[str], L["dimension"]]] = ... +endifpattern: Final[tuple[re.Pattern[str], L["endif"]]] = ... +endpattern: Final[tuple[re.Pattern[str], L["end"]]] = ... +entrypattern: Final[tuple[re.Pattern[str], L["entry"]]] = ... +externalpattern: Final[tuple[re.Pattern[str], L["external"]]] = ... +f2pyenhancementspattern: Final[tuple[re.Pattern[str], L["f2pyenhancements"]]] = ... +formatpattern: Final[tuple[re.Pattern[str], L["format"]]] = ... +functionpattern: Final[tuple[re.Pattern[str], L["begin"]]] = ... +implicitpattern: Final[tuple[re.Pattern[str], L["implicit"]]] = ... +intentpattern: Final[tuple[re.Pattern[str], L["intent"]]] = ... +intrinsicpattern: Final[tuple[re.Pattern[str], L["intrinsic"]]] = ... +optionalpattern: Final[tuple[re.Pattern[str], L["optional"]]] = ... +moduleprocedurepattern: Final[tuple[re.Pattern[str], L["moduleprocedure"]]] = ... +multilinepattern: Final[tuple[re.Pattern[str], L["multiline"]]] = ... +parameterpattern: Final[tuple[re.Pattern[str], L["parameter"]]] = ... +privatepattern: Final[tuple[re.Pattern[str], L["private"]]] = ... +publicpattern: Final[tuple[re.Pattern[str], L["public"]]] = ... +requiredpattern: Final[tuple[re.Pattern[str], L["required"]]] = ... +subroutinepattern: Final[tuple[re.Pattern[str], L["begin"]]] = ... +typespattern: Final[tuple[re.Pattern[str], L["type"]]] = ... +usepattern: Final[tuple[re.Pattern[str], L["use"]]] = ... + +analyzeargs_re_1: Final[re.Pattern[str]] = ... +callnameargspattern: Final[re.Pattern[str]] = ... +charselector: Final[re.Pattern[str]] = ... +crackline_bind_1: Final[re.Pattern[str]] = ... +crackline_bindlang: Final[re.Pattern[str]] = ... +crackline_re_1: Final[re.Pattern[str]] = ... +determineexprtype_re_1: Final[re.Pattern[str]] = ... +determineexprtype_re_2: Final[re.Pattern[str]] = ... +determineexprtype_re_3: Final[re.Pattern[str]] = ... +determineexprtype_re_4: Final[re.Pattern[str]] = ... +determineexprtype_re_5: Final[re.Pattern[str]] = ... +getlincoef_re_1: Final[re.Pattern[str]] = ... +kindselector: Final[re.Pattern[str]] = ... +lenarraypattern: Final[re.Pattern[str]] = ... +lenkindpattern: Final[re.Pattern[str]] = ... +namepattern: Final[re.Pattern[str]] = ... +nameargspattern: Final[re.Pattern[str]] = ... +operatorpattern: Final[re.Pattern[str]] = ... +real16pattern: Final[re.Pattern[str]] = ... +real8pattern: Final[re.Pattern[str]] = ... +selectpattern: Final[re.Pattern[str]] = ... +typedefpattern: Final[re.Pattern[str]] = ... +typespattern4implicit: Final[re.Pattern[str]] = ... +word_pattern: Final[re.Pattern[str]] = ... + +post_processing_hooks: Final[list[_VisitFunc[...]]] = [] + +# +def outmess(line: str, flag: int = 1) -> None: ... +def reset_global_f2py_vars() -> None: ... + +# +def rmbadname1(name: str) -> str: ... +def undo_rmbadname1(name: str) -> str: ... +def rmbadname(names: Iterable[str]) -> list[str]: ... +def undo_rmbadname(names: Iterable[str]) -> list[str]: ... + +# +def openhook(filename: StrPath, mode: str) -> IO[Any]: ... +def is_free_format(fname: StrPath) -> bool: ... +def readfortrancode( + ffile: StrOrBytesPath | Iterable[StrOrBytesPath], + dowithline: Callable[[str, int], object] = ..., + istop: int = 1, +) -> None: ... + +# +def split_by_unquoted(line: str, characters: str) -> tuple[str, str]: ... + +# +def crackline(line: str, reset: int = 0) -> None: ... +def markouterparen(line: str) -> str: ... +def markoutercomma(line: str, comma: str = ",") -> str: ... +def unmarkouterparen(line: str) -> str: ... +def appenddecl(decl: Mapping[str, object] | None, decl2: Mapping[str, object] | None, force: int = 1) -> dict[str, Any]: ... + +# +def parse_name_for_bind(line: str) -> tuple[str, str | None]: ... +def analyzeline(m: re.Match[str], case: str, line: str) -> None: ... +def appendmultiline(group: dict[str, Any], context_name: str, ml: str) -> None: ... +def cracktypespec0(typespec: str, ll: str | None) -> tuple[str, str | None, str | None, str | None]: ... + +# +def removespaces(expr: str) -> str: ... +def markinnerspaces(line: str) -> str: ... +def updatevars(typespec: str, selector: str | None, attrspec: str, entitydecl: str) -> str: ... +def cracktypespec(typespec: str, selector: str | None) -> tuple[dict[str, str] | None, dict[str, str] | None, str | None]: ... + +# +def setattrspec(decl: dict[str, list[str]], attr: str | None, force: int = 0) -> dict[str, list[str]]: ... +def setkindselector(decl: dict[str, dict[str, str]], sel: dict[str, str], force: int = 0) -> dict[str, dict[str, str]]: ... +def setcharselector(decl: dict[str, dict[str, str]], sel: dict[str, str], force: int = 0) -> dict[str, dict[str, str]]: ... +def getblockname(block: Mapping[str, object], unknown: str = "unknown") -> str: ... +def setmesstext(block: Mapping[str, object]) -> None: ... +def get_usedict(block: Mapping[str, object]) -> dict[str, str]: ... +def get_useparameters(block: Mapping[str, object], param_map: Mapping[str, str] | None = None) -> dict[str, str]: ... + +# +@overload +def postcrack2( + block: dict[str, Any], + tab: str = "", + param_map: Mapping[str, str] | None = None, +) -> dict[str, str | Any]: ... +@overload +def postcrack2( + block: list[dict[str, Any]], + tab: str = "", + param_map: Mapping[str, str] | None = None, +) -> list[dict[str, str | Any]]: ... + +# +@overload +def postcrack(block: dict[str, Any], args: Mapping[str, str] | None = None, tab: str = "") -> dict[str, Any]: ... +@overload +def postcrack(block: list[dict[str, str]], args: Mapping[str, str] | None = None, tab: str = "") -> list[dict[str, Any]]: ... + +# +def sortvarnames(vars: Mapping[str, object]) -> list[str]: ... +def analyzecommon(block: Mapping[str, object]) -> dict[str, Any]: ... +def analyzebody(block: Mapping[str, object], args: Mapping[str, str], tab: str = "") -> list[dict[str, Any]]: ... +def buildimplicitrules(block: Mapping[str, object]) -> tuple[dict[str, dict[str, str]], dict[str, str]]: ... +def myeval(e: str, g: object | None = None, l: object | None = None) -> float: ... + +# +def getlincoef(e: str, xset: set[str]) -> tuple[float | None, float | None, str | None]: ... + +# +def get_sorted_names(vars: Mapping[str, Mapping[str, str]]) -> list[str]: ... +def get_parameters(vars: Mapping[str, Mapping[str, str]], global_params: dict[str, str] = {}) -> dict[str, str]: ... + +# +def analyzevars(block: Mapping[str, Any]) -> dict[str, dict[str, str]]: ... + +# +def param_eval(v: str, g_params: dict[str, Any], params: Mapping[str, object], dimspec: str | None = None) -> dict[str, Any]: ... +def param_parse(d: str, params: Mapping[str, str]) -> str: ... +def expr2name(a: str, block: Mapping[str, object], args: list[str] = []) -> str: ... +def analyzeargs(block: Mapping[str, object]) -> dict[str, Any]: ... + +# +def determineexprtype(expr: str, vars: Mapping[str, object], rules: dict[str, Any] = {}) -> dict[str, Any]: ... +def crack2fortrangen(block: Mapping[str, object], tab: str = "\n", as_interface: bool = False) -> str: ... +def common2fortran(common: Mapping[str, object], tab: str = "") -> str: ... +def use2fortran(use: Mapping[str, object], tab: str = "") -> str: ... +def true_intent_list(var: dict[str, list[str]]) -> list[str]: ... +def vars2fortran( + block: Mapping[str, Mapping[str, object]], + vars: Mapping[str, object], + args: Mapping[str, str], + tab: str = "", + as_interface: bool = False, +) -> str: ... + +# +def crackfortran(files: StrOrBytesPath | Iterable[StrOrBytesPath]) -> list[dict[str, Any]]: ... +def crack2fortran(block: Mapping[str, Any]) -> str: ... + +# +def traverse( + obj: tuple[str | None, _VisitResult], + visit: _VisitFunc[_Tss], + parents: list[tuple[str | None, _VisitResult]] = [], + result: list[Any] | dict[str, Any] | None = None, + *args: _Tss.args, + **kwargs: _Tss.kwargs, +) -> _VisitItem | _VisitResult: ... + +# +def character_backward_compatibility_hook( + item: _VisitItem, + parents: list[_VisitItem], + result: object, # ignored + *args: object, # ignored + **kwargs: object, # ignored +) -> _VisitItem | None: ... + +# namespace pollution +c: str +n: str diff --git a/python/user_packages/Python313/site-packages/numpy/f2py/diagnose.py b/python/user_packages/Python313/site-packages/numpy/f2py/diagnose.py new file mode 100644 index 0000000000000000000000000000000000000000..9b8045c0c9d9b18ce55d492826893e95a0c87c7f --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/f2py/diagnose.py @@ -0,0 +1,149 @@ +#!/usr/bin/env python3 +import os +import sys +import tempfile + + +def run(): + _path = os.getcwd() + os.chdir(tempfile.gettempdir()) + print('------') + print(f'os.name={os.name!r}') + print('------') + print(f'sys.platform={sys.platform!r}') + print('------') + print('sys.version:') + print(sys.version) + print('------') + print('sys.prefix:') + print(sys.prefix) + print('------') + print(f"sys.path={':'.join(sys.path)!r}") + print('------') + + try: + import numpy + has_newnumpy = 1 + except ImportError as e: + print('Failed to import new numpy:', e) + has_newnumpy = 0 + + try: + from numpy.f2py import f2py2e + has_f2py2e = 1 + except ImportError as e: + print('Failed to import f2py2e:', e) + has_f2py2e = 0 + + try: + import numpy.distutils + has_numpy_distutils = 2 + except ImportError: + try: + import numpy_distutils + has_numpy_distutils = 1 + except ImportError as e: + print('Failed to import numpy_distutils:', e) + has_numpy_distutils = 0 + + if has_newnumpy: + try: + print(f'Found new numpy version {numpy.__version__!r} in {numpy.__file__}') + except Exception as msg: + print('error:', msg) + print('------') + + if has_f2py2e: + try: + print('Found f2py2e version %r in %s' % + (f2py2e.__version__.version, f2py2e.__file__)) + except Exception as msg: + print('error:', msg) + print('------') + + if has_numpy_distutils: + try: + if has_numpy_distutils == 2: + print('Found numpy.distutils version %r in %r' % ( + numpy.distutils.__version__, + numpy.distutils.__file__)) + else: + print('Found numpy_distutils version %r in %r' % ( + numpy_distutils.numpy_distutils_version.numpy_distutils_version, + numpy_distutils.__file__)) + print('------') + except Exception as msg: + print('error:', msg) + print('------') + try: + if has_numpy_distutils == 1: + print( + 'Importing numpy_distutils.command.build_flib ...', end=' ') + import numpy_distutils.command.build_flib as build_flib + print('ok') + print('------') + try: + print( + 'Checking availability of supported Fortran compilers:') + for compiler_class in build_flib.all_compilers: + compiler_class(verbose=1).is_available() + print('------') + except Exception as msg: + print('error:', msg) + print('------') + except Exception as msg: + print( + 'error:', msg, '(ignore it, build_flib is obsolete for numpy.distutils 0.2.2 and up)') + print('------') + try: + if has_numpy_distutils == 2: + print('Importing numpy.distutils.fcompiler ...', end=' ') + import numpy.distutils.fcompiler as fcompiler + else: + print('Importing numpy_distutils.fcompiler ...', end=' ') + import numpy_distutils.fcompiler as fcompiler + print('ok') + print('------') + try: + print('Checking availability of supported Fortran compilers:') + fcompiler.show_fcompilers() + print('------') + except Exception as msg: + print('error:', msg) + print('------') + except Exception as msg: + print('error:', msg) + print('------') + try: + if has_numpy_distutils == 2: + print('Importing numpy.distutils.cpuinfo ...', end=' ') + from numpy.distutils.cpuinfo import cpuinfo + print('ok') + print('------') + else: + try: + print( + 'Importing numpy_distutils.command.cpuinfo ...', end=' ') + from numpy_distutils.command.cpuinfo import cpuinfo + print('ok') + print('------') + except Exception as msg: + print('error:', msg, '(ignore it)') + print('Importing numpy_distutils.cpuinfo ...', end=' ') + from numpy_distutils.cpuinfo import cpuinfo + print('ok') + print('------') + cpu = cpuinfo() + print('CPU information:', end=' ') + for name in dir(cpuinfo): + if name[0] == '_' and name[1] != '_' and getattr(cpu, name[1:])(): + print(name[1:], end=' ') + print('------') + except Exception as msg: + print('error:', msg) + print('------') + os.chdir(_path) + + +if __name__ == "__main__": + run() diff --git a/python/user_packages/Python313/site-packages/numpy/f2py/diagnose.pyi b/python/user_packages/Python313/site-packages/numpy/f2py/diagnose.pyi new file mode 100644 index 0000000000000000000000000000000000000000..a01716406e010e9b12d804bf60ca5a53df61c661 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/f2py/diagnose.pyi @@ -0,0 +1 @@ +def run() -> None: ... diff --git a/python/user_packages/Python313/site-packages/numpy/f2py/f2py2e.py b/python/user_packages/Python313/site-packages/numpy/f2py/f2py2e.py new file mode 100644 index 0000000000000000000000000000000000000000..a239f1e9a90d48ab60edbfa01056c75bc4775e25 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/f2py/f2py2e.py @@ -0,0 +1,788 @@ +""" + +f2py2e - Fortran to Python C/API generator. 2nd Edition. + See __usage__ below. + +Copyright 1999 -- 2011 Pearu Peterson all rights reserved. +Copyright 2011 -- present NumPy Developers. +Permission to use, modify, and distribute this software is given under the +terms of the NumPy License. + +NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. +""" +import argparse +import os +import pprint +import re +import sys + +from numpy.f2py._backends import f2py_build_generator + +from . import ( + __version__, + auxfuncs, + capi_maps, + cb_rules, + cfuncs, + crackfortran, + f90mod_rules, + rules, +) +from .cfuncs import errmess + +f2py_version = __version__.version +numpy_version = __version__.version + +# outmess=sys.stdout.write +show = pprint.pprint +outmess = auxfuncs.outmess +MESON_ONLY_VER = (sys.version_info >= (3, 12)) + +__usage__ =\ +f"""Usage: + +1) To construct extension module sources: + + f2py [] [[[only:]||[skip:]] \\ + ] \\ + [: ...] + +2) To compile fortran files and build extension modules: + + f2py -c [, , ] + +3) To generate signature files: + + f2py -h ...< same options as in (1) > + +Description: This program generates a Python C/API file (module.c) + that contains wrappers for given fortran functions so that they + can be called from Python. With the -c option the corresponding + extension modules are built. + +Options: + + -h Write signatures of the fortran routines to file + and exit. You can then edit and use it instead + of . If ==stdout then the + signatures are printed to stdout. + Names of fortran routines for which Python C/API + functions will be generated. Default is all that are found + in . + Paths to fortran/signature files that will be scanned for + in order to determine their signatures. + skip: Ignore fortran functions that follow until `:'. + only: Use only fortran functions that follow until `:'. + : Get back to mode. + + -m Name of the module; f2py generates a Python/C API + file module.c or extension module . + Default is 'untitled'. + + '-include

' Writes additional headers in the C wrapper, can be passed + multiple times, generates #include
each time. + + --[no-]lower Do [not] lower the cases in . By default, + --lower is assumed with -h key, and --no-lower without -h key. + + --build-dir All f2py generated files are created in . + Default is tempfile.mkdtemp(). + + --overwrite-signature Overwrite existing signature file. + + --[no-]latex-doc Create (or not) module.tex. + Default is --no-latex-doc. + --short-latex Create 'incomplete' LaTeX document (without commands + \\documentclass, \\tableofcontents, and \\begin{{document}}, + \\end{{document}}). + + --[no-]rest-doc Create (or not) module.rst. + Default is --no-rest-doc. + + --debug-capi Create C/API code that reports the state of the wrappers + during runtime. Useful for debugging. + + --[no-]wrap-functions Create Fortran subroutine wrappers to Fortran 77 + functions. --wrap-functions is default because it ensures + maximum portability/compiler independence. + + --[no-]freethreading-compatible Create a module that declares it does or + doesn't require the GIL. The default is + --freethreading-compatible for backward + compatibility. Inspect the Fortran code you are wrapping for + thread safety issues before passing + --no-freethreading-compatible, as f2py does not analyze + fortran code for thread safety issues. + + --include-paths ::... Search include files from the given + directories. + + --help-link [..] List system resources found by system_info.py. See also + --link- switch below. [..] is optional list + of resources names. E.g. try 'f2py --help-link lapack_opt'. + + --f2cmap Load Fortran-to-Python KIND specification from the given + file. Default: .f2py_f2cmap in current directory. + + --quiet Run quietly. + --verbose Run with extra verbosity. + --skip-empty-wrappers Only generate wrapper files when needed. + -v Print f2py version ID and exit. + + +build backend options (only effective with -c) +[NO_MESON] is used to indicate an option not meant to be used +with the meson backend or above Python 3.12: + + --fcompiler= Specify Fortran compiler type by vendor [NO_MESON] + --compiler= Specify distutils C compiler type [NO_MESON] + + --help-fcompiler List available Fortran compilers and exit [NO_MESON] + --f77exec= Specify the path to F77 compiler [NO_MESON] + --f90exec= Specify the path to F90 compiler [NO_MESON] + --f77flags= Specify F77 compiler flags + --f90flags= Specify F90 compiler flags + --opt= Specify optimization flags [NO_MESON] + --arch= Specify architecture specific optimization flags [NO_MESON] + --noopt Compile without optimization [NO_MESON] + --noarch Compile without arch-dependent optimization [NO_MESON] + --debug Compile with debugging information + + --dep + Specify a meson dependency for the module. This may + be passed multiple times for multiple dependencies. + Dependencies are stored in a list for further processing. + + Example: --dep lapack --dep scalapack + This will identify "lapack" and "scalapack" as dependencies + and remove them from argv, leaving a dependencies list + containing ["lapack", "scalapack"]. + + --backend + Specify the build backend for the compilation process. + The supported backends are 'meson' and 'distutils'. + If not specified, defaults to 'distutils'. On + Python 3.12 or higher, the default is 'meson'. + +Extra options (only effective with -c): + + --link- Link extension module with as defined + by numpy.distutils/system_info.py. E.g. to link + with optimized LAPACK libraries (vecLib on MacOSX, + ATLAS elsewhere), use --link-lapack_opt. + See also --help-link switch. [NO_MESON] + + -L/path/to/lib/ -l + -D -U + -I/path/to/include/ + .o .so .a + + Using the following macros may be required with non-gcc Fortran + compilers: + -DPREPEND_FORTRAN -DNO_APPEND_FORTRAN -DUPPERCASE_FORTRAN + + When using -DF2PY_REPORT_ATEXIT, a performance report of F2PY + interface is printed out at exit (platforms: Linux). + + When using -DF2PY_REPORT_ON_ARRAY_COPY=, a message is + sent to stderr whenever F2PY interface makes a copy of an + array. Integer sets the threshold for array sizes when + a message should be shown. + +Version: {f2py_version} +numpy Version: {numpy_version} +License: NumPy license (see LICENSE.txt in the NumPy source code) +Copyright 1999 -- 2011 Pearu Peterson all rights reserved. +Copyright 2011 -- present NumPy Developers. +https://numpy.org/doc/stable/f2py/index.html\n""" + + +def scaninputline(inputline): + files, skipfuncs, onlyfuncs, debug = [], [], [], [] + f, f2, f3, f5, f6, f8, f9, f10 = 1, 0, 0, 0, 0, 0, 0, 0 + verbose = 1 + emptygen = True + dolc = -1 + dolatexdoc = 0 + dorestdoc = 0 + wrapfuncs = 1 + buildpath = '.' + include_paths, freethreading_compatible, inputline = get_newer_options(inputline) + signsfile, modulename = None, None + options = {'buildpath': buildpath, + 'coutput': None, + 'f2py_wrapper_output': None} + for l in inputline: + if l == '': + pass + elif l == 'only:': + f = 0 + elif l == 'skip:': + f = -1 + elif l == ':': + f = 1 + elif l[:8] == '--debug-': + debug.append(l[8:]) + elif l == '--lower': + dolc = 1 + elif l == '--build-dir': + f6 = 1 + elif l == '--no-lower': + dolc = 0 + elif l == '--quiet': + verbose = 0 + elif l == '--verbose': + verbose += 1 + elif l == '--latex-doc': + dolatexdoc = 1 + elif l == '--no-latex-doc': + dolatexdoc = 0 + elif l == '--rest-doc': + dorestdoc = 1 + elif l == '--no-rest-doc': + dorestdoc = 0 + elif l == '--wrap-functions': + wrapfuncs = 1 + elif l == '--no-wrap-functions': + wrapfuncs = 0 + elif l == '--short-latex': + options['shortlatex'] = 1 + elif l == '--coutput': + f8 = 1 + elif l == '--f2py-wrapper-output': + f9 = 1 + elif l == '--f2cmap': + f10 = 1 + elif l == '--overwrite-signature': + options['h-overwrite'] = 1 + elif l == '-h': + f2 = 1 + elif l == '-m': + f3 = 1 + elif l[:2] == '-v': + print(f2py_version) + sys.exit() + elif l == '--show-compilers': + f5 = 1 + elif l[:8] == '-include': + cfuncs.outneeds['userincludes'].append(l[9:-1]) + cfuncs.userincludes[l[9:-1]] = '#include ' + l[8:] + elif l == '--skip-empty-wrappers': + emptygen = False + elif l[0] == '-': + errmess(f'Unknown option {repr(l)}\n') + sys.exit() + elif f2: + f2 = 0 + signsfile = l + elif f3: + f3 = 0 + modulename = l + elif f6: + f6 = 0 + buildpath = l + elif f8: + f8 = 0 + options["coutput"] = l + elif f9: + f9 = 0 + options["f2py_wrapper_output"] = l + elif f10: + f10 = 0 + options["f2cmap_file"] = l + elif f == 1: + try: + with open(l): + pass + files.append(l) + except OSError as detail: + errmess(f'OSError: {detail!s}. Skipping file "{l!s}".\n') + elif f == -1: + skipfuncs.append(l) + elif f == 0: + onlyfuncs.append(l) + if not f5 and not files and not modulename: + print(__usage__) + sys.exit() + if not os.path.isdir(buildpath): + if not verbose: + outmess(f'Creating build directory {buildpath}\n') + os.mkdir(buildpath) + if signsfile: + signsfile = os.path.join(buildpath, signsfile) + if signsfile and os.path.isfile(signsfile) and 'h-overwrite' not in options: + errmess( + f'Signature file "{signsfile}" exists!!! Use --overwrite-signature to overwrite.\n') + sys.exit() + + options['emptygen'] = emptygen + options['debug'] = debug + options['verbose'] = verbose + if dolc == -1 and not signsfile: + options['do-lower'] = 0 + else: + options['do-lower'] = dolc + if modulename: + options['module'] = modulename + if signsfile: + options['signsfile'] = signsfile + if onlyfuncs: + options['onlyfuncs'] = onlyfuncs + if skipfuncs: + options['skipfuncs'] = skipfuncs + options['dolatexdoc'] = dolatexdoc + options['dorestdoc'] = dorestdoc + options['wrapfuncs'] = wrapfuncs + options['buildpath'] = buildpath + options['include_paths'] = include_paths + options['requires_gil'] = not freethreading_compatible + options.setdefault('f2cmap_file', None) + return files, options + + +def callcrackfortran(files, options): + rules.options = options + crackfortran.debug = options['debug'] + crackfortran.verbose = options['verbose'] + if 'module' in options: + crackfortran.f77modulename = options['module'] + if 'skipfuncs' in options: + crackfortran.skipfuncs = options['skipfuncs'] + if 'onlyfuncs' in options: + crackfortran.onlyfuncs = options['onlyfuncs'] + crackfortran.include_paths[:] = options['include_paths'] + crackfortran.dolowercase = options['do-lower'] + postlist = crackfortran.crackfortran(files) + if 'signsfile' in options: + outmess(f"Saving signatures to file \"{options['signsfile']}\"\n") + pyf = crackfortran.crack2fortran(postlist) + if options['signsfile'][-6:] == 'stdout': + sys.stdout.write(pyf) + else: + with open(options['signsfile'], 'w') as f: + f.write(pyf) + if options["coutput"] is None: + for mod in postlist: + mod["coutput"] = f"{mod['name']}module.c" + else: + for mod in postlist: + mod["coutput"] = options["coutput"] + if options["f2py_wrapper_output"] is None: + for mod in postlist: + mod["f2py_wrapper_output"] = f"{mod['name']}-f2pywrappers.f" + else: + for mod in postlist: + mod["f2py_wrapper_output"] = options["f2py_wrapper_output"] + for mod in postlist: + if options["requires_gil"]: + mod['gil_used'] = 'Py_MOD_GIL_USED' + else: + mod['gil_used'] = 'Py_MOD_GIL_NOT_USED' + # gh-26718 Reset global + crackfortran.f77modulename = '' + return postlist + + +def buildmodules(lst): + cfuncs.buildcfuncs() + outmess('Building modules...\n') + modules, mnames, isusedby = [], [], {} + for item in lst: + if '__user__' in item['name']: + cb_rules.buildcallbacks(item) + else: + if 'use' in item: + for u in item['use'].keys(): + if u not in isusedby: + isusedby[u] = [] + isusedby[u].append(item['name']) + modules.append(item) + mnames.append(item['name']) + ret = {} + for module, name in zip(modules, mnames): + if name in isusedby: + outmess('\tSkipping module "%s" which is used by %s.\n' % ( + name, ','.join('"%s"' % s for s in isusedby[name]))) + else: + um = [] + if 'use' in module: + for u in module['use'].keys(): + if u in isusedby and u in mnames: + um.append(modules[mnames.index(u)]) + else: + outmess( + f'\tModule "{name}" uses nonexisting "{u}" ' + 'which will be ignored.\n') + ret[name] = {} + dict_append(ret[name], rules.buildmodule(module, um)) + return ret + + +def dict_append(d_out, d_in): + for (k, v) in d_in.items(): + if k not in d_out: + d_out[k] = [] + if isinstance(v, list): + d_out[k] = d_out[k] + v + else: + d_out[k].append(v) + + +def run_main(comline_list): + """ + Equivalent to running:: + + f2py + + where ``=string.join(,' ')``, but in Python. Unless + ``-h`` is used, this function returns a dictionary containing + information on generated modules and their dependencies on source + files. + + You cannot build extension modules with this function, that is, + using ``-c`` is not allowed. Use the ``compile`` command instead. + + Examples + -------- + The command ``f2py -m scalar scalar.f`` can be executed from Python as + follows. + + .. literalinclude:: ../../source/f2py/code/results/run_main_session.dat + :language: python + + """ + crackfortran.reset_global_f2py_vars() + f2pydir = os.path.dirname(os.path.abspath(cfuncs.__file__)) + fobjhsrc = os.path.join(f2pydir, 'src', 'fortranobject.h') + fobjcsrc = os.path.join(f2pydir, 'src', 'fortranobject.c') + # gh-22819 -- begin + parser = make_f2py_compile_parser() + args, comline_list = parser.parse_known_args(comline_list) + pyf_files, _ = filter_files("", "[.]pyf([.]src|)", comline_list) + # Checks that no existing modulename is defined in a pyf file + # TODO: Remove all this when scaninputline is replaced + if args.module_name: + if "-h" in comline_list: + modname = ( + args.module_name + ) # Directly use from args when -h is present + else: + modname = validate_modulename( + pyf_files, args.module_name + ) # Validate modname when -h is not present + comline_list += ['-m', modname] # needed for the rest of scaninputline + # gh-22819 -- end + files, options = scaninputline(comline_list) + auxfuncs.options = options + capi_maps.load_f2cmap_file(options['f2cmap_file']) + postlist = callcrackfortran(files, options) + isusedby = {} + for plist in postlist: + if 'use' in plist: + for u in plist['use'].keys(): + if u not in isusedby: + isusedby[u] = [] + isusedby[u].append(plist['name']) + for plist in postlist: + module_name = plist['name'] + if plist['block'] == 'python module' and '__user__' in module_name: + if module_name in isusedby: + # if not quiet: + usedby = ','.join(f'"{s}"' for s in isusedby[module_name]) + outmess( + f'Skipping Makefile build for module "{module_name}" ' + f'which is used by {usedby}\n') + if 'signsfile' in options: + if options['verbose'] > 1: + outmess( + 'Stopping. Edit the signature file and then run f2py on the signature file: ') + outmess(f"{os.path.basename(sys.argv[0])} {options['signsfile']}\n") + return + for plist in postlist: + if plist['block'] != 'python module': + if 'python module' not in options: + errmess( + 'Tip: If your original code is Fortran source then you must use -m option.\n') + raise TypeError('All blocks must be python module blocks but got %s' % ( + repr(plist['block']))) + auxfuncs.debugoptions = options['debug'] + f90mod_rules.options = options + auxfuncs.wrapfuncs = options['wrapfuncs'] + + ret = buildmodules(postlist) + + for mn in ret.keys(): + dict_append(ret[mn], {'csrc': fobjcsrc, 'h': fobjhsrc}) + return ret + + +def filter_files(prefix, suffix, files, remove_prefix=None): + """ + Filter files by prefix and suffix. + """ + filtered, rest = [], [] + match = re.compile(prefix + r'.*' + suffix + r'\Z').match + if remove_prefix: + ind = len(prefix) + else: + ind = 0 + for file in [x.strip() for x in files]: + if match(file): + filtered.append(file[ind:]) + else: + rest.append(file) + return filtered, rest + + +def get_prefix(module): + p = os.path.dirname(os.path.dirname(module.__file__)) + return p + + +class CombineIncludePaths(argparse.Action): + def __call__(self, parser, namespace, values, option_string=None): + include_paths_set = set(getattr(namespace, 'include_paths', []) or []) + if option_string == "--include_paths": + outmess("Use --include-paths or -I instead of --include_paths which will be removed") + if option_string in {"--include-paths", "--include_paths"}: + include_paths_set.update(values.split(':')) + else: + include_paths_set.add(values) + namespace.include_paths = list(include_paths_set) + +def f2py_parser(): + parser = argparse.ArgumentParser(add_help=False) + parser.add_argument("-I", dest="include_paths", action=CombineIncludePaths) + parser.add_argument("--include-paths", dest="include_paths", action=CombineIncludePaths) + parser.add_argument("--include_paths", dest="include_paths", action=CombineIncludePaths) + parser.add_argument("--freethreading-compatible", dest="ftcompat", action=argparse.BooleanOptionalAction) + return parser + +def get_newer_options(iline): + iline = (' '.join(iline)).split() + parser = f2py_parser() + args, remain = parser.parse_known_args(iline) + ipaths = args.include_paths + if args.include_paths is None: + ipaths = [] + return ipaths, args.ftcompat, remain + +def make_f2py_compile_parser(): + parser = argparse.ArgumentParser(add_help=False) + parser.add_argument("--dep", action="append", dest="dependencies") + parser.add_argument("--backend", choices=['meson', 'distutils'], default='distutils') + parser.add_argument("-m", dest="module_name") + return parser + +def preparse_sysargv(): + # To keep backwards bug compatibility, newer flags are handled by argparse, + # and `sys.argv` is passed to the rest of `f2py` as is. + parser = make_f2py_compile_parser() + + args, remaining_argv = parser.parse_known_args() + sys.argv = [sys.argv[0]] + remaining_argv + + backend_key = args.backend + if MESON_ONLY_VER and backend_key == 'distutils': + outmess("Cannot use distutils backend with Python>=3.12," + " using meson backend instead.\n") + backend_key = "meson" + + return { + "dependencies": args.dependencies or [], + "backend": backend_key, + "modulename": args.module_name, + } + +def run_compile(): + """ + Do it all in one call! + """ + import tempfile + + # Collect dependency flags, preprocess sys.argv + argy = preparse_sysargv() + modulename = argy["modulename"] + if modulename is None: + modulename = 'untitled' + dependencies = argy["dependencies"] + backend_key = argy["backend"] + build_backend = f2py_build_generator(backend_key) + + i = sys.argv.index('-c') + del sys.argv[i] + + remove_build_dir = 0 + try: + i = sys.argv.index('--build-dir') + except ValueError: + i = None + if i is not None: + build_dir = sys.argv[i + 1] + del sys.argv[i + 1] + del sys.argv[i] + else: + remove_build_dir = 1 + build_dir = tempfile.mkdtemp() + + _reg1 = re.compile(r'--link-') + sysinfo_flags = [_m for _m in sys.argv[1:] if _reg1.match(_m)] + sys.argv = [_m for _m in sys.argv if _m not in sysinfo_flags] + if sysinfo_flags: + sysinfo_flags = [f[7:] for f in sysinfo_flags] + + _reg2 = re.compile( + r'--((no-|)(wrap-functions|lower|freethreading-compatible)|debug-capi|quiet|skip-empty-wrappers)|-include') + f2py_flags = [_m for _m in sys.argv[1:] if _reg2.match(_m)] + sys.argv = [_m for _m in sys.argv if _m not in f2py_flags] + f2py_flags2 = [] + fl = 0 + for a in sys.argv[1:]: + if a in ['only:', 'skip:']: + fl = 1 + elif a == ':': + fl = 0 + if fl or a == ':': + f2py_flags2.append(a) + if f2py_flags2 and f2py_flags2[-1] != ':': + f2py_flags2.append(':') + f2py_flags.extend(f2py_flags2) + sys.argv = [_m for _m in sys.argv if _m not in f2py_flags2] + _reg3 = re.compile( + r'--((f(90)?compiler(-exec|)|compiler)=|help-compiler)') + flib_flags = [_m for _m in sys.argv[1:] if _reg3.match(_m)] + sys.argv = [_m for _m in sys.argv if _m not in flib_flags] + # TODO: Once distutils is dropped completely, i.e. min_ver >= 3.12, unify into --fflags + reg_f77_f90_flags = re.compile(r'--f(77|90)flags=') + reg_distutils_flags = re.compile(r'--((f(77|90)exec|opt|arch)=|(debug|noopt|noarch|help-fcompiler))') + fc_flags = [_m for _m in sys.argv[1:] if reg_f77_f90_flags.match(_m)] + distutils_flags = [_m for _m in sys.argv[1:] if reg_distutils_flags.match(_m)] + if not (MESON_ONLY_VER or backend_key == 'meson'): + fc_flags.extend(distutils_flags) + sys.argv = [_m for _m in sys.argv if _m not in (fc_flags + distutils_flags)] + + del_list = [] + for s in flib_flags: + v = '--fcompiler=' + if s[:len(v)] == v: + if MESON_ONLY_VER or backend_key == 'meson': + outmess( + "--fcompiler cannot be used with meson," + "set compiler with the FC environment variable\n" + ) + else: + from numpy.distutils import fcompiler + fcompiler.load_all_fcompiler_classes() + allowed_keys = list(fcompiler.fcompiler_class.keys()) + nv = ov = s[len(v):].lower() + if ov not in allowed_keys: + vmap = {} # XXX + try: + nv = vmap[ov] + except KeyError: + if ov not in vmap.values(): + print(f'Unknown vendor: "{s[len(v):]}"') + nv = ov + i = flib_flags.index(s) + flib_flags[i] = '--fcompiler=' + nv # noqa: B909 + continue + for s in del_list: + i = flib_flags.index(s) + del flib_flags[i] + assert len(flib_flags) <= 2, repr(flib_flags) + + _reg5 = re.compile(r'--(verbose)') + setup_flags = [_m for _m in sys.argv[1:] if _reg5.match(_m)] + sys.argv = [_m for _m in sys.argv if _m not in setup_flags] + + if '--quiet' in f2py_flags: + setup_flags.append('--quiet') + + # Ugly filter to remove everything but sources + sources = sys.argv[1:] + f2cmapopt = '--f2cmap' + if f2cmapopt in sys.argv: + i = sys.argv.index(f2cmapopt) + f2py_flags.extend(sys.argv[i:i + 2]) + del sys.argv[i + 1], sys.argv[i] + sources = sys.argv[1:] + + pyf_files, _sources = filter_files("", "[.]pyf([.]src|)", sources) + sources = pyf_files + _sources + modulename = validate_modulename(pyf_files, modulename) + extra_objects, sources = filter_files('', '[.](o|a|so|dylib)', sources) + library_dirs, sources = filter_files('-L', '', sources, remove_prefix=1) + libraries, sources = filter_files('-l', '', sources, remove_prefix=1) + undef_macros, sources = filter_files('-U', '', sources, remove_prefix=1) + define_macros, sources = filter_files('-D', '', sources, remove_prefix=1) + for i in range(len(define_macros)): + name_value = define_macros[i].split('=', 1) + if len(name_value) == 1: + name_value.append(None) + if len(name_value) == 2: + define_macros[i] = tuple(name_value) + else: + print('Invalid use of -D:', name_value) + + # Construct wrappers / signatures / things + if backend_key == 'meson': + if not pyf_files: + outmess('Using meson backend\nWill pass --lower to f2py\nSee https://numpy.org/doc/stable/f2py/buildtools/meson.html\n') + f2py_flags.append('--lower') + run_main(f" {' '.join(f2py_flags)} -m {modulename} {' '.join(sources)}".split()) + else: + run_main(f" {' '.join(f2py_flags)} {' '.join(pyf_files)}".split()) + + # Order matters here, includes are needed for run_main above + include_dirs, _, sources = get_newer_options(sources) + # Now use the builder + builder = build_backend( + modulename, + sources, + extra_objects, + build_dir, + include_dirs, + library_dirs, + libraries, + define_macros, + undef_macros, + f2py_flags, + sysinfo_flags, + fc_flags, + flib_flags, + setup_flags, + remove_build_dir, + {"dependencies": dependencies}, + ) + + builder.compile() + + +def validate_modulename(pyf_files, modulename='untitled'): + if len(pyf_files) > 1: + raise ValueError("Only one .pyf file per call") + if pyf_files: + pyff = pyf_files[0] + pyf_modname = auxfuncs.get_f2py_modulename(pyff) + if modulename != pyf_modname: + outmess( + f"Ignoring -m {modulename}.\n" + f"{pyff} defines {pyf_modname} to be the modulename.\n" + ) + modulename = pyf_modname + return modulename + +def main(): + if '--help-link' in sys.argv[1:]: + sys.argv.remove('--help-link') + if MESON_ONLY_VER: + outmess("Use --dep for meson builds\n") + else: + from numpy.distutils.system_info import show_all + show_all() + return + + if '-c' in sys.argv[1:]: + run_compile() + else: + run_main(sys.argv[1:]) diff --git a/python/user_packages/Python313/site-packages/numpy/f2py/f2py2e.pyi b/python/user_packages/Python313/site-packages/numpy/f2py/f2py2e.pyi new file mode 100644 index 0000000000000000000000000000000000000000..ee16cca9321c038fc7a72aedbdc3923bc33fea56 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/f2py/f2py2e.pyi @@ -0,0 +1,74 @@ +import argparse +import pprint +from collections.abc import Hashable, Iterable, Mapping, MutableMapping, Sequence +from types import ModuleType +from typing import Any, Final, NotRequired, TypedDict, type_check_only +from typing_extensions import TypeVar, override + +from .__version__ import version +from .auxfuncs import _Bool, outmess as outmess + +### + +_KT = TypeVar("_KT", bound=Hashable) +_VT = TypeVar("_VT") + +@type_check_only +class _F2PyDict(TypedDict): + csrc: list[str] + h: list[str] + fsrc: NotRequired[list[str]] + ltx: NotRequired[list[str]] + +@type_check_only +class _PreparseResult(TypedDict): + dependencies: list[str] + backend: str + modulename: str + +### + +MESON_ONLY_VER: Final[bool] +f2py_version: Final = version +numpy_version: Final = version +__usage__: Final[str] + +show = pprint.pprint + +class CombineIncludePaths(argparse.Action): + @override + def __call__( + self, + /, + parser: argparse.ArgumentParser, + namespace: argparse.Namespace, + values: str | Sequence[str] | None, + option_string: str | None = None, + ) -> None: ... + +# +def run_main(comline_list: Iterable[str]) -> dict[str, _F2PyDict]: ... +def run_compile() -> None: ... +def main() -> None: ... + +# +def scaninputline(inputline: Iterable[str]) -> tuple[list[str], dict[str, _Bool]]: ... +def callcrackfortran(files: list[str], options: dict[str, bool]) -> list[dict[str, Any]]: ... +def buildmodules(lst: Iterable[Mapping[str, object]]) -> dict[str, dict[str, Any]]: ... +def dict_append(d_out: MutableMapping[_KT, _VT], d_in: Mapping[_KT, _VT]) -> None: ... +def filter_files( + prefix: str, + suffix: str, + files: Iterable[str], + remove_prefix: _Bool | None = None, +) -> tuple[list[str], list[str]]: ... +def get_prefix(module: ModuleType) -> str: ... +def get_newer_options(iline: Iterable[str]) -> tuple[list[str], Any, list[str]]: ... + +# +def f2py_parser() -> argparse.ArgumentParser: ... +def make_f2py_compile_parser() -> argparse.ArgumentParser: ... + +# +def preparse_sysargv() -> _PreparseResult: ... +def validate_modulename(pyf_files: Sequence[str], modulename: str = "untitled") -> str: ... diff --git a/python/user_packages/Python313/site-packages/numpy/f2py/f90mod_rules.py b/python/user_packages/Python313/site-packages/numpy/f2py/f90mod_rules.py new file mode 100644 index 0000000000000000000000000000000000000000..85c1399e80548d7440b6dddd69a9c67e5e27bf84 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/f2py/f90mod_rules.py @@ -0,0 +1,269 @@ +""" +Build F90 module support for f2py2e. + +Copyright 1999 -- 2011 Pearu Peterson all rights reserved. +Copyright 2011 -- present NumPy Developers. +Permission to use, modify, and distribute this software is given under the +terms of the NumPy License. + +NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. +""" +__version__ = "$Revision: 1.27 $"[10:-1] + +f2py_version = 'See `f2py -v`' + +import numpy as np + +from . import capi_maps, func2subr + +# The environment provided by auxfuncs.py is needed for some calls to eval. +# As the needed functions cannot be determined by static inspection of the +# code, it is safest to use import * pending a major refactoring of f2py. +from .auxfuncs import * +from .crackfortran import undo_rmbadname, undo_rmbadname1 + +options = {} + + +def findf90modules(m): + if ismodule(m): + return [m] + if not hasbody(m): + return [] + ret = [] + for b in m['body']: + if ismodule(b): + ret.append(b) + else: + ret = ret + findf90modules(b) + return ret + + +fgetdims1 = """\ + external f2pysetdata + logical ns + integer r,i + integer(%d) s(*) + ns = .FALSE. + if (allocated(d)) then + do i=1,r + if ((size(d,i).ne.s(i)).and.(s(i).ge.0)) then + ns = .TRUE. + end if + end do + if (ns) then + deallocate(d) + end if + end if + if ((.not.allocated(d)).and.(s(1).ge.1)) then""" % np.intp().itemsize + +fgetdims2 = """\ + end if + if (allocated(d)) then + do i=1,r + s(i) = size(d,i) + end do + end if + flag = 1 + call f2pysetdata(d,allocated(d))""" + +fgetdims2_sa = """\ + end if + if (allocated(d)) then + do i=1,r + s(i) = size(d,i) + end do + !s(r) must be equal to len(d(1)) + end if + flag = 2 + call f2pysetdata(d,allocated(d))""" + + +def buildhooks(pymod): + from . import rules + ret = {'f90modhooks': [], 'initf90modhooks': [], 'body': [], + 'need': ['F_FUNC', 'arrayobject.h'], + 'separatorsfor': {'includes0': '\n', 'includes': '\n'}, + 'docs': ['"Fortran 90/95 modules:\\n"'], + 'latexdoc': []} + fhooks = [''] + + def fadd(line, s=fhooks): + s[0] = f'{s[0]}\n {line}' + doc = [''] + + def dadd(line, s=doc): + s[0] = f'{s[0]}\n{line}' + + usenames = getuseblocks(pymod) + for m in findf90modules(pymod): + sargs, fargs, efargs, modobjs, notvars, onlyvars = [], [], [], [], [ + m['name']], [] + sargsp = [] + ifargs = [] + mfargs = [] + if hasbody(m): + for b in m['body']: + notvars.append(b['name']) + for n in m['vars'].keys(): + var = m['vars'][n] + + if (n not in notvars and isvariable(var)) and (not l_or(isintent_hide, isprivate)(var)): + onlyvars.append(n) + mfargs.append(n) + outmess(f"\t\tConstructing F90 module support for \"{m['name']}\"...\n") + if len(onlyvars) == 0 and len(notvars) == 1 and m['name'] in notvars: + outmess(f"\t\t\tSkipping {m['name']} since there are no public vars/func in this module...\n") + continue + + # gh-25186 + if m['name'] in usenames and containscommon(m): + outmess(f"\t\t\tSkipping {m['name']} since it is in 'use' and contains a common block...\n") + continue + # skip modules with derived types + if m['name'] in usenames and containsderivedtypes(m): + outmess(f"\t\t\tSkipping {m['name']} since it is in 'use' and contains a derived type...\n") + continue + if onlyvars: + outmess(f"\t\t Variables: {' '.join(onlyvars)}\n") + chooks = [''] + + def cadd(line, s=chooks): + s[0] = f'{s[0]}\n{line}' + ihooks = [''] + + def iadd(line, s=ihooks): + s[0] = f'{s[0]}\n{line}' + + vrd = capi_maps.modsign2map(m) + cadd('static FortranDataDef f2py_%s_def[] = {' % (m['name'])) + dadd('\\subsection{Fortran 90/95 module \\texttt{%s}}\n' % (m['name'])) + if hasnote(m): + note = m['note'] + if isinstance(note, list): + note = '\n'.join(note) + dadd(note) + if onlyvars: + dadd('\\begin{description}') + for n in onlyvars: + var = m['vars'][n] + modobjs.append(n) + ct = capi_maps.getctype(var) + at = capi_maps.c2capi_map[ct] + dm = capi_maps.getarrdims(n, var) + dms = dm['dims'].replace('*', '-1').strip() + dms = dms.replace(':', '-1').strip() + if not dms: + dms = '-1' + use_fgetdims2 = fgetdims2 + cadd('\t{"%s",%s,{{%s}},%s, %s},' % + (undo_rmbadname1(n), dm['rank'], dms, at, + capi_maps.get_elsize(var))) + dadd('\\item[]{{}\\verb@%s@{}}' % + (capi_maps.getarrdocsign(n, var))) + if hasnote(var): + note = var['note'] + if isinstance(note, list): + note = '\n'.join(note) + dadd(f'--- {note}') + if isallocatable(var): + fargs.append(f"f2py_{m['name']}_getdims_{n}") + efargs.append(fargs[-1]) + sargs.append( + f'void (*{n})(int*,npy_intp*,void(*)(char*,npy_intp*),int*)') + sargsp.append('void (*)(int*,npy_intp*,void(*)(char*,npy_intp*),int*)') + iadd(f"\tf2py_{m['name']}_def[i_f2py++].func = {n};") + fadd(f'subroutine {fargs[-1]}(r,s,f2pysetdata,flag)') + fadd(f"use {m['name']}, only: d => {undo_rmbadname1(n)}\n") + fadd('integer flag\n') + fhooks[0] = fhooks[0] + fgetdims1 + dms = range(1, int(dm['rank']) + 1) + fadd(' allocate(d(%s))\n' % + (','.join(['s(%s)' % i for i in dms]))) + fhooks[0] = fhooks[0] + use_fgetdims2 + fadd(f'end subroutine {fargs[-1]}') + else: + fargs.append(n) + sargs.append(f'char *{n}') + sargsp.append('char*') + iadd(f"\tf2py_{m['name']}_def[i_f2py++].data = {n};") + if onlyvars: + dadd('\\end{description}') + if hasbody(m): + for b in m['body']: + if not isroutine(b): + outmess("f90mod_rules.buildhooks:" + f" skipping {b['block']} {b['name']}\n") + continue + modobjs.append(f"{b['name']}()") + b['modulename'] = m['name'] + api, wrap = rules.buildapi(b) + if isfunction(b): + fhooks[0] = fhooks[0] + wrap + fargs.append(f"f2pywrap_{m['name']}_{b['name']}") + ifargs.append(func2subr.createfuncwrapper(b, signature=1)) + elif wrap: + fhooks[0] = fhooks[0] + wrap + fargs.append(f"f2pywrap_{m['name']}_{b['name']}") + ifargs.append( + func2subr.createsubrwrapper(b, signature=1)) + else: + fargs.append(b['name']) + mfargs.append(fargs[-1]) + api['externroutines'] = [] + ar = applyrules(api, vrd) + ar['docs'] = [] + ar['docshort'] = [] + ret = dictappend(ret, ar) + cadd(('\t{"%s",-1,{{-1}},0,0,NULL,(void *)' + 'f2py_rout_#modulename#_%s_%s,' + 'doc_f2py_rout_#modulename#_%s_%s},') + % (b['name'], m['name'], b['name'], m['name'], b['name'])) + sargs.append(f"char *{b['name']}") + sargsp.append('char *') + iadd(f"\tf2py_{m['name']}_def[i_f2py++].data = {b['name']};") + cadd('\t{NULL}\n};\n') + iadd('}') + ihooks[0] = 'static void f2py_setup_%s(%s) {\n\tint i_f2py=0;%s' % ( + m['name'], ','.join(sargs), ihooks[0]) + if '_' in m['name']: + F_FUNC = 'F_FUNC_US' + else: + F_FUNC = 'F_FUNC' + iadd('extern void %s(f2pyinit%s,F2PYINIT%s)(void (*)(%s));' + % (F_FUNC, m['name'], m['name'].upper(), ','.join(sargsp))) + iadd('static void f2py_init_%s(void) {' % (m['name'])) + iadd('\t%s(f2pyinit%s,F2PYINIT%s)(f2py_setup_%s);' + % (F_FUNC, m['name'], m['name'].upper(), m['name'])) + iadd('}\n') + ret['f90modhooks'] = ret['f90modhooks'] + chooks + ihooks + ret['initf90modhooks'] = ['\tPyDict_SetItemString(d, "%s", PyFortranObject_New(f2py_%s_def,f2py_init_%s));' % ( + m['name'], m['name'], m['name'])] + ret['initf90modhooks'] + fadd('') + fadd(f"subroutine f2pyinit{m['name']}(f2pysetupfunc)") + if mfargs: + for a in undo_rmbadname(mfargs): + fadd(f"use {m['name']}, only : {a}") + if ifargs: + fadd(' '.join(['interface'] + ifargs)) + fadd('end interface') + fadd('external f2pysetupfunc') + if efargs: + for a in undo_rmbadname(efargs): + fadd(f'external {a}') + fadd(f"call f2pysetupfunc({','.join(undo_rmbadname(fargs))})") + fadd(f"end subroutine f2pyinit{m['name']}\n") + + dadd('\n'.join(ret['latexdoc']).replace( + r'\subsection{', r'\subsubsection{')) + + ret['latexdoc'] = [] + ret['docs'].append(f"\"\t{m['name']} --- {','.join(undo_rmbadname(modobjs))}\"") + + ret['routine_defs'] = '' + ret['doc'] = [] + ret['docshort'] = [] + ret['latexdoc'] = doc[0] + if len(ret['docs']) <= 1: + ret['docs'] = '' + return ret, fhooks[0] diff --git a/python/user_packages/Python313/site-packages/numpy/f2py/f90mod_rules.pyi b/python/user_packages/Python313/site-packages/numpy/f2py/f90mod_rules.pyi new file mode 100644 index 0000000000000000000000000000000000000000..7d033bc1ef88642cdebcc522b1051f58f10b1dbc --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/f2py/f90mod_rules.pyi @@ -0,0 +1,16 @@ +from collections.abc import Mapping +from typing import Any, Final + +from .auxfuncs import isintent_dict as isintent_dict + +__version__: Final[str] = ... +f2py_version: Final = "See `f2py -v`" + +options: Final[dict[str, bool]] + +fgetdims1: Final[str] = ... +fgetdims2: Final[str] = ... +fgetdims2_sa: Final[str] = ... + +def findf90modules(m: Mapping[str, object]) -> list[dict[str, Any]]: ... +def buildhooks(pymod: Mapping[str, object]) -> dict[str, Any]: ... diff --git a/python/user_packages/Python313/site-packages/numpy/f2py/func2subr.py b/python/user_packages/Python313/site-packages/numpy/f2py/func2subr.py new file mode 100644 index 0000000000000000000000000000000000000000..f298bd1526a380053170786f93610b0a79305a1a --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/f2py/func2subr.py @@ -0,0 +1,329 @@ +""" + +Rules for building C/API module with f2py2e. + +Copyright 1999 -- 2011 Pearu Peterson all rights reserved. +Copyright 2011 -- present NumPy Developers. +Permission to use, modify, and distribute this software is given under the +terms of the NumPy License. + +NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. +""" +import copy + +from ._isocbind import isoc_kindmap +from .auxfuncs import ( + getfortranname, + isexternal, + isfunction, + isfunction_wrap, + isintent_in, + isintent_out, + islogicalfunction, + ismoduleroutine, + isscalar, + issubroutine, + issubroutine_wrap, + outmess, + show, +) + + +def var2fixfortran(vars, a, fa=None, f90mode=None): + if fa is None: + fa = a + if a not in vars: + show(vars) + outmess(f'var2fixfortran: No definition for argument "{a}".\n') + return '' + if 'typespec' not in vars[a]: + show(vars[a]) + outmess(f'var2fixfortran: No typespec for argument "{a}".\n') + return '' + vardef = vars[a]['typespec'] + if vardef == 'type' and 'typename' in vars[a]: + vardef = f"{vardef}({vars[a]['typename']})" + selector = {} + lk = '' + if 'kindselector' in vars[a]: + selector = vars[a]['kindselector'] + lk = 'kind' + elif 'charselector' in vars[a]: + selector = vars[a]['charselector'] + lk = 'len' + if '*' in selector: + if f90mode: + if selector['*'] in ['*', ':', '(*)']: + vardef = f'{vardef}(len=*)' + else: + vardef = f"{vardef}({lk}={selector['*']})" + elif selector['*'] in ['*', ':']: + vardef = f"{vardef}*({selector['*']})" + else: + vardef = f"{vardef}*{selector['*']}" + elif 'len' in selector: + vardef = f"{vardef}(len={selector['len']}" + if 'kind' in selector: + vardef = f"{vardef},kind={selector['kind']})" + else: + vardef = f'{vardef})' + elif 'kind' in selector: + vardef = f"{vardef}(kind={selector['kind']})" + + vardef = f'{vardef} {fa}' + if 'dimension' in vars[a]: + vardef = f"{vardef}({','.join(vars[a]['dimension'])})" + return vardef + +def useiso_c_binding(rout): + useisoc = False + for value in rout['vars'].values(): + kind_value = value.get('kindselector', {}).get('kind') + if kind_value in isoc_kindmap: + return True + return useisoc + +def createfuncwrapper(rout, signature=0): + assert isfunction(rout) + + extra_args = [] + vars = rout['vars'] + for a in rout['args']: + v = rout['vars'][a] + for i, d in enumerate(v.get('dimension', [])): + if d == ':': + dn = f'f2py_{a}_d{i}' + dv = {'typespec': 'integer', 'intent': ['hide']} + dv['='] = f'shape({a}, {i})' + extra_args.append(dn) + vars[dn] = dv + v['dimension'][i] = dn + rout['args'].extend(extra_args) + need_interface = bool(extra_args) + + ret = [''] + + def add(line, ret=ret): + ret[0] = f'{ret[0]}\n {line}' + name = rout['name'] + fortranname = getfortranname(rout) + f90mode = ismoduleroutine(rout) + newname = f'{name}f2pywrap' + + if newname not in vars: + vars[newname] = vars[name] + args = [newname] + rout['args'][1:] + else: + args = [newname] + rout['args'] + + l_tmpl = var2fixfortran(vars, name, '@@@NAME@@@', f90mode) + if l_tmpl[:13] == 'character*(*)': + if f90mode: + l_tmpl = 'character(len=10)' + l_tmpl[13:] + else: + l_tmpl = 'character*10' + l_tmpl[13:] + charselect = vars[name]['charselector'] + if charselect.get('*', '') == '(*)': + charselect['*'] = '10' + + l1 = l_tmpl.replace('@@@NAME@@@', newname) + rl = None + + useisoc = useiso_c_binding(rout) + sargs = ', '.join(args) + if f90mode: + # gh-23598 fix warning + # Essentially, this gets called again with modules where the name of the + # function is added to the arguments, which is not required, and removed + sargs = sargs.replace(f"{name}, ", '') + args = [arg for arg in args if arg != name] + rout['args'] = args + add(f"subroutine f2pywrap_{rout['modulename']}_{name} ({sargs})") + if not signature: + add(f"use {rout['modulename']}, only : {fortranname}") + if useisoc: + add('use iso_c_binding') + else: + add(f'subroutine f2pywrap{name} ({sargs})') + if useisoc: + add('use iso_c_binding') + if not need_interface: + add(f'external {fortranname}') + rl = l_tmpl.replace('@@@NAME@@@', '') + ' ' + fortranname + + if need_interface: + for line in rout['saved_interface'].split('\n'): + if line.lstrip().startswith('use ') and '__user__' not in line: + add(line) + + args = args[1:] + dumped_args = [] + for a in args: + if isexternal(vars[a]): + add(f'external {a}') + dumped_args.append(a) + for a in args: + if a in dumped_args: + continue + if isscalar(vars[a]): + add(var2fixfortran(vars, a, f90mode=f90mode)) + dumped_args.append(a) + for a in args: + if a in dumped_args: + continue + if isintent_in(vars[a]): + add(var2fixfortran(vars, a, f90mode=f90mode)) + dumped_args.append(a) + for a in args: + if a in dumped_args: + continue + add(var2fixfortran(vars, a, f90mode=f90mode)) + + add(l1) + if rl is not None: + add(rl) + + if need_interface: + if f90mode: + # f90 module already defines needed interface + pass + else: + add('interface') + add(rout['saved_interface'].lstrip()) + add('end interface') + + sargs = ', '.join([a for a in args if a not in extra_args]) + + if not signature: + if islogicalfunction(rout): + add(f'{newname} = .not.(.not.{fortranname}({sargs}))') + else: + add(f'{newname} = {fortranname}({sargs})') + if f90mode: + add(f"end subroutine f2pywrap_{rout['modulename']}_{name}") + else: + add('end') + return ret[0] + + +def createsubrwrapper(rout, signature=0): + assert issubroutine(rout) + + extra_args = [] + vars = rout['vars'] + for a in rout['args']: + v = rout['vars'][a] + for i, d in enumerate(v.get('dimension', [])): + if d == ':': + dn = f'f2py_{a}_d{i}' + dv = {'typespec': 'integer', 'intent': ['hide']} + dv['='] = f'shape({a}, {i})' + extra_args.append(dn) + vars[dn] = dv + v['dimension'][i] = dn + rout['args'].extend(extra_args) + need_interface = bool(extra_args) + + ret = [''] + + def add(line, ret=ret): + ret[0] = f'{ret[0]}\n {line}' + name = rout['name'] + fortranname = getfortranname(rout) + f90mode = ismoduleroutine(rout) + + args = rout['args'] + + useisoc = useiso_c_binding(rout) + sargs = ', '.join(args) + if f90mode: + add(f"subroutine f2pywrap_{rout['modulename']}_{name} ({sargs})") + if useisoc: + add('use iso_c_binding') + if not signature: + add(f"use {rout['modulename']}, only : {fortranname}") + else: + add(f'subroutine f2pywrap{name} ({sargs})') + if useisoc: + add('use iso_c_binding') + if not need_interface: + add(f'external {fortranname}') + + if need_interface: + for line in rout['saved_interface'].split('\n'): + if line.lstrip().startswith('use ') and '__user__' not in line: + add(line) + + dumped_args = [] + for a in args: + if isexternal(vars[a]): + add(f'external {a}') + dumped_args.append(a) + for a in args: + if a in dumped_args: + continue + if isscalar(vars[a]): + add(var2fixfortran(vars, a, f90mode=f90mode)) + dumped_args.append(a) + for a in args: + if a in dumped_args: + continue + add(var2fixfortran(vars, a, f90mode=f90mode)) + + if need_interface: + if f90mode: + # f90 module already defines needed interface + pass + else: + add('interface') + for line in rout['saved_interface'].split('\n'): + if line.lstrip().startswith('use ') and '__user__' in line: + continue + add(line) + add('end interface') + + sargs = ', '.join([a for a in args if a not in extra_args]) + + if not signature: + add(f'call {fortranname}({sargs})') + if f90mode: + add(f"end subroutine f2pywrap_{rout['modulename']}_{name}") + else: + add('end') + return ret[0] + + +def assubr(rout): + if isfunction_wrap(rout): + fortranname = getfortranname(rout) + name = rout['name'] + outmess('\t\tCreating wrapper for Fortran function "%s"("%s")...\n' % ( + name, fortranname)) + rout = copy.copy(rout) + fname = name + rname = fname + if 'result' in rout: + rname = rout['result'] + rout['vars'][fname] = rout['vars'][rname] + fvar = rout['vars'][fname] + if not isintent_out(fvar): + if 'intent' not in fvar: + fvar['intent'] = [] + fvar['intent'].append('out') + flag = 1 + for i in fvar['intent']: + if i.startswith('out='): + flag = 0 + break + if flag: + fvar['intent'].append(f'out={rname}') + rout['args'][:] = [fname] + rout['args'] + return rout, createfuncwrapper(rout) + if issubroutine_wrap(rout): + fortranname = getfortranname(rout) + name = rout['name'] + outmess('\t\tCreating wrapper for Fortran subroutine "%s"("%s")...\n' + % (name, fortranname)) + rout = copy.copy(rout) + return rout, createsubrwrapper(rout) + return rout, '' diff --git a/python/user_packages/Python313/site-packages/numpy/f2py/func2subr.pyi b/python/user_packages/Python313/site-packages/numpy/f2py/func2subr.pyi new file mode 100644 index 0000000000000000000000000000000000000000..58497b96949ad820378172dc29a5e26177832088 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/f2py/func2subr.pyi @@ -0,0 +1,7 @@ +from .auxfuncs import _Bool, _ROut, _Var + +def var2fixfortran(vars: _Var, a: str, fa: str | None = None, f90mode: _Bool | None = None) -> str: ... +def useiso_c_binding(rout: _ROut) -> bool: ... +def createfuncwrapper(rout: _ROut, signature: int = 0) -> str: ... +def createsubrwrapper(rout: _ROut, signature: int = 0) -> str: ... +def assubr(rout: _ROut) -> tuple[dict[str, str], str]: ... diff --git a/python/user_packages/Python313/site-packages/numpy/f2py/rules.py b/python/user_packages/Python313/site-packages/numpy/f2py/rules.py new file mode 100644 index 0000000000000000000000000000000000000000..cbbad061c892db7660fcdebba00c337535735abb --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/f2py/rules.py @@ -0,0 +1,1629 @@ +""" + +Rules for building C/API module with f2py2e. + +Here is a skeleton of a new wrapper function (13Dec2001): + +wrapper_function(args) + declarations + get_python_arguments, say, `a' and `b' + + get_a_from_python + if (successful) { + + get_b_from_python + if (successful) { + + callfortran + if (successful) { + + put_a_to_python + if (successful) { + + put_b_to_python + if (successful) { + + buildvalue = ... + + } + + } + + } + + } + cleanup_b + + } + cleanup_a + + return buildvalue + +Copyright 1999 -- 2011 Pearu Peterson all rights reserved. +Copyright 2011 -- present NumPy Developers. +Permission to use, modify, and distribute this software is given under the +terms of the NumPy License. + +NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. +""" +import copy +import os +import sys +import time +from pathlib import Path + +# __version__.version is now the same as the NumPy version +from . import ( + __version__, + capi_maps, + cfuncs, + common_rules, + f90mod_rules, + func2subr, + use_rules, +) +from .auxfuncs import ( + applyrules, + debugcapi, + dictappend, + errmess, + gentitle, + getargs2, + hascallstatement, + hasexternals, + hasinitvalue, + hasnote, + hasresultnote, + isarray, + isarrayofstrings, + isattr_value, + ischaracter, + ischaracter_or_characterarray, + ischaracterarray, + iscomplex, + iscomplexarray, + iscomplexfunction, + iscomplexfunction_warn, + isdummyroutine, + isexternal, + isfunction, + isfunction_wrap, + isint1, + isint1array, + isintent_aux, + isintent_c, + isintent_callback, + isintent_copy, + isintent_hide, + isintent_inout, + isintent_nothide, + isintent_out, + isintent_overwrite, + islogical, + islong_complex, + islong_double, + islong_doublefunction, + islong_long, + islong_longfunction, + ismoduleroutine, + isoptional, + isrequired, + isscalar, + issigned_long_longarray, + isstring, + isstringarray, + isstringfunction, + issubroutine, + issubroutine_wrap, + isthreadsafe, + isunsigned, + isunsigned_char, + isunsigned_chararray, + isunsigned_long_long, + isunsigned_long_longarray, + isunsigned_short, + isunsigned_shortarray, + l_and, + l_not, + l_or, + outmess, + replace, + requiresf90wrapper, + stripcomma, +) + +f2py_version = __version__.version +numpy_version = __version__.version + +options = {} +sepdict = {} +# for k in ['need_cfuncs']: sepdict[k]=',' +for k in ['decl', + 'frompyobj', + 'cleanupfrompyobj', + 'topyarr', 'method', + 'pyobjfrom', 'closepyobjfrom', + 'freemem', + 'userincludes', + 'includes0', 'includes', 'typedefs', 'typedefs_generated', + 'cppmacros', 'cfuncs', 'callbacks', + 'latexdoc', + 'restdoc', + 'routine_defs', 'externroutines', + 'initf2pywraphooks', + 'commonhooks', 'initcommonhooks', + 'f90modhooks', 'initf90modhooks']: + sepdict[k] = '\n' + +#################### Rules for C/API module ################# + +generationtime = int(os.environ.get('SOURCE_DATE_EPOCH', time.time())) +module_rules = { + 'modulebody': """\ +/* File: #modulename#module.c + * This file is auto-generated with f2py (version:#f2py_version#). + * f2py is a Fortran to Python Interface Generator (FPIG), Second Edition, + * written by Pearu Peterson . + * Generation date: """ + time.asctime(time.gmtime(generationtime)) + """ + * Do not edit this file directly unless you know what you are doing!!! + */ + +#ifdef __cplusplus +extern \"C\" { +#endif + +#ifndef PY_SSIZE_T_CLEAN +#define PY_SSIZE_T_CLEAN +#endif /* PY_SSIZE_T_CLEAN */ + +/* Unconditionally included */ +#include +#include + +""" + gentitle("See f2py2e/cfuncs.py: includes") + """ +#includes# +#includes0# + +""" + gentitle("See f2py2e/rules.py: mod_rules['modulebody']") + """ +static PyObject *#modulename#_error; +static PyObject *#modulename#_module; + +""" + gentitle("See f2py2e/cfuncs.py: typedefs") + """ +#typedefs# + +""" + gentitle("See f2py2e/cfuncs.py: typedefs_generated") + """ +#typedefs_generated# + +""" + gentitle("See f2py2e/cfuncs.py: cppmacros") + """ +#cppmacros# + +""" + gentitle("See f2py2e/cfuncs.py: cfuncs") + """ +#cfuncs# + +""" + gentitle("See f2py2e/cfuncs.py: userincludes") + """ +#userincludes# + +""" + gentitle("See f2py2e/capi_rules.py: usercode") + """ +#usercode# + +/* See f2py2e/rules.py */ +#externroutines# + +""" + gentitle("See f2py2e/capi_rules.py: usercode1") + """ +#usercode1# + +""" + gentitle("See f2py2e/cb_rules.py: buildcallback") + """ +#callbacks# + +""" + gentitle("See f2py2e/rules.py: buildapi") + """ +#body# + +""" + gentitle("See f2py2e/f90mod_rules.py: buildhooks") + """ +#f90modhooks# + +""" + gentitle("See f2py2e/rules.py: module_rules['modulebody']") + """ + +""" + gentitle("See f2py2e/common_rules.py: buildhooks") + """ +#commonhooks# + +""" + gentitle("See f2py2e/rules.py") + """ + +static FortranDataDef f2py_routine_defs[] = { +#routine_defs# + {NULL} +}; + +static PyMethodDef f2py_module_methods[] = { +#pymethoddef# + {NULL,NULL} +}; + +static struct PyModuleDef moduledef = { + PyModuleDef_HEAD_INIT, + "#modulename#", + NULL, + -1, + f2py_module_methods, + NULL, + NULL, + NULL, + NULL +}; + +PyMODINIT_FUNC PyInit_#modulename#(void) { + int i; + PyObject *m,*d, *s, *tmp; + m = #modulename#_module = PyModule_Create(&moduledef); + Py_SET_TYPE(&PyFortran_Type, &PyType_Type); + import_array(); + if (PyErr_Occurred()) + {PyErr_SetString(PyExc_ImportError, \"can't initialize module #modulename# (failed to import numpy)\"); return m;} + d = PyModule_GetDict(m); + s = PyUnicode_FromString(\"#f2py_version#\"); + PyDict_SetItemString(d, \"__version__\", s); + Py_DECREF(s); + s = PyUnicode_FromString( + \"This module '#modulename#' is auto-generated with f2py (version:#f2py_version#).\\nFunctions:\\n\"\n#docs#\".\"); + PyDict_SetItemString(d, \"__doc__\", s); + Py_DECREF(s); + s = PyUnicode_FromString(\"""" + numpy_version + """\"); + PyDict_SetItemString(d, \"__f2py_numpy_version__\", s); + Py_DECREF(s); + #modulename#_error = PyErr_NewException (\"#modulename#.error\", NULL, NULL); + /* + * Store the error object inside the dict, so that it could get deallocated. + * (in practice, this is a module, so it likely will not and cannot.) + */ + PyDict_SetItemString(d, \"_#modulename#_error\", #modulename#_error); + Py_DECREF(#modulename#_error); + for(i=0;f2py_routine_defs[i].name!=NULL;i++) { + tmp = PyFortranObject_NewAsAttr(&f2py_routine_defs[i]); + PyDict_SetItemString(d, f2py_routine_defs[i].name, tmp); + Py_DECREF(tmp); + } +#initf2pywraphooks# +#initf90modhooks# +#initcommonhooks# +#interface_usercode# + +#ifdef Py_GIL_DISABLED + // signal whether this module supports running with the GIL disabled + PyUnstable_Module_SetGIL(m , #gil_used#); +#endif + +#ifdef F2PY_REPORT_ATEXIT + if (! PyErr_Occurred()) + on_exit(f2py_report_on_exit,(void*)\"#modulename#\"); +#endif + + if (PyType_Ready(&PyFortran_Type) < 0) { + return NULL; + } + + return m; +} +#ifdef __cplusplus +} +#endif +""", + 'separatorsfor': {'latexdoc': '\n\n', + 'restdoc': '\n\n'}, + 'latexdoc': ['\\section{Module \\texttt{#texmodulename#}}\n', + '#modnote#\n', + '#latexdoc#'], + 'restdoc': ['Module #modulename#\n' + '=' * 80, + '\n#restdoc#'] +} + +defmod_rules = [ + {'body': '/*eof body*/', + 'method': '/*eof method*/', + 'externroutines': '/*eof externroutines*/', + 'routine_defs': '/*eof routine_defs*/', + 'initf90modhooks': '/*eof initf90modhooks*/', + 'initf2pywraphooks': '/*eof initf2pywraphooks*/', + 'initcommonhooks': '/*eof initcommonhooks*/', + 'latexdoc': '', + 'restdoc': '', + 'modnote': {hasnote: '#note#', l_not(hasnote): ''}, + } +] + +routine_rules = { + 'separatorsfor': sepdict, + 'body': """ +#begintitle# +static char doc_#apiname#[] = \"\\\n#docreturn##name#(#docsignatureshort#)\\n\\nWrapper for ``#name#``.\\\n\\n#docstrsigns#\"; +/* #declfortranroutine# */ +static PyObject *#apiname#(const PyObject *capi_self, + PyObject *capi_args, + PyObject *capi_keywds, + #functype# (*f2py_func)(#callprotoargument#)) { + PyObject * volatile capi_buildvalue = NULL; + volatile int f2py_success = 1; +#decl# + static char *capi_kwlist[] = {#kwlist##kwlistopt##kwlistxa#NULL}; +#usercode# +#routdebugenter# +#ifdef F2PY_REPORT_ATEXIT +f2py_start_clock(); +#endif + if (!PyArg_ParseTupleAndKeywords(capi_args,capi_keywds,\\ + \"#argformat#|#keyformat##xaformat#:#pyname#\",\\ + capi_kwlist#args_capi##keys_capi##keys_xa#))\n return NULL; +#frompyobj# +/*end of frompyobj*/ +#ifdef F2PY_REPORT_ATEXIT +f2py_start_call_clock(); +#endif +#callfortranroutine# +if (PyErr_Occurred()) + f2py_success = 0; +#ifdef F2PY_REPORT_ATEXIT +f2py_stop_call_clock(); +#endif +/*end of callfortranroutine*/ + if (f2py_success) { +#pyobjfrom# +/*end of pyobjfrom*/ + CFUNCSMESS(\"Building return value.\\n\"); + capi_buildvalue = Py_BuildValue(\"#returnformat#\"#return#); +/*closepyobjfrom*/ +#closepyobjfrom# + } /*if (f2py_success) after callfortranroutine*/ +/*cleanupfrompyobj*/ +#cleanupfrompyobj# + if (capi_buildvalue == NULL) { +#routdebugfailure# + } else { +#routdebugleave# + } + CFUNCSMESS(\"Freeing memory.\\n\"); +#freemem# +#ifdef F2PY_REPORT_ATEXIT +f2py_stop_clock(); +#endif + return capi_buildvalue; +} +#endtitle# +""", + 'routine_defs': '#routine_def#', + 'initf2pywraphooks': '#initf2pywraphook#', + 'externroutines': '#declfortranroutine#', + 'doc': '#docreturn##name#(#docsignature#)', + 'docshort': '#docreturn##name#(#docsignatureshort#)', + 'docs': '" #docreturn##name#(#docsignature#)\\n"\n', + 'need': ['arrayobject.h', 'CFUNCSMESS', 'MINMAX'], + 'cppmacros': {debugcapi: '#define DEBUGCFUNCS'}, + 'latexdoc': ['\\subsection{Wrapper function \\texttt{#texname#}}\n', + """ +\\noindent{{}\\verb@#docreturn##name#@{}}\\texttt{(#latexdocsignatureshort#)} +#routnote# + +#latexdocstrsigns# +"""], + 'restdoc': ['Wrapped function ``#name#``\n' + '-' * 80, + + ] +} + +################## Rules for C/API function ############## + +rout_rules = [ + { # Init + 'separatorsfor': {'callfortranroutine': '\n', 'routdebugenter': '\n', 'decl': '\n', + 'routdebugleave': '\n', 'routdebugfailure': '\n', + 'setjmpbuf': ' || ', + 'docstrreq': '\n', 'docstropt': '\n', 'docstrout': '\n', + 'docstrcbs': '\n', 'docstrsigns': '\\n"\n"', + 'latexdocstrsigns': '\n', + 'latexdocstrreq': '\n', 'latexdocstropt': '\n', + 'latexdocstrout': '\n', 'latexdocstrcbs': '\n', + }, + 'kwlist': '', 'kwlistopt': '', 'callfortran': '', 'callfortranappend': '', + 'docsign': '', 'docsignopt': '', 'decl': '/*decl*/', + 'freemem': '/*freemem*/', + 'docsignshort': '', 'docsignoptshort': '', + 'docstrsigns': '', 'latexdocstrsigns': '', + 'docstrreq': '\\nParameters\\n----------', + 'docstropt': '\\nOther Parameters\\n----------------', + 'docstrout': '\\nReturns\\n-------', + 'docstrcbs': '\\nNotes\\n-----\\nCall-back functions::\\n', + 'latexdocstrreq': '\\noindent Required arguments:', + 'latexdocstropt': '\\noindent Optional arguments:', + 'latexdocstrout': '\\noindent Return objects:', + 'latexdocstrcbs': '\\noindent Call-back functions:', + 'args_capi': '', 'keys_capi': '', 'functype': '', + 'frompyobj': '/*frompyobj*/', + # this list will be reversed + 'cleanupfrompyobj': ['/*end of cleanupfrompyobj*/'], + 'pyobjfrom': '/*pyobjfrom*/', + # this list will be reversed + 'closepyobjfrom': ['/*end of closepyobjfrom*/'], + 'topyarr': '/*topyarr*/', 'routdebugleave': '/*routdebugleave*/', + 'routdebugenter': '/*routdebugenter*/', + 'routdebugfailure': '/*routdebugfailure*/', + 'callfortranroutine': '/*callfortranroutine*/', + 'argformat': '', 'keyformat': '', 'need_cfuncs': '', + 'docreturn': '', 'return': '', 'returnformat': '', 'rformat': '', + 'kwlistxa': '', 'keys_xa': '', 'xaformat': '', 'docsignxa': '', 'docsignxashort': '', + 'initf2pywraphook': '', + 'routnote': {hasnote: '--- #note#', l_not(hasnote): ''}, + }, { + 'apiname': 'f2py_rout_#modulename#_#name#', + 'pyname': '#modulename#.#name#', + 'decl': '', + '_check': l_not(ismoduleroutine) + }, { + 'apiname': 'f2py_rout_#modulename#_#f90modulename#_#name#', + 'pyname': '#modulename#.#f90modulename#.#name#', + 'decl': '', + '_check': ismoduleroutine + }, { # Subroutine + 'functype': 'void', + 'declfortranroutine': {l_and(l_not(l_or(ismoduleroutine, isintent_c)), l_not(isdummyroutine)): 'extern void #F_FUNC#(#fortranname#,#FORTRANNAME#)(#callprotoargument#);', + l_and(l_not(ismoduleroutine), isintent_c, l_not(isdummyroutine)): 'extern void #fortranname#(#callprotoargument#);', + ismoduleroutine: '', + isdummyroutine: '' + }, + 'routine_def': { + l_not(l_or(ismoduleroutine, isintent_c, isdummyroutine)): + ' {\"#name#\",-1,{{-1}},0,0,(char *)' + ' #F_FUNC#(#fortranname#,#FORTRANNAME#),' + ' (f2py_init_func)#apiname#,doc_#apiname#},', + l_and(l_not(ismoduleroutine), isintent_c, l_not(isdummyroutine)): + ' {\"#name#\",-1,{{-1}},0,0,(char *)#fortranname#,' + ' (f2py_init_func)#apiname#,doc_#apiname#},', + l_and(l_not(ismoduleroutine), isdummyroutine): + ' {\"#name#\",-1,{{-1}},0,0,NULL,' + ' (f2py_init_func)#apiname#,doc_#apiname#},', + }, + 'need': {l_and(l_not(l_or(ismoduleroutine, isintent_c)), l_not(isdummyroutine)): 'F_FUNC'}, + 'callfortranroutine': [ + {debugcapi: [ + """ fprintf(stderr,\"debug-capi:Fortran subroutine `#fortranname#(#callfortran#)\'\\n\");"""]}, + {hasexternals: """\ + if (#setjmpbuf#) { + f2py_success = 0; + } else {"""}, + {isthreadsafe: ' Py_BEGIN_ALLOW_THREADS'}, + {hascallstatement: ''' #callstatement#; + /*(*f2py_func)(#callfortran#);*/'''}, + {l_not(l_or(hascallstatement, isdummyroutine)) + : ' (*f2py_func)(#callfortran#);'}, + {isthreadsafe: ' Py_END_ALLOW_THREADS'}, + {hasexternals: """ }"""} + ], + '_check': l_and(issubroutine, l_not(issubroutine_wrap)), + }, { # Wrapped function + 'functype': 'void', + 'declfortranroutine': {l_not(l_or(ismoduleroutine, isdummyroutine)): 'extern void #F_WRAPPEDFUNC#(#name_lower#,#NAME#)(#callprotoargument#);', + isdummyroutine: '', + }, + + 'routine_def': { + l_not(l_or(ismoduleroutine, isdummyroutine)): + ' {\"#name#\",-1,{{-1}},0,0,(char *)' + ' #F_WRAPPEDFUNC#(#name_lower#,#NAME#),' + ' (f2py_init_func)#apiname#,doc_#apiname#},', + isdummyroutine: + ' {\"#name#\",-1,{{-1}},0,0,NULL,' + ' (f2py_init_func)#apiname#,doc_#apiname#},', + }, + 'initf2pywraphook': {l_not(l_or(ismoduleroutine, isdummyroutine)): ''' + { + extern #ctype# #F_FUNC#(#name_lower#,#NAME#)(void); + PyObject* o = PyDict_GetItemString(d,"#name#"); + tmp = F2PyCapsule_FromVoidPtr((void*)#F_WRAPPEDFUNC#(#name_lower#,#NAME#),NULL); + PyObject_SetAttrString(o,"_cpointer", tmp); + Py_DECREF(tmp); + s = PyUnicode_FromString("#name#"); + PyObject_SetAttrString(o,"__name__", s); + Py_DECREF(s); + } + '''}, + 'need': {l_not(l_or(ismoduleroutine, isdummyroutine)): ['F_WRAPPEDFUNC', 'F_FUNC']}, + 'callfortranroutine': [ + {debugcapi: [ + """ fprintf(stderr,\"debug-capi:Fortran subroutine `f2pywrap#name_lower#(#callfortran#)\'\\n\");"""]}, + {hasexternals: """\ + if (#setjmpbuf#) { + f2py_success = 0; + } else {"""}, + {isthreadsafe: ' Py_BEGIN_ALLOW_THREADS'}, + {l_not(l_or(hascallstatement, isdummyroutine)) + : ' (*f2py_func)(#callfortran#);'}, + {hascallstatement: + ' #callstatement#;\n /*(*f2py_func)(#callfortran#);*/'}, + {isthreadsafe: ' Py_END_ALLOW_THREADS'}, + {hasexternals: ' }'} + ], + '_check': isfunction_wrap, + }, { # Wrapped subroutine + 'functype': 'void', + 'declfortranroutine': {l_not(l_or(ismoduleroutine, isdummyroutine)): 'extern void #F_WRAPPEDFUNC#(#name_lower#,#NAME#)(#callprotoargument#);', + isdummyroutine: '', + }, + + 'routine_def': { + l_not(l_or(ismoduleroutine, isdummyroutine)): + ' {\"#name#\",-1,{{-1}},0,0,(char *)' + ' #F_WRAPPEDFUNC#(#name_lower#,#NAME#),' + ' (f2py_init_func)#apiname#,doc_#apiname#},', + isdummyroutine: + ' {\"#name#\",-1,{{-1}},0,0,NULL,' + ' (f2py_init_func)#apiname#,doc_#apiname#},', + }, + 'initf2pywraphook': {l_not(l_or(ismoduleroutine, isdummyroutine)): ''' + { + extern void #F_FUNC#(#name_lower#,#NAME#)(void); + PyObject* o = PyDict_GetItemString(d,"#name#"); + tmp = F2PyCapsule_FromVoidPtr((void*)#F_FUNC#(#name_lower#,#NAME#),NULL); + PyObject_SetAttrString(o,"_cpointer", tmp); + Py_DECREF(tmp); + s = PyUnicode_FromString("#name#"); + PyObject_SetAttrString(o,"__name__", s); + Py_DECREF(s); + } + '''}, + 'need': {l_not(l_or(ismoduleroutine, isdummyroutine)): ['F_WRAPPEDFUNC', 'F_FUNC']}, + 'callfortranroutine': [ + {debugcapi: [ + """ fprintf(stderr,\"debug-capi:Fortran subroutine `f2pywrap#name_lower#(#callfortran#)\'\\n\");"""]}, + {hasexternals: """\ + if (#setjmpbuf#) { + f2py_success = 0; + } else {"""}, + {isthreadsafe: ' Py_BEGIN_ALLOW_THREADS'}, + {l_not(l_or(hascallstatement, isdummyroutine)) + : ' (*f2py_func)(#callfortran#);'}, + {hascallstatement: + ' #callstatement#;\n /*(*f2py_func)(#callfortran#);*/'}, + {isthreadsafe: ' Py_END_ALLOW_THREADS'}, + {hasexternals: ' }'} + ], + '_check': issubroutine_wrap, + }, { # Function + 'functype': '#ctype#', + 'docreturn': {l_not(isintent_hide): '#rname#,'}, + 'docstrout': '#pydocsignout#', + 'latexdocstrout': ['\\item[]{{}\\verb@#pydocsignout#@{}}', + {hasresultnote: '--- #resultnote#'}], + 'callfortranroutine': [{l_and(debugcapi, isstringfunction): """\ +#ifdef USESCOMPAQFORTRAN + fprintf(stderr,\"debug-capi:Fortran function #ctype# #fortranname#(#callcompaqfortran#)\\n\"); +#else + fprintf(stderr,\"debug-capi:Fortran function #ctype# #fortranname#(#callfortran#)\\n\"); +#endif +"""}, + {l_and(debugcapi, l_not(isstringfunction)): """\ + fprintf(stderr,\"debug-capi:Fortran function #ctype# #fortranname#(#callfortran#)\\n\"); +"""} + ], + '_check': l_and(isfunction, l_not(isfunction_wrap)) + }, { # Scalar function + 'declfortranroutine': {l_and(l_not(l_or(ismoduleroutine, isintent_c)), l_not(isdummyroutine)): 'extern #ctype# #F_FUNC#(#fortranname#,#FORTRANNAME#)(#callprotoargument#);', + l_and(l_not(ismoduleroutine), isintent_c, l_not(isdummyroutine)): 'extern #ctype# #fortranname#(#callprotoargument#);', + isdummyroutine: '' + }, + 'routine_def': { + l_and(l_not(l_or(ismoduleroutine, isintent_c)), + l_not(isdummyroutine)): + (' {\"#name#\",-1,{{-1}},0,0,(char *)' + ' #F_FUNC#(#fortranname#,#FORTRANNAME#),' + ' (f2py_init_func)#apiname#,doc_#apiname#},'), + l_and(l_not(ismoduleroutine), isintent_c, l_not(isdummyroutine)): + (' {\"#name#\",-1,{{-1}},0,0,(char *)#fortranname#,' + ' (f2py_init_func)#apiname#,doc_#apiname#},'), + isdummyroutine: + ' {\"#name#\",-1,{{-1}},0,0,NULL,' + '(f2py_init_func)#apiname#,doc_#apiname#},', + }, + 'decl': [{iscomplexfunction_warn: ' #ctype# #name#_return_value={0,0};', + l_not(iscomplexfunction): ' #ctype# #name#_return_value=0;'}, + {iscomplexfunction: + ' PyObject *#name#_return_value_capi = Py_None;'} + ], + 'callfortranroutine': [ + {hasexternals: """\ + if (#setjmpbuf#) { + f2py_success = 0; + } else {"""}, + {isthreadsafe: ' Py_BEGIN_ALLOW_THREADS'}, + {hascallstatement: ''' #callstatement#; +/* #name#_return_value = (*f2py_func)(#callfortran#);*/ +'''}, + {l_not(l_or(hascallstatement, isdummyroutine)) + : ' #name#_return_value = (*f2py_func)(#callfortran#);'}, + {isthreadsafe: ' Py_END_ALLOW_THREADS'}, + {hasexternals: ' }'}, + {l_and(debugcapi, iscomplexfunction) + : ' fprintf(stderr,"#routdebugshowvalue#\\n",#name#_return_value.r,#name#_return_value.i);'}, + {l_and(debugcapi, l_not(iscomplexfunction)): ' fprintf(stderr,"#routdebugshowvalue#\\n",#name#_return_value);'}], + 'pyobjfrom': {iscomplexfunction: ' #name#_return_value_capi = pyobj_from_#ctype#1(#name#_return_value);'}, + 'need': [{l_not(isdummyroutine): 'F_FUNC'}, + {iscomplexfunction: 'pyobj_from_#ctype#1'}, + {islong_longfunction: 'long_long'}, + {islong_doublefunction: 'long_double'}], + 'returnformat': {l_not(isintent_hide): '#rformat#'}, + 'return': {iscomplexfunction: ',#name#_return_value_capi', + l_not(l_or(iscomplexfunction, isintent_hide)): ',#name#_return_value'}, + '_check': l_and(isfunction, l_not(isstringfunction), l_not(isfunction_wrap)) + }, { # String function # in use for --no-wrap + 'declfortranroutine': 'extern void #F_FUNC#(#fortranname#,#FORTRANNAME#)(#callprotoargument#);', + 'routine_def': {l_not(l_or(ismoduleroutine, isintent_c)): + ' {\"#name#\",-1,{{-1}},0,0,(char *)#F_FUNC#(#fortranname#,#FORTRANNAME#),(f2py_init_func)#apiname#,doc_#apiname#},', + l_and(l_not(ismoduleroutine), isintent_c): + ' {\"#name#\",-1,{{-1}},0,0,(char *)#fortranname#,(f2py_init_func)#apiname#,doc_#apiname#},' + }, + 'decl': [' #ctype# #name#_return_value = NULL;', + ' int #name#_return_value_len = 0;'], + 'callfortran': '#name#_return_value,#name#_return_value_len,', + 'callfortranroutine': [' #name#_return_value_len = #rlength#;', + ' if ((#name#_return_value = (string)malloc(#name#_return_value_len+1) == NULL) {', + ' PyErr_SetString(PyExc_MemoryError, \"out of memory\");', + ' f2py_success = 0;', + ' } else {', + " (#name#_return_value)[#name#_return_value_len] = '\\0';", + ' }', + ' if (f2py_success) {', + {hasexternals: """\ + if (#setjmpbuf#) { + f2py_success = 0; + } else {"""}, + {isthreadsafe: ' Py_BEGIN_ALLOW_THREADS'}, + """\ +#ifdef USESCOMPAQFORTRAN + (*f2py_func)(#callcompaqfortran#); +#else + (*f2py_func)(#callfortran#); +#endif +""", + {isthreadsafe: ' Py_END_ALLOW_THREADS'}, + {hasexternals: ' }'}, + {debugcapi: + ' fprintf(stderr,"#routdebugshowvalue#\\n",#name#_return_value_len,#name#_return_value);'}, + ' } /* if (f2py_success) after (string)malloc */', + ], + 'returnformat': '#rformat#', + 'return': ',#name#_return_value', + 'freemem': ' STRINGFREE(#name#_return_value);', + 'need': ['F_FUNC', '#ctype#', 'STRINGFREE'], + '_check': l_and(isstringfunction, l_not(isfunction_wrap)) # ???obsolete + }, + { # Debugging + 'routdebugenter': ' fprintf(stderr,"debug-capi:Python C/API function #modulename#.#name#(#docsignature#)\\n");', + 'routdebugleave': ' fprintf(stderr,"debug-capi:Python C/API function #modulename#.#name#: successful.\\n");', + 'routdebugfailure': ' fprintf(stderr,"debug-capi:Python C/API function #modulename#.#name#: failure.\\n");', + '_check': debugcapi + } +] + +################ Rules for arguments ################## + +typedef_need_dict = {islong_long: 'long_long', + islong_double: 'long_double', + islong_complex: 'complex_long_double', + isunsigned_char: 'unsigned_char', + isunsigned_short: 'unsigned_short', + isunsigned: 'unsigned', + isunsigned_long_long: 'unsigned_long_long', + isunsigned_chararray: 'unsigned_char', + isunsigned_shortarray: 'unsigned_short', + isunsigned_long_longarray: 'unsigned_long_long', + issigned_long_longarray: 'long_long', + isint1: 'signed_char', + ischaracter_or_characterarray: 'character', + } + +aux_rules = [ + { + 'separatorsfor': sepdict + }, + { # Common + 'frompyobj': [' /* Processing auxiliary variable #varname# */', + {debugcapi: ' fprintf(stderr,"#vardebuginfo#\\n");'}, ], + 'cleanupfrompyobj': ' /* End of cleaning variable #varname# */', + 'need': typedef_need_dict, + }, + # Scalars (not complex) + { # Common + 'decl': ' #ctype# #varname# = 0;', + 'need': {hasinitvalue: 'math.h'}, + 'frompyobj': {hasinitvalue: ' #varname# = #init#;'}, + '_check': l_and(isscalar, l_not(iscomplex)), + }, + { + 'return': ',#varname#', + 'docstrout': '#pydocsignout#', + 'docreturn': '#outvarname#,', + 'returnformat': '#varrformat#', + '_check': l_and(isscalar, l_not(iscomplex), isintent_out), + }, + # Complex scalars + { # Common + 'decl': ' #ctype# #varname#;', + 'frompyobj': {hasinitvalue: ' #varname#.r = #init.r#, #varname#.i = #init.i#;'}, + '_check': iscomplex + }, + # String + { # Common + 'decl': [' #ctype# #varname# = NULL;', + ' int slen(#varname#);', + ], + 'need': ['len..'], + '_check': isstring + }, + # Array + { # Common + 'decl': [' #ctype# *#varname# = NULL;', + ' npy_intp #varname#_Dims[#rank#] = {#rank*[-1]#};', + ' const int #varname#_Rank = #rank#;', + ], + 'need': ['len..', {hasinitvalue: 'forcomb'}, {hasinitvalue: 'CFUNCSMESS'}], + '_check': isarray + }, + # Scalararray + { # Common + '_check': l_and(isarray, l_not(iscomplexarray)) + }, { # Not hidden + '_check': l_and(isarray, l_not(iscomplexarray), isintent_nothide) + }, + # Integer*1 array + {'need': '#ctype#', + '_check': isint1array, + '_depend': '' + }, + # Integer*-1 array + {'need': '#ctype#', + '_check': l_or(isunsigned_chararray, isunsigned_char), + '_depend': '' + }, + # Integer*-2 array + {'need': '#ctype#', + '_check': isunsigned_shortarray, + '_depend': '' + }, + # Integer*-8 array + {'need': '#ctype#', + '_check': isunsigned_long_longarray, + '_depend': '' + }, + # Complexarray + {'need': '#ctype#', + '_check': iscomplexarray, + '_depend': '' + }, + # Stringarray + { + 'callfortranappend': {isarrayofstrings: 'flen(#varname#),'}, + 'need': 'string', + '_check': isstringarray + } +] + +arg_rules = [ + { + 'separatorsfor': sepdict + }, + { # Common + 'frompyobj': [' /* Processing variable #varname# */', + {debugcapi: ' fprintf(stderr,"#vardebuginfo#\\n");'}, ], + 'cleanupfrompyobj': ' /* End of cleaning variable #varname# */', + '_depend': '', + 'need': typedef_need_dict, + }, + # Doc signatures + { + 'docstropt': {l_and(isoptional, isintent_nothide): '#pydocsign#'}, + 'docstrreq': {l_and(isrequired, isintent_nothide): '#pydocsign#'}, + 'docstrout': {isintent_out: '#pydocsignout#'}, + 'latexdocstropt': {l_and(isoptional, isintent_nothide): ['\\item[]{{}\\verb@#pydocsign#@{}}', + {hasnote: '--- #note#'}]}, + 'latexdocstrreq': {l_and(isrequired, isintent_nothide): ['\\item[]{{}\\verb@#pydocsign#@{}}', + {hasnote: '--- #note#'}]}, + 'latexdocstrout': {isintent_out: ['\\item[]{{}\\verb@#pydocsignout#@{}}', + {l_and(hasnote, isintent_hide): '--- #note#', + l_and(hasnote, isintent_nothide): '--- See above.'}]}, + 'depend': '' + }, + # Required/Optional arguments + { + 'kwlist': '"#varname#",', + 'docsign': '#varname#,', + '_check': l_and(isintent_nothide, l_not(isoptional)) + }, + { + 'kwlistopt': '"#varname#",', + 'docsignopt': '#varname#=#showinit#,', + 'docsignoptshort': '#varname#,', + '_check': l_and(isintent_nothide, isoptional) + }, + # Docstring/BuildValue + { + 'docreturn': '#outvarname#,', + 'returnformat': '#varrformat#', + '_check': isintent_out + }, + # Externals (call-back functions) + { # Common + 'docsignxa': {isintent_nothide: '#varname#_extra_args=(),'}, + 'docsignxashort': {isintent_nothide: '#varname#_extra_args,'}, + 'docstropt': {isintent_nothide: '#varname#_extra_args : input tuple, optional\\n Default: ()'}, + 'docstrcbs': '#cbdocstr#', + 'latexdocstrcbs': '\\item[] #cblatexdocstr#', + 'latexdocstropt': {isintent_nothide: '\\item[]{{}\\verb@#varname#_extra_args := () input tuple@{}} --- Extra arguments for call-back function {{}\\verb@#varname#@{}}.'}, + 'decl': [' #cbname#_t #varname#_cb = { Py_None, NULL, 0 };', + ' #cbname#_t *#varname#_cb_ptr = &#varname#_cb;', + ' PyTupleObject *#varname#_xa_capi = NULL;', + {l_not(isintent_callback): + ' #cbname#_typedef #varname#_cptr;'} + ], + 'kwlistxa': {isintent_nothide: '"#varname#_extra_args",'}, + 'argformat': {isrequired: 'O'}, + 'keyformat': {isoptional: 'O'}, + 'xaformat': {isintent_nothide: 'O!'}, + 'args_capi': {isrequired: ',&#varname#_cb.capi'}, + 'keys_capi': {isoptional: ',&#varname#_cb.capi'}, + 'keys_xa': ',&PyTuple_Type,&#varname#_xa_capi', + 'setjmpbuf': '(setjmp(#varname#_cb.jmpbuf))', + 'callfortran': {l_not(isintent_callback): '#varname#_cptr,'}, + 'need': ['#cbname#', 'setjmp.h'], + '_check': isexternal + }, + { + 'frompyobj': [{l_not(isintent_callback): """\ +if(F2PyCapsule_Check(#varname#_cb.capi)) { + #varname#_cptr = F2PyCapsule_AsVoidPtr(#varname#_cb.capi); +} else { + #varname#_cptr = #cbname#; +} +"""}, {isintent_callback: """\ +if (#varname#_cb.capi==Py_None) { + #varname#_cb.capi = PyObject_GetAttrString(#modulename#_module,\"#varname#\"); + if (#varname#_cb.capi) { + if (#varname#_xa_capi==NULL) { + if (PyObject_HasAttrString(#modulename#_module,\"#varname#_extra_args\")) { + PyObject* capi_tmp = PyObject_GetAttrString(#modulename#_module,\"#varname#_extra_args\"); + if (capi_tmp) { + #varname#_xa_capi = (PyTupleObject *)PySequence_Tuple(capi_tmp); + Py_DECREF(capi_tmp); + } + else { + #varname#_xa_capi = (PyTupleObject *)Py_BuildValue(\"()\"); + } + if (#varname#_xa_capi==NULL) { + PyErr_SetString(#modulename#_error,\"Failed to convert #modulename#.#varname#_extra_args to tuple.\\n\"); + return NULL; + } + } + } + } + if (#varname#_cb.capi==NULL) { + PyErr_SetString(#modulename#_error,\"Callback #varname# not defined (as an argument or module #modulename# attribute).\\n\"); + return NULL; + } +} +"""}, + """\ + if (create_cb_arglist(#varname#_cb.capi,#varname#_xa_capi,#maxnofargs#,#nofoptargs#,&#varname#_cb.nofargs,&#varname#_cb.args_capi,\"failed in processing argument list for call-back #varname#.\")) { +""", + {debugcapi: ["""\ + fprintf(stderr,\"debug-capi:Assuming %d arguments; at most #maxnofargs#(-#nofoptargs#) is expected.\\n\",#varname#_cb.nofargs); + CFUNCSMESSPY(\"for #varname#=\",#varname#_cb.capi);""", + {l_not(isintent_callback): """ fprintf(stderr,\"#vardebugshowvalue# (call-back in C).\\n\",#cbname#);"""}]}, + """\ + CFUNCSMESS(\"Saving callback variables for `#varname#`.\\n\"); + #varname#_cb_ptr = swap_active_#cbname#(#varname#_cb_ptr);""", + ], + 'cleanupfrompyobj': + """\ + CFUNCSMESS(\"Restoring callback variables for `#varname#`.\\n\"); + #varname#_cb_ptr = swap_active_#cbname#(#varname#_cb_ptr); + Py_DECREF(#varname#_cb.args_capi); + }""", + 'need': ['SWAP', 'create_cb_arglist'], + '_check': isexternal, + '_depend': '' + }, + # Scalars (not complex) + { # Common + 'decl': ' #ctype# #varname# = 0;', + 'pyobjfrom': {debugcapi: ' fprintf(stderr,"#vardebugshowvalue#\\n",#varname#);'}, + 'callfortran': {l_or(isintent_c, isattr_value): '#varname#,', l_not(l_or(isintent_c, isattr_value)): '&#varname#,'}, + 'return': {isintent_out: ',#varname#'}, + '_check': l_and(isscalar, l_not(iscomplex)) + }, { + 'need': {hasinitvalue: 'math.h'}, + '_check': l_and(isscalar, l_not(iscomplex)), + }, { # Not hidden + 'decl': ' PyObject *#varname#_capi = Py_None;', + 'argformat': {isrequired: 'O'}, + 'keyformat': {isoptional: 'O'}, + 'args_capi': {isrequired: ',&#varname#_capi'}, + 'keys_capi': {isoptional: ',&#varname#_capi'}, + 'pyobjfrom': {isintent_inout: """\ + f2py_success = try_pyarr_from_#ctype#(#varname#_capi,&#varname#); + if (f2py_success) {"""}, + 'closepyobjfrom': {isintent_inout: " } /*if (f2py_success) of #varname# pyobjfrom*/"}, + 'need': {isintent_inout: 'try_pyarr_from_#ctype#'}, + '_check': l_and(isscalar, l_not(iscomplex), l_not(isstring), + isintent_nothide) + }, { + 'frompyobj': [ + # hasinitvalue... + # if pyobj is None: + # varname = init + # else + # from_pyobj(varname) + # + # isoptional and noinitvalue... + # if pyobj is not None: + # from_pyobj(varname) + # else: + # varname is uninitialized + # + # ... + # from_pyobj(varname) + # + {hasinitvalue: ' if (#varname#_capi == Py_None) #varname# = #init#; else', + '_depend': ''}, + {l_and(isoptional, l_not(hasinitvalue)): ' if (#varname#_capi != Py_None)', + '_depend': ''}, + {l_not(islogical): '''\ + f2py_success = #ctype#_from_pyobj(&#varname#,#varname#_capi,"#pyname#() #nth# (#varname#) can\'t be converted to #ctype#"); + if (f2py_success) {'''}, + {islogical: '''\ + #varname# = (#ctype#)PyObject_IsTrue(#varname#_capi); + f2py_success = 1; + if (f2py_success) {'''}, + ], + 'cleanupfrompyobj': ' } /*if (f2py_success) of #varname#*/', + 'need': {l_not(islogical): '#ctype#_from_pyobj'}, + '_check': l_and(isscalar, l_not(iscomplex), isintent_nothide), + '_depend': '' + }, { # Hidden + 'frompyobj': {hasinitvalue: ' #varname# = #init#;'}, + 'need': typedef_need_dict, + '_check': l_and(isscalar, l_not(iscomplex), isintent_hide), + '_depend': '' + }, { # Common + 'frompyobj': {debugcapi: ' fprintf(stderr,"#vardebugshowvalue#\\n",#varname#);'}, + '_check': l_and(isscalar, l_not(iscomplex)), + '_depend': '' + }, + # Complex scalars + { # Common + 'decl': ' #ctype# #varname#;', + 'callfortran': {isintent_c: '#varname#,', l_not(isintent_c): '&#varname#,'}, + 'pyobjfrom': {debugcapi: ' fprintf(stderr,"#vardebugshowvalue#\\n",#varname#.r,#varname#.i);'}, + 'return': {isintent_out: ',#varname#_capi'}, + '_check': iscomplex + }, { # Not hidden + 'decl': ' PyObject *#varname#_capi = Py_None;', + 'argformat': {isrequired: 'O'}, + 'keyformat': {isoptional: 'O'}, + 'args_capi': {isrequired: ',&#varname#_capi'}, + 'keys_capi': {isoptional: ',&#varname#_capi'}, + 'need': {isintent_inout: 'try_pyarr_from_#ctype#'}, + 'pyobjfrom': {isintent_inout: """\ + f2py_success = try_pyarr_from_#ctype#(#varname#_capi,&#varname#); + if (f2py_success) {"""}, + 'closepyobjfrom': {isintent_inout: " } /*if (f2py_success) of #varname# pyobjfrom*/"}, + '_check': l_and(iscomplex, isintent_nothide) + }, { + 'frompyobj': [{hasinitvalue: ' if (#varname#_capi==Py_None) {#varname#.r = #init.r#, #varname#.i = #init.i#;} else'}, + {l_and(isoptional, l_not(hasinitvalue)) + : ' if (#varname#_capi != Py_None)'}, + ' f2py_success = #ctype#_from_pyobj(&#varname#,#varname#_capi,"#pyname#() #nth# (#varname#) can\'t be converted to #ctype#");' + '\n if (f2py_success) {'], + 'cleanupfrompyobj': ' } /*if (f2py_success) of #varname# frompyobj*/', + 'need': ['#ctype#_from_pyobj'], + '_check': l_and(iscomplex, isintent_nothide), + '_depend': '' + }, { # Hidden + 'decl': {isintent_out: ' PyObject *#varname#_capi = Py_None;'}, + '_check': l_and(iscomplex, isintent_hide) + }, { + 'frompyobj': {hasinitvalue: ' #varname#.r = #init.r#, #varname#.i = #init.i#;'}, + '_check': l_and(iscomplex, isintent_hide), + '_depend': '' + }, { # Common + 'pyobjfrom': {isintent_out: ' #varname#_capi = pyobj_from_#ctype#1(#varname#);'}, + 'need': ['pyobj_from_#ctype#1'], + '_check': iscomplex + }, { + 'frompyobj': {debugcapi: ' fprintf(stderr,"#vardebugshowvalue#\\n",#varname#.r,#varname#.i);'}, + '_check': iscomplex, + '_depend': '' + }, + # String + { # Common + 'decl': [' #ctype# #varname# = NULL;', + ' int slen(#varname#);', + ' PyObject *#varname#_capi = Py_None;'], + 'callfortran': '#varname#,', + 'callfortranappend': 'slen(#varname#),', + 'pyobjfrom': [ + {debugcapi: + ' fprintf(stderr,' + '"#vardebugshowvalue#\\n",slen(#varname#),#varname#);'}, + # The trailing null value for Fortran is blank. + {l_and(isintent_out, l_not(isintent_c)): + " STRINGPADN(#varname#, slen(#varname#), ' ', '\\0');"}, + ], + 'return': {isintent_out: ',#varname#'}, + 'need': ['len..', + {l_and(isintent_out, l_not(isintent_c)): 'STRINGPADN'}], + '_check': isstring + }, { # Common + 'frompyobj': [ + """\ + slen(#varname#) = #elsize#; + f2py_success = #ctype#_from_pyobj(&#varname#,&slen(#varname#),#init#,""" +"""#varname#_capi,\"#ctype#_from_pyobj failed in converting #nth#""" +"""`#varname#\' of #pyname# to C #ctype#\"); + if (f2py_success) {""", + # The trailing null value for Fortran is blank. + {l_not(isintent_c): + " STRINGPADN(#varname#, slen(#varname#), '\\0', ' ');"}, + ], + 'cleanupfrompyobj': """\ + STRINGFREE(#varname#); + } /*if (f2py_success) of #varname#*/""", + 'need': ['#ctype#_from_pyobj', 'len..', 'STRINGFREE', + {l_not(isintent_c): 'STRINGPADN'}], + '_check': isstring, + '_depend': '' + }, { # Not hidden + 'argformat': {isrequired: 'O'}, + 'keyformat': {isoptional: 'O'}, + 'args_capi': {isrequired: ',&#varname#_capi'}, + 'keys_capi': {isoptional: ',&#varname#_capi'}, + 'pyobjfrom': [ + {l_and(isintent_inout, l_not(isintent_c)): + " STRINGPADN(#varname#, slen(#varname#), ' ', '\\0');"}, + {isintent_inout: '''\ + f2py_success = try_pyarr_from_#ctype#(#varname#_capi, #varname#, + slen(#varname#)); + if (f2py_success) {'''}], + 'closepyobjfrom': {isintent_inout: ' } /*if (f2py_success) of #varname# pyobjfrom*/'}, + 'need': {isintent_inout: 'try_pyarr_from_#ctype#', + l_and(isintent_inout, l_not(isintent_c)): 'STRINGPADN'}, + '_check': l_and(isstring, isintent_nothide) + }, { # Hidden + '_check': l_and(isstring, isintent_hide) + }, { + 'frompyobj': {debugcapi: ' fprintf(stderr,"#vardebugshowvalue#\\n",slen(#varname#),#varname#);'}, + '_check': isstring, + '_depend': '' + }, + # Array + { # Common + 'decl': [' #ctype# *#varname# = NULL;', + ' npy_intp #varname#_Dims[#rank#] = {#rank*[-1]#};', + ' const int #varname#_Rank = #rank#;', + ' PyArrayObject *capi_#varname#_as_array = NULL;', + ' int capi_#varname#_intent = 0;', + {isstringarray: ' int slen(#varname#) = 0;'}, + ], + 'callfortran': '#varname#,', + 'callfortranappend': {isstringarray: 'slen(#varname#),'}, + 'return': {isintent_out: ',capi_#varname#_as_array'}, + 'need': 'len..', + '_check': isarray + }, { # intent(overwrite) array + 'decl': ' int capi_overwrite_#varname# = 1;', + 'kwlistxa': '"overwrite_#varname#",', + 'xaformat': 'i', + 'keys_xa': ',&capi_overwrite_#varname#', + 'docsignxa': 'overwrite_#varname#=1,', + 'docsignxashort': 'overwrite_#varname#,', + 'docstropt': 'overwrite_#varname# : input int, optional\\n Default: 1', + '_check': l_and(isarray, isintent_overwrite), + }, { + 'frompyobj': ' capi_#varname#_intent |= (capi_overwrite_#varname#?0:F2PY_INTENT_COPY);', + '_check': l_and(isarray, isintent_overwrite), + '_depend': '', + }, + { # intent(copy) array + 'decl': ' int capi_overwrite_#varname# = 0;', + 'kwlistxa': '"overwrite_#varname#",', + 'xaformat': 'i', + 'keys_xa': ',&capi_overwrite_#varname#', + 'docsignxa': 'overwrite_#varname#=0,', + 'docsignxashort': 'overwrite_#varname#,', + 'docstropt': 'overwrite_#varname# : input int, optional\\n Default: 0', + '_check': l_and(isarray, isintent_copy), + }, { + 'frompyobj': ' capi_#varname#_intent |= (capi_overwrite_#varname#?0:F2PY_INTENT_COPY);', + '_check': l_and(isarray, isintent_copy), + '_depend': '', + }, { + 'need': [{hasinitvalue: 'forcomb'}, {hasinitvalue: 'CFUNCSMESS'}], + '_check': isarray, + '_depend': '' + }, { # Not hidden + 'decl': ' PyObject *#varname#_capi = Py_None;', + 'argformat': {isrequired: 'O'}, + 'keyformat': {isoptional: 'O'}, + 'args_capi': {isrequired: ',&#varname#_capi'}, + 'keys_capi': {isoptional: ',&#varname#_capi'}, + '_check': l_and(isarray, isintent_nothide) + }, { + 'frompyobj': [ + ' #setdims#;', + ' capi_#varname#_intent |= #intent#;', + (' const char capi_errmess[] = "#modulename#.#pyname#:' + ' failed to create array from the #nth# `#varname#`";'), + {isintent_hide: + ' capi_#varname#_as_array = ndarray_from_pyobj(' + ' #atype#,#elsize#,#varname#_Dims,#varname#_Rank,' + ' capi_#varname#_intent,Py_None,capi_errmess);'}, + {isintent_nothide: + ' capi_#varname#_as_array = ndarray_from_pyobj(' + ' #atype#,#elsize#,#varname#_Dims,#varname#_Rank,' + ' capi_#varname#_intent,#varname#_capi,capi_errmess);'}, + """\ + if (capi_#varname#_as_array == NULL) { + PyObject* capi_err = PyErr_Occurred(); + if (capi_err == NULL) { + capi_err = #modulename#_error; + PyErr_SetString(capi_err, capi_errmess); + } + } else { + #varname# = (#ctype# *)(PyArray_DATA(capi_#varname#_as_array)); +""", + {isstringarray: + ' slen(#varname#) = f2py_itemsize(#varname#);'}, + {hasinitvalue: [ + {isintent_nothide: + ' if (#varname#_capi == Py_None) {'}, + {isintent_hide: ' {'}, + {iscomplexarray: ' #ctype# capi_c;'}, + """\ + int *_i,capi_i=0; + CFUNCSMESS(\"#name#: Initializing #varname#=#init#\\n\"); + struct ForcombCache cache; + if (initforcomb(&cache, PyArray_DIMS(capi_#varname#_as_array), + PyArray_NDIM(capi_#varname#_as_array),1)) { + while ((_i = nextforcomb(&cache))) + #varname#[capi_i++] = #init#; /* fortran way */ + } else { + PyObject *exc, *val, *tb; + PyErr_Fetch(&exc, &val, &tb); + PyErr_SetString(exc ? exc : #modulename#_error, + \"Initialization of #nth# #varname# failed (initforcomb).\"); + npy_PyErr_ChainExceptionsCause(exc, val, tb); + f2py_success = 0; + } + } + if (f2py_success) {"""]}, + ], + 'cleanupfrompyobj': [ # note that this list will be reversed + ' } ' + '/* if (capi_#varname#_as_array == NULL) ... else of #varname# */', + {l_not(l_or(isintent_out, isintent_hide)): """\ + if((PyObject *)capi_#varname#_as_array!=#varname#_capi) { + Py_XDECREF(capi_#varname#_as_array); }"""}, + {l_and(isintent_hide, l_not(isintent_out)) + : """ Py_XDECREF(capi_#varname#_as_array);"""}, + {hasinitvalue: ' } /*if (f2py_success) of #varname# init*/'}, + ], + '_check': isarray, + '_depend': '' + }, + # Scalararray + { # Common + '_check': l_and(isarray, l_not(iscomplexarray)) + }, { # Not hidden + '_check': l_and(isarray, l_not(iscomplexarray), isintent_nothide) + }, + # Integer*1 array + {'need': '#ctype#', + '_check': isint1array, + '_depend': '' + }, + # Integer*-1 array + {'need': '#ctype#', + '_check': isunsigned_chararray, + '_depend': '' + }, + # Integer*-2 array + {'need': '#ctype#', + '_check': isunsigned_shortarray, + '_depend': '' + }, + # Integer*-8 array + {'need': '#ctype#', + '_check': isunsigned_long_longarray, + '_depend': '' + }, + # Complexarray + {'need': '#ctype#', + '_check': iscomplexarray, + '_depend': '' + }, + # Character + { + 'need': 'string', + '_check': ischaracter, + }, + # Character array + { + 'need': 'string', + '_check': ischaracterarray, + }, + # Stringarray + { + 'callfortranappend': {isarrayofstrings: 'flen(#varname#),'}, + 'need': 'string', + '_check': isstringarray + } +] + +################# Rules for checking ############### + +check_rules = [ + { + 'frompyobj': {debugcapi: ' fprintf(stderr,\"debug-capi:Checking `#check#\'\\n\");'}, + 'need': 'len..' + }, { + 'frompyobj': ' CHECKSCALAR(#check#,\"#check#\",\"#nth# #varname#\",\"#varshowvalue#\",#varname#) {', + 'cleanupfrompyobj': ' } /*CHECKSCALAR(#check#)*/', + 'need': 'CHECKSCALAR', + '_check': l_and(isscalar, l_not(iscomplex)), + '_break': '' + }, { + 'frompyobj': ' CHECKSTRING(#check#,\"#check#\",\"#nth# #varname#\",\"#varshowvalue#\",#varname#) {', + 'cleanupfrompyobj': ' } /*CHECKSTRING(#check#)*/', + 'need': 'CHECKSTRING', + '_check': isstring, + '_break': '' + }, { + 'need': 'CHECKARRAY', + 'frompyobj': ' CHECKARRAY(#check#,\"#check#\",\"#nth# #varname#\") {', + 'cleanupfrompyobj': ' } /*CHECKARRAY(#check#)*/', + '_check': isarray, + '_break': '' + }, { + 'need': 'CHECKGENERIC', + 'frompyobj': ' CHECKGENERIC(#check#,\"#check#\",\"#nth# #varname#\") {', + 'cleanupfrompyobj': ' } /*CHECKGENERIC(#check#)*/', + } +] + +########## Applying the rules. No need to modify what follows ############# + +#################### Build C/API module ####################### + + +def buildmodule(m, um): + """ + Return + """ + outmess(f" Building module \"{m['name']}\"...\n") + ret = {} + mod_rules = defmod_rules[:] + vrd = capi_maps.modsign2map(m) + rd = dictappend({'f2py_version': f2py_version}, vrd) + funcwrappers = [] + funcwrappers2 = [] # F90 codes + for n in m['interfaced']: + nb = None + for bi in m['body']: + if bi['block'] not in ['interface', 'abstract interface']: + errmess('buildmodule: Expected interface block. Skipping.\n') + continue + for b in bi['body']: + if b['name'] == n: + nb = b + break + + if not nb: + print( + f'buildmodule: Could not find the body of interfaced routine "{n}". Skipping.\n', file=sys.stderr) + continue + nb_list = [nb] + if 'entry' in nb: + for k, a in nb['entry'].items(): + nb1 = copy.deepcopy(nb) + del nb1['entry'] + nb1['name'] = k + nb1['args'] = a + nb_list.append(nb1) + for nb in nb_list: + # requiresf90wrapper must be called before buildapi as it + # rewrites assumed shape arrays as automatic arrays. + isf90 = requiresf90wrapper(nb) + # options is in scope here + if options['emptygen']: + b_path = options['buildpath'] + m_name = vrd['modulename'] + outmess(' Generating possibly empty wrappers"\n') + Path(f"{b_path}/{vrd['coutput']}").touch() + if isf90: + # f77 + f90 wrappers + outmess(f' Maybe empty "{m_name}-f2pywrappers2.f90"\n') + Path(f'{b_path}/{m_name}-f2pywrappers2.f90').touch() + outmess(f' Maybe empty "{m_name}-f2pywrappers.f"\n') + Path(f'{b_path}/{m_name}-f2pywrappers.f').touch() + else: + # only f77 wrappers + outmess(f' Maybe empty "{m_name}-f2pywrappers.f"\n') + Path(f'{b_path}/{m_name}-f2pywrappers.f').touch() + api, wrap = buildapi(nb) + if wrap: + if isf90: + funcwrappers2.append(wrap) + else: + funcwrappers.append(wrap) + ar = applyrules(api, vrd) + rd = dictappend(rd, ar) + + # Construct COMMON block support + cr, wrap = common_rules.buildhooks(m) + if wrap: + funcwrappers.append(wrap) + ar = applyrules(cr, vrd) + rd = dictappend(rd, ar) + + # Construct F90 module support + mr, wrap = f90mod_rules.buildhooks(m) + if wrap: + funcwrappers2.append(wrap) + ar = applyrules(mr, vrd) + rd = dictappend(rd, ar) + + for u in um: + ar = use_rules.buildusevars(u, m['use'][u['name']]) + rd = dictappend(rd, ar) + + needs = cfuncs.get_needs() + # Add mapped definitions + needs['typedefs'] += [cvar for cvar in capi_maps.f2cmap_mapped # + if cvar in typedef_need_dict.values()] + code = {} + for n in needs.keys(): + code[n] = [] + for k in needs[n]: + c = '' + if k in cfuncs.includes0: + c = cfuncs.includes0[k] + elif k in cfuncs.includes: + c = cfuncs.includes[k] + elif k in cfuncs.userincludes: + c = cfuncs.userincludes[k] + elif k in cfuncs.typedefs: + c = cfuncs.typedefs[k] + elif k in cfuncs.typedefs_generated: + c = cfuncs.typedefs_generated[k] + elif k in cfuncs.cppmacros: + c = cfuncs.cppmacros[k] + elif k in cfuncs.cfuncs: + c = cfuncs.cfuncs[k] + elif k in cfuncs.callbacks: + c = cfuncs.callbacks[k] + elif k in cfuncs.f90modhooks: + c = cfuncs.f90modhooks[k] + elif k in cfuncs.commonhooks: + c = cfuncs.commonhooks[k] + else: + errmess(f'buildmodule: unknown need {repr(k)}.\n') + continue + code[n].append(c) + mod_rules.append(code) + for r in mod_rules: + if ('_check' in r and r['_check'](m)) or ('_check' not in r): + ar = applyrules(r, vrd, m) + rd = dictappend(rd, ar) + ar = applyrules(module_rules, rd) + + fn = os.path.join(options['buildpath'], vrd['coutput']) + ret['csrc'] = fn + with open(fn, 'w') as f: + f.write(ar['modulebody'].replace('\t', 2 * ' ')) + outmess(f" Wrote C/API module \"{m['name']}\" to file \"{fn}\"\n") + + if options['dorestdoc']: + fn = os.path.join( + options['buildpath'], vrd['modulename'] + 'module.rest') + with open(fn, 'w') as f: + f.write('.. -*- rest -*-\n') + f.write('\n'.join(ar['restdoc'])) + outmess(' ReST Documentation is saved to file "%s/%smodule.rest"\n' % + (options['buildpath'], vrd['modulename'])) + if options['dolatexdoc']: + fn = os.path.join( + options['buildpath'], vrd['modulename'] + 'module.tex') + ret['ltx'] = fn + with open(fn, 'w') as f: + f.write( + f'% This file is auto-generated with f2py (version:{f2py_version})\n') + if 'shortlatex' not in options: + f.write( + '\\documentclass{article}\n\\usepackage{a4wide}\n\\begin{document}\n\\tableofcontents\n\n') + f.write('\n'.join(ar['latexdoc'])) + if 'shortlatex' not in options: + f.write('\\end{document}') + outmess(' Documentation is saved to file "%s/%smodule.tex"\n' % + (options['buildpath'], vrd['modulename'])) + if funcwrappers: + wn = os.path.join(options['buildpath'], vrd['f2py_wrapper_output']) + ret['fsrc'] = wn + with open(wn, 'w') as f: + f.write('C -*- fortran -*-\n') + f.write( + f'C This file is autogenerated with f2py (version:{f2py_version})\n') + f.write( + 'C It contains Fortran 77 wrappers to fortran functions.\n') + lines = [] + for l in ('\n\n'.join(funcwrappers) + '\n').split('\n'): + if 0 <= l.find('!') < 66: + # don't split comment lines + lines.append(l + '\n') + elif l and l[0] == ' ': + while len(l) >= 66: + lines.append(l[:66] + '\n &') + l = l[66:] + lines.append(l + '\n') + else: + lines.append(l + '\n') + lines = ''.join(lines).replace('\n &\n', '\n') + f.write(lines) + outmess(f' Fortran 77 wrappers are saved to "{wn}\"\n') + if funcwrappers2: + wn = os.path.join( + options['buildpath'], f"{vrd['modulename']}-f2pywrappers2.f90") + ret['fsrc'] = wn + with open(wn, 'w') as f: + f.write('! -*- f90 -*-\n') + f.write( + f'! This file is autogenerated with f2py (version:{f2py_version})\n') + f.write( + '! It contains Fortran 90 wrappers to fortran functions.\n') + lines = [] + for l in ('\n\n'.join(funcwrappers2) + '\n').split('\n'): + if 0 <= l.find('!') < 72: + # don't split comment lines + lines.append(l + '\n') + elif len(l) > 72 and l[0] == ' ': + lines.append(l[:72] + '&\n &') + l = l[72:] + while len(l) > 66: + lines.append(l[:66] + '&\n &') + l = l[66:] + lines.append(l + '\n') + else: + lines.append(l + '\n') + lines = ''.join(lines).replace('\n &\n', '\n') + f.write(lines) + outmess(f' Fortran 90 wrappers are saved to "{wn}\"\n') + return ret + +################## Build C/API function ############# + + +stnd = {1: 'st', 2: 'nd', 3: 'rd', 4: 'th', 5: 'th', + 6: 'th', 7: 'th', 8: 'th', 9: 'th', 0: 'th'} + + +def buildapi(rout): + rout, wrap = func2subr.assubr(rout) + args, depargs = getargs2(rout) + capi_maps.depargs = depargs + var = rout['vars'] + + if ismoduleroutine(rout): + outmess(' Constructing wrapper function "%s.%s"...\n' % + (rout['modulename'], rout['name'])) + else: + outmess(f" Constructing wrapper function \"{rout['name']}\"...\n") + # Routine + vrd = capi_maps.routsign2map(rout) + rd = dictappend({}, vrd) + for r in rout_rules: + if ('_check' in r and r['_check'](rout)) or ('_check' not in r): + ar = applyrules(r, vrd, rout) + rd = dictappend(rd, ar) + + # Args + nth, nthk = 0, 0 + savevrd = {} + for a in args: + vrd = capi_maps.sign2map(a, var[a]) + if isintent_aux(var[a]): + _rules = aux_rules + else: + _rules = arg_rules + if not isintent_hide(var[a]): + if not isoptional(var[a]): + nth = nth + 1 + vrd['nth'] = repr(nth) + stnd[nth % 10] + ' argument' + else: + nthk = nthk + 1 + vrd['nth'] = repr(nthk) + stnd[nthk % 10] + ' keyword' + else: + vrd['nth'] = 'hidden' + savevrd[a] = vrd + for r in _rules: + if '_depend' in r: + continue + if ('_check' in r and r['_check'](var[a])) or ('_check' not in r): + ar = applyrules(r, vrd, var[a]) + rd = dictappend(rd, ar) + if '_break' in r: + break + for a in depargs: + if isintent_aux(var[a]): + _rules = aux_rules + else: + _rules = arg_rules + vrd = savevrd[a] + for r in _rules: + if '_depend' not in r: + continue + if ('_check' in r and r['_check'](var[a])) or ('_check' not in r): + ar = applyrules(r, vrd, var[a]) + rd = dictappend(rd, ar) + if '_break' in r: + break + if 'check' in var[a]: + for c in var[a]['check']: + vrd['check'] = c + ar = applyrules(check_rules, vrd, var[a]) + rd = dictappend(rd, ar) + if isinstance(rd['cleanupfrompyobj'], list): + rd['cleanupfrompyobj'].reverse() + if isinstance(rd['closepyobjfrom'], list): + rd['closepyobjfrom'].reverse() + rd['docsignature'] = stripcomma(replace('#docsign##docsignopt##docsignxa#', + {'docsign': rd['docsign'], + 'docsignopt': rd['docsignopt'], + 'docsignxa': rd['docsignxa']})) + optargs = stripcomma(replace('#docsignopt##docsignxa#', + {'docsignxa': rd['docsignxashort'], + 'docsignopt': rd['docsignoptshort']} + )) + if optargs == '': + rd['docsignatureshort'] = stripcomma( + replace('#docsign#', {'docsign': rd['docsign']})) + else: + rd['docsignatureshort'] = replace('#docsign#[#docsignopt#]', + {'docsign': rd['docsign'], + 'docsignopt': optargs, + }) + rd['latexdocsignatureshort'] = rd['docsignatureshort'].replace('_', '\\_') + rd['latexdocsignatureshort'] = rd[ + 'latexdocsignatureshort'].replace(',', ', ') + cfs = stripcomma(replace('#callfortran##callfortranappend#', { + 'callfortran': rd['callfortran'], 'callfortranappend': rd['callfortranappend']})) + if len(rd['callfortranappend']) > 1: + rd['callcompaqfortran'] = stripcomma(replace('#callfortran# 0,#callfortranappend#', { + 'callfortran': rd['callfortran'], 'callfortranappend': rd['callfortranappend']})) + else: + rd['callcompaqfortran'] = cfs + rd['callfortran'] = cfs + if isinstance(rd['docreturn'], list): + rd['docreturn'] = stripcomma( + replace('#docreturn#', {'docreturn': rd['docreturn']})) + ' = ' + rd['docstrsigns'] = [] + rd['latexdocstrsigns'] = [] + for k in ['docstrreq', 'docstropt', 'docstrout', 'docstrcbs']: + if k in rd and isinstance(rd[k], list): + rd['docstrsigns'] = rd['docstrsigns'] + rd[k] + k = 'latex' + k + if k in rd and isinstance(rd[k], list): + rd['latexdocstrsigns'] = rd['latexdocstrsigns'] + rd[k][0:1] +\ + ['\\begin{description}'] + rd[k][1:] +\ + ['\\end{description}'] + + ar = applyrules(routine_rules, rd) + if ismoduleroutine(rout): + outmess(f" {ar['docshort']}\n") + else: + outmess(f" {ar['docshort']}\n") + return ar, wrap + + +#################### EOF rules.py ####################### diff --git a/python/user_packages/Python313/site-packages/numpy/f2py/rules.pyi b/python/user_packages/Python313/site-packages/numpy/f2py/rules.pyi new file mode 100644 index 0000000000000000000000000000000000000000..811a38c2da89f891462d4b19f38a349207cba751 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/f2py/rules.pyi @@ -0,0 +1,41 @@ +from collections.abc import Callable, Iterable, Mapping +from typing import Any, Final, Literal as L, TypeAlias +from typing_extensions import TypeVar + +from .__version__ import version +from .auxfuncs import _Bool, _Var + +### + +_VT = TypeVar("_VT", default=str) + +_Predicate: TypeAlias = Callable[[_Var], _Bool] +_RuleDict: TypeAlias = dict[str, _VT] +_DefDict: TypeAlias = dict[_Predicate, _VT] + +### + +f2py_version: Final = version +numpy_version: Final = version + +options: Final[dict[str, bool]] = ... +sepdict: Final[dict[str, str]] = ... + +generationtime: Final[int] = ... +typedef_need_dict: Final[_DefDict[str]] = ... + +module_rules: Final[_RuleDict[str | list[str] | _RuleDict]] = ... +routine_rules: Final[_RuleDict[str | list[str] | _DefDict | _RuleDict]] = ... +defmod_rules: Final[list[_RuleDict[str | _DefDict]]] = ... +rout_rules: Final[list[_RuleDict[str | Any]]] = ... +aux_rules: Final[list[_RuleDict[str | Any]]] = ... +arg_rules: Final[list[_RuleDict[str | Any]]] = ... +check_rules: Final[list[_RuleDict[str | Any]]] = ... + +stnd: Final[dict[L[1, 2, 3, 4, 5, 6, 7, 8, 9, 0], L["st", "nd", "rd", "th"]]] = ... + +def buildmodule(m: Mapping[str, str | Any], um: Iterable[Mapping[str, str | Any]]) -> _RuleDict: ... +def buildapi(rout: Mapping[str, str]) -> tuple[_RuleDict, str]: ... + +# namespace pollution +k: str diff --git a/python/user_packages/Python313/site-packages/numpy/f2py/setup.cfg b/python/user_packages/Python313/site-packages/numpy/f2py/setup.cfg new file mode 100644 index 0000000000000000000000000000000000000000..fd3c6f4895e598adbd2c4c875052f464066a5742 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/f2py/setup.cfg @@ -0,0 +1,3 @@ +[bdist_rpm] +doc_files = docs/ + tests/ \ No newline at end of file diff --git a/python/user_packages/Python313/site-packages/numpy/f2py/symbolic.py b/python/user_packages/Python313/site-packages/numpy/f2py/symbolic.py new file mode 100644 index 0000000000000000000000000000000000000000..47a3e6b61e63902df5d472373295ba707bcff2fe --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/f2py/symbolic.py @@ -0,0 +1,1518 @@ +"""Fortran/C symbolic expressions + +References: +- J3/21-007: Draft Fortran 202x. https://j3-fortran.org/doc/year/21/21-007.pdf + +Copyright 1999 -- 2011 Pearu Peterson all rights reserved. +Copyright 2011 -- present NumPy Developers. +Permission to use, modify, and distribute this software is given under the +terms of the NumPy License. + +NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. +""" + +# To analyze Fortran expressions to solve dimensions specifications, +# for instances, we implement a minimal symbolic engine for parsing +# expressions into a tree of expression instances. As a first +# instance, we care only about arithmetic expressions involving +# integers and operations like addition (+), subtraction (-), +# multiplication (*), division (Fortran / is Python //, Fortran // is +# concatenate), and exponentiation (**). In addition, .pyf files may +# contain C expressions that support here is implemented as well. +# +# TODO: support logical constants (Op.BOOLEAN) +# TODO: support logical operators (.AND., ...) +# TODO: support defined operators (.MYOP., ...) +# +__all__ = ['Expr'] + + +import re +import warnings +from enum import Enum +from math import gcd + + +class Language(Enum): + """ + Used as Expr.tostring language argument. + """ + Python = 0 + Fortran = 1 + C = 2 + + +class Op(Enum): + """ + Used as Expr op attribute. + """ + INTEGER = 10 + REAL = 12 + COMPLEX = 15 + STRING = 20 + ARRAY = 30 + SYMBOL = 40 + TERNARY = 100 + APPLY = 200 + INDEXING = 210 + CONCAT = 220 + RELATIONAL = 300 + TERMS = 1000 + FACTORS = 2000 + REF = 3000 + DEREF = 3001 + + +class RelOp(Enum): + """ + Used in Op.RELATIONAL expression to specify the function part. + """ + EQ = 1 + NE = 2 + LT = 3 + LE = 4 + GT = 5 + GE = 6 + + @classmethod + def fromstring(cls, s, language=Language.C): + if language is Language.Fortran: + return {'.eq.': RelOp.EQ, '.ne.': RelOp.NE, + '.lt.': RelOp.LT, '.le.': RelOp.LE, + '.gt.': RelOp.GT, '.ge.': RelOp.GE}[s.lower()] + return {'==': RelOp.EQ, '!=': RelOp.NE, '<': RelOp.LT, + '<=': RelOp.LE, '>': RelOp.GT, '>=': RelOp.GE}[s] + + def tostring(self, language=Language.C): + if language is Language.Fortran: + return {RelOp.EQ: '.eq.', RelOp.NE: '.ne.', + RelOp.LT: '.lt.', RelOp.LE: '.le.', + RelOp.GT: '.gt.', RelOp.GE: '.ge.'}[self] + return {RelOp.EQ: '==', RelOp.NE: '!=', + RelOp.LT: '<', RelOp.LE: '<=', + RelOp.GT: '>', RelOp.GE: '>='}[self] + + +class ArithOp(Enum): + """ + Used in Op.APPLY expression to specify the function part. + """ + POS = 1 + NEG = 2 + ADD = 3 + SUB = 4 + MUL = 5 + DIV = 6 + POW = 7 + + +class OpError(Exception): + pass + + +class Precedence(Enum): + """ + Used as Expr.tostring precedence argument. + """ + ATOM = 0 + POWER = 1 + UNARY = 2 + PRODUCT = 3 + SUM = 4 + LT = 6 + EQ = 7 + LAND = 11 + LOR = 12 + TERNARY = 13 + ASSIGN = 14 + TUPLE = 15 + NONE = 100 + + +integer_types = (int,) +number_types = (int, float) + + +def _pairs_add(d, k, v): + # Internal utility method for updating terms and factors data. + c = d.get(k) + if c is None: + d[k] = v + else: + c = c + v + if c: + d[k] = c + else: + del d[k] + + +class ExprWarning(UserWarning): + pass + + +def ewarn(message): + warnings.warn(message, ExprWarning, stacklevel=2) + + +class Expr: + """Represents a Fortran expression as an op-data pair. + + Expr instances are hashable and sortable. + """ + + @staticmethod + def parse(s, language=Language.C): + """Parse a Fortran expression to an Expr. + """ + return fromstring(s, language=language) + + def __init__(self, op, data): + assert isinstance(op, Op) + + # sanity checks + if op is Op.INTEGER: + # data is a 2-tuple of numeric object and a kind value + # (default is 4) + assert isinstance(data, tuple) and len(data) == 2 + assert isinstance(data[0], int) + assert isinstance(data[1], (int, str)), data + elif op is Op.REAL: + # data is a 2-tuple of numeric object and a kind value + # (default is 4) + assert isinstance(data, tuple) and len(data) == 2 + assert isinstance(data[0], float) + assert isinstance(data[1], (int, str)), data + elif op is Op.COMPLEX: + # data is a 2-tuple of constant expressions + assert isinstance(data, tuple) and len(data) == 2 + elif op is Op.STRING: + # data is a 2-tuple of quoted string and a kind value + # (default is 1) + assert isinstance(data, tuple) and len(data) == 2 + assert (isinstance(data[0], str) + and data[0][::len(data[0]) - 1] in ('""', "''", '@@')) + assert isinstance(data[1], (int, str)), data + elif op is Op.SYMBOL: + # data is any hashable object + assert hash(data) is not None + elif op in (Op.ARRAY, Op.CONCAT): + # data is a tuple of expressions + assert isinstance(data, tuple) + assert all(isinstance(item, Expr) for item in data), data + elif op in (Op.TERMS, Op.FACTORS): + # data is {:} where dict values + # are nonzero Python integers + assert isinstance(data, dict) + elif op is Op.APPLY: + # data is (, , ) where + # operands are Expr instances + assert isinstance(data, tuple) and len(data) == 3 + # function is any hashable object + assert hash(data[0]) is not None + assert isinstance(data[1], tuple) + assert isinstance(data[2], dict) + elif op is Op.INDEXING: + # data is (, ) + assert isinstance(data, tuple) and len(data) == 2 + # function is any hashable object + assert hash(data[0]) is not None + elif op is Op.TERNARY: + # data is (, , ) + assert isinstance(data, tuple) and len(data) == 3 + elif op in (Op.REF, Op.DEREF): + # data is Expr instance + assert isinstance(data, Expr) + elif op is Op.RELATIONAL: + # data is (, , ) + assert isinstance(data, tuple) and len(data) == 3 + else: + raise NotImplementedError( + f'unknown op or missing sanity check: {op}') + + self.op = op + self.data = data + + def __eq__(self, other): + return (isinstance(other, Expr) + and self.op is other.op + and self.data == other.data) + + def __hash__(self): + if self.op in (Op.TERMS, Op.FACTORS): + data = tuple(sorted(self.data.items())) + elif self.op is Op.APPLY: + data = self.data[:2] + tuple(sorted(self.data[2].items())) + else: + data = self.data + return hash((self.op, data)) + + def __lt__(self, other): + if isinstance(other, Expr): + if self.op is not other.op: + return self.op.value < other.op.value + if self.op in (Op.TERMS, Op.FACTORS): + return (tuple(sorted(self.data.items())) + < tuple(sorted(other.data.items()))) + if self.op is Op.APPLY: + if self.data[:2] != other.data[:2]: + return self.data[:2] < other.data[:2] + return tuple(sorted(self.data[2].items())) < tuple( + sorted(other.data[2].items())) + return self.data < other.data + return NotImplemented + + def __le__(self, other): return self == other or self < other + + def __gt__(self, other): return not (self <= other) + + def __ge__(self, other): return not (self < other) + + def __repr__(self): + return f'{type(self).__name__}({self.op}, {self.data!r})' + + def __str__(self): + return self.tostring() + + def tostring(self, parent_precedence=Precedence.NONE, + language=Language.Fortran): + """Return a string representation of Expr. + """ + if self.op in (Op.INTEGER, Op.REAL): + precedence = (Precedence.SUM if self.data[0] < 0 + else Precedence.ATOM) + r = str(self.data[0]) + (f'_{self.data[1]}' + if self.data[1] != 4 else '') + elif self.op is Op.COMPLEX: + r = ', '.join(item.tostring(Precedence.TUPLE, language=language) + for item in self.data) + r = '(' + r + ')' + precedence = Precedence.ATOM + elif self.op is Op.SYMBOL: + precedence = Precedence.ATOM + r = str(self.data) + elif self.op is Op.STRING: + r = self.data[0] + if self.data[1] != 1: + r = self.data[1] + '_' + r + precedence = Precedence.ATOM + elif self.op is Op.ARRAY: + r = ', '.join(item.tostring(Precedence.TUPLE, language=language) + for item in self.data) + r = '[' + r + ']' + precedence = Precedence.ATOM + elif self.op is Op.TERMS: + terms = [] + for term, coeff in sorted(self.data.items()): + if coeff < 0: + op = ' - ' + coeff = -coeff + else: + op = ' + ' + if coeff == 1: + term = term.tostring(Precedence.SUM, language=language) + elif term == as_number(1): + term = str(coeff) + else: + term = f'{coeff} * ' + term.tostring( + Precedence.PRODUCT, language=language) + if terms: + terms.append(op) + elif op == ' - ': + terms.append('-') + terms.append(term) + r = ''.join(terms) or '0' + precedence = Precedence.SUM if terms else Precedence.ATOM + elif self.op is Op.FACTORS: + factors = [] + tail = [] + for base, exp in sorted(self.data.items()): + op = ' * ' + if exp == 1: + factor = base.tostring(Precedence.PRODUCT, + language=language) + elif language is Language.C: + if exp in range(2, 10): + factor = base.tostring(Precedence.PRODUCT, + language=language) + factor = ' * '.join([factor] * exp) + elif exp in range(-10, 0): + factor = base.tostring(Precedence.PRODUCT, + language=language) + tail += [factor] * -exp + continue + else: + factor = base.tostring(Precedence.TUPLE, + language=language) + factor = f'pow({factor}, {exp})' + else: + factor = base.tostring(Precedence.POWER, + language=language) + f' ** {exp}' + if factors: + factors.append(op) + factors.append(factor) + if tail: + if not factors: + factors += ['1'] + factors += ['/', '(', ' * '.join(tail), ')'] + r = ''.join(factors) or '1' + precedence = Precedence.PRODUCT if factors else Precedence.ATOM + elif self.op is Op.APPLY: + name, args, kwargs = self.data + if name is ArithOp.DIV and language is Language.C: + numer, denom = [arg.tostring(Precedence.PRODUCT, + language=language) + for arg in args] + r = f'{numer} / {denom}' + precedence = Precedence.PRODUCT + else: + args = [arg.tostring(Precedence.TUPLE, language=language) + for arg in args] + args += [k + '=' + v.tostring(Precedence.NONE) + for k, v in kwargs.items()] + r = f'{name}({", ".join(args)})' + precedence = Precedence.ATOM + elif self.op is Op.INDEXING: + name = self.data[0] + args = [arg.tostring(Precedence.TUPLE, language=language) + for arg in self.data[1:]] + r = f'{name}[{", ".join(args)}]' + precedence = Precedence.ATOM + elif self.op is Op.CONCAT: + args = [arg.tostring(Precedence.PRODUCT, language=language) + for arg in self.data] + r = " // ".join(args) + precedence = Precedence.PRODUCT + elif self.op is Op.TERNARY: + cond, expr1, expr2 = [a.tostring(Precedence.TUPLE, + language=language) + for a in self.data] + if language is Language.C: + r = f'({cond}?{expr1}:{expr2})' + elif language is Language.Python: + r = f'({expr1} if {cond} else {expr2})' + elif language is Language.Fortran: + r = f'merge({expr1}, {expr2}, {cond})' + else: + raise NotImplementedError( + f'tostring for {self.op} and {language}') + precedence = Precedence.ATOM + elif self.op is Op.REF: + r = '&' + self.data.tostring(Precedence.UNARY, language=language) + precedence = Precedence.UNARY + elif self.op is Op.DEREF: + r = '*' + self.data.tostring(Precedence.UNARY, language=language) + precedence = Precedence.UNARY + elif self.op is Op.RELATIONAL: + rop, left, right = self.data + precedence = (Precedence.EQ if rop in (RelOp.EQ, RelOp.NE) + else Precedence.LT) + left = left.tostring(precedence, language=language) + right = right.tostring(precedence, language=language) + rop = rop.tostring(language=language) + r = f'{left} {rop} {right}' + else: + raise NotImplementedError(f'tostring for op {self.op}') + if parent_precedence.value < precedence.value: + # If parent precedence is higher than operand precedence, + # operand will be enclosed in parenthesis. + return '(' + r + ')' + return r + + def __pos__(self): + return self + + def __neg__(self): + return self * -1 + + def __add__(self, other): + other = as_expr(other) + if isinstance(other, Expr): + if self.op is other.op: + if self.op in (Op.INTEGER, Op.REAL): + return as_number( + self.data[0] + other.data[0], + max(self.data[1], other.data[1])) + if self.op is Op.COMPLEX: + r1, i1 = self.data + r2, i2 = other.data + return as_complex(r1 + r2, i1 + i2) + if self.op is Op.TERMS: + r = Expr(self.op, dict(self.data)) + for k, v in other.data.items(): + _pairs_add(r.data, k, v) + return normalize(r) + if self.op is Op.COMPLEX and other.op in (Op.INTEGER, Op.REAL): + return self + as_complex(other) + elif self.op in (Op.INTEGER, Op.REAL) and other.op is Op.COMPLEX: + return as_complex(self) + other + elif self.op is Op.REAL and other.op is Op.INTEGER: + return self + as_real(other, kind=self.data[1]) + elif self.op is Op.INTEGER and other.op is Op.REAL: + return as_real(self, kind=other.data[1]) + other + return as_terms(self) + as_terms(other) + return NotImplemented + + def __radd__(self, other): + if isinstance(other, number_types): + return as_number(other) + self + return NotImplemented + + def __sub__(self, other): + return self + (-other) + + def __rsub__(self, other): + if isinstance(other, number_types): + return as_number(other) - self + return NotImplemented + + def __mul__(self, other): + other = as_expr(other) + if isinstance(other, Expr): + if self.op is other.op: + if self.op in (Op.INTEGER, Op.REAL): + return as_number(self.data[0] * other.data[0], + max(self.data[1], other.data[1])) + elif self.op is Op.COMPLEX: + r1, i1 = self.data + r2, i2 = other.data + return as_complex(r1 * r2 - i1 * i2, r1 * i2 + r2 * i1) + + if self.op is Op.FACTORS: + r = Expr(self.op, dict(self.data)) + for k, v in other.data.items(): + _pairs_add(r.data, k, v) + return normalize(r) + elif self.op is Op.TERMS: + r = Expr(self.op, {}) + for t1, c1 in self.data.items(): + for t2, c2 in other.data.items(): + _pairs_add(r.data, t1 * t2, c1 * c2) + return normalize(r) + + if self.op is Op.COMPLEX and other.op in (Op.INTEGER, Op.REAL): + return self * as_complex(other) + elif other.op is Op.COMPLEX and self.op in (Op.INTEGER, Op.REAL): + return as_complex(self) * other + elif self.op is Op.REAL and other.op is Op.INTEGER: + return self * as_real(other, kind=self.data[1]) + elif self.op is Op.INTEGER and other.op is Op.REAL: + return as_real(self, kind=other.data[1]) * other + + if self.op is Op.TERMS: + return self * as_terms(other) + elif other.op is Op.TERMS: + return as_terms(self) * other + + return as_factors(self) * as_factors(other) + return NotImplemented + + def __rmul__(self, other): + if isinstance(other, number_types): + return as_number(other) * self + return NotImplemented + + def __pow__(self, other): + other = as_expr(other) + if isinstance(other, Expr): + if other.op is Op.INTEGER: + exponent = other.data[0] + # TODO: other kind not used + if exponent == 0: + return as_number(1) + if exponent == 1: + return self + if exponent > 0: + if self.op is Op.FACTORS: + r = Expr(self.op, {}) + for k, v in self.data.items(): + r.data[k] = v * exponent + return normalize(r) + return self * (self ** (exponent - 1)) + elif exponent != -1: + return (self ** (-exponent)) ** -1 + return Expr(Op.FACTORS, {self: exponent}) + return as_apply(ArithOp.POW, self, other) + return NotImplemented + + def __truediv__(self, other): + other = as_expr(other) + if isinstance(other, Expr): + # Fortran / is different from Python /: + # - `/` is a truncate operation for integer operands + return normalize(as_apply(ArithOp.DIV, self, other)) + return NotImplemented + + def __rtruediv__(self, other): + other = as_expr(other) + if isinstance(other, Expr): + return other / self + return NotImplemented + + def __floordiv__(self, other): + other = as_expr(other) + if isinstance(other, Expr): + # Fortran // is different from Python //: + # - `//` is a concatenate operation for string operands + return normalize(Expr(Op.CONCAT, (self, other))) + return NotImplemented + + def __rfloordiv__(self, other): + other = as_expr(other) + if isinstance(other, Expr): + return other // self + return NotImplemented + + def __call__(self, *args, **kwargs): + # In Fortran, parenthesis () are use for both function call as + # well as indexing operations. + # + # TODO: implement a method for deciding when __call__ should + # return an INDEXING expression. + return as_apply(self, *map(as_expr, args), + **{k: as_expr(v) for k, v in kwargs.items()}) + + def __getitem__(self, index): + # Provided to support C indexing operations that .pyf files + # may contain. + index = as_expr(index) + if not isinstance(index, tuple): + index = index, + if len(index) > 1: + ewarn(f'C-index should be a single expression but got `{index}`') + return Expr(Op.INDEXING, (self,) + index) + + def substitute(self, symbols_map): + """Recursively substitute symbols with values in symbols map. + + Symbols map is a dictionary of symbol-expression pairs. + """ + if self.op is Op.SYMBOL: + value = symbols_map.get(self) + if value is None: + return self + m = re.match(r'\A(@__f2py_PARENTHESIS_(\w+)_\d+@)\Z', self.data) + if m: + # complement to fromstring method + items, paren = m.groups() + if paren in ['ROUNDDIV', 'SQUARE']: + return as_array(value) + assert paren == 'ROUND', (paren, value) + return value + if self.op in (Op.INTEGER, Op.REAL, Op.STRING): + return self + if self.op in (Op.ARRAY, Op.COMPLEX): + return Expr(self.op, tuple(item.substitute(symbols_map) + for item in self.data)) + if self.op is Op.CONCAT: + return normalize(Expr(self.op, tuple(item.substitute(symbols_map) + for item in self.data))) + if self.op is Op.TERMS: + r = None + for term, coeff in self.data.items(): + if r is None: + r = term.substitute(symbols_map) * coeff + else: + r += term.substitute(symbols_map) * coeff + if r is None: + ewarn('substitute: empty TERMS expression interpreted as' + ' int-literal 0') + return as_number(0) + return r + if self.op is Op.FACTORS: + r = None + for base, exponent in self.data.items(): + if r is None: + r = base.substitute(symbols_map) ** exponent + else: + r *= base.substitute(symbols_map) ** exponent + if r is None: + ewarn('substitute: empty FACTORS expression interpreted' + ' as int-literal 1') + return as_number(1) + return r + if self.op is Op.APPLY: + target, args, kwargs = self.data + if isinstance(target, Expr): + target = target.substitute(symbols_map) + args = tuple(a.substitute(symbols_map) for a in args) + kwargs = {k: v.substitute(symbols_map) + for k, v in kwargs.items()} + return normalize(Expr(self.op, (target, args, kwargs))) + if self.op is Op.INDEXING: + func = self.data[0] + if isinstance(func, Expr): + func = func.substitute(symbols_map) + args = tuple(a.substitute(symbols_map) for a in self.data[1:]) + return normalize(Expr(self.op, (func,) + args)) + if self.op is Op.TERNARY: + operands = tuple(a.substitute(symbols_map) for a in self.data) + return normalize(Expr(self.op, operands)) + if self.op in (Op.REF, Op.DEREF): + return normalize(Expr(self.op, self.data.substitute(symbols_map))) + if self.op is Op.RELATIONAL: + rop, left, right = self.data + left = left.substitute(symbols_map) + right = right.substitute(symbols_map) + return normalize(Expr(self.op, (rop, left, right))) + raise NotImplementedError(f'substitute method for {self.op}: {self!r}') + + def traverse(self, visit, *args, **kwargs): + """Traverse expression tree with visit function. + + The visit function is applied to an expression with given args + and kwargs. + + Traverse call returns an expression returned by visit when not + None, otherwise return a new normalized expression with + traverse-visit sub-expressions. + """ + result = visit(self, *args, **kwargs) + if result is not None: + return result + + if self.op in (Op.INTEGER, Op.REAL, Op.STRING, Op.SYMBOL): + return self + elif self.op in (Op.COMPLEX, Op.ARRAY, Op.CONCAT, Op.TERNARY): + return normalize(Expr(self.op, tuple( + item.traverse(visit, *args, **kwargs) + for item in self.data))) + elif self.op in (Op.TERMS, Op.FACTORS): + data = {} + for k, v in self.data.items(): + k = k.traverse(visit, *args, **kwargs) + v = (v.traverse(visit, *args, **kwargs) + if isinstance(v, Expr) else v) + if k in data: + v = data[k] + v + data[k] = v + return normalize(Expr(self.op, data)) + elif self.op is Op.APPLY: + obj = self.data[0] + func = (obj.traverse(visit, *args, **kwargs) + if isinstance(obj, Expr) else obj) + operands = tuple(operand.traverse(visit, *args, **kwargs) + for operand in self.data[1]) + kwoperands = {k: v.traverse(visit, *args, **kwargs) + for k, v in self.data[2].items()} + return normalize(Expr(self.op, (func, operands, kwoperands))) + elif self.op is Op.INDEXING: + obj = self.data[0] + obj = (obj.traverse(visit, *args, **kwargs) + if isinstance(obj, Expr) else obj) + indices = tuple(index.traverse(visit, *args, **kwargs) + for index in self.data[1:]) + return normalize(Expr(self.op, (obj,) + indices)) + elif self.op in (Op.REF, Op.DEREF): + return normalize(Expr(self.op, + self.data.traverse(visit, *args, **kwargs))) + elif self.op is Op.RELATIONAL: + rop, left, right = self.data + left = left.traverse(visit, *args, **kwargs) + right = right.traverse(visit, *args, **kwargs) + return normalize(Expr(self.op, (rop, left, right))) + raise NotImplementedError(f'traverse method for {self.op}') + + def contains(self, other): + """Check if self contains other. + """ + found = [] + + def visit(expr, found=found): + if found: + return expr + elif expr == other: + found.append(1) + return expr + + self.traverse(visit) + + return len(found) != 0 + + def symbols(self): + """Return a set of symbols contained in self. + """ + found = set() + + def visit(expr, found=found): + if expr.op is Op.SYMBOL: + found.add(expr) + + self.traverse(visit) + + return found + + def polynomial_atoms(self): + """Return a set of expressions used as atoms in polynomial self. + """ + found = set() + + def visit(expr, found=found): + if expr.op is Op.FACTORS: + for b in expr.data: + b.traverse(visit) + return expr + if expr.op in (Op.TERMS, Op.COMPLEX): + return + if expr.op is Op.APPLY and isinstance(expr.data[0], ArithOp): + if expr.data[0] is ArithOp.POW: + expr.data[1][0].traverse(visit) + return expr + return + if expr.op in (Op.INTEGER, Op.REAL): + return expr + + found.add(expr) + + if expr.op in (Op.INDEXING, Op.APPLY): + return expr + + self.traverse(visit) + + return found + + def linear_solve(self, symbol): + """Return a, b such that a * symbol + b == self. + + If self is not linear with respect to symbol, raise RuntimeError. + """ + b = self.substitute({symbol: as_number(0)}) + ax = self - b + a = ax.substitute({symbol: as_number(1)}) + + zero, _ = as_numer_denom(a * symbol - ax) + + if zero != as_number(0): + raise RuntimeError(f'not a {symbol}-linear equation:' + f' {a} * {symbol} + {b} == {self}') + return a, b + + +def normalize(obj): + """Normalize Expr and apply basic evaluation methods. + """ + if not isinstance(obj, Expr): + return obj + + if obj.op is Op.TERMS: + d = {} + for t, c in obj.data.items(): + if c == 0: + continue + if t.op is Op.COMPLEX and c != 1: + t = t * c + c = 1 + if t.op is Op.TERMS: + for t1, c1 in t.data.items(): + _pairs_add(d, t1, c1 * c) + else: + _pairs_add(d, t, c) + if len(d) == 0: + # TODO: determine correct kind + return as_number(0) + elif len(d) == 1: + (t, c), = d.items() + if c == 1: + return t + return Expr(Op.TERMS, d) + + if obj.op is Op.FACTORS: + coeff = 1 + d = {} + for b, e in obj.data.items(): + if e == 0: + continue + if b.op is Op.TERMS and isinstance(e, integer_types) and e > 1: + # expand integer powers of sums + b = b * (b ** (e - 1)) + e = 1 + + if b.op in (Op.INTEGER, Op.REAL): + if e == 1: + coeff *= b.data[0] + elif e > 0: + coeff *= b.data[0] ** e + else: + _pairs_add(d, b, e) + elif b.op is Op.FACTORS: + if e > 0 and isinstance(e, integer_types): + for b1, e1 in b.data.items(): + _pairs_add(d, b1, e1 * e) + else: + _pairs_add(d, b, e) + else: + _pairs_add(d, b, e) + if len(d) == 0 or coeff == 0: + # TODO: determine correct kind + assert isinstance(coeff, number_types) + return as_number(coeff) + elif len(d) == 1: + (b, e), = d.items() + if e == 1: + t = b + else: + t = Expr(Op.FACTORS, d) + if coeff == 1: + return t + return Expr(Op.TERMS, {t: coeff}) + elif coeff == 1: + return Expr(Op.FACTORS, d) + else: + return Expr(Op.TERMS, {Expr(Op.FACTORS, d): coeff}) + + if obj.op is Op.APPLY and obj.data[0] is ArithOp.DIV: + dividend, divisor = obj.data[1] + t1, c1 = as_term_coeff(dividend) + t2, c2 = as_term_coeff(divisor) + if isinstance(c1, integer_types) and isinstance(c2, integer_types): + g = gcd(c1, c2) + c1, c2 = c1 // g, c2 // g + else: + c1, c2 = c1 / c2, 1 + + if t1.op is Op.APPLY and t1.data[0] is ArithOp.DIV: + numer = t1.data[1][0] * c1 + denom = t1.data[1][1] * t2 * c2 + return as_apply(ArithOp.DIV, numer, denom) + + if t2.op is Op.APPLY and t2.data[0] is ArithOp.DIV: + numer = t2.data[1][1] * t1 * c1 + denom = t2.data[1][0] * c2 + return as_apply(ArithOp.DIV, numer, denom) + + d = dict(as_factors(t1).data) + for b, e in as_factors(t2).data.items(): + _pairs_add(d, b, -e) + numer, denom = {}, {} + for b, e in d.items(): + if e > 0: + numer[b] = e + else: + denom[b] = -e + numer = normalize(Expr(Op.FACTORS, numer)) * c1 + denom = normalize(Expr(Op.FACTORS, denom)) * c2 + + if denom.op in (Op.INTEGER, Op.REAL) and denom.data[0] == 1: + # TODO: denom kind not used + return numer + return as_apply(ArithOp.DIV, numer, denom) + + if obj.op is Op.CONCAT: + lst = [obj.data[0]] + for s in obj.data[1:]: + last = lst[-1] + if ( + last.op is Op.STRING + and s.op is Op.STRING + and last.data[0][0] in '"\'' + and s.data[0][0] == last.data[0][-1] + ): + new_last = as_string(last.data[0][:-1] + s.data[0][1:], + max(last.data[1], s.data[1])) + lst[-1] = new_last + else: + lst.append(s) + if len(lst) == 1: + return lst[0] + return Expr(Op.CONCAT, tuple(lst)) + + if obj.op is Op.TERNARY: + cond, expr1, expr2 = map(normalize, obj.data) + if cond.op is Op.INTEGER: + return expr1 if cond.data[0] else expr2 + return Expr(Op.TERNARY, (cond, expr1, expr2)) + + return obj + + +def as_expr(obj): + """Convert non-Expr objects to Expr objects. + """ + if isinstance(obj, complex): + return as_complex(obj.real, obj.imag) + if isinstance(obj, number_types): + return as_number(obj) + if isinstance(obj, str): + # STRING expression holds string with boundary quotes, hence + # applying repr: + return as_string(repr(obj)) + if isinstance(obj, tuple): + return tuple(map(as_expr, obj)) + return obj + + +def as_symbol(obj): + """Return object as SYMBOL expression (variable or unparsed expression). + """ + return Expr(Op.SYMBOL, obj) + + +def as_number(obj, kind=4): + """Return object as INTEGER or REAL constant. + """ + if isinstance(obj, int): + return Expr(Op.INTEGER, (obj, kind)) + if isinstance(obj, float): + return Expr(Op.REAL, (obj, kind)) + if isinstance(obj, Expr): + if obj.op in (Op.INTEGER, Op.REAL): + return obj + raise OpError(f'cannot convert {obj} to INTEGER or REAL constant') + + +def as_integer(obj, kind=4): + """Return object as INTEGER constant. + """ + if isinstance(obj, int): + return Expr(Op.INTEGER, (obj, kind)) + if isinstance(obj, Expr): + if obj.op is Op.INTEGER: + return obj + raise OpError(f'cannot convert {obj} to INTEGER constant') + + +def as_real(obj, kind=4): + """Return object as REAL constant. + """ + if isinstance(obj, int): + return Expr(Op.REAL, (float(obj), kind)) + if isinstance(obj, float): + return Expr(Op.REAL, (obj, kind)) + if isinstance(obj, Expr): + if obj.op is Op.REAL: + return obj + elif obj.op is Op.INTEGER: + return Expr(Op.REAL, (float(obj.data[0]), kind)) + raise OpError(f'cannot convert {obj} to REAL constant') + + +def as_string(obj, kind=1): + """Return object as STRING expression (string literal constant). + """ + return Expr(Op.STRING, (obj, kind)) + + +def as_array(obj): + """Return object as ARRAY expression (array constant). + """ + if isinstance(obj, Expr): + obj = obj, + return Expr(Op.ARRAY, obj) + + +def as_complex(real, imag=0): + """Return object as COMPLEX expression (complex literal constant). + """ + return Expr(Op.COMPLEX, (as_expr(real), as_expr(imag))) + + +def as_apply(func, *args, **kwargs): + """Return object as APPLY expression (function call, constructor, etc.) + """ + return Expr(Op.APPLY, + (func, tuple(map(as_expr, args)), + {k: as_expr(v) for k, v in kwargs.items()})) + + +def as_ternary(cond, expr1, expr2): + """Return object as TERNARY expression (cond?expr1:expr2). + """ + return Expr(Op.TERNARY, (cond, expr1, expr2)) + + +def as_ref(expr): + """Return object as referencing expression. + """ + return Expr(Op.REF, expr) + + +def as_deref(expr): + """Return object as dereferencing expression. + """ + return Expr(Op.DEREF, expr) + + +def as_eq(left, right): + return Expr(Op.RELATIONAL, (RelOp.EQ, left, right)) + + +def as_ne(left, right): + return Expr(Op.RELATIONAL, (RelOp.NE, left, right)) + + +def as_lt(left, right): + return Expr(Op.RELATIONAL, (RelOp.LT, left, right)) + + +def as_le(left, right): + return Expr(Op.RELATIONAL, (RelOp.LE, left, right)) + + +def as_gt(left, right): + return Expr(Op.RELATIONAL, (RelOp.GT, left, right)) + + +def as_ge(left, right): + return Expr(Op.RELATIONAL, (RelOp.GE, left, right)) + + +def as_terms(obj): + """Return expression as TERMS expression. + """ + if isinstance(obj, Expr): + obj = normalize(obj) + if obj.op is Op.TERMS: + return obj + if obj.op is Op.INTEGER: + return Expr(Op.TERMS, {as_integer(1, obj.data[1]): obj.data[0]}) + if obj.op is Op.REAL: + return Expr(Op.TERMS, {as_real(1, obj.data[1]): obj.data[0]}) + return Expr(Op.TERMS, {obj: 1}) + raise OpError(f'cannot convert {type(obj)} to terms Expr') + + +def as_factors(obj): + """Return expression as FACTORS expression. + """ + if isinstance(obj, Expr): + obj = normalize(obj) + if obj.op is Op.FACTORS: + return obj + if obj.op is Op.TERMS: + if len(obj.data) == 1: + (term, coeff), = obj.data.items() + if coeff == 1: + return Expr(Op.FACTORS, {term: 1}) + return Expr(Op.FACTORS, {term: 1, Expr.number(coeff): 1}) + if (obj.op is Op.APPLY + and obj.data[0] is ArithOp.DIV + and not obj.data[2]): + return Expr(Op.FACTORS, {obj.data[1][0]: 1, obj.data[1][1]: -1}) + return Expr(Op.FACTORS, {obj: 1}) + raise OpError(f'cannot convert {type(obj)} to terms Expr') + + +def as_term_coeff(obj): + """Return expression as term-coefficient pair. + """ + if isinstance(obj, Expr): + obj = normalize(obj) + if obj.op is Op.INTEGER: + return as_integer(1, obj.data[1]), obj.data[0] + if obj.op is Op.REAL: + return as_real(1, obj.data[1]), obj.data[0] + if obj.op is Op.TERMS: + if len(obj.data) == 1: + (term, coeff), = obj.data.items() + return term, coeff + # TODO: find common divisor of coefficients + if obj.op is Op.APPLY and obj.data[0] is ArithOp.DIV: + t, c = as_term_coeff(obj.data[1][0]) + return as_apply(ArithOp.DIV, t, obj.data[1][1]), c + return obj, 1 + raise OpError(f'cannot convert {type(obj)} to term and coeff') + + +def as_numer_denom(obj): + """Return expression as numer-denom pair. + """ + if isinstance(obj, Expr): + obj = normalize(obj) + if obj.op in (Op.INTEGER, Op.REAL, Op.COMPLEX, Op.SYMBOL, + Op.INDEXING, Op.TERNARY): + return obj, as_number(1) + elif obj.op is Op.APPLY: + if obj.data[0] is ArithOp.DIV and not obj.data[2]: + numers, denoms = map(as_numer_denom, obj.data[1]) + return numers[0] * denoms[1], numers[1] * denoms[0] + return obj, as_number(1) + elif obj.op is Op.TERMS: + numers, denoms = [], [] + for term, coeff in obj.data.items(): + n, d = as_numer_denom(term) + n = n * coeff + numers.append(n) + denoms.append(d) + numer, denom = as_number(0), as_number(1) + for i in range(len(numers)): + n = numers[i] + for j in range(len(numers)): + if i != j: + n *= denoms[j] + numer += n + denom *= denoms[i] + if denom.op in (Op.INTEGER, Op.REAL) and denom.data[0] < 0: + numer, denom = -numer, -denom + return numer, denom + elif obj.op is Op.FACTORS: + numer, denom = as_number(1), as_number(1) + for b, e in obj.data.items(): + bnumer, bdenom = as_numer_denom(b) + if e > 0: + numer *= bnumer ** e + denom *= bdenom ** e + elif e < 0: + numer *= bdenom ** (-e) + denom *= bnumer ** (-e) + return numer, denom + raise OpError(f'cannot convert {type(obj)} to numer and denom') + + +def _counter(): + # Used internally to generate unique dummy symbols + counter = 0 + while True: + counter += 1 + yield counter + + +COUNTER = _counter() + + +def eliminate_quotes(s): + """Replace quoted substrings of input string. + + Return a new string and a mapping of replacements. + """ + d = {} + + def repl(m): + kind, value = m.groups()[:2] + if kind: + # remove trailing underscore + kind = kind[:-1] + p = {"'": "SINGLE", '"': "DOUBLE"}[value[0]] + k = f'{kind}@__f2py_QUOTES_{p}_{COUNTER.__next__()}@' + d[k] = value + return k + + new_s = re.sub(r'({kind}_|)({single_quoted}|{double_quoted})'.format( + kind=r'\w[\w\d_]*', + single_quoted=r"('([^'\\]|(\\.))*')", + double_quoted=r'("([^"\\]|(\\.))*")'), + repl, s) + + assert '"' not in new_s + assert "'" not in new_s + + return new_s, d + + +def insert_quotes(s, d): + """Inverse of eliminate_quotes. + """ + for k, v in d.items(): + kind = k[:k.find('@')] + if kind: + kind += '_' + s = s.replace(k, kind + v) + return s + + +def replace_parenthesis(s): + """Replace substrings of input that are enclosed in parenthesis. + + Return a new string and a mapping of replacements. + """ + # Find a parenthesis pair that appears first. + + # Fortran deliminator are `(`, `)`, `[`, `]`, `(/', '/)`, `/`. + # We don't handle `/` deliminator because it is not a part of an + # expression. + left, right = None, None + mn_i = len(s) + for left_, right_ in (('(/', '/)'), + '()', + '{}', # to support C literal structs + '[]'): + i = s.find(left_) + if i == -1: + continue + if i < mn_i: + mn_i = i + left, right = left_, right_ + + if left is None: + return s, {} + + i = mn_i + j = s.find(right, i) + if j == -1: + raise ValueError(f'Mismatch of {left + right} parenthesis in {s!r}') + + while s.count(left, i + 1, j) != s.count(right, i + 1, j): + j = s.find(right, j + 1) + if j == -1: + raise ValueError(f'Mismatch of {left + right} parenthesis in {s!r}') + + p = {'(': 'ROUND', '[': 'SQUARE', '{': 'CURLY', '(/': 'ROUNDDIV'}[left] + + k = f'@__f2py_PARENTHESIS_{p}_{COUNTER.__next__()}@' + v = s[i + len(left):j] + r, d = replace_parenthesis(s[j + len(right):]) + d[k] = v + return s[:i] + k + r, d + + +def _get_parenthesis_kind(s): + assert s.startswith('@__f2py_PARENTHESIS_'), s + return s.split('_')[4] + + +def unreplace_parenthesis(s, d): + """Inverse of replace_parenthesis. + """ + for k, v in d.items(): + p = _get_parenthesis_kind(k) + left = {'ROUND': '(', 'SQUARE': '[', 'CURLY': '{', 'ROUNDDIV': '(/'}[p] + right = {'ROUND': ')', 'SQUARE': ']', 'CURLY': '}', 'ROUNDDIV': '/)'}[p] + s = s.replace(k, left + v + right) + return s + + +def fromstring(s, language=Language.C): + """Create an expression from a string. + + This is a "lazy" parser, that is, only arithmetic operations are + resolved, non-arithmetic operations are treated as symbols. + """ + r = _FromStringWorker(language=language).parse(s) + if isinstance(r, Expr): + return r + raise ValueError(f'failed to parse `{s}` to Expr instance: got `{r}`') + + +class _Pair: + # Internal class to represent a pair of expressions + + def __init__(self, left, right): + self.left = left + self.right = right + + def substitute(self, symbols_map): + left, right = self.left, self.right + if isinstance(left, Expr): + left = left.substitute(symbols_map) + if isinstance(right, Expr): + right = right.substitute(symbols_map) + return _Pair(left, right) + + def __repr__(self): + return f'{type(self).__name__}({self.left}, {self.right})' + + +class _FromStringWorker: + + def __init__(self, language=Language.C): + self.original = None + self.quotes_map = None + self.language = language + + def finalize_string(self, s): + return insert_quotes(s, self.quotes_map) + + def parse(self, inp): + self.original = inp + unquoted, self.quotes_map = eliminate_quotes(inp) + return self.process(unquoted) + + def process(self, s, context='expr'): + """Parse string within the given context. + + The context may define the result in case of ambiguous + expressions. For instance, consider expressions `f(x, y)` and + `(x, y) + (a, b)` where `f` is a function and pair `(x, y)` + denotes complex number. Specifying context as "args" or + "expr", the subexpression `(x, y)` will be parse to an + argument list or to a complex number, respectively. + """ + if isinstance(s, (list, tuple)): + return type(s)(self.process(s_, context) for s_ in s) + + assert isinstance(s, str), (type(s), s) + + # replace subexpressions in parenthesis with f2py @-names + r, raw_symbols_map = replace_parenthesis(s) + r = r.strip() + + def restore(r): + # restores subexpressions marked with f2py @-names + if isinstance(r, (list, tuple)): + return type(r)(map(restore, r)) + return unreplace_parenthesis(r, raw_symbols_map) + + # comma-separated tuple + if ',' in r: + operands = restore(r.split(',')) + if context == 'args': + return tuple(self.process(operands)) + if context == 'expr': + if len(operands) == 2: + # complex number literal + return as_complex(*self.process(operands)) + raise NotImplementedError( + f'parsing comma-separated list (context={context}): {r}') + + # ternary operation + m = re.match(r'\A([^?]+)[?]([^:]+)[:](.+)\Z', r) + if m: + assert context == 'expr', context + oper, expr1, expr2 = restore(m.groups()) + oper = self.process(oper) + expr1 = self.process(expr1) + expr2 = self.process(expr2) + return as_ternary(oper, expr1, expr2) + + # relational expression + if self.language is Language.Fortran: + m = re.match( + r'\A(.+)\s*[.](eq|ne|lt|le|gt|ge)[.]\s*(.+)\Z', r, re.I) + else: + m = re.match( + r'\A(.+)\s*([=][=]|[!][=]|[<][=]|[<]|[>][=]|[>])\s*(.+)\Z', r) + if m: + left, rop, right = m.groups() + if self.language is Language.Fortran: + rop = '.' + rop + '.' + left, right = self.process(restore((left, right))) + rop = RelOp.fromstring(rop, language=self.language) + return Expr(Op.RELATIONAL, (rop, left, right)) + + # keyword argument + m = re.match(r'\A(\w[\w\d_]*)\s*[=](.*)\Z', r) + if m: + keyname, value = m.groups() + value = restore(value) + return _Pair(keyname, self.process(value)) + + # addition/subtraction operations + operands = re.split(r'((? 1: + result = self.process(restore(operands[0] or '0')) + for op, operand in zip(operands[1::2], operands[2::2]): + operand = self.process(restore(operand)) + op = op.strip() + if op == '+': + result += operand + else: + assert op == '-' + result -= operand + return result + + # string concatenate operation + if self.language is Language.Fortran and '//' in r: + operands = restore(r.split('//')) + return Expr(Op.CONCAT, + tuple(self.process(operands))) + + # multiplication/division operations + operands = re.split(r'(?<=[@\w\d_])\s*([*]|/)', + (r if self.language is Language.C + else r.replace('**', '@__f2py_DOUBLE_STAR@'))) + if len(operands) > 1: + operands = restore(operands) + if self.language is not Language.C: + operands = [operand.replace('@__f2py_DOUBLE_STAR@', '**') + for operand in operands] + # Expression is an arithmetic product + result = self.process(operands[0]) + for op, operand in zip(operands[1::2], operands[2::2]): + operand = self.process(operand) + op = op.strip() + if op == '*': + result *= operand + else: + assert op == '/' + result /= operand + return result + + # referencing/dereferencing + if r.startswith(('*', '&')): + op = {'*': Op.DEREF, '&': Op.REF}[r[0]] + operand = self.process(restore(r[1:])) + return Expr(op, operand) + + # exponentiation operations + if self.language is not Language.C and '**' in r: + operands = list(reversed(restore(r.split('**')))) + result = self.process(operands[0]) + for operand in operands[1:]: + operand = self.process(operand) + result = operand ** result + return result + + # int-literal-constant + m = re.match(r'\A({digit_string})({kind}|)\Z'.format( + digit_string=r'\d+', + kind=r'_(\d+|\w[\w\d_]*)'), r) + if m: + value, _, kind = m.groups() + if kind and kind.isdigit(): + kind = int(kind) + return as_integer(int(value), kind or 4) + + # real-literal-constant + m = re.match(r'\A({significant}({exponent}|)|\d+{exponent})({kind}|)\Z' + .format( + significant=r'[.]\d+|\d+[.]\d*', + exponent=r'[edED][+-]?\d+', + kind=r'_(\d+|\w[\w\d_]*)'), r) + if m: + value, _, _, kind = m.groups() + if kind and kind.isdigit(): + kind = int(kind) + value = value.lower() + if 'd' in value: + return as_real(float(value.replace('d', 'e')), kind or 8) + return as_real(float(value), kind or 4) + + # string-literal-constant with kind parameter specification + if r in self.quotes_map: + kind = r[:r.find('@')] + return as_string(self.quotes_map[r], kind or 1) + + # array constructor or literal complex constant or + # parenthesized expression + if r in raw_symbols_map: + paren = _get_parenthesis_kind(r) + items = self.process(restore(raw_symbols_map[r]), + 'expr' if paren == 'ROUND' else 'args') + if paren == 'ROUND': + if isinstance(items, Expr): + return items + if paren in ['ROUNDDIV', 'SQUARE']: + # Expression is an array constructor + if isinstance(items, Expr): + items = (items,) + return as_array(items) + + # function call/indexing + m = re.match(r'\A(.+)\s*(@__f2py_PARENTHESIS_(ROUND|SQUARE)_\d+@)\Z', + r) + if m: + target, args, paren = m.groups() + target = self.process(restore(target)) + args = self.process(restore(args)[1:-1], 'args') + if not isinstance(args, tuple): + args = args, + if paren == 'ROUND': + kwargs = {a.left: a.right for a in args + if isinstance(a, _Pair)} + args = tuple(a for a in args if not isinstance(a, _Pair)) + # Warning: this could also be Fortran indexing operation.. + return as_apply(target, *args, **kwargs) + else: + # Expression is a C/Python indexing operation + # (e.g. used in .pyf files) + assert paren == 'SQUARE' + return target[args] + + # Fortran standard conforming identifier + m = re.match(r'\A\w[\w\d_]*\Z', r) + if m: + return as_symbol(r) + + # fall-back to symbol + r = self.finalize_string(restore(r)) + ewarn( + f'fromstring: treating {r!r} as symbol (original={self.original})') + return as_symbol(r) diff --git a/python/user_packages/Python313/site-packages/numpy/f2py/symbolic.pyi b/python/user_packages/Python313/site-packages/numpy/f2py/symbolic.pyi new file mode 100644 index 0000000000000000000000000000000000000000..3d4b8a70dc8526c5c119b70f50964fd5b2b25e48 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/f2py/symbolic.pyi @@ -0,0 +1,219 @@ +from collections.abc import Callable, Mapping +from enum import Enum +from typing import Any, Generic, Literal as L, ParamSpec, Self, TypeAlias, overload +from typing_extensions import TypeVar + +__all__ = ["Expr"] + +### + +_Tss = ParamSpec("_Tss") +_ExprT = TypeVar("_ExprT", bound=Expr) +_ExprT1 = TypeVar("_ExprT1", bound=Expr) +_ExprT2 = TypeVar("_ExprT2", bound=Expr) +_OpT_co = TypeVar("_OpT_co", bound=Op, default=Op, covariant=True) +_LanguageT_co = TypeVar("_LanguageT_co", bound=Language, default=Language, covariant=True) +_DataT_co = TypeVar("_DataT_co", default=Any, covariant=True) +_LeftT_co = TypeVar("_LeftT_co", default=Any, covariant=True) +_RightT_co = TypeVar("_RightT_co", default=Any, covariant=True) + +_RelCOrPy: TypeAlias = L["==", "!=", "<", "<=", ">", ">="] +_RelFortran: TypeAlias = L[".eq.", ".ne.", ".lt.", ".le.", ".gt.", ".ge."] + +_ToExpr: TypeAlias = Expr | complex | str +_ToExprN: TypeAlias = _ToExpr | tuple[_ToExprN, ...] +_NestedString: TypeAlias = str | tuple[_NestedString, ...] | list[_NestedString] + +### + +class OpError(Exception): ... +class ExprWarning(UserWarning): ... + +class Language(Enum): + Python = 0 + Fortran = 1 + C = 2 + +class Op(Enum): + INTEGER = 10 + REAL = 12 + COMPLEX = 15 + STRING = 20 + ARRAY = 30 + SYMBOL = 40 + TERNARY = 100 + APPLY = 200 + INDEXING = 210 + CONCAT = 220 + RELATIONAL = 300 + TERMS = 1_000 + FACTORS = 2_000 + REF = 3_000 + DEREF = 3_001 + +class RelOp(Enum): + EQ = 1 + NE = 2 + LT = 3 + LE = 4 + GT = 5 + GE = 6 + + @overload + @classmethod + def fromstring(cls, s: _RelCOrPy, language: L[Language.C, Language.Python] = ...) -> RelOp: ... + @overload + @classmethod + def fromstring(cls, s: _RelFortran, language: L[Language.Fortran]) -> RelOp: ... + + # + @overload + def tostring(self, /, language: L[Language.C, Language.Python] = ...) -> _RelCOrPy: ... + @overload + def tostring(self, /, language: L[Language.Fortran]) -> _RelFortran: ... + +class ArithOp(Enum): + POS = 1 + NEG = 2 + ADD = 3 + SUB = 4 + MUL = 5 + DIV = 6 + POW = 7 + +class Precedence(Enum): + ATOM = 0 + POWER = 1 + UNARY = 2 + PRODUCT = 3 + SUM = 4 + LT = 6 + EQ = 7 + LAND = 11 + LOR = 12 + TERNARY = 13 + ASSIGN = 14 + TUPLE = 15 + NONE = 100 + +class Expr(Generic[_OpT_co, _DataT_co]): + op: _OpT_co + data: _DataT_co + + @staticmethod + def parse(s: str, language: Language = ...) -> Expr: ... + + # + def __init__(self, /, op: Op, data: _DataT_co) -> None: ... + + # + def __lt__(self, other: Expr, /) -> bool: ... + def __le__(self, other: Expr, /) -> bool: ... + def __gt__(self, other: Expr, /) -> bool: ... + def __ge__(self, other: Expr, /) -> bool: ... + + # + def __pos__(self, /) -> Self: ... + def __neg__(self, /) -> Expr: ... + + # + def __add__(self, other: Expr, /) -> Expr: ... + def __radd__(self, other: Expr, /) -> Expr: ... + + # + def __sub__(self, other: Expr, /) -> Expr: ... + def __rsub__(self, other: Expr, /) -> Expr: ... + + # + def __mul__(self, other: Expr, /) -> Expr: ... + def __rmul__(self, other: Expr, /) -> Expr: ... + + # + def __pow__(self, other: Expr, /) -> Expr: ... + + # + def __truediv__(self, other: Expr, /) -> Expr: ... + def __rtruediv__(self, other: Expr, /) -> Expr: ... + + # + def __floordiv__(self, other: Expr, /) -> Expr: ... + def __rfloordiv__(self, other: Expr, /) -> Expr: ... + + # + def __call__( + self, + /, + *args: _ToExprN, + **kwargs: _ToExprN, + ) -> Expr[L[Op.APPLY], tuple[Self, tuple[Expr, ...], dict[str, Expr]]]: ... + + # + @overload + def __getitem__(self, index: _ExprT | tuple[_ExprT], /) -> Expr[L[Op.INDEXING], tuple[Self, _ExprT]]: ... + @overload + def __getitem__(self, index: _ToExpr | tuple[_ToExpr], /) -> Expr[L[Op.INDEXING], tuple[Self, Expr]]: ... + + # + def substitute(self, /, symbols_map: Mapping[Expr, Expr]) -> Expr: ... + + # + @overload + def traverse(self, /, visit: Callable[_Tss, None], *args: _Tss.args, **kwargs: _Tss.kwargs) -> Expr: ... + @overload + def traverse(self, /, visit: Callable[_Tss, _ExprT], *args: _Tss.args, **kwargs: _Tss.kwargs) -> _ExprT: ... + + # + def contains(self, /, other: Expr) -> bool: ... + + # + def symbols(self, /) -> set[Expr]: ... + def polynomial_atoms(self, /) -> set[Expr]: ... + + # + def linear_solve(self, /, symbol: Expr) -> tuple[Expr, Expr]: ... + + # + def tostring(self, /, parent_precedence: Precedence = ..., language: Language = ...) -> str: ... + +class _Pair(Generic[_LeftT_co, _RightT_co]): + left: _LeftT_co + right: _RightT_co + + def __init__(self, /, left: _LeftT_co, right: _RightT_co) -> None: ... + + # + @overload + def substitute(self: _Pair[_ExprT1, _ExprT2], /, symbols_map: Mapping[Expr, Expr]) -> _Pair[Expr, Expr]: ... + @overload + def substitute(self: _Pair[_ExprT1, object], /, symbols_map: Mapping[Expr, Expr]) -> _Pair[Expr, Any]: ... + @overload + def substitute(self: _Pair[object, _ExprT2], /, symbols_map: Mapping[Expr, Expr]) -> _Pair[Any, Expr]: ... + @overload + def substitute(self, /, symbols_map: Mapping[Expr, Expr]) -> _Pair: ... + +class _FromStringWorker(Generic[_LanguageT_co]): + language: _LanguageT_co + + original: str | None + quotes_map: dict[str, str] + + @overload + def __init__(self: _FromStringWorker[L[Language.C]], /, language: L[Language.C] = ...) -> None: ... + @overload + def __init__(self, /, language: _LanguageT_co) -> None: ... + + # + def finalize_string(self, /, s: str) -> str: ... + + # + def parse(self, /, inp: str) -> Expr | _Pair: ... + + # + @overload + def process(self, /, s: str, context: str = "expr") -> Expr | _Pair: ... + @overload + def process(self, /, s: list[str], context: str = "expr") -> list[Expr | _Pair]: ... + @overload + def process(self, /, s: tuple[str, ...], context: str = "expr") -> tuple[Expr | _Pair, ...]: ... + @overload + def process(self, /, s: _NestedString, context: str = "expr") -> Any: ... # noqa: ANN401 diff --git a/python/user_packages/Python313/site-packages/numpy/f2py/use_rules.py b/python/user_packages/Python313/site-packages/numpy/f2py/use_rules.py new file mode 100644 index 0000000000000000000000000000000000000000..e7b7e8a2ba0220752afbc01f1170b6717fbdfd93 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/f2py/use_rules.py @@ -0,0 +1,99 @@ +""" +Build 'use others module data' mechanism for f2py2e. + +Copyright 1999 -- 2011 Pearu Peterson all rights reserved. +Copyright 2011 -- present NumPy Developers. +Permission to use, modify, and distribute this software is given under the +terms of the NumPy License. + +NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. +""" +__version__ = "$Revision: 1.3 $"[10:-1] + +f2py_version = 'See `f2py -v`' + + +from .auxfuncs import applyrules, dictappend, gentitle, hasnote, outmess + +usemodule_rules = { + 'body': """ +#begintitle# +static char doc_#apiname#[] = \"\\\nVariable wrapper signature:\\n\\ +\t #name# = get_#name#()\\n\\ +Arguments:\\n\\ +#docstr#\"; +extern F_MODFUNC(#usemodulename#,#USEMODULENAME#,#realname#,#REALNAME#); +static PyObject *#apiname#(PyObject *capi_self, PyObject *capi_args) { +/*#decl#*/ +\tif (!PyArg_ParseTuple(capi_args, \"\")) goto capi_fail; +printf(\"c: %d\\n\",F_MODFUNC(#usemodulename#,#USEMODULENAME#,#realname#,#REALNAME#)); +\treturn Py_BuildValue(\"\"); +capi_fail: +\treturn NULL; +} +""", + 'method': '\t{\"get_#name#\",#apiname#,METH_VARARGS|METH_KEYWORDS,doc_#apiname#},', + 'need': ['F_MODFUNC'] +} + +################ + + +def buildusevars(m, r): + ret = {} + outmess( + f"\t\tBuilding use variable hooks for module \"{m['name']}\" (feature only for F90/F95)...\n") + varsmap = {} + revmap = {} + if 'map' in r: + for k in r['map'].keys(): + if r['map'][k] in revmap: + outmess('\t\t\tVariable "%s<=%s" is already mapped by "%s". Skipping.\n' % ( + r['map'][k], k, revmap[r['map'][k]])) + else: + revmap[r['map'][k]] = k + if r.get('only'): + for v in r['map'].keys(): + if r['map'][v] in m['vars']: + + if revmap[r['map'][v]] == v: + varsmap[v] = r['map'][v] + else: + outmess(f"\t\t\tIgnoring map \"{v}=>{r['map'][v]}\". See above.\n") + else: + outmess( + f"\t\t\tNo definition for variable \"{v}=>{r['map'][v]}\". Skipping.\n") + else: + for v in m['vars'].keys(): + varsmap[v] = revmap.get(v, v) + for v in varsmap.keys(): + ret = dictappend(ret, buildusevar(v, varsmap[v], m['vars'], m['name'])) + return ret + + +def buildusevar(name, realname, vars, usemodulename): + outmess('\t\t\tConstructing wrapper function for variable "%s=>%s"...\n' % ( + name, realname)) + ret = {} + vrd = {'name': name, + 'realname': realname, + 'REALNAME': realname.upper(), + 'usemodulename': usemodulename, + 'USEMODULENAME': usemodulename.upper(), + 'texname': name.replace('_', '\\_'), + 'begintitle': gentitle(f'{name}=>{realname}'), + 'endtitle': gentitle(f'end of {name}=>{realname}'), + 'apiname': f'#modulename#_use_{realname}_from_{usemodulename}' + } + nummap = {0: 'Ro', 1: 'Ri', 2: 'Rii', 3: 'Riii', 4: 'Riv', + 5: 'Rv', 6: 'Rvi', 7: 'Rvii', 8: 'Rviii', 9: 'Rix'} + vrd['texnamename'] = name + for i in nummap.keys(): + vrd['texnamename'] = vrd['texnamename'].replace(repr(i), nummap[i]) + if hasnote(vars[realname]): + vrd['note'] = vars[realname]['note'] + rd = dictappend({}, vrd) + + print(name, realname, vars[realname]) + ret = applyrules(usemodule_rules, rd) + return ret diff --git a/python/user_packages/Python313/site-packages/numpy/f2py/use_rules.pyi b/python/user_packages/Python313/site-packages/numpy/f2py/use_rules.pyi new file mode 100644 index 0000000000000000000000000000000000000000..b7f2002a32dec2d95f699157f35b8c45b8759df3 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/f2py/use_rules.pyi @@ -0,0 +1,9 @@ +from collections.abc import Mapping +from typing import Any, Final + +__version__: Final[str] = ... +f2py_version: Final = "See `f2py -v`" +usemodule_rules: Final[dict[str, str | list[str]]] = ... + +def buildusevars(m: Mapping[str, object], r: Mapping[str, Mapping[str, object]]) -> dict[str, Any]: ... +def buildusevar(name: str, realname: str, vars: Mapping[str, Mapping[str, object]], usemodulename: str) -> dict[str, Any]: ... diff --git a/python/user_packages/Python313/site-packages/numpy/fft/__init__.py b/python/user_packages/Python313/site-packages/numpy/fft/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a24f3a533bf3b9eb999604ee0809825ba6c7747c --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/fft/__init__.py @@ -0,0 +1,213 @@ +""" +Discrete Fourier Transform +========================== + +.. currentmodule:: numpy.fft + +The SciPy module `scipy.fft` is a more comprehensive superset +of `numpy.fft`, which includes only a basic set of routines. + +Standard FFTs +------------- + +.. autosummary:: + :toctree: generated/ + + fft Discrete Fourier transform. + ifft Inverse discrete Fourier transform. + fft2 Discrete Fourier transform in two dimensions. + ifft2 Inverse discrete Fourier transform in two dimensions. + fftn Discrete Fourier transform in N-dimensions. + ifftn Inverse discrete Fourier transform in N dimensions. + +Real FFTs +--------- + +.. autosummary:: + :toctree: generated/ + + rfft Real discrete Fourier transform. + irfft Inverse real discrete Fourier transform. + rfft2 Real discrete Fourier transform in two dimensions. + irfft2 Inverse real discrete Fourier transform in two dimensions. + rfftn Real discrete Fourier transform in N dimensions. + irfftn Inverse real discrete Fourier transform in N dimensions. + +Hermitian FFTs +-------------- + +.. autosummary:: + :toctree: generated/ + + hfft Hermitian discrete Fourier transform. + ihfft Inverse Hermitian discrete Fourier transform. + +Helper routines +--------------- + +.. autosummary:: + :toctree: generated/ + + fftfreq Discrete Fourier Transform sample frequencies. + rfftfreq DFT sample frequencies (for usage with rfft, irfft). + fftshift Shift zero-frequency component to center of spectrum. + ifftshift Inverse of fftshift. + + +Background information +---------------------- + +Fourier analysis is fundamentally a method for expressing a function as a +sum of periodic components, and for recovering the function from those +components. When both the function and its Fourier transform are +replaced with discretized counterparts, it is called the discrete Fourier +transform (DFT). The DFT has become a mainstay of numerical computing in +part because of a very fast algorithm for computing it, called the Fast +Fourier Transform (FFT), which was known to Gauss (1805) and was brought +to light in its current form by Cooley and Tukey [CT]_. Press et al. [NR]_ +provide an accessible introduction to Fourier analysis and its +applications. + +Because the discrete Fourier transform separates its input into +components that contribute at discrete frequencies, it has a great number +of applications in digital signal processing, e.g., for filtering, and in +this context the discretized input to the transform is customarily +referred to as a *signal*, which exists in the *time domain*. The output +is called a *spectrum* or *transform* and exists in the *frequency +domain*. + +Implementation details +---------------------- + +There are many ways to define the DFT, varying in the sign of the +exponent, normalization, etc. In this implementation, the DFT is defined +as + +.. math:: + A_k = \\sum_{m=0}^{n-1} a_m \\exp\\left\\{-2\\pi i{mk \\over n}\\right\\} + \\qquad k = 0,\\ldots,n-1. + +The DFT is in general defined for complex inputs and outputs, and a +single-frequency component at linear frequency :math:`f` is +represented by a complex exponential +:math:`a_m = \\exp\\{2\\pi i\\,f m\\Delta t\\}`, where :math:`\\Delta t` +is the sampling interval. + +The values in the result follow so-called "standard" order: If ``A = +fft(a, n)``, then ``A[0]`` contains the zero-frequency term (the sum of +the signal), which is always purely real for real inputs. Then ``A[1:n/2]`` +contains the positive-frequency terms, and ``A[n/2+1:]`` contains the +negative-frequency terms, in order of decreasingly negative frequency. +For an even number of input points, ``A[n/2]`` represents both positive and +negative Nyquist frequency, and is also purely real for real input. For +an odd number of input points, ``A[(n-1)/2]`` contains the largest positive +frequency, while ``A[(n+1)/2]`` contains the largest negative frequency. +The routine ``np.fft.fftfreq(n)`` returns an array giving the frequencies +of corresponding elements in the output. The routine +``np.fft.fftshift(A)`` shifts transforms and their frequencies to put the +zero-frequency components in the middle, and ``np.fft.ifftshift(A)`` undoes +that shift. + +When the input `a` is a time-domain signal and ``A = fft(a)``, ``np.abs(A)`` +is its amplitude spectrum and ``np.abs(A)**2`` is its power spectrum. +The phase spectrum is obtained by ``np.angle(A)``. + +The inverse DFT is defined as + +.. math:: + a_m = \\frac{1}{n}\\sum_{k=0}^{n-1}A_k\\exp\\left\\{2\\pi i{mk\\over n}\\right\\} + \\qquad m = 0,\\ldots,n-1. + +It differs from the forward transform by the sign of the exponential +argument and the default normalization by :math:`1/n`. + +Type Promotion +-------------- + +`numpy.fft` promotes ``float32`` and ``complex64`` arrays to ``float64`` and +``complex128`` arrays respectively. For an FFT implementation that does not +promote input arrays, see `scipy.fftpack`. + +Normalization +------------- + +The argument ``norm`` indicates which direction of the pair of direct/inverse +transforms is scaled and with what normalization factor. +The default normalization (``"backward"``) has the direct (forward) transforms +unscaled and the inverse (backward) transforms scaled by :math:`1/n`. It is +possible to obtain unitary transforms by setting the keyword argument ``norm`` +to ``"ortho"`` so that both direct and inverse transforms are scaled by +:math:`1/\\sqrt{n}`. Finally, setting the keyword argument ``norm`` to +``"forward"`` has the direct transforms scaled by :math:`1/n` and the inverse +transforms unscaled (i.e. exactly opposite to the default ``"backward"``). +`None` is an alias of the default option ``"backward"`` for backward +compatibility. + +Real and Hermitian transforms +----------------------------- + +When the input is purely real, its transform is Hermitian, i.e., the +component at frequency :math:`f_k` is the complex conjugate of the +component at frequency :math:`-f_k`, which means that for real +inputs there is no information in the negative frequency components that +is not already available from the positive frequency components. +The family of `rfft` functions is +designed to operate on real inputs, and exploits this symmetry by +computing only the positive frequency components, up to and including the +Nyquist frequency. Thus, ``n`` input points produce ``n/2+1`` complex +output points. The inverses of this family assumes the same symmetry of +its input, and for an output of ``n`` points uses ``n/2+1`` input points. + +Correspondingly, when the spectrum is purely real, the signal is +Hermitian. The `hfft` family of functions exploits this symmetry by +using ``n/2+1`` complex points in the input (time) domain for ``n`` real +points in the frequency domain. + +In higher dimensions, FFTs are used, e.g., for image analysis and +filtering. The computational efficiency of the FFT means that it can +also be a faster way to compute large convolutions, using the property +that a convolution in the time domain is equivalent to a point-by-point +multiplication in the frequency domain. + +Higher dimensions +----------------- + +In two dimensions, the DFT is defined as + +.. math:: + A_{kl} = \\sum_{m=0}^{M-1} \\sum_{n=0}^{N-1} + a_{mn}\\exp\\left\\{-2\\pi i \\left({mk\\over M}+{nl\\over N}\\right)\\right\\} + \\qquad k = 0, \\ldots, M-1;\\quad l = 0, \\ldots, N-1, + +which extends in the obvious way to higher dimensions, and the inverses +in higher dimensions also extend in the same way. + +References +---------- + +.. [CT] Cooley, James W., and John W. Tukey, 1965, "An algorithm for the + machine calculation of complex Fourier series," *Math. Comput.* + 19: 297-301. + +.. [NR] Press, W., Teukolsky, S., Vetterline, W.T., and Flannery, B.P., + 2007, *Numerical Recipes: The Art of Scientific Computing*, ch. + 12-13. Cambridge Univ. Press, Cambridge, UK. + +Examples +-------- + +For examples, see the various functions. + +""" + +from . import _helper, _pocketfft +from ._helper import * +from ._pocketfft import * + +__all__ = _pocketfft.__all__.copy() # noqa: PLE0605 +__all__ += _helper.__all__ + +from numpy._pytesttester import PytestTester + +test = PytestTester(__name__) +del PytestTester diff --git a/python/user_packages/Python313/site-packages/numpy/fft/__init__.pyi b/python/user_packages/Python313/site-packages/numpy/fft/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..bb7fa064cca5d5c9bbff322def21186cd06c3293 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/fft/__init__.pyi @@ -0,0 +1,38 @@ +from ._helper import fftfreq, fftshift, ifftshift, rfftfreq +from ._pocketfft import ( + fft, + fft2, + fftn, + hfft, + ifft, + ifft2, + ifftn, + ihfft, + irfft, + irfft2, + irfftn, + rfft, + rfft2, + rfftn, +) + +__all__ = [ + "fft", + "ifft", + "rfft", + "irfft", + "hfft", + "ihfft", + "rfftn", + "irfftn", + "rfft2", + "irfft2", + "fft2", + "ifft2", + "fftn", + "ifftn", + "fftshift", + "ifftshift", + "fftfreq", + "rfftfreq", +] diff --git a/python/user_packages/Python313/site-packages/numpy/fft/_helper.py b/python/user_packages/Python313/site-packages/numpy/fft/_helper.py new file mode 100644 index 0000000000000000000000000000000000000000..cafa85a5695a75ba297591b4a9643a0944291c02 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/fft/_helper.py @@ -0,0 +1,235 @@ +""" +Discrete Fourier Transforms - _helper.py + +""" +from numpy._core import arange, asarray, empty, integer, roll +from numpy._core.overrides import array_function_dispatch, set_module + +# Created by Pearu Peterson, September 2002 + +__all__ = ['fftshift', 'ifftshift', 'fftfreq', 'rfftfreq'] + +integer_types = (int, integer) + + +def _fftshift_dispatcher(x, axes=None): + return (x,) + + +@array_function_dispatch(_fftshift_dispatcher, module='numpy.fft') +def fftshift(x, axes=None): + """ + Shift the zero-frequency component to the center of the spectrum. + + This function swaps half-spaces for all axes listed (defaults to all). + Note that ``y[0]`` is the Nyquist component only if ``len(x)`` is even. + + Parameters + ---------- + x : array_like + Input array. + axes : int or shape tuple, optional + Axes over which to shift. Default is None, which shifts all axes. + + Returns + ------- + y : ndarray + The shifted array. + + See Also + -------- + ifftshift : The inverse of `fftshift`. + + Examples + -------- + >>> import numpy as np + >>> freqs = np.fft.fftfreq(10, 0.1) + >>> freqs + array([ 0., 1., 2., ..., -3., -2., -1.]) + >>> np.fft.fftshift(freqs) + array([-5., -4., -3., -2., -1., 0., 1., 2., 3., 4.]) + + Shift the zero-frequency component only along the second axis: + + >>> freqs = np.fft.fftfreq(9, d=1./9).reshape(3, 3) + >>> freqs + array([[ 0., 1., 2.], + [ 3., 4., -4.], + [-3., -2., -1.]]) + >>> np.fft.fftshift(freqs, axes=(1,)) + array([[ 2., 0., 1.], + [-4., 3., 4.], + [-1., -3., -2.]]) + + """ + x = asarray(x) + if axes is None: + axes = tuple(range(x.ndim)) + shift = [dim // 2 for dim in x.shape] + elif isinstance(axes, integer_types): + shift = x.shape[axes] // 2 + else: + shift = [x.shape[ax] // 2 for ax in axes] + + return roll(x, shift, axes) + + +@array_function_dispatch(_fftshift_dispatcher, module='numpy.fft') +def ifftshift(x, axes=None): + """ + The inverse of `fftshift`. Although identical for even-length `x`, the + functions differ by one sample for odd-length `x`. + + Parameters + ---------- + x : array_like + Input array. + axes : int or shape tuple, optional + Axes over which to calculate. Defaults to None, which shifts all axes. + + Returns + ------- + y : ndarray + The shifted array. + + See Also + -------- + fftshift : Shift zero-frequency component to the center of the spectrum. + + Examples + -------- + >>> import numpy as np + >>> freqs = np.fft.fftfreq(9, d=1./9).reshape(3, 3) + >>> freqs + array([[ 0., 1., 2.], + [ 3., 4., -4.], + [-3., -2., -1.]]) + >>> np.fft.ifftshift(np.fft.fftshift(freqs)) + array([[ 0., 1., 2.], + [ 3., 4., -4.], + [-3., -2., -1.]]) + + """ + x = asarray(x) + if axes is None: + axes = tuple(range(x.ndim)) + shift = [-(dim // 2) for dim in x.shape] + elif isinstance(axes, integer_types): + shift = -(x.shape[axes] // 2) + else: + shift = [-(x.shape[ax] // 2) for ax in axes] + + return roll(x, shift, axes) + + +@set_module('numpy.fft') +def fftfreq(n, d=1.0, device=None): + """ + Return the Discrete Fourier Transform sample frequencies. + + The returned float array `f` contains the frequency bin centers in cycles + per unit of the sample spacing (with zero at the start). For instance, if + the sample spacing is in seconds, then the frequency unit is cycles/second. + + Given a window length `n` and a sample spacing `d`:: + + f = [0, 1, ..., n/2-1, -n/2, ..., -1] / (d*n) if n is even + f = [0, 1, ..., (n-1)/2, -(n-1)/2, ..., -1] / (d*n) if n is odd + + Parameters + ---------- + n : int + Window length. + d : scalar, optional + Sample spacing (inverse of the sampling rate). Defaults to 1. + device : str, optional + The device on which to place the created array. Default: ``None``. + For Array-API interoperability only, so must be ``"cpu"`` if passed. + + .. versionadded:: 2.0.0 + + Returns + ------- + f : ndarray + Array of length `n` containing the sample frequencies. + + Examples + -------- + >>> import numpy as np + >>> signal = np.array([-2, 8, 6, 4, 1, 0, 3, 5], dtype=float) + >>> fourier = np.fft.fft(signal) + >>> n = signal.size + >>> timestep = 0.1 + >>> freq = np.fft.fftfreq(n, d=timestep) + >>> freq + array([ 0. , 1.25, 2.5 , ..., -3.75, -2.5 , -1.25]) + + """ + if not isinstance(n, integer_types): + raise ValueError("n should be an integer") + val = 1.0 / (n * d) + results = empty(n, int, device=device) + N = (n - 1) // 2 + 1 + p1 = arange(0, N, dtype=int, device=device) + results[:N] = p1 + p2 = arange(-(n // 2), 0, dtype=int, device=device) + results[N:] = p2 + return results * val + + +@set_module('numpy.fft') +def rfftfreq(n, d=1.0, device=None): + """ + Return the Discrete Fourier Transform sample frequencies + (for usage with rfft, irfft). + + The returned float array `f` contains the frequency bin centers in cycles + per unit of the sample spacing (with zero at the start). For instance, if + the sample spacing is in seconds, then the frequency unit is cycles/second. + + Given a window length `n` and a sample spacing `d`:: + + f = [0, 1, ..., n/2-1, n/2] / (d*n) if n is even + f = [0, 1, ..., (n-1)/2-1, (n-1)/2] / (d*n) if n is odd + + Unlike `fftfreq` (but like `scipy.fftpack.rfftfreq`) + the Nyquist frequency component is considered to be positive. + + Parameters + ---------- + n : int + Window length. + d : scalar, optional + Sample spacing (inverse of the sampling rate). Defaults to 1. + device : str, optional + The device on which to place the created array. Default: ``None``. + For Array-API interoperability only, so must be ``"cpu"`` if passed. + + .. versionadded:: 2.0.0 + + Returns + ------- + f : ndarray + Array of length ``n//2 + 1`` containing the sample frequencies. + + Examples + -------- + >>> import numpy as np + >>> signal = np.array([-2, 8, 6, 4, 1, 0, 3, 5, -3, 4], dtype=float) + >>> fourier = np.fft.rfft(signal) + >>> n = signal.size + >>> sample_rate = 100 + >>> freq = np.fft.fftfreq(n, d=1./sample_rate) + >>> freq + array([ 0., 10., 20., ..., -30., -20., -10.]) + >>> freq = np.fft.rfftfreq(n, d=1./sample_rate) + >>> freq + array([ 0., 10., 20., 30., 40., 50.]) + + """ + if not isinstance(n, integer_types): + raise ValueError("n should be an integer") + val = 1.0 / (n * d) + N = n // 2 + 1 + results = arange(0, N, dtype=int, device=device) + return results * val diff --git a/python/user_packages/Python313/site-packages/numpy/fft/_helper.pyi b/python/user_packages/Python313/site-packages/numpy/fft/_helper.pyi new file mode 100644 index 0000000000000000000000000000000000000000..cb6d41977463fc50ce5140d0811b55e18fc6b102 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/fft/_helper.pyi @@ -0,0 +1,44 @@ +from typing import Any, Final, Literal as L, TypeVar, overload + +from numpy import complexfloating, floating, generic, integer +from numpy._typing import ( + ArrayLike, + NDArray, + _ArrayLike, + _ArrayLikeComplex_co, + _ArrayLikeFloat_co, + _ShapeLike, +) + +__all__ = ["fftfreq", "fftshift", "ifftshift", "rfftfreq"] + +_ScalarT = TypeVar("_ScalarT", bound=generic) + +### + +integer_types: Final[tuple[type[int], type[integer]]] = ... + +### + +@overload +def fftshift(x: _ArrayLike[_ScalarT], axes: _ShapeLike | None = None) -> NDArray[_ScalarT]: ... +@overload +def fftshift(x: ArrayLike, axes: _ShapeLike | None = None) -> NDArray[Any]: ... + +# +@overload +def ifftshift(x: _ArrayLike[_ScalarT], axes: _ShapeLike | None = None) -> NDArray[_ScalarT]: ... +@overload +def ifftshift(x: ArrayLike, axes: _ShapeLike | None = None) -> NDArray[Any]: ... + +# +@overload +def fftfreq(n: int | integer, d: _ArrayLikeFloat_co = 1.0, device: L["cpu"] | None = None) -> NDArray[floating]: ... +@overload +def fftfreq(n: int | integer, d: _ArrayLikeComplex_co = 1.0, device: L["cpu"] | None = None) -> NDArray[complexfloating]: ... + +# +@overload +def rfftfreq(n: int | integer, d: _ArrayLikeFloat_co = 1.0, device: L["cpu"] | None = None) -> NDArray[floating]: ... +@overload +def rfftfreq(n: int | integer, d: _ArrayLikeComplex_co = 1.0, device: L["cpu"] | None = None) -> NDArray[complexfloating]: ... diff --git a/python/user_packages/Python313/site-packages/numpy/fft/_pocketfft.py b/python/user_packages/Python313/site-packages/numpy/fft/_pocketfft.py new file mode 100644 index 0000000000000000000000000000000000000000..ffac7935f301809e8eac74981b83d625b6c2a2f8 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/fft/_pocketfft.py @@ -0,0 +1,1693 @@ +""" +Discrete Fourier Transforms + +Routines in this module: + +fft(a, n=None, axis=-1, norm="backward") +ifft(a, n=None, axis=-1, norm="backward") +rfft(a, n=None, axis=-1, norm="backward") +irfft(a, n=None, axis=-1, norm="backward") +hfft(a, n=None, axis=-1, norm="backward") +ihfft(a, n=None, axis=-1, norm="backward") +fftn(a, s=None, axes=None, norm="backward") +ifftn(a, s=None, axes=None, norm="backward") +rfftn(a, s=None, axes=None, norm="backward") +irfftn(a, s=None, axes=None, norm="backward") +fft2(a, s=None, axes=(-2,-1), norm="backward") +ifft2(a, s=None, axes=(-2, -1), norm="backward") +rfft2(a, s=None, axes=(-2,-1), norm="backward") +irfft2(a, s=None, axes=(-2, -1), norm="backward") + +i = inverse transform +r = transform of purely real data +h = Hermite transform +n = n-dimensional transform +2 = 2-dimensional transform +(Note: 2D routines are just nD routines with different default +behavior.) + +""" +__all__ = ['fft', 'ifft', 'rfft', 'irfft', 'hfft', 'ihfft', 'rfftn', + 'irfftn', 'rfft2', 'irfft2', 'fft2', 'ifft2', 'fftn', 'ifftn'] + +import functools +import warnings + +from numpy._core import ( + asarray, + conjugate, + empty_like, + overrides, + reciprocal, + result_type, + sqrt, + take, +) +from numpy.lib.array_utils import normalize_axis_index + +from . import _pocketfft_umath as pfu + +array_function_dispatch = functools.partial( + overrides.array_function_dispatch, module='numpy.fft') + + +# `inv_norm` is a float by which the result of the transform needs to be +# divided. This replaces the original, more intuitive 'fct` parameter to avoid +# divisions by zero (or alternatively additional checks) in the case of +# zero-length axes during its computation. +def _raw_fft(a, n, axis, is_real, is_forward, norm, out=None): + if n < 1: + raise ValueError(f"Invalid number of FFT data points ({n}) specified.") + + # Calculate the normalization factor, passing in the array dtype to + # avoid precision loss in the possible sqrt or reciprocal. + if not is_forward: + norm = _swap_direction(norm) + + real_dtype = result_type(a.real.dtype, 1.0) + if norm is None or norm == "backward": + fct = 1 + elif norm == "ortho": + fct = reciprocal(sqrt(n, dtype=real_dtype)) + elif norm == "forward": + fct = reciprocal(n, dtype=real_dtype) + else: + raise ValueError(f'Invalid norm value {norm}; should be "backward",' + '"ortho" or "forward".') + + n_out = n + if is_real: + if is_forward: + ufunc = pfu.rfft_n_even if n % 2 == 0 else pfu.rfft_n_odd + n_out = n // 2 + 1 + else: + ufunc = pfu.irfft + else: + ufunc = pfu.fft if is_forward else pfu.ifft + + axis = normalize_axis_index(axis, a.ndim) + + if out is None: + if is_real and not is_forward: # irfft, complex in, real output. + out_dtype = real_dtype + else: # Others, complex output. + out_dtype = result_type(a.dtype, 1j) + out = empty_like(a, shape=a.shape[:axis] + (n_out,) + a.shape[axis + 1:], + dtype=out_dtype) + elif ((shape := getattr(out, "shape", None)) is not None + and (len(shape) != a.ndim or shape[axis] != n_out)): + raise ValueError("output array has wrong shape.") + + return ufunc(a, fct, axes=[(axis,), (), (axis,)], out=out) + + +_SWAP_DIRECTION_MAP = {"backward": "forward", None: "forward", + "ortho": "ortho", "forward": "backward"} + + +def _swap_direction(norm): + try: + return _SWAP_DIRECTION_MAP[norm] + except KeyError: + raise ValueError(f'Invalid norm value {norm}; should be "backward", ' + '"ortho" or "forward".') from None + + +def _fft_dispatcher(a, n=None, axis=None, norm=None, out=None): + return (a, out) + + +@array_function_dispatch(_fft_dispatcher) +def fft(a, n=None, axis=-1, norm=None, out=None): + """ + Compute the one-dimensional discrete Fourier Transform. + + This function computes the one-dimensional *n*-point discrete Fourier + Transform (DFT) with the efficient Fast Fourier Transform (FFT) + algorithm [CT]_. + + Parameters + ---------- + a : array_like + Input array, can be complex. + n : int, optional + Length of the transformed axis of the output. + If `n` is smaller than the length of the input, the input is cropped. + If it is larger, the input is padded with zeros. If `n` is not given, + the length of the input along the axis specified by `axis` is used. + axis : int, optional + Axis over which to compute the FFT. If not given, the last axis is + used. + norm : {"backward", "ortho", "forward"}, optional + Normalization mode (see `numpy.fft`). Default is "backward". + Indicates which direction of the forward/backward pair of transforms + is scaled and with what normalization factor. + + .. versionadded:: 1.20.0 + + The "backward", "forward" values were added. + out : complex ndarray, optional + If provided, the result will be placed in this array. It should be + of the appropriate shape and dtype. + + .. versionadded:: 2.0.0 + + Returns + ------- + out : complex ndarray + The truncated or zero-padded input, transformed along the axis + indicated by `axis`, or the last one if `axis` is not specified. + + Raises + ------ + IndexError + If `axis` is not a valid axis of `a`. + + See Also + -------- + numpy.fft : for definition of the DFT and conventions used. + ifft : The inverse of `fft`. + fft2 : The two-dimensional FFT. + fftn : The *n*-dimensional FFT. + rfftn : The *n*-dimensional FFT of real input. + fftfreq : Frequency bins for given FFT parameters. + + Notes + ----- + FFT (Fast Fourier Transform) refers to a way the discrete Fourier + Transform (DFT) can be calculated efficiently, by using symmetries in the + calculated terms. The symmetry is highest when `n` is a power of 2, and + the transform is therefore most efficient for these sizes. + + The DFT is defined, with the conventions used in this implementation, in + the documentation for the `numpy.fft` module. + + References + ---------- + .. [CT] Cooley, James W., and John W. Tukey, 1965, "An algorithm for the + machine calculation of complex Fourier series," *Math. Comput.* + 19: 297-301. + + Examples + -------- + >>> import numpy as np + >>> np.fft.fft(np.exp(2j * np.pi * np.arange(8) / 8)) + array([-2.33486982e-16+1.14423775e-17j, 8.00000000e+00-1.25557246e-15j, + 2.33486982e-16+2.33486982e-16j, 0.00000000e+00+1.22464680e-16j, + -1.14423775e-17+2.33486982e-16j, 0.00000000e+00+5.20784380e-16j, + 1.14423775e-17+1.14423775e-17j, 0.00000000e+00+1.22464680e-16j]) + + In this example, real input has an FFT which is Hermitian, i.e., symmetric + in the real part and anti-symmetric in the imaginary part, as described in + the `numpy.fft` documentation: + + >>> import matplotlib.pyplot as plt + >>> t = np.arange(256) + >>> sp = np.fft.fft(np.sin(t)) + >>> freq = np.fft.fftfreq(t.shape[-1]) + >>> _ = plt.plot(freq, sp.real, freq, sp.imag) + >>> plt.show() + + """ + a = asarray(a) + if n is None: + n = a.shape[axis] + output = _raw_fft(a, n, axis, False, True, norm, out) + return output + + +@array_function_dispatch(_fft_dispatcher) +def ifft(a, n=None, axis=-1, norm=None, out=None): + """ + Compute the one-dimensional inverse discrete Fourier Transform. + + This function computes the inverse of the one-dimensional *n*-point + discrete Fourier transform computed by `fft`. In other words, + ``ifft(fft(a)) == a`` to within numerical accuracy. + For a general description of the algorithm and definitions, + see `numpy.fft`. + + The input should be ordered in the same way as is returned by `fft`, + i.e., + + * ``a[0]`` should contain the zero frequency term, + * ``a[1:n//2]`` should contain the positive-frequency terms, + * ``a[n//2 + 1:]`` should contain the negative-frequency terms, in + increasing order starting from the most negative frequency. + + For an even number of input points, ``A[n//2]`` represents the sum of + the values at the positive and negative Nyquist frequencies, as the two + are aliased together. See `numpy.fft` for details. + + Parameters + ---------- + a : array_like + Input array, can be complex. + n : int, optional + Length of the transformed axis of the output. + If `n` is smaller than the length of the input, the input is cropped. + If it is larger, the input is padded with zeros. If `n` is not given, + the length of the input along the axis specified by `axis` is used. + See notes about padding issues. + axis : int, optional + Axis over which to compute the inverse DFT. If not given, the last + axis is used. + norm : {"backward", "ortho", "forward"}, optional + Normalization mode (see `numpy.fft`). Default is "backward". + Indicates which direction of the forward/backward pair of transforms + is scaled and with what normalization factor. + + .. versionadded:: 1.20.0 + + The "backward", "forward" values were added. + + out : complex ndarray, optional + If provided, the result will be placed in this array. It should be + of the appropriate shape and dtype. + + .. versionadded:: 2.0.0 + + Returns + ------- + out : complex ndarray + The truncated or zero-padded input, transformed along the axis + indicated by `axis`, or the last one if `axis` is not specified. + + Raises + ------ + IndexError + If `axis` is not a valid axis of `a`. + + See Also + -------- + numpy.fft : An introduction, with definitions and general explanations. + fft : The one-dimensional (forward) FFT, of which `ifft` is the inverse + ifft2 : The two-dimensional inverse FFT. + ifftn : The n-dimensional inverse FFT. + + Notes + ----- + If the input parameter `n` is larger than the size of the input, the input + is padded by appending zeros at the end. Even though this is the common + approach, it might lead to surprising results. If a different padding is + desired, it must be performed before calling `ifft`. + + Examples + -------- + >>> import numpy as np + >>> np.fft.ifft([0, 4, 0, 0]) + array([ 1.+0.j, 0.+1.j, -1.+0.j, 0.-1.j]) # may vary + + Create and plot a band-limited signal with random phases: + + >>> import matplotlib.pyplot as plt + >>> t = np.arange(400) + >>> n = np.zeros((400,), dtype=complex) + >>> n[40:60] = np.exp(1j*np.random.uniform(0, 2*np.pi, (20,))) + >>> s = np.fft.ifft(n) + >>> plt.plot(t, s.real, label='real') + [] + >>> plt.plot(t, s.imag, '--', label='imaginary') + [] + >>> plt.legend() + + >>> plt.show() + + """ + a = asarray(a) + if n is None: + n = a.shape[axis] + output = _raw_fft(a, n, axis, False, False, norm, out=out) + return output + + +@array_function_dispatch(_fft_dispatcher) +def rfft(a, n=None, axis=-1, norm=None, out=None): + """ + Compute the one-dimensional discrete Fourier Transform for real input. + + This function computes the one-dimensional *n*-point discrete Fourier + Transform (DFT) of a real-valued array by means of an efficient algorithm + called the Fast Fourier Transform (FFT). + + Parameters + ---------- + a : array_like + Input array + n : int, optional + Number of points along transformation axis in the input to use. + If `n` is smaller than the length of the input, the input is cropped. + If it is larger, the input is padded with zeros. If `n` is not given, + the length of the input along the axis specified by `axis` is used. + axis : int, optional + Axis over which to compute the FFT. If not given, the last axis is + used. + norm : {"backward", "ortho", "forward"}, optional + Normalization mode (see `numpy.fft`). Default is "backward". + Indicates which direction of the forward/backward pair of transforms + is scaled and with what normalization factor. + + .. versionadded:: 1.20.0 + + The "backward", "forward" values were added. + + out : complex ndarray, optional + If provided, the result will be placed in this array. It should be + of the appropriate shape and dtype. + + .. versionadded:: 2.0.0 + + Returns + ------- + out : complex ndarray + The truncated or zero-padded input, transformed along the axis + indicated by `axis`, or the last one if `axis` is not specified. + If `n` is even, the length of the transformed axis is ``(n/2)+1``. + If `n` is odd, the length is ``(n+1)/2``. + + Raises + ------ + IndexError + If `axis` is not a valid axis of `a`. + + See Also + -------- + numpy.fft : For definition of the DFT and conventions used. + irfft : The inverse of `rfft`. + fft : The one-dimensional FFT of general (complex) input. + fftn : The *n*-dimensional FFT. + rfftn : The *n*-dimensional FFT of real input. + + Notes + ----- + When the DFT is computed for purely real input, the output is + Hermitian-symmetric, i.e. the negative frequency terms are just the complex + conjugates of the corresponding positive-frequency terms, and the + negative-frequency terms are therefore redundant. This function does not + compute the negative frequency terms, and the length of the transformed + axis of the output is therefore ``n//2 + 1``. + + When ``A = rfft(a)`` and fs is the sampling frequency, ``A[0]`` contains + the zero-frequency term 0*fs, which is real due to Hermitian symmetry. + + If `n` is even, ``A[-1]`` contains the term representing both positive + and negative Nyquist frequency (+fs/2 and -fs/2), and must also be purely + real. If `n` is odd, there is no term at fs/2; ``A[-1]`` contains + the largest positive frequency (fs/2*(n-1)/n), and is complex in the + general case. + + If the input `a` contains an imaginary part, it is silently discarded. + + Examples + -------- + >>> import numpy as np + >>> np.fft.fft([0, 1, 0, 0]) + array([ 1.+0.j, 0.-1.j, -1.+0.j, 0.+1.j]) # may vary + >>> np.fft.rfft([0, 1, 0, 0]) + array([ 1.+0.j, 0.-1.j, -1.+0.j]) # may vary + + Notice how the final element of the `fft` output is the complex conjugate + of the second element, for real input. For `rfft`, this symmetry is + exploited to compute only the non-negative frequency terms. + + """ + a = asarray(a) + if n is None: + n = a.shape[axis] + output = _raw_fft(a, n, axis, True, True, norm, out=out) + return output + + +@array_function_dispatch(_fft_dispatcher) +def irfft(a, n=None, axis=-1, norm=None, out=None): + """ + Computes the inverse of `rfft`. + + This function computes the inverse of the one-dimensional *n*-point + discrete Fourier Transform of real input computed by `rfft`. + In other words, ``irfft(rfft(a), len(a)) == a`` to within numerical + accuracy. (See Notes below for why ``len(a)`` is necessary here.) + + The input is expected to be in the form returned by `rfft`, i.e. the + real zero-frequency term followed by the complex positive frequency terms + in order of increasing frequency. Since the discrete Fourier Transform of + real input is Hermitian-symmetric, the negative frequency terms are taken + to be the complex conjugates of the corresponding positive frequency terms. + + Parameters + ---------- + a : array_like + The input array. + n : int, optional + Length of the transformed axis of the output. + For `n` output points, ``n//2+1`` input points are necessary. If the + input is longer than this, it is cropped. If it is shorter than this, + it is padded with zeros. If `n` is not given, it is taken to be + ``2*(m-1)`` where ``m`` is the length of the input along the axis + specified by `axis`. + axis : int, optional + Axis over which to compute the inverse FFT. If not given, the last + axis is used. + norm : {"backward", "ortho", "forward"}, optional + Normalization mode (see `numpy.fft`). Default is "backward". + Indicates which direction of the forward/backward pair of transforms + is scaled and with what normalization factor. + + .. versionadded:: 1.20.0 + + The "backward", "forward" values were added. + + out : ndarray, optional + If provided, the result will be placed in this array. It should be + of the appropriate shape and dtype. + + .. versionadded:: 2.0.0 + + Returns + ------- + out : ndarray + The truncated or zero-padded input, transformed along the axis + indicated by `axis`, or the last one if `axis` is not specified. + The length of the transformed axis is `n`, or, if `n` is not given, + ``2*(m-1)`` where ``m`` is the length of the transformed axis of the + input. To get an odd number of output points, `n` must be specified. + + Raises + ------ + IndexError + If `axis` is not a valid axis of `a`. + + See Also + -------- + numpy.fft : For definition of the DFT and conventions used. + rfft : The one-dimensional FFT of real input, of which `irfft` is inverse. + fft : The one-dimensional FFT. + irfft2 : The inverse of the two-dimensional FFT of real input. + irfftn : The inverse of the *n*-dimensional FFT of real input. + + Notes + ----- + Returns the real valued `n`-point inverse discrete Fourier transform + of `a`, where `a` contains the non-negative frequency terms of a + Hermitian-symmetric sequence. `n` is the length of the result, not the + input. + + If you specify an `n` such that `a` must be zero-padded or truncated, the + extra/removed values will be added/removed at high frequencies. One can + thus resample a series to `m` points via Fourier interpolation by: + ``a_resamp = irfft(rfft(a), m)``. + + The correct interpretation of the hermitian input depends on the length of + the original data, as given by `n`. This is because each input shape could + correspond to either an odd or even length signal. By default, `irfft` + assumes an even output length which puts the last entry at the Nyquist + frequency; aliasing with its symmetric counterpart. By Hermitian symmetry, + the value is thus treated as purely real. To avoid losing information, the + correct length of the real input **must** be given. + + Examples + -------- + >>> import numpy as np + >>> np.fft.ifft([1, -1j, -1, 1j]) + array([0.+0.j, 1.+0.j, 0.+0.j, 0.+0.j]) # may vary + >>> np.fft.irfft([1, -1j, -1]) + array([0., 1., 0., 0.]) + + Notice how the last term in the input to the ordinary `ifft` is the + complex conjugate of the second term, and the output has zero imaginary + part everywhere. When calling `irfft`, the negative frequencies are not + specified, and the output array is purely real. + + """ + a = asarray(a) + if n is None: + n = (a.shape[axis] - 1) * 2 + output = _raw_fft(a, n, axis, True, False, norm, out=out) + return output + + +@array_function_dispatch(_fft_dispatcher) +def hfft(a, n=None, axis=-1, norm=None, out=None): + """ + Compute the FFT of a signal that has Hermitian symmetry, i.e., a real + spectrum. + + Parameters + ---------- + a : array_like + The input array. + n : int, optional + Length of the transformed axis of the output. For `n` output + points, ``n//2 + 1`` input points are necessary. If the input is + longer than this, it is cropped. If it is shorter than this, it is + padded with zeros. If `n` is not given, it is taken to be ``2*(m-1)`` + where ``m`` is the length of the input along the axis specified by + `axis`. + axis : int, optional + Axis over which to compute the FFT. If not given, the last + axis is used. + norm : {"backward", "ortho", "forward"}, optional + Normalization mode (see `numpy.fft`). Default is "backward". + Indicates which direction of the forward/backward pair of transforms + is scaled and with what normalization factor. + + .. versionadded:: 1.20.0 + + The "backward", "forward" values were added. + + out : ndarray, optional + If provided, the result will be placed in this array. It should be + of the appropriate shape and dtype. + + .. versionadded:: 2.0.0 + + Returns + ------- + out : ndarray + The truncated or zero-padded input, transformed along the axis + indicated by `axis`, or the last one if `axis` is not specified. + The length of the transformed axis is `n`, or, if `n` is not given, + ``2*m - 2`` where ``m`` is the length of the transformed axis of + the input. To get an odd number of output points, `n` must be + specified, for instance as ``2*m - 1`` in the typical case, + + Raises + ------ + IndexError + If `axis` is not a valid axis of `a`. + + See also + -------- + rfft : Compute the one-dimensional FFT for real input. + ihfft : The inverse of `hfft`. + + Notes + ----- + `hfft`/`ihfft` are a pair analogous to `rfft`/`irfft`, but for the + opposite case: here the signal has Hermitian symmetry in the time + domain and is real in the frequency domain. So here it's `hfft` for + which you must supply the length of the result if it is to be odd. + + * even: ``ihfft(hfft(a, 2*len(a) - 2)) == a``, within roundoff error, + * odd: ``ihfft(hfft(a, 2*len(a) - 1)) == a``, within roundoff error. + + The correct interpretation of the hermitian input depends on the length of + the original data, as given by `n`. This is because each input shape could + correspond to either an odd or even length signal. By default, `hfft` + assumes an even output length which puts the last entry at the Nyquist + frequency; aliasing with its symmetric counterpart. By Hermitian symmetry, + the value is thus treated as purely real. To avoid losing information, the + shape of the full signal **must** be given. + + Examples + -------- + >>> import numpy as np + >>> signal = np.array([1, 2, 3, 4, 3, 2]) + >>> np.fft.fft(signal) + array([15.+0.j, -4.+0.j, 0.+0.j, -1.-0.j, 0.+0.j, -4.+0.j]) # may vary + >>> np.fft.hfft(signal[:4]) # Input first half of signal + array([15., -4., 0., -1., 0., -4.]) + >>> np.fft.hfft(signal, 6) # Input entire signal and truncate + array([15., -4., 0., -1., 0., -4.]) + + + >>> signal = np.array([[1, 1.j], [-1.j, 2]]) + >>> np.conj(signal.T) - signal # check Hermitian symmetry + array([[ 0.-0.j, -0.+0.j], # may vary + [ 0.+0.j, 0.-0.j]]) + >>> freq_spectrum = np.fft.hfft(signal) + >>> freq_spectrum + array([[ 1., 1.], + [ 2., -2.]]) + + """ + a = asarray(a) + if n is None: + n = (a.shape[axis] - 1) * 2 + new_norm = _swap_direction(norm) + output = irfft(conjugate(a), n, axis, norm=new_norm, out=None) + return output + + +@array_function_dispatch(_fft_dispatcher) +def ihfft(a, n=None, axis=-1, norm=None, out=None): + """ + Compute the inverse FFT of a signal that has Hermitian symmetry. + + Parameters + ---------- + a : array_like + Input array. + n : int, optional + Length of the inverse FFT, the number of points along + transformation axis in the input to use. If `n` is smaller than + the length of the input, the input is cropped. If it is larger, + the input is padded with zeros. If `n` is not given, the length of + the input along the axis specified by `axis` is used. + axis : int, optional + Axis over which to compute the inverse FFT. If not given, the last + axis is used. + norm : {"backward", "ortho", "forward"}, optional + Normalization mode (see `numpy.fft`). Default is "backward". + Indicates which direction of the forward/backward pair of transforms + is scaled and with what normalization factor. + + .. versionadded:: 1.20.0 + + The "backward", "forward" values were added. + + out : complex ndarray, optional + If provided, the result will be placed in this array. It should be + of the appropriate shape and dtype. + + .. versionadded:: 2.0.0 + + Returns + ------- + out : complex ndarray + The truncated or zero-padded input, transformed along the axis + indicated by `axis`, or the last one if `axis` is not specified. + The length of the transformed axis is ``n//2 + 1``. + + See also + -------- + hfft, irfft + + Notes + ----- + `hfft`/`ihfft` are a pair analogous to `rfft`/`irfft`, but for the + opposite case: here the signal has Hermitian symmetry in the time + domain and is real in the frequency domain. So here it's `hfft` for + which you must supply the length of the result if it is to be odd: + + * even: ``ihfft(hfft(a, 2*len(a) - 2)) == a``, within roundoff error, + * odd: ``ihfft(hfft(a, 2*len(a) - 1)) == a``, within roundoff error. + + Examples + -------- + >>> import numpy as np + >>> spectrum = np.array([ 15, -4, 0, -1, 0, -4]) + >>> np.fft.ifft(spectrum) + array([1.+0.j, 2.+0.j, 3.+0.j, 4.+0.j, 3.+0.j, 2.+0.j]) # may vary + >>> np.fft.ihfft(spectrum) + array([ 1.-0.j, 2.-0.j, 3.-0.j, 4.-0.j]) # may vary + + """ + a = asarray(a) + if n is None: + n = a.shape[axis] + new_norm = _swap_direction(norm) + out = rfft(a, n, axis, norm=new_norm, out=out) + return conjugate(out, out=out) + + +def _cook_nd_args(a, s=None, axes=None, invreal=0): + if s is None: + shapeless = True + if axes is None: + s = list(a.shape) + else: + s = take(a.shape, axes) + else: + shapeless = False + s = list(s) + if axes is None: + if not shapeless: + msg = ("`axes` should not be `None` if `s` is not `None` " + "(Deprecated in NumPy 2.0). In a future version of NumPy, " + "this will raise an error and `s[i]` will correspond to " + "the size along the transformed axis specified by " + "`axes[i]`. To retain current behaviour, pass a sequence " + "[0, ..., k-1] to `axes` for an array of dimension k.") + warnings.warn(msg, DeprecationWarning, stacklevel=3) + axes = list(range(-len(s), 0)) + if len(s) != len(axes): + raise ValueError("Shape and axes have different lengths.") + if invreal and shapeless: + s[-1] = (a.shape[axes[-1]] - 1) * 2 + if None in s: + msg = ("Passing an array containing `None` values to `s` is " + "deprecated in NumPy 2.0 and will raise an error in " + "a future version of NumPy. To use the default behaviour " + "of the corresponding 1-D transform, pass the value matching " + "the default for its `n` parameter. To use the default " + "behaviour for every axis, the `s` argument can be omitted.") + warnings.warn(msg, DeprecationWarning, stacklevel=3) + # use the whole input array along axis `i` if `s[i] == -1` + s = [a.shape[_a] if _s == -1 else _s for _s, _a in zip(s, axes)] + return s, axes + + +def _raw_fftnd(a, s=None, axes=None, function=fft, norm=None, out=None): + a = asarray(a) + s, axes = _cook_nd_args(a, s, axes) + itl = list(range(len(axes))) + itl.reverse() + for ii in itl: + a = function(a, n=s[ii], axis=axes[ii], norm=norm, out=out) + return a + + +def _fftn_dispatcher(a, s=None, axes=None, norm=None, out=None): + return (a, out) + + +@array_function_dispatch(_fftn_dispatcher) +def fftn(a, s=None, axes=None, norm=None, out=None): + """ + Compute the N-dimensional discrete Fourier Transform. + + This function computes the *N*-dimensional discrete Fourier Transform over + any number of axes in an *M*-dimensional array by means of the Fast Fourier + Transform (FFT). + + Parameters + ---------- + a : array_like + Input array, can be complex. + s : sequence of ints, optional + Shape (length of each transformed axis) of the output + (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.). + This corresponds to ``n`` for ``fft(x, n)``. + Along any axis, if the given shape is smaller than that of the input, + the input is cropped. If it is larger, the input is padded with zeros. + + .. versionchanged:: 2.0 + + If it is ``-1``, the whole input is used (no padding/trimming). + + If `s` is not given, the shape of the input along the axes specified + by `axes` is used. + + .. deprecated:: 2.0 + + If `s` is not ``None``, `axes` must not be ``None`` either. + + .. deprecated:: 2.0 + + `s` must contain only ``int`` s, not ``None`` values. ``None`` + values currently mean that the default value for ``n`` is used + in the corresponding 1-D transform, but this behaviour is + deprecated. + + axes : sequence of ints, optional + Axes over which to compute the FFT. If not given, the last ``len(s)`` + axes are used, or all axes if `s` is also not specified. + Repeated indices in `axes` means that the transform over that axis is + performed multiple times. + + .. deprecated:: 2.0 + + If `s` is specified, the corresponding `axes` to be transformed + must be explicitly specified too. + + norm : {"backward", "ortho", "forward"}, optional + Normalization mode (see `numpy.fft`). Default is "backward". + Indicates which direction of the forward/backward pair of transforms + is scaled and with what normalization factor. + + .. versionadded:: 1.20.0 + + The "backward", "forward" values were added. + + out : complex ndarray, optional + If provided, the result will be placed in this array. It should be + of the appropriate shape and dtype for all axes (and hence is + incompatible with passing in all but the trivial ``s``). + + .. versionadded:: 2.0.0 + + Returns + ------- + out : complex ndarray + The truncated or zero-padded input, transformed along the axes + indicated by `axes`, or by a combination of `s` and `a`, + as explained in the parameters section above. + + Raises + ------ + ValueError + If `s` and `axes` have different length. + IndexError + If an element of `axes` is larger than than the number of axes of `a`. + + See Also + -------- + numpy.fft : Overall view of discrete Fourier transforms, with definitions + and conventions used. + ifftn : The inverse of `fftn`, the inverse *n*-dimensional FFT. + fft : The one-dimensional FFT, with definitions and conventions used. + rfftn : The *n*-dimensional FFT of real input. + fft2 : The two-dimensional FFT. + fftshift : Shifts zero-frequency terms to centre of array + + Notes + ----- + The output, analogously to `fft`, contains the term for zero frequency in + the low-order corner of all axes, the positive frequency terms in the + first half of all axes, the term for the Nyquist frequency in the middle + of all axes and the negative frequency terms in the second half of all + axes, in order of decreasingly negative frequency. + + See `numpy.fft` for details, definitions and conventions used. + + Examples + -------- + >>> import numpy as np + >>> a = np.mgrid[:3, :3, :3][0] + >>> np.fft.fftn(a, axes=(1, 2)) + array([[[ 0.+0.j, 0.+0.j, 0.+0.j], # may vary + [ 0.+0.j, 0.+0.j, 0.+0.j], + [ 0.+0.j, 0.+0.j, 0.+0.j]], + [[ 9.+0.j, 0.+0.j, 0.+0.j], + [ 0.+0.j, 0.+0.j, 0.+0.j], + [ 0.+0.j, 0.+0.j, 0.+0.j]], + [[18.+0.j, 0.+0.j, 0.+0.j], + [ 0.+0.j, 0.+0.j, 0.+0.j], + [ 0.+0.j, 0.+0.j, 0.+0.j]]]) + >>> np.fft.fftn(a, (2, 2), axes=(0, 1)) + array([[[ 2.+0.j, 2.+0.j, 2.+0.j], # may vary + [ 0.+0.j, 0.+0.j, 0.+0.j]], + [[-2.+0.j, -2.+0.j, -2.+0.j], + [ 0.+0.j, 0.+0.j, 0.+0.j]]]) + + >>> import matplotlib.pyplot as plt + >>> [X, Y] = np.meshgrid(2 * np.pi * np.arange(200) / 12, + ... 2 * np.pi * np.arange(200) / 34) + >>> S = np.sin(X) + np.cos(Y) + np.random.uniform(0, 1, X.shape) + >>> FS = np.fft.fftn(S) + >>> plt.imshow(np.log(np.abs(np.fft.fftshift(FS))**2)) + + >>> plt.show() + + """ + return _raw_fftnd(a, s, axes, fft, norm, out=out) + + +@array_function_dispatch(_fftn_dispatcher) +def ifftn(a, s=None, axes=None, norm=None, out=None): + """ + Compute the N-dimensional inverse discrete Fourier Transform. + + This function computes the inverse of the N-dimensional discrete + Fourier Transform over any number of axes in an M-dimensional array by + means of the Fast Fourier Transform (FFT). In other words, + ``ifftn(fftn(a)) == a`` to within numerical accuracy. + For a description of the definitions and conventions used, see `numpy.fft`. + + The input, analogously to `ifft`, should be ordered in the same way as is + returned by `fftn`, i.e. it should have the term for zero frequency + in all axes in the low-order corner, the positive frequency terms in the + first half of all axes, the term for the Nyquist frequency in the middle + of all axes and the negative frequency terms in the second half of all + axes, in order of decreasingly negative frequency. + + Parameters + ---------- + a : array_like + Input array, can be complex. + s : sequence of ints, optional + Shape (length of each transformed axis) of the output + (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.). + This corresponds to ``n`` for ``ifft(x, n)``. + Along any axis, if the given shape is smaller than that of the input, + the input is cropped. If it is larger, the input is padded with zeros. + + .. versionchanged:: 2.0 + + If it is ``-1``, the whole input is used (no padding/trimming). + + If `s` is not given, the shape of the input along the axes specified + by `axes` is used. See notes for issue on `ifft` zero padding. + + .. deprecated:: 2.0 + + If `s` is not ``None``, `axes` must not be ``None`` either. + + .. deprecated:: 2.0 + + `s` must contain only ``int`` s, not ``None`` values. ``None`` + values currently mean that the default value for ``n`` is used + in the corresponding 1-D transform, but this behaviour is + deprecated. + + axes : sequence of ints, optional + Axes over which to compute the IFFT. If not given, the last ``len(s)`` + axes are used, or all axes if `s` is also not specified. + Repeated indices in `axes` means that the inverse transform over that + axis is performed multiple times. + + .. deprecated:: 2.0 + + If `s` is specified, the corresponding `axes` to be transformed + must be explicitly specified too. + + norm : {"backward", "ortho", "forward"}, optional + Normalization mode (see `numpy.fft`). Default is "backward". + Indicates which direction of the forward/backward pair of transforms + is scaled and with what normalization factor. + + .. versionadded:: 1.20.0 + + The "backward", "forward" values were added. + + out : complex ndarray, optional + If provided, the result will be placed in this array. It should be + of the appropriate shape and dtype for all axes (and hence is + incompatible with passing in all but the trivial ``s``). + + .. versionadded:: 2.0.0 + + Returns + ------- + out : complex ndarray + The truncated or zero-padded input, transformed along the axes + indicated by `axes`, or by a combination of `s` or `a`, + as explained in the parameters section above. + + Raises + ------ + ValueError + If `s` and `axes` have different length. + IndexError + If an element of `axes` is larger than than the number of axes of `a`. + + See Also + -------- + numpy.fft : Overall view of discrete Fourier transforms, with definitions + and conventions used. + fftn : The forward *n*-dimensional FFT, of which `ifftn` is the inverse. + ifft : The one-dimensional inverse FFT. + ifft2 : The two-dimensional inverse FFT. + ifftshift : Undoes `fftshift`, shifts zero-frequency terms to beginning + of array. + + Notes + ----- + See `numpy.fft` for definitions and conventions used. + + Zero-padding, analogously with `ifft`, is performed by appending zeros to + the input along the specified dimension. Although this is the common + approach, it might lead to surprising results. If another form of zero + padding is desired, it must be performed before `ifftn` is called. + + Examples + -------- + >>> import numpy as np + >>> a = np.eye(4) + >>> np.fft.ifftn(np.fft.fftn(a, axes=(0,)), axes=(1,)) + array([[1.+0.j, 0.+0.j, 0.+0.j, 0.+0.j], # may vary + [0.+0.j, 1.+0.j, 0.+0.j, 0.+0.j], + [0.+0.j, 0.+0.j, 1.+0.j, 0.+0.j], + [0.+0.j, 0.+0.j, 0.+0.j, 1.+0.j]]) + + + Create and plot an image with band-limited frequency content: + + >>> import matplotlib.pyplot as plt + >>> n = np.zeros((200,200), dtype=complex) + >>> n[60:80, 20:40] = np.exp(1j*np.random.uniform(0, 2*np.pi, (20, 20))) + >>> im = np.fft.ifftn(n).real + >>> plt.imshow(im) + + >>> plt.show() + + """ + return _raw_fftnd(a, s, axes, ifft, norm, out=out) + + +@array_function_dispatch(_fftn_dispatcher) +def fft2(a, s=None, axes=(-2, -1), norm=None, out=None): + """ + Compute the 2-dimensional discrete Fourier Transform. + + This function computes the *n*-dimensional discrete Fourier Transform + over any axes in an *M*-dimensional array by means of the + Fast Fourier Transform (FFT). By default, the transform is computed over + the last two axes of the input array, i.e., a 2-dimensional FFT. + + Parameters + ---------- + a : array_like + Input array, can be complex + s : sequence of ints, optional + Shape (length of each transformed axis) of the output + (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.). + This corresponds to ``n`` for ``fft(x, n)``. + Along each axis, if the given shape is smaller than that of the input, + the input is cropped. If it is larger, the input is padded with zeros. + + .. versionchanged:: 2.0 + + If it is ``-1``, the whole input is used (no padding/trimming). + + If `s` is not given, the shape of the input along the axes specified + by `axes` is used. + + .. deprecated:: 2.0 + + If `s` is not ``None``, `axes` must not be ``None`` either. + + .. deprecated:: 2.0 + + `s` must contain only ``int`` s, not ``None`` values. ``None`` + values currently mean that the default value for ``n`` is used + in the corresponding 1-D transform, but this behaviour is + deprecated. + + axes : sequence of ints, optional + Axes over which to compute the FFT. If not given, the last two + axes are used. A repeated index in `axes` means the transform over + that axis is performed multiple times. A one-element sequence means + that a one-dimensional FFT is performed. Default: ``(-2, -1)``. + + .. deprecated:: 2.0 + + If `s` is specified, the corresponding `axes` to be transformed + must not be ``None``. + + norm : {"backward", "ortho", "forward"}, optional + Normalization mode (see `numpy.fft`). Default is "backward". + Indicates which direction of the forward/backward pair of transforms + is scaled and with what normalization factor. + + .. versionadded:: 1.20.0 + + The "backward", "forward" values were added. + + out : complex ndarray, optional + If provided, the result will be placed in this array. It should be + of the appropriate shape and dtype for all axes (and hence only the + last axis can have ``s`` not equal to the shape at that axis). + + .. versionadded:: 2.0.0 + + Returns + ------- + out : complex ndarray + The truncated or zero-padded input, transformed along the axes + indicated by `axes`, or the last two axes if `axes` is not given. + + Raises + ------ + ValueError + If `s` and `axes` have different length, or `axes` not given and + ``len(s) != 2``. + IndexError + If an element of `axes` is larger than than the number of axes of `a`. + + See Also + -------- + numpy.fft : Overall view of discrete Fourier transforms, with definitions + and conventions used. + ifft2 : The inverse two-dimensional FFT. + fft : The one-dimensional FFT. + fftn : The *n*-dimensional FFT. + fftshift : Shifts zero-frequency terms to the center of the array. + For two-dimensional input, swaps first and third quadrants, and second + and fourth quadrants. + + Notes + ----- + `fft2` is just `fftn` with a different default for `axes`. + + The output, analogously to `fft`, contains the term for zero frequency in + the low-order corner of the transformed axes, the positive frequency terms + in the first half of these axes, the term for the Nyquist frequency in the + middle of the axes and the negative frequency terms in the second half of + the axes, in order of decreasingly negative frequency. + + See `fftn` for details and a plotting example, and `numpy.fft` for + definitions and conventions used. + + + Examples + -------- + >>> import numpy as np + >>> a = np.mgrid[:5, :5][0] + >>> np.fft.fft2(a) + array([[ 50. +0.j , 0. +0.j , 0. +0.j , # may vary + 0. +0.j , 0. +0.j ], + [-12.5+17.20477401j, 0. +0.j , 0. +0.j , + 0. +0.j , 0. +0.j ], + [-12.5 +4.0614962j , 0. +0.j , 0. +0.j , + 0. +0.j , 0. +0.j ], + [-12.5 -4.0614962j , 0. +0.j , 0. +0.j , + 0. +0.j , 0. +0.j ], + [-12.5-17.20477401j, 0. +0.j , 0. +0.j , + 0. +0.j , 0. +0.j ]]) + + """ + return _raw_fftnd(a, s, axes, fft, norm, out=out) + + +@array_function_dispatch(_fftn_dispatcher) +def ifft2(a, s=None, axes=(-2, -1), norm=None, out=None): + """ + Compute the 2-dimensional inverse discrete Fourier Transform. + + This function computes the inverse of the 2-dimensional discrete Fourier + Transform over any number of axes in an M-dimensional array by means of + the Fast Fourier Transform (FFT). In other words, ``ifft2(fft2(a)) == a`` + to within numerical accuracy. By default, the inverse transform is + computed over the last two axes of the input array. + + The input, analogously to `ifft`, should be ordered in the same way as is + returned by `fft2`, i.e. it should have the term for zero frequency + in the low-order corner of the two axes, the positive frequency terms in + the first half of these axes, the term for the Nyquist frequency in the + middle of the axes and the negative frequency terms in the second half of + both axes, in order of decreasingly negative frequency. + + Parameters + ---------- + a : array_like + Input array, can be complex. + s : sequence of ints, optional + Shape (length of each axis) of the output (``s[0]`` refers to axis 0, + ``s[1]`` to axis 1, etc.). This corresponds to `n` for ``ifft(x, n)``. + Along each axis, if the given shape is smaller than that of the input, + the input is cropped. If it is larger, the input is padded with zeros. + + .. versionchanged:: 2.0 + + If it is ``-1``, the whole input is used (no padding/trimming). + + If `s` is not given, the shape of the input along the axes specified + by `axes` is used. See notes for issue on `ifft` zero padding. + + .. deprecated:: 2.0 + + If `s` is not ``None``, `axes` must not be ``None`` either. + + .. deprecated:: 2.0 + + `s` must contain only ``int`` s, not ``None`` values. ``None`` + values currently mean that the default value for ``n`` is used + in the corresponding 1-D transform, but this behaviour is + deprecated. + + axes : sequence of ints, optional + Axes over which to compute the FFT. If not given, the last two + axes are used. A repeated index in `axes` means the transform over + that axis is performed multiple times. A one-element sequence means + that a one-dimensional FFT is performed. Default: ``(-2, -1)``. + + .. deprecated:: 2.0 + + If `s` is specified, the corresponding `axes` to be transformed + must not be ``None``. + + norm : {"backward", "ortho", "forward"}, optional + Normalization mode (see `numpy.fft`). Default is "backward". + Indicates which direction of the forward/backward pair of transforms + is scaled and with what normalization factor. + + .. versionadded:: 1.20.0 + + The "backward", "forward" values were added. + + out : complex ndarray, optional + If provided, the result will be placed in this array. It should be + of the appropriate shape and dtype for all axes (and hence is + incompatible with passing in all but the trivial ``s``). + + .. versionadded:: 2.0.0 + + Returns + ------- + out : complex ndarray + The truncated or zero-padded input, transformed along the axes + indicated by `axes`, or the last two axes if `axes` is not given. + + Raises + ------ + ValueError + If `s` and `axes` have different length, or `axes` not given and + ``len(s) != 2``. + IndexError + If an element of `axes` is larger than than the number of axes of `a`. + + See Also + -------- + numpy.fft : Overall view of discrete Fourier transforms, with definitions + and conventions used. + fft2 : The forward 2-dimensional FFT, of which `ifft2` is the inverse. + ifftn : The inverse of the *n*-dimensional FFT. + fft : The one-dimensional FFT. + ifft : The one-dimensional inverse FFT. + + Notes + ----- + `ifft2` is just `ifftn` with a different default for `axes`. + + See `ifftn` for details and a plotting example, and `numpy.fft` for + definition and conventions used. + + Zero-padding, analogously with `ifft`, is performed by appending zeros to + the input along the specified dimension. Although this is the common + approach, it might lead to surprising results. If another form of zero + padding is desired, it must be performed before `ifft2` is called. + + Examples + -------- + >>> import numpy as np + >>> a = 4 * np.eye(4) + >>> np.fft.ifft2(a) + array([[1.+0.j, 0.+0.j, 0.+0.j, 0.+0.j], # may vary + [0.+0.j, 0.+0.j, 0.+0.j, 1.+0.j], + [0.+0.j, 0.+0.j, 1.+0.j, 0.+0.j], + [0.+0.j, 1.+0.j, 0.+0.j, 0.+0.j]]) + + """ + return _raw_fftnd(a, s, axes, ifft, norm, out=None) + + +@array_function_dispatch(_fftn_dispatcher) +def rfftn(a, s=None, axes=None, norm=None, out=None): + """ + Compute the N-dimensional discrete Fourier Transform for real input. + + This function computes the N-dimensional discrete Fourier Transform over + any number of axes in an M-dimensional real array by means of the Fast + Fourier Transform (FFT). By default, all axes are transformed, with the + real transform performed over the last axis, while the remaining + transforms are complex. + + Parameters + ---------- + a : array_like + Input array, taken to be real. + s : sequence of ints, optional + Shape (length along each transformed axis) to use from the input. + (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.). + The final element of `s` corresponds to `n` for ``rfft(x, n)``, while + for the remaining axes, it corresponds to `n` for ``fft(x, n)``. + Along any axis, if the given shape is smaller than that of the input, + the input is cropped. If it is larger, the input is padded with zeros. + + .. versionchanged:: 2.0 + + If it is ``-1``, the whole input is used (no padding/trimming). + + If `s` is not given, the shape of the input along the axes specified + by `axes` is used. + + .. deprecated:: 2.0 + + If `s` is not ``None``, `axes` must not be ``None`` either. + + .. deprecated:: 2.0 + + `s` must contain only ``int`` s, not ``None`` values. ``None`` + values currently mean that the default value for ``n`` is used + in the corresponding 1-D transform, but this behaviour is + deprecated. + + axes : sequence of ints, optional + Axes over which to compute the FFT. If not given, the last ``len(s)`` + axes are used, or all axes if `s` is also not specified. + + .. deprecated:: 2.0 + + If `s` is specified, the corresponding `axes` to be transformed + must be explicitly specified too. + + norm : {"backward", "ortho", "forward"}, optional + Normalization mode (see `numpy.fft`). Default is "backward". + Indicates which direction of the forward/backward pair of transforms + is scaled and with what normalization factor. + + .. versionadded:: 1.20.0 + + The "backward", "forward" values were added. + + out : complex ndarray, optional + If provided, the result will be placed in this array. It should be + of the appropriate shape and dtype for all axes (and hence is + incompatible with passing in all but the trivial ``s``). + + .. versionadded:: 2.0.0 + + Returns + ------- + out : complex ndarray + The truncated or zero-padded input, transformed along the axes + indicated by `axes`, or by a combination of `s` and `a`, + as explained in the parameters section above. + The length of the last axis transformed will be ``s[-1]//2+1``, + while the remaining transformed axes will have lengths according to + `s`, or unchanged from the input. + + Raises + ------ + ValueError + If `s` and `axes` have different length. + IndexError + If an element of `axes` is larger than than the number of axes of `a`. + + See Also + -------- + irfftn : The inverse of `rfftn`, i.e. the inverse of the n-dimensional FFT + of real input. + fft : The one-dimensional FFT, with definitions and conventions used. + rfft : The one-dimensional FFT of real input. + fftn : The n-dimensional FFT. + rfft2 : The two-dimensional FFT of real input. + + Notes + ----- + The transform for real input is performed over the last transformation + axis, as by `rfft`, then the transform over the remaining axes is + performed as by `fftn`. The order of the output is as for `rfft` for the + final transformation axis, and as for `fftn` for the remaining + transformation axes. + + See `fft` for details, definitions and conventions used. + + Examples + -------- + >>> import numpy as np + >>> a = np.ones((2, 2, 2)) + >>> np.fft.rfftn(a) + array([[[8.+0.j, 0.+0.j], # may vary + [0.+0.j, 0.+0.j]], + [[0.+0.j, 0.+0.j], + [0.+0.j, 0.+0.j]]]) + + >>> np.fft.rfftn(a, axes=(2, 0)) + array([[[4.+0.j, 0.+0.j], # may vary + [4.+0.j, 0.+0.j]], + [[0.+0.j, 0.+0.j], + [0.+0.j, 0.+0.j]]]) + + """ + a = asarray(a) + s, axes = _cook_nd_args(a, s, axes) + a = rfft(a, s[-1], axes[-1], norm, out=out) + for ii in range(len(axes) - 2, -1, -1): + a = fft(a, s[ii], axes[ii], norm, out=out) + return a + + +@array_function_dispatch(_fftn_dispatcher) +def rfft2(a, s=None, axes=(-2, -1), norm=None, out=None): + """ + Compute the 2-dimensional FFT of a real array. + + Parameters + ---------- + a : array + Input array, taken to be real. + s : sequence of ints, optional + Shape of the FFT. + + .. versionchanged:: 2.0 + + If it is ``-1``, the whole input is used (no padding/trimming). + + .. deprecated:: 2.0 + + If `s` is not ``None``, `axes` must not be ``None`` either. + + .. deprecated:: 2.0 + + `s` must contain only ``int`` s, not ``None`` values. ``None`` + values currently mean that the default value for ``n`` is used + in the corresponding 1-D transform, but this behaviour is + deprecated. + + axes : sequence of ints, optional + Axes over which to compute the FFT. Default: ``(-2, -1)``. + + .. deprecated:: 2.0 + + If `s` is specified, the corresponding `axes` to be transformed + must not be ``None``. + + norm : {"backward", "ortho", "forward"}, optional + Normalization mode (see `numpy.fft`). Default is "backward". + Indicates which direction of the forward/backward pair of transforms + is scaled and with what normalization factor. + + .. versionadded:: 1.20.0 + + The "backward", "forward" values were added. + + out : complex ndarray, optional + If provided, the result will be placed in this array. It should be + of the appropriate shape and dtype for the last inverse transform. + incompatible with passing in all but the trivial ``s``). + + .. versionadded:: 2.0.0 + + Returns + ------- + out : ndarray + The result of the real 2-D FFT. + + See Also + -------- + rfftn : Compute the N-dimensional discrete Fourier Transform for real + input. + + Notes + ----- + This is really just `rfftn` with different default behavior. + For more details see `rfftn`. + + Examples + -------- + >>> import numpy as np + >>> a = np.mgrid[:5, :5][0] + >>> np.fft.rfft2(a) + array([[ 50. +0.j , 0. +0.j , 0. +0.j ], + [-12.5+17.20477401j, 0. +0.j , 0. +0.j ], + [-12.5 +4.0614962j , 0. +0.j , 0. +0.j ], + [-12.5 -4.0614962j , 0. +0.j , 0. +0.j ], + [-12.5-17.20477401j, 0. +0.j , 0. +0.j ]]) + """ + return rfftn(a, s, axes, norm, out=out) + + +@array_function_dispatch(_fftn_dispatcher) +def irfftn(a, s=None, axes=None, norm=None, out=None): + """ + Computes the inverse of `rfftn`. + + This function computes the inverse of the N-dimensional discrete + Fourier Transform for real input over any number of axes in an + M-dimensional array by means of the Fast Fourier Transform (FFT). In + other words, ``irfftn(rfftn(a), a.shape) == a`` to within numerical + accuracy. (The ``a.shape`` is necessary like ``len(a)`` is for `irfft`, + and for the same reason.) + + The input should be ordered in the same way as is returned by `rfftn`, + i.e. as for `irfft` for the final transformation axis, and as for `ifftn` + along all the other axes. + + Parameters + ---------- + a : array_like + Input array. + s : sequence of ints, optional + Shape (length of each transformed axis) of the output + (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.). `s` is also the + number of input points used along this axis, except for the last axis, + where ``s[-1]//2+1`` points of the input are used. + Along any axis, if the shape indicated by `s` is smaller than that of + the input, the input is cropped. If it is larger, the input is padded + with zeros. + + .. versionchanged:: 2.0 + + If it is ``-1``, the whole input is used (no padding/trimming). + + If `s` is not given, the shape of the input along the axes + specified by axes is used. Except for the last axis which is taken to + be ``2*(m-1)`` where ``m`` is the length of the input along that axis. + + .. deprecated:: 2.0 + + If `s` is not ``None``, `axes` must not be ``None`` either. + + .. deprecated:: 2.0 + + `s` must contain only ``int`` s, not ``None`` values. ``None`` + values currently mean that the default value for ``n`` is used + in the corresponding 1-D transform, but this behaviour is + deprecated. + + axes : sequence of ints, optional + Axes over which to compute the inverse FFT. If not given, the last + `len(s)` axes are used, or all axes if `s` is also not specified. + Repeated indices in `axes` means that the inverse transform over that + axis is performed multiple times. + + .. deprecated:: 2.0 + + If `s` is specified, the corresponding `axes` to be transformed + must be explicitly specified too. + + norm : {"backward", "ortho", "forward"}, optional + Normalization mode (see `numpy.fft`). Default is "backward". + Indicates which direction of the forward/backward pair of transforms + is scaled and with what normalization factor. + + .. versionadded:: 1.20.0 + + The "backward", "forward" values were added. + + out : ndarray, optional + If provided, the result will be placed in this array. It should be + of the appropriate shape and dtype for the last transformation. + + .. versionadded:: 2.0.0 + + Returns + ------- + out : ndarray + The truncated or zero-padded input, transformed along the axes + indicated by `axes`, or by a combination of `s` or `a`, + as explained in the parameters section above. + The length of each transformed axis is as given by the corresponding + element of `s`, or the length of the input in every axis except for the + last one if `s` is not given. In the final transformed axis the length + of the output when `s` is not given is ``2*(m-1)`` where ``m`` is the + length of the final transformed axis of the input. To get an odd + number of output points in the final axis, `s` must be specified. + + Raises + ------ + ValueError + If `s` and `axes` have different length. + IndexError + If an element of `axes` is larger than than the number of axes of `a`. + + See Also + -------- + rfftn : The forward n-dimensional FFT of real input, + of which `ifftn` is the inverse. + fft : The one-dimensional FFT, with definitions and conventions used. + irfft : The inverse of the one-dimensional FFT of real input. + irfft2 : The inverse of the two-dimensional FFT of real input. + + Notes + ----- + See `fft` for definitions and conventions used. + + See `rfft` for definitions and conventions used for real input. + + The correct interpretation of the hermitian input depends on the shape of + the original data, as given by `s`. This is because each input shape could + correspond to either an odd or even length signal. By default, `irfftn` + assumes an even output length which puts the last entry at the Nyquist + frequency; aliasing with its symmetric counterpart. When performing the + final complex to real transform, the last value is thus treated as purely + real. To avoid losing information, the correct shape of the real input + **must** be given. + + Examples + -------- + >>> import numpy as np + >>> a = np.zeros((3, 2, 2)) + >>> a[0, 0, 0] = 3 * 2 * 2 + >>> np.fft.irfftn(a) + array([[[1., 1.], + [1., 1.]], + [[1., 1.], + [1., 1.]], + [[1., 1.], + [1., 1.]]]) + + """ + a = asarray(a) + s, axes = _cook_nd_args(a, s, axes, invreal=1) + for ii in range(len(axes) - 1): + a = ifft(a, s[ii], axes[ii], norm) + a = irfft(a, s[-1], axes[-1], norm, out=out) + return a + + +@array_function_dispatch(_fftn_dispatcher) +def irfft2(a, s=None, axes=(-2, -1), norm=None, out=None): + """ + Computes the inverse of `rfft2`. + + Parameters + ---------- + a : array_like + The input array + s : sequence of ints, optional + Shape of the real output to the inverse FFT. + + .. versionchanged:: 2.0 + + If it is ``-1``, the whole input is used (no padding/trimming). + + .. deprecated:: 2.0 + + If `s` is not ``None``, `axes` must not be ``None`` either. + + .. deprecated:: 2.0 + + `s` must contain only ``int`` s, not ``None`` values. ``None`` + values currently mean that the default value for ``n`` is used + in the corresponding 1-D transform, but this behaviour is + deprecated. + + axes : sequence of ints, optional + The axes over which to compute the inverse fft. + Default: ``(-2, -1)``, the last two axes. + + .. deprecated:: 2.0 + + If `s` is specified, the corresponding `axes` to be transformed + must not be ``None``. + + norm : {"backward", "ortho", "forward"}, optional + Normalization mode (see `numpy.fft`). Default is "backward". + Indicates which direction of the forward/backward pair of transforms + is scaled and with what normalization factor. + + .. versionadded:: 1.20.0 + + The "backward", "forward" values were added. + + out : ndarray, optional + If provided, the result will be placed in this array. It should be + of the appropriate shape and dtype for the last transformation. + + .. versionadded:: 2.0.0 + + Returns + ------- + out : ndarray + The result of the inverse real 2-D FFT. + + See Also + -------- + rfft2 : The forward two-dimensional FFT of real input, + of which `irfft2` is the inverse. + rfft : The one-dimensional FFT for real input. + irfft : The inverse of the one-dimensional FFT of real input. + irfftn : Compute the inverse of the N-dimensional FFT of real input. + + Notes + ----- + This is really `irfftn` with different defaults. + For more details see `irfftn`. + + Examples + -------- + >>> import numpy as np + >>> a = np.mgrid[:5, :5][0] + >>> A = np.fft.rfft2(a) + >>> np.fft.irfft2(A, s=a.shape) + array([[0., 0., 0., 0., 0.], + [1., 1., 1., 1., 1.], + [2., 2., 2., 2., 2.], + [3., 3., 3., 3., 3.], + [4., 4., 4., 4., 4.]]) + """ + return irfftn(a, s, axes, norm, out=None) diff --git a/python/user_packages/Python313/site-packages/numpy/fft/_pocketfft.pyi b/python/user_packages/Python313/site-packages/numpy/fft/_pocketfft.pyi new file mode 100644 index 0000000000000000000000000000000000000000..8dd1b43f0ff11b3441555bbeaaad6145bc64a052 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/fft/_pocketfft.pyi @@ -0,0 +1,137 @@ +from collections.abc import Sequence +from typing import Literal as L, TypeAlias + +from numpy import complex128, float64 +from numpy._typing import ArrayLike, NDArray, _ArrayLikeNumber_co + +__all__ = [ + "fft", + "ifft", + "rfft", + "irfft", + "hfft", + "ihfft", + "rfftn", + "irfftn", + "rfft2", + "irfft2", + "fft2", + "ifft2", + "fftn", + "ifftn", +] + +_NormKind: TypeAlias = L["backward", "ortho", "forward"] | None + +def fft( + a: ArrayLike, + n: int | None = None, + axis: int = -1, + norm: _NormKind = None, + out: NDArray[complex128] | None = None, +) -> NDArray[complex128]: ... + +def ifft( + a: ArrayLike, + n: int | None = None, + axis: int = -1, + norm: _NormKind = None, + out: NDArray[complex128] | None = None, +) -> NDArray[complex128]: ... + +def rfft( + a: ArrayLike, + n: int | None = None, + axis: int = -1, + norm: _NormKind = None, + out: NDArray[complex128] | None = None, +) -> NDArray[complex128]: ... + +def irfft( + a: ArrayLike, + n: int | None = None, + axis: int = -1, + norm: _NormKind = None, + out: NDArray[float64] | None = None, +) -> NDArray[float64]: ... + +# Input array must be compatible with `np.conjugate` +def hfft( + a: _ArrayLikeNumber_co, + n: int | None = None, + axis: int = -1, + norm: _NormKind = None, + out: NDArray[float64] | None = None, +) -> NDArray[float64]: ... + +def ihfft( + a: ArrayLike, + n: int | None = None, + axis: int = -1, + norm: _NormKind = None, + out: NDArray[complex128] | None = None, +) -> NDArray[complex128]: ... + +def fftn( + a: ArrayLike, + s: Sequence[int] | None = None, + axes: Sequence[int] | None = None, + norm: _NormKind = None, + out: NDArray[complex128] | None = None, +) -> NDArray[complex128]: ... + +def ifftn( + a: ArrayLike, + s: Sequence[int] | None = None, + axes: Sequence[int] | None = None, + norm: _NormKind = None, + out: NDArray[complex128] | None = None, +) -> NDArray[complex128]: ... + +def rfftn( + a: ArrayLike, + s: Sequence[int] | None = None, + axes: Sequence[int] | None = None, + norm: _NormKind = None, + out: NDArray[complex128] | None = None, +) -> NDArray[complex128]: ... + +def irfftn( + a: ArrayLike, + s: Sequence[int] | None = None, + axes: Sequence[int] | None = None, + norm: _NormKind = None, + out: NDArray[float64] | None = None, +) -> NDArray[float64]: ... + +def fft2( + a: ArrayLike, + s: Sequence[int] | None = None, + axes: Sequence[int] | None = (-2, -1), + norm: _NormKind = None, + out: NDArray[complex128] | None = None, +) -> NDArray[complex128]: ... + +def ifft2( + a: ArrayLike, + s: Sequence[int] | None = None, + axes: Sequence[int] | None = (-2, -1), + norm: _NormKind = None, + out: NDArray[complex128] | None = None, +) -> NDArray[complex128]: ... + +def rfft2( + a: ArrayLike, + s: Sequence[int] | None = None, + axes: Sequence[int] | None = (-2, -1), + norm: _NormKind = None, + out: NDArray[complex128] | None = None, +) -> NDArray[complex128]: ... + +def irfft2( + a: ArrayLike, + s: Sequence[int] | None = None, + axes: Sequence[int] | None = (-2, -1), + norm: _NormKind = None, + out: NDArray[float64] | None = None, +) -> NDArray[float64]: ... diff --git a/python/user_packages/Python313/site-packages/numpy/fft/_pocketfft_umath.cp313-win_amd64.lib b/python/user_packages/Python313/site-packages/numpy/fft/_pocketfft_umath.cp313-win_amd64.lib new file mode 100644 index 0000000000000000000000000000000000000000..c475d20a36e1940345accb1b0afbf5058b85a60e Binary files /dev/null and b/python/user_packages/Python313/site-packages/numpy/fft/_pocketfft_umath.cp313-win_amd64.lib differ diff --git a/python/user_packages/Python313/site-packages/numpy/lib/__init__.py b/python/user_packages/Python313/site-packages/numpy/lib/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e38e7e7c6e05db903d270eff6a3a67188f294dac --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/lib/__init__.py @@ -0,0 +1,97 @@ +""" +``numpy.lib`` is mostly a space for implementing functions that don't +belong in core or in another NumPy submodule with a clear purpose +(e.g. ``random``, ``fft``, ``linalg``, ``ma``). + +``numpy.lib``'s private submodules contain basic functions that are used by +other public modules and are useful to have in the main name-space. + +""" + +# Public submodules +# Note: recfunctions is public, but not imported +from numpy._core._multiarray_umath import add_docstring, tracemalloc_domain +from numpy._core.function_base import add_newdoc + +# Private submodules +# load module names. See https://github.com/networkx/networkx/issues/5838 +from . import ( + _arraypad_impl, + _arraysetops_impl, + _arrayterator_impl, + _function_base_impl, + _histograms_impl, + _index_tricks_impl, + _nanfunctions_impl, + _npyio_impl, + _polynomial_impl, + _shape_base_impl, + _stride_tricks_impl, + _twodim_base_impl, + _type_check_impl, + _ufunclike_impl, + _utils_impl, + _version, + array_utils, + format, + introspect, + mixins, + npyio, + scimath, + stride_tricks, +) + +# numpy.lib namespace members +from ._arrayterator_impl import Arrayterator +from ._version import NumpyVersion + +__all__ = [ + "Arrayterator", "add_docstring", "add_newdoc", "array_utils", + "format", "introspect", "mixins", "NumpyVersion", "npyio", "scimath", + "stride_tricks", "tracemalloc_domain", +] + +add_newdoc.__module__ = "numpy.lib" + +from numpy._pytesttester import PytestTester + +test = PytestTester(__name__) +del PytestTester + +def __getattr__(attr): + # Warn for deprecated/removed aliases + import math + import warnings + + if attr == "math": + warnings.warn( + "`np.lib.math` is a deprecated alias for the standard library " + "`math` module (Deprecated Numpy 1.25). Replace usages of " + "`numpy.lib.math` with `math`", DeprecationWarning, stacklevel=2) + return math + elif attr == "emath": + raise AttributeError( + "numpy.lib.emath was an alias for emath module that was removed " + "in NumPy 2.0. Replace usages of numpy.lib.emath with " + "numpy.emath.", + name=None + ) + elif attr in ( + "histograms", "type_check", "nanfunctions", "function_base", + "arraypad", "arraysetops", "ufunclike", "utils", "twodim_base", + "shape_base", "polynomial", "index_tricks", + ): + raise AttributeError( + f"numpy.lib.{attr} is now private. If you are using a public " + "function, it should be available in the main numpy namespace, " + "otherwise check the NumPy 2.0 migration guide.", + name=None + ) + elif attr == "arrayterator": + raise AttributeError( + "numpy.lib.arrayterator submodule is now private. To access " + "Arrayterator class use numpy.lib.Arrayterator.", + name=None + ) + else: + raise AttributeError(f"module {__name__!r} has no attribute {attr!r}") diff --git a/python/user_packages/Python313/site-packages/numpy/lib/__init__.pyi b/python/user_packages/Python313/site-packages/numpy/lib/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..a0794c21512966a7c52621cc416067bc4e39936c --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/lib/__init__.pyi @@ -0,0 +1,52 @@ +from numpy._core.function_base import add_newdoc +from numpy._core.multiarray import add_docstring, tracemalloc_domain + +# all submodules of `lib` are accessible at runtime through `__getattr__`, +# so we implicitly re-export them here +from . import ( + _array_utils_impl as _array_utils_impl, + _arraypad_impl as _arraypad_impl, + _arraysetops_impl as _arraysetops_impl, + _arrayterator_impl as _arrayterator_impl, + _datasource as _datasource, + _format_impl as _format_impl, + _function_base_impl as _function_base_impl, + _histograms_impl as _histograms_impl, + _index_tricks_impl as _index_tricks_impl, + _iotools as _iotools, + _nanfunctions_impl as _nanfunctions_impl, + _npyio_impl as _npyio_impl, + _polynomial_impl as _polynomial_impl, + _scimath_impl as _scimath_impl, + _shape_base_impl as _shape_base_impl, + _stride_tricks_impl as _stride_tricks_impl, + _twodim_base_impl as _twodim_base_impl, + _type_check_impl as _type_check_impl, + _ufunclike_impl as _ufunclike_impl, + _utils_impl as _utils_impl, + _version as _version, + array_utils, + format, + introspect, + mixins, + npyio, + scimath, + stride_tricks, +) +from ._arrayterator_impl import Arrayterator +from ._version import NumpyVersion + +__all__ = [ + "Arrayterator", + "add_docstring", + "add_newdoc", + "array_utils", + "format", + "introspect", + "mixins", + "NumpyVersion", + "npyio", + "scimath", + "stride_tricks", + "tracemalloc_domain", +] diff --git a/python/user_packages/Python313/site-packages/numpy/lib/_array_utils_impl.py b/python/user_packages/Python313/site-packages/numpy/lib/_array_utils_impl.py new file mode 100644 index 0000000000000000000000000000000000000000..3fa8210a69eaff9521b79a50abff792860546a8a --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/lib/_array_utils_impl.py @@ -0,0 +1,62 @@ +""" +Miscellaneous utils. +""" +from numpy._core import asarray +from numpy._core.numeric import normalize_axis_index, normalize_axis_tuple +from numpy._utils import set_module + +__all__ = ["byte_bounds", "normalize_axis_tuple", "normalize_axis_index"] + + +@set_module("numpy.lib.array_utils") +def byte_bounds(a): + """ + Returns pointers to the end-points of an array. + + Parameters + ---------- + a : ndarray + Input array. It must conform to the Python-side of the array + interface. + + Returns + ------- + (low, high) : tuple of 2 integers + The first integer is the first byte of the array, the second + integer is just past the last byte of the array. If `a` is not + contiguous it will not use every byte between the (`low`, `high`) + values. + + Examples + -------- + >>> import numpy as np + >>> I = np.eye(2, dtype='f'); I.dtype + dtype('float32') + >>> low, high = np.lib.array_utils.byte_bounds(I) + >>> high - low == I.size*I.itemsize + True + >>> I = np.eye(2); I.dtype + dtype('float64') + >>> low, high = np.lib.array_utils.byte_bounds(I) + >>> high - low == I.size*I.itemsize + True + + """ + ai = a.__array_interface__ + a_data = ai['data'][0] + astrides = ai['strides'] + ashape = ai['shape'] + bytes_a = asarray(a).dtype.itemsize + + a_low = a_high = a_data + if astrides is None: + # contiguous case + a_high += a.size * bytes_a + else: + for shape, stride in zip(ashape, astrides): + if stride < 0: + a_low += (shape - 1) * stride + else: + a_high += (shape - 1) * stride + a_high += bytes_a + return a_low, a_high diff --git a/python/user_packages/Python313/site-packages/numpy/lib/_array_utils_impl.pyi b/python/user_packages/Python313/site-packages/numpy/lib/_array_utils_impl.pyi new file mode 100644 index 0000000000000000000000000000000000000000..999594d037e3fe53cc8c18bfe1d3da04136ea84f --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/lib/_array_utils_impl.pyi @@ -0,0 +1,10 @@ +import numpy as np +from numpy._core.numeric import normalize_axis_index, normalize_axis_tuple + +__all__ = ["byte_bounds", "normalize_axis_tuple", "normalize_axis_index"] + +# NOTE: In practice `byte_bounds` can (potentially) take any object +# implementing the `__array_interface__` protocol. The caveat is +# that certain keys, marked as optional in the spec, must be present for +# `byte_bounds`. This concerns `"strides"` and `"data"`. +def byte_bounds(a: np.generic | np.ndarray) -> tuple[int, int]: ... diff --git a/python/user_packages/Python313/site-packages/numpy/lib/_arraypad_impl.py b/python/user_packages/Python313/site-packages/numpy/lib/_arraypad_impl.py new file mode 100644 index 0000000000000000000000000000000000000000..01516351fcc76803e0626d73ba9426b9253a3482 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/lib/_arraypad_impl.py @@ -0,0 +1,926 @@ +""" +The arraypad module contains a group of functions to pad values onto the edges +of an n-dimensional array. + +""" +import typing + +import numpy as np +from numpy._core.overrides import array_function_dispatch +from numpy.lib._index_tricks_impl import ndindex + +__all__ = ['pad'] + + +############################################################################### +# Private utility functions. + + +def _round_if_needed(arr, dtype): + """ + Rounds arr inplace if destination dtype is integer. + + Parameters + ---------- + arr : ndarray + Input array. + dtype : dtype + The dtype of the destination array. + """ + if np.issubdtype(dtype, np.integer): + arr.round(out=arr) + + +def _slice_at_axis(sl, axis): + """ + Construct tuple of slices to slice an array in the given dimension. + + Parameters + ---------- + sl : slice + The slice for the given dimension. + axis : int + The axis to which `sl` is applied. All other dimensions are left + "unsliced". + + Returns + ------- + sl : tuple of slices + A tuple with slices matching `shape` in length. + + Examples + -------- + >>> np._slice_at_axis(slice(None, 3, -1), 1) + (slice(None, None, None), slice(None, 3, -1), (...,)) + """ + return (slice(None),) * axis + (sl,) + (...,) + + +def _view_roi(array, original_area_slice, axis): + """ + Get a view of the current region of interest during iterative padding. + + When padding multiple dimensions iteratively corner values are + unnecessarily overwritten multiple times. This function reduces the + working area for the first dimensions so that corners are excluded. + + Parameters + ---------- + array : ndarray + The array with the region of interest. + original_area_slice : tuple of slices + Denotes the area with original values of the unpadded array. + axis : int + The currently padded dimension assuming that `axis` is padded before + `axis` + 1. + + Returns + ------- + roi : ndarray + The region of interest of the original `array`. + """ + axis += 1 + sl = (slice(None),) * axis + original_area_slice[axis:] + return array[sl] + + +def _pad_simple(array, pad_width, fill_value=None): + """ + Pad array on all sides with either a single value or undefined values. + + Parameters + ---------- + array : ndarray + Array to grow. + pad_width : sequence of tuple[int, int] + Pad width on both sides for each dimension in `arr`. + fill_value : scalar, optional + If provided the padded area is filled with this value, otherwise + the pad area left undefined. + + Returns + ------- + padded : ndarray + The padded array with the same dtype as`array`. Its order will default + to C-style if `array` is not F-contiguous. + original_area_slice : tuple + A tuple of slices pointing to the area of the original array. + """ + # Allocate grown array + new_shape = tuple( + left + size + right + for size, (left, right) in zip(array.shape, pad_width) + ) + order = 'F' if array.flags.fnc else 'C' # Fortran and not also C-order + padded = np.empty(new_shape, dtype=array.dtype, order=order) + + if fill_value is not None: + padded.fill(fill_value) + + # Copy old array into correct space + original_area_slice = tuple( + slice(left, left + size) + for size, (left, right) in zip(array.shape, pad_width) + ) + padded[original_area_slice] = array + + return padded, original_area_slice + + +def _set_pad_area(padded, axis, width_pair, value_pair): + """ + Set empty-padded area in given dimension. + + Parameters + ---------- + padded : ndarray + Array with the pad area which is modified inplace. + axis : int + Dimension with the pad area to set. + width_pair : (int, int) + Pair of widths that mark the pad area on both sides in the given + dimension. + value_pair : tuple of scalars or ndarrays + Values inserted into the pad area on each side. It must match or be + broadcastable to the shape of `arr`. + """ + left_slice = _slice_at_axis(slice(None, width_pair[0]), axis) + padded[left_slice] = value_pair[0] + + right_slice = _slice_at_axis( + slice(padded.shape[axis] - width_pair[1], None), axis) + padded[right_slice] = value_pair[1] + + +def _get_edges(padded, axis, width_pair): + """ + Retrieve edge values from empty-padded array in given dimension. + + Parameters + ---------- + padded : ndarray + Empty-padded array. + axis : int + Dimension in which the edges are considered. + width_pair : (int, int) + Pair of widths that mark the pad area on both sides in the given + dimension. + + Returns + ------- + left_edge, right_edge : ndarray + Edge values of the valid area in `padded` in the given dimension. Its + shape will always match `padded` except for the dimension given by + `axis` which will have a length of 1. + """ + left_index = width_pair[0] + left_slice = _slice_at_axis(slice(left_index, left_index + 1), axis) + left_edge = padded[left_slice] + + right_index = padded.shape[axis] - width_pair[1] + right_slice = _slice_at_axis(slice(right_index - 1, right_index), axis) + right_edge = padded[right_slice] + + return left_edge, right_edge + + +def _get_linear_ramps(padded, axis, width_pair, end_value_pair): + """ + Construct linear ramps for empty-padded array in given dimension. + + Parameters + ---------- + padded : ndarray + Empty-padded array. + axis : int + Dimension in which the ramps are constructed. + width_pair : (int, int) + Pair of widths that mark the pad area on both sides in the given + dimension. + end_value_pair : (scalar, scalar) + End values for the linear ramps which form the edge of the fully padded + array. These values are included in the linear ramps. + + Returns + ------- + left_ramp, right_ramp : ndarray + Linear ramps to set on both sides of `padded`. + """ + edge_pair = _get_edges(padded, axis, width_pair) + + left_ramp, right_ramp = ( + np.linspace( + start=end_value, + stop=edge.squeeze(axis), # Dimension is replaced by linspace + num=width, + endpoint=False, + dtype=padded.dtype, + axis=axis + ) + for end_value, edge, width in zip( + end_value_pair, edge_pair, width_pair + ) + ) + + # Reverse linear space in appropriate dimension + right_ramp = right_ramp[_slice_at_axis(slice(None, None, -1), axis)] + + return left_ramp, right_ramp + + +def _get_stats(padded, axis, width_pair, length_pair, stat_func): + """ + Calculate statistic for the empty-padded array in given dimension. + + Parameters + ---------- + padded : ndarray + Empty-padded array. + axis : int + Dimension in which the statistic is calculated. + width_pair : (int, int) + Pair of widths that mark the pad area on both sides in the given + dimension. + length_pair : 2-element sequence of None or int + Gives the number of values in valid area from each side that is + taken into account when calculating the statistic. If None the entire + valid area in `padded` is considered. + stat_func : function + Function to compute statistic. The expected signature is + ``stat_func(x: ndarray, axis: int, keepdims: bool) -> ndarray``. + + Returns + ------- + left_stat, right_stat : ndarray + Calculated statistic for both sides of `padded`. + """ + # Calculate indices of the edges of the area with original values + left_index = width_pair[0] + right_index = padded.shape[axis] - width_pair[1] + # as well as its length + max_length = right_index - left_index + + # Limit stat_lengths to max_length + left_length, right_length = length_pair + if left_length is None or max_length < left_length: + left_length = max_length + if right_length is None or max_length < right_length: + right_length = max_length + + if (left_length == 0 or right_length == 0) \ + and stat_func in {np.amax, np.amin}: + # amax and amin can't operate on an empty array, + # raise a more descriptive warning here instead of the default one + raise ValueError("stat_length of 0 yields no value for padding") + + # Calculate statistic for the left side + left_slice = _slice_at_axis( + slice(left_index, left_index + left_length), axis) + left_chunk = padded[left_slice] + left_stat = stat_func(left_chunk, axis=axis, keepdims=True) + _round_if_needed(left_stat, padded.dtype) + + if left_length == right_length == max_length: + # return early as right_stat must be identical to left_stat + return left_stat, left_stat + + # Calculate statistic for the right side + right_slice = _slice_at_axis( + slice(right_index - right_length, right_index), axis) + right_chunk = padded[right_slice] + right_stat = stat_func(right_chunk, axis=axis, keepdims=True) + _round_if_needed(right_stat, padded.dtype) + + return left_stat, right_stat + + +def _set_reflect_both(padded, axis, width_pair, method, + original_period, include_edge=False): + """ + Pad `axis` of `arr` with reflection. + + Parameters + ---------- + padded : ndarray + Input array of arbitrary shape. + axis : int + Axis along which to pad `arr`. + width_pair : (int, int) + Pair of widths that mark the pad area on both sides in the given + dimension. + method : str + Controls method of reflection; options are 'even' or 'odd'. + original_period : int + Original length of data on `axis` of `arr`. + include_edge : bool + If true, edge value is included in reflection, otherwise the edge + value forms the symmetric axis to the reflection. + + Returns + ------- + pad_amt : tuple of ints, length 2 + New index positions of padding to do along the `axis`. If these are + both 0, padding is done in this dimension. + """ + left_pad, right_pad = width_pair + old_length = padded.shape[axis] - right_pad - left_pad + + if include_edge: + # Avoid wrapping with only a subset of the original area + # by ensuring period can only be a multiple of the original + # area's length. + old_length = old_length // original_period * original_period + # Edge is included, we need to offset the pad amount by 1 + edge_offset = 1 + else: + # Avoid wrapping with only a subset of the original area + # by ensuring period can only be a multiple of the original + # area's length. + old_length = ((old_length - 1) // (original_period - 1) + * (original_period - 1) + 1) + edge_offset = 0 # Edge is not included, no need to offset pad amount + old_length -= 1 # but must be omitted from the chunk + + if left_pad > 0: + # Pad with reflected values on left side: + # First limit chunk size which can't be larger than pad area + chunk_length = min(old_length, left_pad) + # Slice right to left, stop on or next to edge, start relative to stop + stop = left_pad - edge_offset + start = stop + chunk_length + left_slice = _slice_at_axis(slice(start, stop, -1), axis) + left_chunk = padded[left_slice] + + if method == "odd": + # Negate chunk and align with edge + edge_slice = _slice_at_axis(slice(left_pad, left_pad + 1), axis) + left_chunk = 2 * padded[edge_slice] - left_chunk + + # Insert chunk into padded area + start = left_pad - chunk_length + stop = left_pad + pad_area = _slice_at_axis(slice(start, stop), axis) + padded[pad_area] = left_chunk + # Adjust pointer to left edge for next iteration + left_pad -= chunk_length + + if right_pad > 0: + # Pad with reflected values on right side: + # First limit chunk size which can't be larger than pad area + chunk_length = min(old_length, right_pad) + # Slice right to left, start on or next to edge, stop relative to start + start = -right_pad + edge_offset - 2 + stop = start - chunk_length + right_slice = _slice_at_axis(slice(start, stop, -1), axis) + right_chunk = padded[right_slice] + + if method == "odd": + # Negate chunk and align with edge + edge_slice = _slice_at_axis( + slice(-right_pad - 1, -right_pad), axis) + right_chunk = 2 * padded[edge_slice] - right_chunk + + # Insert chunk into padded area + start = padded.shape[axis] - right_pad + stop = start + chunk_length + pad_area = _slice_at_axis(slice(start, stop), axis) + padded[pad_area] = right_chunk + # Adjust pointer to right edge for next iteration + right_pad -= chunk_length + + return left_pad, right_pad + + +def _set_wrap_both(padded, axis, width_pair, original_period): + """ + Pad `axis` of `arr` with wrapped values. + + Parameters + ---------- + padded : ndarray + Input array of arbitrary shape. + axis : int + Axis along which to pad `arr`. + width_pair : (int, int) + Pair of widths that mark the pad area on both sides in the given + dimension. + original_period : int + Original length of data on `axis` of `arr`. + + Returns + ------- + pad_amt : tuple of ints, length 2 + New index positions of padding to do along the `axis`. If these are + both 0, padding is done in this dimension. + """ + left_pad, right_pad = width_pair + period = padded.shape[axis] - right_pad - left_pad + # Avoid wrapping with only a subset of the original area by ensuring period + # can only be a multiple of the original area's length. + period = period // original_period * original_period + + # If the current dimension of `arr` doesn't contain enough valid values + # (not part of the undefined pad area) we need to pad multiple times. + # Each time the pad area shrinks on both sides which is communicated with + # these variables. + new_left_pad = 0 + new_right_pad = 0 + + if left_pad > 0: + # Pad with wrapped values on left side + # First slice chunk from left side of the non-pad area. + # Use min(period, left_pad) to ensure that chunk is not larger than + # pad area. + slice_end = left_pad + period + slice_start = slice_end - min(period, left_pad) + right_slice = _slice_at_axis(slice(slice_start, slice_end), axis) + right_chunk = padded[right_slice] + + if left_pad > period: + # Chunk is smaller than pad area + pad_area = _slice_at_axis(slice(left_pad - period, left_pad), axis) + new_left_pad = left_pad - period + else: + # Chunk matches pad area + pad_area = _slice_at_axis(slice(None, left_pad), axis) + padded[pad_area] = right_chunk + + if right_pad > 0: + # Pad with wrapped values on right side + # First slice chunk from right side of the non-pad area. + # Use min(period, right_pad) to ensure that chunk is not larger than + # pad area. + slice_start = -right_pad - period + slice_end = slice_start + min(period, right_pad) + left_slice = _slice_at_axis(slice(slice_start, slice_end), axis) + left_chunk = padded[left_slice] + + if right_pad > period: + # Chunk is smaller than pad area + pad_area = _slice_at_axis( + slice(-right_pad, -right_pad + period), axis) + new_right_pad = right_pad - period + else: + # Chunk matches pad area + pad_area = _slice_at_axis(slice(-right_pad, None), axis) + padded[pad_area] = left_chunk + + return new_left_pad, new_right_pad + + +def _as_pairs(x, ndim, as_index=False): + """ + Broadcast `x` to an array with the shape (`ndim`, 2). + + A helper function for `pad` that prepares and validates arguments like + `pad_width` for iteration in pairs. + + Parameters + ---------- + x : {None, scalar, array-like} + The object to broadcast to the shape (`ndim`, 2). + ndim : int + Number of pairs the broadcasted `x` will have. + as_index : bool, optional + If `x` is not None, try to round each element of `x` to an integer + (dtype `np.intp`) and ensure every element is positive. + + Returns + ------- + pairs : nested iterables, shape (`ndim`, 2) + The broadcasted version of `x`. + + Raises + ------ + ValueError + If `as_index` is True and `x` contains negative elements. + Or if `x` is not broadcastable to the shape (`ndim`, 2). + """ + if x is None: + # Pass through None as a special case, otherwise np.round(x) fails + # with an AttributeError + return ((None, None),) * ndim + + x = np.array(x) + if as_index: + x = np.round(x).astype(np.intp, copy=False) + + if x.ndim < 3: + # Optimization: Possibly use faster paths for cases where `x` has + # only 1 or 2 elements. `np.broadcast_to` could handle these as well + # but is currently slower + + if x.size == 1: + # x was supplied as a single value + x = x.ravel() # Ensure x[0] works for x.ndim == 0, 1, 2 + if as_index and x < 0: + raise ValueError("index can't contain negative values") + return ((x[0], x[0]),) * ndim + + if x.size == 2 and x.shape != (2, 1): + # x was supplied with a single value for each side + # but except case when each dimension has a single value + # which should be broadcasted to a pair, + # e.g. [[1], [2]] -> [[1, 1], [2, 2]] not [[1, 2], [1, 2]] + x = x.ravel() # Ensure x[0], x[1] works + if as_index and (x[0] < 0 or x[1] < 0): + raise ValueError("index can't contain negative values") + return ((x[0], x[1]),) * ndim + + if as_index and x.min() < 0: + raise ValueError("index can't contain negative values") + + # Converting the array with `tolist` seems to improve performance + # when iterating and indexing the result (see usage in `pad`) + return np.broadcast_to(x, (ndim, 2)).tolist() + + +def _pad_dispatcher(array, pad_width, mode=None, **kwargs): + return (array,) + + +############################################################################### +# Public functions + + +@array_function_dispatch(_pad_dispatcher, module='numpy') +def pad(array, pad_width, mode='constant', **kwargs): + """ + Pad an array. + + Parameters + ---------- + array : array_like of rank N + The array to pad. + pad_width : {sequence, array_like, int, dict} + Number of values padded to the edges of each axis. + ``((before_1, after_1), ... (before_N, after_N))`` unique pad widths + for each axis. + ``(before, after)`` or ``((before, after),)`` yields same before + and after pad for each axis. + ``(pad,)`` or ``int`` is a shortcut for before = after = pad width + for all axes. + If a ``dict``, each key is an axis and its corresponding value is an ``int`` or + ``int`` pair describing the padding ``(before, after)`` or ``pad`` width for + that axis. + mode : str or function, optional + One of the following string values or a user supplied function. + + 'constant' (default) + Pads with a constant value. + 'edge' + Pads with the edge values of array. + 'linear_ramp' + Pads with the linear ramp between end_value and the + array edge value. + 'maximum' + Pads with the maximum value of all or part of the + vector along each axis. + 'mean' + Pads with the mean value of all or part of the + vector along each axis. + 'median' + Pads with the median value of all or part of the + vector along each axis. + 'minimum' + Pads with the minimum value of all or part of the + vector along each axis. + 'reflect' + Pads with the reflection of the vector mirrored on + the first and last values of the vector along each + axis. + 'symmetric' + Pads with the reflection of the vector mirrored + along the edge of the array. + 'wrap' + Pads with the wrap of the vector along the axis. + The first values are used to pad the end and the + end values are used to pad the beginning. + 'empty' + Pads with undefined values. + + + Padding function, see Notes. + stat_length : sequence or int, optional + Used in 'maximum', 'mean', 'median', and 'minimum'. Number of + values at edge of each axis used to calculate the statistic value. + + ``((before_1, after_1), ... (before_N, after_N))`` unique statistic + lengths for each axis. + + ``(before, after)`` or ``((before, after),)`` yields same before + and after statistic lengths for each axis. + + ``(stat_length,)`` or ``int`` is a shortcut for + ``before = after = statistic`` length for all axes. + + Default is ``None``, to use the entire axis. + constant_values : sequence or scalar, optional + Used in 'constant'. The values to set the padded values for each + axis. + + ``((before_1, after_1), ... (before_N, after_N))`` unique pad constants + for each axis. + + ``(before, after)`` or ``((before, after),)`` yields same before + and after constants for each axis. + + ``(constant,)`` or ``constant`` is a shortcut for + ``before = after = constant`` for all axes. + + Default is 0. + end_values : sequence or scalar, optional + Used in 'linear_ramp'. The values used for the ending value of the + linear_ramp and that will form the edge of the padded array. + + ``((before_1, after_1), ... (before_N, after_N))`` unique end values + for each axis. + + ``(before, after)`` or ``((before, after),)`` yields same before + and after end values for each axis. + + ``(constant,)`` or ``constant`` is a shortcut for + ``before = after = constant`` for all axes. + + Default is 0. + reflect_type : {'even', 'odd'}, optional + Used in 'reflect', and 'symmetric'. The 'even' style is the + default with an unaltered reflection around the edge value. For + the 'odd' style, the extended part of the array is created by + subtracting the reflected values from two times the edge value. + + Returns + ------- + pad : ndarray + Padded array of rank equal to `array` with shape increased + according to `pad_width`. + + Notes + ----- + For an array with rank greater than 1, some of the padding of later + axes is calculated from padding of previous axes. This is easiest to + think about with a rank 2 array where the corners of the padded array + are calculated by using padded values from the first axis. + + The padding function, if used, should modify a rank 1 array in-place. It + has the following signature:: + + padding_func(vector, iaxis_pad_width, iaxis, kwargs) + + where + + vector : ndarray + A rank 1 array already padded with zeros. Padded values are + vector[:iaxis_pad_width[0]] and vector[-iaxis_pad_width[1]:]. + iaxis_pad_width : tuple + A 2-tuple of ints, iaxis_pad_width[0] represents the number of + values padded at the beginning of vector where + iaxis_pad_width[1] represents the number of values padded at + the end of vector. + iaxis : int + The axis currently being calculated. + kwargs : dict + Any keyword arguments the function requires. + + Examples + -------- + >>> import numpy as np + >>> a = [1, 2, 3, 4, 5] + >>> np.pad(a, (2, 3), 'constant', constant_values=(4, 6)) + array([4, 4, 1, ..., 6, 6, 6]) + + >>> np.pad(a, (2, 3), 'edge') + array([1, 1, 1, ..., 5, 5, 5]) + + >>> np.pad(a, (2, 3), 'linear_ramp', end_values=(5, -4)) + array([ 5, 3, 1, 2, 3, 4, 5, 2, -1, -4]) + + >>> np.pad(a, (2,), 'maximum') + array([5, 5, 1, 2, 3, 4, 5, 5, 5]) + + >>> np.pad(a, (2,), 'mean') + array([3, 3, 1, 2, 3, 4, 5, 3, 3]) + + >>> np.pad(a, (2,), 'median') + array([3, 3, 1, 2, 3, 4, 5, 3, 3]) + + >>> a = [[1, 2], [3, 4]] + >>> np.pad(a, ((3, 2), (2, 3)), 'minimum') + array([[1, 1, 1, 2, 1, 1, 1], + [1, 1, 1, 2, 1, 1, 1], + [1, 1, 1, 2, 1, 1, 1], + [1, 1, 1, 2, 1, 1, 1], + [3, 3, 3, 4, 3, 3, 3], + [1, 1, 1, 2, 1, 1, 1], + [1, 1, 1, 2, 1, 1, 1]]) + + >>> a = [1, 2, 3, 4, 5] + >>> np.pad(a, (2, 3), 'reflect') + array([3, 2, 1, 2, 3, 4, 5, 4, 3, 2]) + + >>> np.pad(a, (2, 3), 'reflect', reflect_type='odd') + array([-1, 0, 1, 2, 3, 4, 5, 6, 7, 8]) + + >>> np.pad(a, (2, 3), 'symmetric') + array([2, 1, 1, 2, 3, 4, 5, 5, 4, 3]) + + >>> np.pad(a, (2, 3), 'symmetric', reflect_type='odd') + array([0, 1, 1, 2, 3, 4, 5, 5, 6, 7]) + + >>> np.pad(a, (2, 3), 'wrap') + array([4, 5, 1, 2, 3, 4, 5, 1, 2, 3]) + + >>> def pad_with(vector, pad_width, iaxis, kwargs): + ... pad_value = kwargs.get('padder', 10) + ... vector[:pad_width[0]] = pad_value + ... vector[-pad_width[1]:] = pad_value + >>> a = np.arange(6) + >>> a = a.reshape((2, 3)) + >>> np.pad(a, 2, pad_with) + array([[10, 10, 10, 10, 10, 10, 10], + [10, 10, 10, 10, 10, 10, 10], + [10, 10, 0, 1, 2, 10, 10], + [10, 10, 3, 4, 5, 10, 10], + [10, 10, 10, 10, 10, 10, 10], + [10, 10, 10, 10, 10, 10, 10]]) + >>> np.pad(a, 2, pad_with, padder=100) + array([[100, 100, 100, 100, 100, 100, 100], + [100, 100, 100, 100, 100, 100, 100], + [100, 100, 0, 1, 2, 100, 100], + [100, 100, 3, 4, 5, 100, 100], + [100, 100, 100, 100, 100, 100, 100], + [100, 100, 100, 100, 100, 100, 100]]) + + >>> a = np.arange(1, 7).reshape(2, 3) + >>> np.pad(a, {1: (1, 2)}) + array([[0, 1, 2, 3, 0, 0], + [0, 4, 5, 6, 0, 0]]) + >>> np.pad(a, {-1: 2}) + array([[0, 0, 1, 2, 3, 0, 0], + [0, 0, 4, 5, 6, 0, 0]]) + >>> np.pad(a, {0: (3, 0)}) + array([[0, 0, 0], + [0, 0, 0], + [0, 0, 0], + [1, 2, 3], + [4, 5, 6]]) + >>> np.pad(a, {0: (3, 0), 1: 2}) + array([[0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 2, 3, 0, 0], + [0, 0, 4, 5, 6, 0, 0]]) + """ + array = np.asarray(array) + if isinstance(pad_width, dict): + seq = [(0, 0)] * array.ndim + for axis, width in pad_width.items(): + match width: + case int(both): + seq[axis] = both, both + case tuple((int(before), int(after))): + seq[axis] = before, after + case _ as invalid: + typing.assert_never(invalid) + pad_width = seq + pad_width = np.asarray(pad_width) + + if not pad_width.dtype.kind == 'i': + raise TypeError('`pad_width` must be of integral type.') + + # Broadcast to shape (array.ndim, 2) + pad_width = _as_pairs(pad_width, array.ndim, as_index=True) + + if callable(mode): + # Old behavior: Use user-supplied function with np.apply_along_axis + function = mode + # Create a new zero padded array + padded, _ = _pad_simple(array, pad_width, fill_value=0) + # And apply along each axis + + for axis in range(padded.ndim): + # Iterate using ndindex as in apply_along_axis, but assuming that + # function operates inplace on the padded array. + + # view with the iteration axis at the end + view = np.moveaxis(padded, axis, -1) + + # compute indices for the iteration axes, and append a trailing + # ellipsis to prevent 0d arrays decaying to scalars (gh-8642) + inds = ndindex(view.shape[:-1]) + inds = (ind + (Ellipsis,) for ind in inds) + for ind in inds: + function(view[ind], pad_width[axis], axis, kwargs) + + return padded + + # Make sure that no unsupported keywords were passed for the current mode + allowed_kwargs = { + 'empty': [], 'edge': [], 'wrap': [], + 'constant': ['constant_values'], + 'linear_ramp': ['end_values'], + 'maximum': ['stat_length'], + 'mean': ['stat_length'], + 'median': ['stat_length'], + 'minimum': ['stat_length'], + 'reflect': ['reflect_type'], + 'symmetric': ['reflect_type'], + } + try: + unsupported_kwargs = set(kwargs) - set(allowed_kwargs[mode]) + except KeyError: + raise ValueError(f"mode '{mode}' is not supported") from None + if unsupported_kwargs: + raise ValueError("unsupported keyword arguments for mode " + f"'{mode}': {unsupported_kwargs}") + + stat_functions = {"maximum": np.amax, "minimum": np.amin, + "mean": np.mean, "median": np.median} + + # Create array with final shape and original values + # (padded area is undefined) + padded, original_area_slice = _pad_simple(array, pad_width) + # And prepare iteration over all dimensions + # (zipping may be more readable than using enumerate) + axes = range(padded.ndim) + + if mode == "constant": + values = kwargs.get("constant_values", 0) + values = _as_pairs(values, padded.ndim) + for axis, width_pair, value_pair in zip(axes, pad_width, values): + roi = _view_roi(padded, original_area_slice, axis) + _set_pad_area(roi, axis, width_pair, value_pair) + + elif mode == "empty": + pass # Do nothing as _pad_simple already returned the correct result + + elif array.size == 0: + # Only modes "constant" and "empty" can extend empty axes, all other + # modes depend on `array` not being empty + # -> ensure every empty axis is only "padded with 0" + for axis, width_pair in zip(axes, pad_width): + if array.shape[axis] == 0 and any(width_pair): + raise ValueError( + f"can't extend empty axis {axis} using modes other than " + "'constant' or 'empty'" + ) + # passed, don't need to do anything more as _pad_simple already + # returned the correct result + + elif mode == "edge": + for axis, width_pair in zip(axes, pad_width): + roi = _view_roi(padded, original_area_slice, axis) + edge_pair = _get_edges(roi, axis, width_pair) + _set_pad_area(roi, axis, width_pair, edge_pair) + + elif mode == "linear_ramp": + end_values = kwargs.get("end_values", 0) + end_values = _as_pairs(end_values, padded.ndim) + for axis, width_pair, value_pair in zip(axes, pad_width, end_values): + roi = _view_roi(padded, original_area_slice, axis) + ramp_pair = _get_linear_ramps(roi, axis, width_pair, value_pair) + _set_pad_area(roi, axis, width_pair, ramp_pair) + + elif mode in stat_functions: + func = stat_functions[mode] + length = kwargs.get("stat_length") + length = _as_pairs(length, padded.ndim, as_index=True) + for axis, width_pair, length_pair in zip(axes, pad_width, length): + roi = _view_roi(padded, original_area_slice, axis) + stat_pair = _get_stats(roi, axis, width_pair, length_pair, func) + _set_pad_area(roi, axis, width_pair, stat_pair) + + elif mode in {"reflect", "symmetric"}: + method = kwargs.get("reflect_type", "even") + include_edge = mode == "symmetric" + for axis, (left_index, right_index) in zip(axes, pad_width): + if array.shape[axis] == 1 and (left_index > 0 or right_index > 0): + # Extending singleton dimension for 'reflect' is legacy + # behavior; it really should raise an error. + edge_pair = _get_edges(padded, axis, (left_index, right_index)) + _set_pad_area( + padded, axis, (left_index, right_index), edge_pair) + continue + + roi = _view_roi(padded, original_area_slice, axis) + while left_index > 0 or right_index > 0: + # Iteratively pad until dimension is filled with reflected + # values. This is necessary if the pad area is larger than + # the length of the original values in the current dimension. + left_index, right_index = _set_reflect_both( + roi, axis, (left_index, right_index), + method, array.shape[axis], include_edge + ) + + elif mode == "wrap": + for axis, (left_index, right_index) in zip(axes, pad_width): + roi = _view_roi(padded, original_area_slice, axis) + original_period = padded.shape[axis] - right_index - left_index + while left_index > 0 or right_index > 0: + # Iteratively pad until dimension is filled with wrapped + # values. This is necessary if the pad area is larger than + # the length of the original values in the current dimension. + left_index, right_index = _set_wrap_both( + roi, axis, (left_index, right_index), original_period) + + return padded diff --git a/python/user_packages/Python313/site-packages/numpy/lib/_arraypad_impl.pyi b/python/user_packages/Python313/site-packages/numpy/lib/_arraypad_impl.pyi new file mode 100644 index 0000000000000000000000000000000000000000..1e91aa17916d292ab441601744168f902d3b85d3 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/lib/_arraypad_impl.pyi @@ -0,0 +1,88 @@ +from typing import ( + Any, + Literal as L, + Protocol, + TypeAlias, + TypeVar, + overload, + type_check_only, +) + +from numpy import generic +from numpy._typing import ArrayLike, NDArray, _ArrayLike, _ArrayLikeInt + +__all__ = ["pad"] + +_ScalarT = TypeVar("_ScalarT", bound=generic) + +@type_check_only +class _ModeFunc(Protocol): + def __call__( + self, + vector: NDArray[Any], + iaxis_pad_width: tuple[int, int], + iaxis: int, + kwargs: dict[str, Any], + /, + ) -> None: ... + +_ModeKind: TypeAlias = L[ + "constant", + "edge", + "linear_ramp", + "maximum", + "mean", + "median", + "minimum", + "reflect", + "symmetric", + "wrap", + "empty", +] + +# TODO: In practice each keyword argument is exclusive to one or more +# specific modes. Consider adding more overloads to express this in the future. + +_PadWidth: TypeAlias = ( + _ArrayLikeInt + | dict[int, int] + | dict[int, tuple[int, int]] + | dict[int, int | tuple[int, int]] +) +# Expand `**kwargs` into explicit keyword-only arguments +@overload +def pad( + array: _ArrayLike[_ScalarT], + pad_width: _PadWidth, + mode: _ModeKind = "constant", + *, + stat_length: _ArrayLikeInt | None = None, + constant_values: ArrayLike = 0, + end_values: ArrayLike = 0, + reflect_type: L["odd", "even"] = "even", +) -> NDArray[_ScalarT]: ... +@overload +def pad( + array: ArrayLike, + pad_width: _PadWidth, + mode: _ModeKind = "constant", + *, + stat_length: _ArrayLikeInt | None = None, + constant_values: ArrayLike = 0, + end_values: ArrayLike = 0, + reflect_type: L["odd", "even"] = "even", +) -> NDArray[Any]: ... +@overload +def pad( + array: _ArrayLike[_ScalarT], + pad_width: _PadWidth, + mode: _ModeFunc, + **kwargs: Any, +) -> NDArray[_ScalarT]: ... +@overload +def pad( + array: ArrayLike, + pad_width: _PadWidth, + mode: _ModeFunc, + **kwargs: Any, +) -> NDArray[Any]: ... diff --git a/python/user_packages/Python313/site-packages/numpy/lib/_arraysetops_impl.py b/python/user_packages/Python313/site-packages/numpy/lib/_arraysetops_impl.py new file mode 100644 index 0000000000000000000000000000000000000000..6a9d14675f7cffd838309dbcaaed6b336df69c3d --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/lib/_arraysetops_impl.py @@ -0,0 +1,1158 @@ +""" +Set operations for arrays based on sorting. + +Notes +----- + +For floating point arrays, inaccurate results may appear due to usual round-off +and floating point comparison issues. + +Speed could be gained in some operations by an implementation of +`numpy.sort`, that can provide directly the permutation vectors, thus avoiding +calls to `numpy.argsort`. + +Original author: Robert Cimrman + +""" +import functools +from typing import NamedTuple + +import numpy as np +from numpy._core import overrides +from numpy._core._multiarray_umath import _array_converter, _unique_hash +from numpy.lib.array_utils import normalize_axis_index + +array_function_dispatch = functools.partial( + overrides.array_function_dispatch, module='numpy') + + +__all__ = [ + "ediff1d", "intersect1d", "isin", "setdiff1d", "setxor1d", + "union1d", "unique", "unique_all", "unique_counts", "unique_inverse", + "unique_values" +] + + +def _ediff1d_dispatcher(ary, to_end=None, to_begin=None): + return (ary, to_end, to_begin) + + +@array_function_dispatch(_ediff1d_dispatcher) +def ediff1d(ary, to_end=None, to_begin=None): + """ + The differences between consecutive elements of an array. + + Parameters + ---------- + ary : array_like + If necessary, will be flattened before the differences are taken. + to_end : array_like, optional + Number(s) to append at the end of the returned differences. + to_begin : array_like, optional + Number(s) to prepend at the beginning of the returned differences. + + Returns + ------- + ediff1d : ndarray + The differences. Loosely, this is ``ary.flat[1:] - ary.flat[:-1]``. + + See Also + -------- + diff, gradient + + Notes + ----- + When applied to masked arrays, this function drops the mask information + if the `to_begin` and/or `to_end` parameters are used. + + Examples + -------- + >>> import numpy as np + >>> x = np.array([1, 2, 4, 7, 0]) + >>> np.ediff1d(x) + array([ 1, 2, 3, -7]) + + >>> np.ediff1d(x, to_begin=-99, to_end=np.array([88, 99])) + array([-99, 1, 2, ..., -7, 88, 99]) + + The returned array is always 1D. + + >>> y = [[1, 2, 4], [1, 6, 24]] + >>> np.ediff1d(y) + array([ 1, 2, -3, 5, 18]) + + """ + conv = _array_converter(ary) + # Convert to (any) array and ravel: + ary = conv[0].ravel() + + # enforce that the dtype of `ary` is used for the output + dtype_req = ary.dtype + + # fast track default case + if to_begin is None and to_end is None: + return ary[1:] - ary[:-1] + + if to_begin is None: + l_begin = 0 + else: + to_begin = np.asanyarray(to_begin) + if not np.can_cast(to_begin, dtype_req, casting="same_kind"): + raise TypeError("dtype of `to_begin` must be compatible " + "with input `ary` under the `same_kind` rule.") + + to_begin = to_begin.ravel() + l_begin = len(to_begin) + + if to_end is None: + l_end = 0 + else: + to_end = np.asanyarray(to_end) + if not np.can_cast(to_end, dtype_req, casting="same_kind"): + raise TypeError("dtype of `to_end` must be compatible " + "with input `ary` under the `same_kind` rule.") + + to_end = to_end.ravel() + l_end = len(to_end) + + # do the calculation in place and copy to_begin and to_end + l_diff = max(len(ary) - 1, 0) + result = np.empty_like(ary, shape=l_diff + l_begin + l_end) + + if l_begin > 0: + result[:l_begin] = to_begin + if l_end > 0: + result[l_begin + l_diff:] = to_end + np.subtract(ary[1:], ary[:-1], result[l_begin:l_begin + l_diff]) + + return conv.wrap(result) + + +def _unpack_tuple(x): + """ Unpacks one-element tuples for use as return values """ + if len(x) == 1: + return x[0] + else: + return x + + +def _unique_dispatcher(ar, return_index=None, return_inverse=None, + return_counts=None, axis=None, *, equal_nan=None, + sorted=True): + return (ar,) + + +@array_function_dispatch(_unique_dispatcher) +def unique(ar, return_index=False, return_inverse=False, + return_counts=False, axis=None, *, equal_nan=True, + sorted=True): + """ + Find the unique elements of an array. + + Returns the sorted unique elements of an array. There are three optional + outputs in addition to the unique elements: + + * the indices of the input array that give the unique values + * the indices of the unique array that reconstruct the input array + * the number of times each unique value comes up in the input array + + Parameters + ---------- + ar : array_like + Input array. Unless `axis` is specified, this will be flattened if it + is not already 1-D. + return_index : bool, optional + If True, also return the indices of `ar` (along the specified axis, + if provided, or in the flattened array) that result in the unique array. + return_inverse : bool, optional + If True, also return the indices of the unique array (for the specified + axis, if provided) that can be used to reconstruct `ar`. + return_counts : bool, optional + If True, also return the number of times each unique item appears + in `ar`. + axis : int or None, optional + The axis to operate on. If None, `ar` will be flattened. If an integer, + the subarrays indexed by the given axis will be flattened and treated + as the elements of a 1-D array with the dimension of the given axis, + see the notes for more details. Object arrays or structured arrays + that contain objects are not supported if the `axis` kwarg is used. The + default is None. + + equal_nan : bool, optional + If True, collapses multiple NaN values in the return array into one. + + .. versionadded:: 1.24 + + sorted : bool, optional + If True, the unique elements are sorted. Elements may be sorted in + practice even if ``sorted=False``, but this could change without + notice. + + .. versionadded:: 2.3 + + Returns + ------- + unique : ndarray + The sorted unique values. + unique_indices : ndarray, optional + The indices of the first occurrences of the unique values in the + original array. Only provided if `return_index` is True. + unique_inverse : ndarray, optional + The indices to reconstruct the original array from the + unique array. Only provided if `return_inverse` is True. + unique_counts : ndarray, optional + The number of times each of the unique values comes up in the + original array. Only provided if `return_counts` is True. + + See Also + -------- + repeat : Repeat elements of an array. + sort : Return a sorted copy of an array. + + Notes + ----- + When an axis is specified the subarrays indexed by the axis are sorted. + This is done by making the specified axis the first dimension of the array + (move the axis to the first dimension to keep the order of the other axes) + and then flattening the subarrays in C order. The flattened subarrays are + then viewed as a structured type with each element given a label, with the + effect that we end up with a 1-D array of structured types that can be + treated in the same way as any other 1-D array. The result is that the + flattened subarrays are sorted in lexicographic order starting with the + first element. + + .. versionchanged:: 1.21 + Like np.sort, NaN will sort to the end of the values. + For complex arrays all NaN values are considered equivalent + (no matter whether the NaN is in the real or imaginary part). + As the representant for the returned array the smallest one in the + lexicographical order is chosen - see np.sort for how the lexicographical + order is defined for complex arrays. + + .. versionchanged:: 2.0 + For multi-dimensional inputs, ``unique_inverse`` is reshaped + such that the input can be reconstructed using + ``np.take(unique, unique_inverse, axis=axis)``. The result is + now not 1-dimensional when ``axis=None``. + + Note that in NumPy 2.0.0 a higher dimensional array was returned also + when ``axis`` was not ``None``. This was reverted, but + ``inverse.reshape(-1)`` can be used to ensure compatibility with both + versions. + + Examples + -------- + >>> import numpy as np + >>> np.unique([1, 1, 2, 2, 3, 3]) + array([1, 2, 3]) + >>> a = np.array([[1, 1], [2, 3]]) + >>> np.unique(a) + array([1, 2, 3]) + + Return the unique rows of a 2D array + + >>> a = np.array([[1, 0, 0], [1, 0, 0], [2, 3, 4]]) + >>> np.unique(a, axis=0) + array([[1, 0, 0], [2, 3, 4]]) + + Return the indices of the original array that give the unique values: + + >>> a = np.array(['a', 'b', 'b', 'c', 'a']) + >>> u, indices = np.unique(a, return_index=True) + >>> u + array(['a', 'b', 'c'], dtype='>> indices + array([0, 1, 3]) + >>> a[indices] + array(['a', 'b', 'c'], dtype='>> a = np.array([1, 2, 6, 4, 2, 3, 2]) + >>> u, indices = np.unique(a, return_inverse=True) + >>> u + array([1, 2, 3, 4, 6]) + >>> indices + array([0, 1, 4, 3, 1, 2, 1]) + >>> u[indices] + array([1, 2, 6, 4, 2, 3, 2]) + + Reconstruct the input values from the unique values and counts: + + >>> a = np.array([1, 2, 6, 4, 2, 3, 2]) + >>> values, counts = np.unique(a, return_counts=True) + >>> values + array([1, 2, 3, 4, 6]) + >>> counts + array([1, 3, 1, 1, 1]) + >>> np.repeat(values, counts) + array([1, 2, 2, 2, 3, 4, 6]) # original order not preserved + + """ + ar = np.asanyarray(ar) + if axis is None or ar.ndim == 1: + if axis is not None: + normalize_axis_index(axis, ar.ndim) + ret = _unique1d(ar, return_index, return_inverse, return_counts, + equal_nan=equal_nan, inverse_shape=ar.shape, axis=None, + sorted=sorted) + return _unpack_tuple(ret) + + # axis was specified and not None + try: + ar = np.moveaxis(ar, axis, 0) + except np.exceptions.AxisError: + # this removes the "axis1" or "axis2" prefix from the error message + raise np.exceptions.AxisError(axis, ar.ndim) from None + inverse_shape = [1] * ar.ndim + inverse_shape[axis] = ar.shape[0] + + # Must reshape to a contiguous 2D array for this to work... + orig_shape, orig_dtype = ar.shape, ar.dtype + ar = ar.reshape(orig_shape[0], np.prod(orig_shape[1:], dtype=np.intp)) + ar = np.ascontiguousarray(ar) + dtype = [(f'f{i}', ar.dtype) for i in range(ar.shape[1])] + + # At this point, `ar` has shape `(n, m)`, and `dtype` is a structured + # data type with `m` fields where each field has the data type of `ar`. + # In the following, we create the array `consolidated`, which has + # shape `(n,)` with data type `dtype`. + try: + if ar.shape[1] > 0: + consolidated = ar.view(dtype) + else: + # If ar.shape[1] == 0, then dtype will be `np.dtype([])`, which is + # a data type with itemsize 0, and the call `ar.view(dtype)` will + # fail. Instead, we'll use `np.empty` to explicitly create the + # array with shape `(len(ar),)`. Because `dtype` in this case has + # itemsize 0, the total size of the result is still 0 bytes. + consolidated = np.empty(len(ar), dtype=dtype) + except TypeError as e: + # There's no good way to do this for object arrays, etc... + msg = 'The axis argument to unique is not supported for dtype {dt}' + raise TypeError(msg.format(dt=ar.dtype)) from e + + def reshape_uniq(uniq): + n = len(uniq) + uniq = uniq.view(orig_dtype) + uniq = uniq.reshape(n, *orig_shape[1:]) + uniq = np.moveaxis(uniq, 0, axis) + return uniq + + output = _unique1d(consolidated, return_index, + return_inverse, return_counts, + equal_nan=equal_nan, inverse_shape=inverse_shape, + axis=axis, sorted=sorted) + output = (reshape_uniq(output[0]),) + output[1:] + return _unpack_tuple(output) + + +def _unique1d(ar, return_index=False, return_inverse=False, + return_counts=False, *, equal_nan=True, inverse_shape=None, + axis=None, sorted=True): + """ + Find the unique elements of an array, ignoring shape. + + Uses a hash table to find the unique elements if possible. + """ + ar = np.asanyarray(ar).flatten() + if len(ar.shape) != 1: + # np.matrix, and maybe some other array subclasses, insist on keeping + # two dimensions for all operations. Coerce to an ndarray in such cases. + ar = np.asarray(ar).flatten() + + optional_indices = return_index or return_inverse + + # masked arrays are not supported yet. + if not optional_indices and not return_counts and not np.ma.is_masked(ar): + # First we convert the array to a numpy array, later we wrap it back + # in case it was a subclass of numpy.ndarray. + conv = _array_converter(ar) + ar_, = conv + + if (hash_unique := _unique_hash(ar_, equal_nan=equal_nan)) \ + is not NotImplemented: + if sorted: + hash_unique.sort() + # We wrap the result back in case it was a subclass of numpy.ndarray. + return (conv.wrap(hash_unique),) + + # If we don't use the hash map, we use the slower sorting method. + if optional_indices: + perm = ar.argsort(kind='mergesort' if return_index else 'quicksort') + aux = ar[perm] + else: + ar.sort() + aux = ar + mask = np.empty(aux.shape, dtype=np.bool) + mask[:1] = True + if (equal_nan and aux.shape[0] > 0 and aux.dtype.kind in "cfmM" and + np.isnan(aux[-1])): + if aux.dtype.kind == "c": # for complex all NaNs are considered equivalent + aux_firstnan = np.searchsorted(np.isnan(aux), True, side='left') + else: + aux_firstnan = np.searchsorted(aux, aux[-1], side='left') + if aux_firstnan > 0: + mask[1:aux_firstnan] = ( + aux[1:aux_firstnan] != aux[:aux_firstnan - 1]) + mask[aux_firstnan] = True + mask[aux_firstnan + 1:] = False + else: + mask[1:] = aux[1:] != aux[:-1] + + ret = (aux[mask],) + if return_index: + ret += (perm[mask],) + if return_inverse: + imask = np.cumsum(mask) - 1 + inv_idx = np.empty(mask.shape, dtype=np.intp) + inv_idx[perm] = imask + ret += (inv_idx.reshape(inverse_shape) if axis is None else inv_idx,) + if return_counts: + idx = np.concatenate(np.nonzero(mask) + ([mask.size],)) + ret += (np.diff(idx),) + return ret + + +# Array API set functions + +class UniqueAllResult(NamedTuple): + values: np.ndarray + indices: np.ndarray + inverse_indices: np.ndarray + counts: np.ndarray + + +class UniqueCountsResult(NamedTuple): + values: np.ndarray + counts: np.ndarray + + +class UniqueInverseResult(NamedTuple): + values: np.ndarray + inverse_indices: np.ndarray + + +def _unique_all_dispatcher(x, /): + return (x,) + + +@array_function_dispatch(_unique_all_dispatcher) +def unique_all(x): + """ + Find the unique elements of an array, and counts, inverse, and indices. + + This function is an Array API compatible alternative to:: + + np.unique(x, return_index=True, return_inverse=True, + return_counts=True, equal_nan=False, sorted=False) + + but returns a namedtuple for easier access to each output. + + .. note:: + This function currently always returns a sorted result, however, + this could change in any NumPy minor release. + + Parameters + ---------- + x : array_like + Input array. It will be flattened if it is not already 1-D. + + Returns + ------- + out : namedtuple + The result containing: + + * values - The unique elements of an input array. + * indices - The first occurring indices for each unique element. + * inverse_indices - The indices from the set of unique elements + that reconstruct `x`. + * counts - The corresponding counts for each unique element. + + See Also + -------- + unique : Find the unique elements of an array. + + Examples + -------- + >>> import numpy as np + >>> x = [1, 1, 2] + >>> uniq = np.unique_all(x) + >>> uniq.values + array([1, 2]) + >>> uniq.indices + array([0, 2]) + >>> uniq.inverse_indices + array([0, 0, 1]) + >>> uniq.counts + array([2, 1]) + """ + result = unique( + x, + return_index=True, + return_inverse=True, + return_counts=True, + equal_nan=False, + ) + return UniqueAllResult(*result) + + +def _unique_counts_dispatcher(x, /): + return (x,) + + +@array_function_dispatch(_unique_counts_dispatcher) +def unique_counts(x): + """ + Find the unique elements and counts of an input array `x`. + + This function is an Array API compatible alternative to:: + + np.unique(x, return_counts=True, equal_nan=False, sorted=False) + + but returns a namedtuple for easier access to each output. + + .. note:: + This function currently always returns a sorted result, however, + this could change in any NumPy minor release. + + Parameters + ---------- + x : array_like + Input array. It will be flattened if it is not already 1-D. + + Returns + ------- + out : namedtuple + The result containing: + + * values - The unique elements of an input array. + * counts - The corresponding counts for each unique element. + + See Also + -------- + unique : Find the unique elements of an array. + + Examples + -------- + >>> import numpy as np + >>> x = [1, 1, 2] + >>> uniq = np.unique_counts(x) + >>> uniq.values + array([1, 2]) + >>> uniq.counts + array([2, 1]) + """ + result = unique( + x, + return_index=False, + return_inverse=False, + return_counts=True, + equal_nan=False, + ) + return UniqueCountsResult(*result) + + +def _unique_inverse_dispatcher(x, /): + return (x,) + + +@array_function_dispatch(_unique_inverse_dispatcher) +def unique_inverse(x): + """ + Find the unique elements of `x` and indices to reconstruct `x`. + + This function is an Array API compatible alternative to:: + + np.unique(x, return_inverse=True, equal_nan=False, sorted=False) + + but returns a namedtuple for easier access to each output. + + .. note:: + This function currently always returns a sorted result, however, + this could change in any NumPy minor release. + + Parameters + ---------- + x : array_like + Input array. It will be flattened if it is not already 1-D. + + Returns + ------- + out : namedtuple + The result containing: + + * values - The unique elements of an input array. + * inverse_indices - The indices from the set of unique elements + that reconstruct `x`. + + See Also + -------- + unique : Find the unique elements of an array. + + Examples + -------- + >>> import numpy as np + >>> x = [1, 1, 2] + >>> uniq = np.unique_inverse(x) + >>> uniq.values + array([1, 2]) + >>> uniq.inverse_indices + array([0, 0, 1]) + """ + result = unique( + x, + return_index=False, + return_inverse=True, + return_counts=False, + equal_nan=False, + ) + return UniqueInverseResult(*result) + + +def _unique_values_dispatcher(x, /): + return (x,) + + +@array_function_dispatch(_unique_values_dispatcher) +def unique_values(x): + """ + Returns the unique elements of an input array `x`. + + This function is an Array API compatible alternative to:: + + np.unique(x, equal_nan=False, sorted=False) + + .. versionchanged:: 2.3 + The algorithm was changed to a faster one that does not rely on + sorting, and hence the results are no longer implicitly sorted. + + Parameters + ---------- + x : array_like + Input array. It will be flattened if it is not already 1-D. + + Returns + ------- + out : ndarray + The unique elements of an input array. + + See Also + -------- + unique : Find the unique elements of an array. + + Examples + -------- + >>> import numpy as np + >>> np.unique_values([1, 1, 2]) + array([1, 2]) # may vary + + """ + return unique( + x, + return_index=False, + return_inverse=False, + return_counts=False, + equal_nan=False, + sorted=False, + ) + + +def _intersect1d_dispatcher( + ar1, ar2, assume_unique=None, return_indices=None): + return (ar1, ar2) + + +@array_function_dispatch(_intersect1d_dispatcher) +def intersect1d(ar1, ar2, assume_unique=False, return_indices=False): + """ + Find the intersection of two arrays. + + Return the sorted, unique values that are in both of the input arrays. + + Parameters + ---------- + ar1, ar2 : array_like + Input arrays. Will be flattened if not already 1D. + assume_unique : bool + If True, the input arrays are both assumed to be unique, which + can speed up the calculation. If True but ``ar1`` or ``ar2`` are not + unique, incorrect results and out-of-bounds indices could result. + Default is False. + return_indices : bool + If True, the indices which correspond to the intersection of the two + arrays are returned. The first instance of a value is used if there are + multiple. Default is False. + + Returns + ------- + intersect1d : ndarray + Sorted 1D array of common and unique elements. + comm1 : ndarray + The indices of the first occurrences of the common values in `ar1`. + Only provided if `return_indices` is True. + comm2 : ndarray + The indices of the first occurrences of the common values in `ar2`. + Only provided if `return_indices` is True. + + Examples + -------- + >>> import numpy as np + >>> np.intersect1d([1, 3, 4, 3], [3, 1, 2, 1]) + array([1, 3]) + + To intersect more than two arrays, use functools.reduce: + + >>> from functools import reduce + >>> reduce(np.intersect1d, ([1, 3, 4, 3], [3, 1, 2, 1], [6, 3, 4, 2])) + array([3]) + + To return the indices of the values common to the input arrays + along with the intersected values: + + >>> x = np.array([1, 1, 2, 3, 4]) + >>> y = np.array([2, 1, 4, 6]) + >>> xy, x_ind, y_ind = np.intersect1d(x, y, return_indices=True) + >>> x_ind, y_ind + (array([0, 2, 4]), array([1, 0, 2])) + >>> xy, x[x_ind], y[y_ind] + (array([1, 2, 4]), array([1, 2, 4]), array([1, 2, 4])) + + """ + ar1 = np.asanyarray(ar1) + ar2 = np.asanyarray(ar2) + + if not assume_unique: + if return_indices: + ar1, ind1 = unique(ar1, return_index=True) + ar2, ind2 = unique(ar2, return_index=True) + else: + ar1 = unique(ar1) + ar2 = unique(ar2) + else: + ar1 = ar1.ravel() + ar2 = ar2.ravel() + + aux = np.concatenate((ar1, ar2)) + if return_indices: + aux_sort_indices = np.argsort(aux, kind='mergesort') + aux = aux[aux_sort_indices] + else: + aux.sort() + + mask = aux[1:] == aux[:-1] + int1d = aux[:-1][mask] + + if return_indices: + ar1_indices = aux_sort_indices[:-1][mask] + ar2_indices = aux_sort_indices[1:][mask] - ar1.size + if not assume_unique: + ar1_indices = ind1[ar1_indices] + ar2_indices = ind2[ar2_indices] + + return int1d, ar1_indices, ar2_indices + else: + return int1d + + +def _setxor1d_dispatcher(ar1, ar2, assume_unique=None): + return (ar1, ar2) + + +@array_function_dispatch(_setxor1d_dispatcher) +def setxor1d(ar1, ar2, assume_unique=False): + """ + Find the set exclusive-or of two arrays. + + Return the sorted, unique values that are in only one (not both) of the + input arrays. + + Parameters + ---------- + ar1, ar2 : array_like + Input arrays. + assume_unique : bool + If True, the input arrays are both assumed to be unique, which + can speed up the calculation. Default is False. + + Returns + ------- + setxor1d : ndarray + Sorted 1D array of unique values that are in only one of the input + arrays. + + Examples + -------- + >>> import numpy as np + >>> a = np.array([1, 2, 3, 2, 4]) + >>> b = np.array([2, 3, 5, 7, 5]) + >>> np.setxor1d(a,b) + array([1, 4, 5, 7]) + + """ + if not assume_unique: + ar1 = unique(ar1) + ar2 = unique(ar2) + + aux = np.concatenate((ar1, ar2), axis=None) + if aux.size == 0: + return aux + + aux.sort() + flag = np.concatenate(([True], aux[1:] != aux[:-1], [True])) + return aux[flag[1:] & flag[:-1]] + + +def _isin(ar1, ar2, assume_unique=False, invert=False, *, kind=None): + # Ravel both arrays, behavior for the first array could be different + ar1 = np.asarray(ar1).ravel() + ar2 = np.asarray(ar2).ravel() + + # Ensure that iteration through object arrays yields size-1 arrays + if ar2.dtype == object: + ar2 = ar2.reshape(-1, 1) + + if kind not in {None, 'sort', 'table'}: + raise ValueError( + f"Invalid kind: '{kind}'. Please use None, 'sort' or 'table'.") + + # Can use the table method if all arrays are integers or boolean: + is_int_arrays = all(ar.dtype.kind in ("u", "i", "b") for ar in (ar1, ar2)) + use_table_method = is_int_arrays and kind in {None, 'table'} + + if use_table_method: + if ar2.size == 0: + if invert: + return np.ones_like(ar1, dtype=bool) + else: + return np.zeros_like(ar1, dtype=bool) + + # Convert booleans to uint8 so we can use the fast integer algorithm + if ar1.dtype == bool: + ar1 = ar1.astype(np.uint8) + if ar2.dtype == bool: + ar2 = ar2.astype(np.uint8) + + ar2_min = int(np.min(ar2)) + ar2_max = int(np.max(ar2)) + + ar2_range = ar2_max - ar2_min + + # Constraints on whether we can actually use the table method: + # 1. Assert memory usage is not too large + below_memory_constraint = ar2_range <= 6 * (ar1.size + ar2.size) + # 2. Check overflows for (ar2 - ar2_min); dtype=ar2.dtype + range_safe_from_overflow = ar2_range <= np.iinfo(ar2.dtype).max + + # Optimal performance is for approximately + # log10(size) > (log10(range) - 2.27) / 0.927. + # However, here we set the requirement that by default + # the intermediate array can only be 6x + # the combined memory allocation of the original + # arrays. See discussion on + # https://github.com/numpy/numpy/pull/12065. + + if ( + range_safe_from_overflow and + (below_memory_constraint or kind == 'table') + ): + + if invert: + outgoing_array = np.ones_like(ar1, dtype=bool) + else: + outgoing_array = np.zeros_like(ar1, dtype=bool) + + # Make elements 1 where the integer exists in ar2 + if invert: + isin_helper_ar = np.ones(ar2_range + 1, dtype=bool) + isin_helper_ar[ar2 - ar2_min] = 0 + else: + isin_helper_ar = np.zeros(ar2_range + 1, dtype=bool) + isin_helper_ar[ar2 - ar2_min] = 1 + + # Mask out elements we know won't work + basic_mask = (ar1 <= ar2_max) & (ar1 >= ar2_min) + in_range_ar1 = ar1[basic_mask] + if in_range_ar1.size == 0: + # Nothing more to do, since all values are out of range. + return outgoing_array + + # Unfortunately, ar2_min can be out of range for `intp` even + # if the calculation result must fit in range (and be positive). + # In that case, use ar2.dtype which must work for all unmasked + # values. + try: + ar2_min = np.array(ar2_min, dtype=np.intp) + dtype = np.intp + except OverflowError: + dtype = ar2.dtype + + out = np.empty_like(in_range_ar1, dtype=np.intp) + outgoing_array[basic_mask] = isin_helper_ar[ + np.subtract(in_range_ar1, ar2_min, dtype=dtype, + out=out, casting="unsafe")] + + return outgoing_array + elif kind == 'table': # not range_safe_from_overflow + raise RuntimeError( + "You have specified kind='table', " + "but the range of values in `ar2` or `ar1` exceed the " + "maximum integer of the datatype. " + "Please set `kind` to None or 'sort'." + ) + elif kind == 'table': + raise ValueError( + "The 'table' method is only " + "supported for boolean or integer arrays. " + "Please select 'sort' or None for kind." + ) + + # Check if one of the arrays may contain arbitrary objects + contains_object = ar1.dtype.hasobject or ar2.dtype.hasobject + + # This code is run when + # a) the first condition is true, making the code significantly faster + # b) the second condition is true (i.e. `ar1` or `ar2` may contain + # arbitrary objects), since then sorting is not guaranteed to work + if len(ar2) < 10 * len(ar1) ** 0.145 or contains_object: + if invert: + mask = np.ones(len(ar1), dtype=bool) + for a in ar2: + mask &= (ar1 != a) + else: + mask = np.zeros(len(ar1), dtype=bool) + for a in ar2: + mask |= (ar1 == a) + return mask + + # Otherwise use sorting + if not assume_unique: + ar1, rev_idx = np.unique(ar1, return_inverse=True) + ar2 = np.unique(ar2) + + ar = np.concatenate((ar1, ar2)) + # We need this to be a stable sort, so always use 'mergesort' + # here. The values from the first array should always come before + # the values from the second array. + order = ar.argsort(kind='mergesort') + sar = ar[order] + if invert: + bool_ar = (sar[1:] != sar[:-1]) + else: + bool_ar = (sar[1:] == sar[:-1]) + flag = np.concatenate((bool_ar, [invert])) + ret = np.empty(ar.shape, dtype=bool) + ret[order] = flag + + if assume_unique: + return ret[:len(ar1)] + else: + return ret[rev_idx] + + +def _isin_dispatcher(element, test_elements, assume_unique=None, invert=None, + *, kind=None): + return (element, test_elements) + + +@array_function_dispatch(_isin_dispatcher) +def isin(element, test_elements, assume_unique=False, invert=False, *, + kind=None): + """ + Calculates ``element in test_elements``, broadcasting over `element` only. + Returns a boolean array of the same shape as `element` that is True + where an element of `element` is in `test_elements` and False otherwise. + + Parameters + ---------- + element : array_like + Input array. + test_elements : array_like + The values against which to test each value of `element`. + This argument is flattened if it is an array or array_like. + See notes for behavior with non-array-like parameters. + assume_unique : bool, optional + If True, the input arrays are both assumed to be unique, which + can speed up the calculation. Default is False. + invert : bool, optional + If True, the values in the returned array are inverted, as if + calculating `element not in test_elements`. Default is False. + ``np.isin(a, b, invert=True)`` is equivalent to (but faster + than) ``np.invert(np.isin(a, b))``. + kind : {None, 'sort', 'table'}, optional + The algorithm to use. This will not affect the final result, + but will affect the speed and memory use. The default, None, + will select automatically based on memory considerations. + + * If 'sort', will use a mergesort-based approach. This will have + a memory usage of roughly 6 times the sum of the sizes of + `element` and `test_elements`, not accounting for size of dtypes. + * If 'table', will use a lookup table approach similar + to a counting sort. This is only available for boolean and + integer arrays. This will have a memory usage of the + size of `element` plus the max-min value of `test_elements`. + `assume_unique` has no effect when the 'table' option is used. + * If None, will automatically choose 'table' if + the required memory allocation is less than or equal to + 6 times the sum of the sizes of `element` and `test_elements`, + otherwise will use 'sort'. This is done to not use + a large amount of memory by default, even though + 'table' may be faster in most cases. If 'table' is chosen, + `assume_unique` will have no effect. + + + Returns + ------- + isin : ndarray, bool + Has the same shape as `element`. The values `element[isin]` + are in `test_elements`. + + Notes + ----- + `isin` is an element-wise function version of the python keyword `in`. + ``isin(a, b)`` is roughly equivalent to + ``np.array([item in b for item in a])`` if `a` and `b` are 1-D sequences. + + `element` and `test_elements` are converted to arrays if they are not + already. If `test_elements` is a set (or other non-sequence collection) + it will be converted to an object array with one element, rather than an + array of the values contained in `test_elements`. This is a consequence + of the `array` constructor's way of handling non-sequence collections. + Converting the set to a list usually gives the desired behavior. + + Using ``kind='table'`` tends to be faster than `kind='sort'` if the + following relationship is true: + ``log10(len(test_elements)) > + (log10(max(test_elements)-min(test_elements)) - 2.27) / 0.927``, + but may use greater memory. The default value for `kind` will + be automatically selected based only on memory usage, so one may + manually set ``kind='table'`` if memory constraints can be relaxed. + + Examples + -------- + >>> import numpy as np + >>> element = 2*np.arange(4).reshape((2, 2)) + >>> element + array([[0, 2], + [4, 6]]) + >>> test_elements = [1, 2, 4, 8] + >>> mask = np.isin(element, test_elements) + >>> mask + array([[False, True], + [ True, False]]) + >>> element[mask] + array([2, 4]) + + The indices of the matched values can be obtained with `nonzero`: + + >>> np.nonzero(mask) + (array([0, 1]), array([1, 0])) + + The test can also be inverted: + + >>> mask = np.isin(element, test_elements, invert=True) + >>> mask + array([[ True, False], + [False, True]]) + >>> element[mask] + array([0, 6]) + + Because of how `array` handles sets, the following does not + work as expected: + + >>> test_set = {1, 2, 4, 8} + >>> np.isin(element, test_set) + array([[False, False], + [False, False]]) + + Casting the set to a list gives the expected result: + + >>> np.isin(element, list(test_set)) + array([[False, True], + [ True, False]]) + """ + element = np.asarray(element) + return _isin(element, test_elements, assume_unique=assume_unique, + invert=invert, kind=kind).reshape(element.shape) + + +def _union1d_dispatcher(ar1, ar2): + return (ar1, ar2) + + +@array_function_dispatch(_union1d_dispatcher) +def union1d(ar1, ar2): + """ + Find the union of two arrays. + + Return the unique, sorted array of values that are in either of the two + input arrays. + + Parameters + ---------- + ar1, ar2 : array_like + Input arrays. They are flattened if they are not already 1D. + + Returns + ------- + union1d : ndarray + Unique, sorted union of the input arrays. + + Examples + -------- + >>> import numpy as np + >>> np.union1d([-1, 0, 1], [-2, 0, 2]) + array([-2, -1, 0, 1, 2]) + + To find the union of more than two arrays, use functools.reduce: + + >>> from functools import reduce + >>> reduce(np.union1d, ([1, 3, 4, 3], [3, 1, 2, 1], [6, 3, 4, 2])) + array([1, 2, 3, 4, 6]) + """ + return unique(np.concatenate((ar1, ar2), axis=None)) + + +def _setdiff1d_dispatcher(ar1, ar2, assume_unique=None): + return (ar1, ar2) + + +@array_function_dispatch(_setdiff1d_dispatcher) +def setdiff1d(ar1, ar2, assume_unique=False): + """ + Find the set difference of two arrays. + + Return the unique values in `ar1` that are not in `ar2`. + + Parameters + ---------- + ar1 : array_like + Input array. + ar2 : array_like + Input comparison array. + assume_unique : bool + If True, the input arrays are both assumed to be unique, which + can speed up the calculation. Default is False. + + Returns + ------- + setdiff1d : ndarray + 1D array of values in `ar1` that are not in `ar2`. The result + is sorted when `assume_unique=False`, but otherwise only sorted + if the input is sorted. + + Examples + -------- + >>> import numpy as np + >>> a = np.array([1, 2, 3, 2, 4, 1]) + >>> b = np.array([3, 4, 5, 6]) + >>> np.setdiff1d(a, b) + array([1, 2]) + + """ + if assume_unique: + ar1 = np.asarray(ar1).ravel() + else: + ar1 = unique(ar1) + ar2 = unique(ar2) + return ar1[_isin(ar1, ar2, assume_unique=True, invert=True)] diff --git a/python/user_packages/Python313/site-packages/numpy/lib/_arraysetops_impl.pyi b/python/user_packages/Python313/site-packages/numpy/lib/_arraysetops_impl.pyi new file mode 100644 index 0000000000000000000000000000000000000000..777fca8a0f4dd43cccf85522e6fc24ede62d9764 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/lib/_arraysetops_impl.pyi @@ -0,0 +1,462 @@ +from typing import ( + Any, + Generic, + Literal as L, + NamedTuple, + SupportsIndex, + TypeAlias, + overload, +) +from typing_extensions import TypeVar + +import numpy as np +from numpy._typing import ( + ArrayLike, + NDArray, + _ArrayLike, + _ArrayLikeBool_co, + _ArrayLikeNumber_co, +) + +__all__ = [ + "ediff1d", + "intersect1d", + "isin", + "setdiff1d", + "setxor1d", + "union1d", + "unique", + "unique_all", + "unique_counts", + "unique_inverse", + "unique_values", +] + +_ScalarT = TypeVar("_ScalarT", bound=np.generic) +_NumericT = TypeVar("_NumericT", bound=np.number | np.timedelta64 | np.object_) + +# Explicitly set all allowed values to prevent accidental castings to +# abstract dtypes (their common super-type). +# Only relevant if two or more arguments are parametrized, (e.g. `setdiff1d`) +# which could result in, for example, `int64` and `float64`producing a +# `number[_64Bit]` array +_EitherSCT = TypeVar( + "_EitherSCT", + np.bool, + np.int8, np.int16, np.int32, np.int64, np.intp, + np.uint8, np.uint16, np.uint32, np.uint64, np.uintp, + np.float16, np.float32, np.float64, np.longdouble, + np.complex64, np.complex128, np.clongdouble, + np.timedelta64, np.datetime64, + np.bytes_, np.str_, np.void, np.object_, + np.integer, np.floating, np.complexfloating, np.character, +) # fmt: skip + +_AnyArray: TypeAlias = NDArray[Any] +_IntArray: TypeAlias = NDArray[np.intp] + +### + +class UniqueAllResult(NamedTuple, Generic[_ScalarT]): + values: NDArray[_ScalarT] + indices: _IntArray + inverse_indices: _IntArray + counts: _IntArray + +class UniqueCountsResult(NamedTuple, Generic[_ScalarT]): + values: NDArray[_ScalarT] + counts: _IntArray + +class UniqueInverseResult(NamedTuple, Generic[_ScalarT]): + values: NDArray[_ScalarT] + inverse_indices: _IntArray + +# +@overload +def ediff1d( + ary: _ArrayLikeBool_co, + to_end: ArrayLike | None = None, + to_begin: ArrayLike | None = None, +) -> NDArray[np.int8]: ... +@overload +def ediff1d( + ary: _ArrayLike[_NumericT], + to_end: ArrayLike | None = None, + to_begin: ArrayLike | None = None, +) -> NDArray[_NumericT]: ... +@overload +def ediff1d( + ary: _ArrayLike[np.datetime64[Any]], + to_end: ArrayLike | None = None, + to_begin: ArrayLike | None = None, +) -> NDArray[np.timedelta64]: ... +@overload +def ediff1d( + ary: _ArrayLikeNumber_co, + to_end: ArrayLike | None = None, + to_begin: ArrayLike | None = None, +) -> _AnyArray: ... + +# +@overload # known scalar-type, FFF +def unique( + ar: _ArrayLike[_ScalarT], + return_index: L[False] = False, + return_inverse: L[False] = False, + return_counts: L[False] = False, + axis: SupportsIndex | None = None, + *, + equal_nan: bool = True, + sorted: bool = True, +) -> NDArray[_ScalarT]: ... +@overload # unknown scalar-type, FFF +def unique( + ar: ArrayLike, + return_index: L[False] = False, + return_inverse: L[False] = False, + return_counts: L[False] = False, + axis: SupportsIndex | None = None, + *, + equal_nan: bool = True, + sorted: bool = True, +) -> _AnyArray: ... +@overload # known scalar-type, TFF +def unique( + ar: _ArrayLike[_ScalarT], + return_index: L[True], + return_inverse: L[False] = False, + return_counts: L[False] = False, + axis: SupportsIndex | None = None, + *, + equal_nan: bool = True, + sorted: bool = True, +) -> tuple[NDArray[_ScalarT], _IntArray]: ... +@overload # unknown scalar-type, TFF +def unique( + ar: ArrayLike, + return_index: L[True], + return_inverse: L[False] = False, + return_counts: L[False] = False, + axis: SupportsIndex | None = None, + *, + equal_nan: bool = True, + sorted: bool = True, +) -> tuple[_AnyArray, _IntArray]: ... +@overload # known scalar-type, FTF (positional) +def unique( + ar: _ArrayLike[_ScalarT], + return_index: L[False], + return_inverse: L[True], + return_counts: L[False] = False, + axis: SupportsIndex | None = None, + *, + equal_nan: bool = True, + sorted: bool = True, +) -> tuple[NDArray[_ScalarT], _IntArray]: ... +@overload # known scalar-type, FTF (keyword) +def unique( + ar: _ArrayLike[_ScalarT], + return_index: L[False] = False, + *, + return_inverse: L[True], + return_counts: L[False] = False, + axis: SupportsIndex | None = None, + equal_nan: bool = True, + sorted: bool = True, +) -> tuple[NDArray[_ScalarT], _IntArray]: ... +@overload # unknown scalar-type, FTF (positional) +def unique( + ar: ArrayLike, + return_index: L[False], + return_inverse: L[True], + return_counts: L[False] = False, + axis: SupportsIndex | None = None, + *, + equal_nan: bool = True, + sorted: bool = True, +) -> tuple[_AnyArray, _IntArray]: ... +@overload # unknown scalar-type, FTF (keyword) +def unique( + ar: ArrayLike, + return_index: L[False] = False, + *, + return_inverse: L[True], + return_counts: L[False] = False, + axis: SupportsIndex | None = None, + equal_nan: bool = True, + sorted: bool = True, +) -> tuple[_AnyArray, _IntArray]: ... +@overload # known scalar-type, FFT (positional) +def unique( + ar: _ArrayLike[_ScalarT], + return_index: L[False], + return_inverse: L[False], + return_counts: L[True], + axis: SupportsIndex | None = None, + *, + equal_nan: bool = True, + sorted: bool = True, +) -> tuple[NDArray[_ScalarT], _IntArray]: ... +@overload # known scalar-type, FFT (keyword) +def unique( + ar: _ArrayLike[_ScalarT], + return_index: L[False] = False, + return_inverse: L[False] = False, + *, + return_counts: L[True], + axis: SupportsIndex | None = None, + equal_nan: bool = True, + sorted: bool = True, +) -> tuple[NDArray[_ScalarT], _IntArray]: ... +@overload # unknown scalar-type, FFT (positional) +def unique( + ar: ArrayLike, + return_index: L[False], + return_inverse: L[False], + return_counts: L[True], + axis: SupportsIndex | None = None, + *, + equal_nan: bool = True, + sorted: bool = True, +) -> tuple[_AnyArray, _IntArray]: ... +@overload # unknown scalar-type, FFT (keyword) +def unique( + ar: ArrayLike, + return_index: L[False] = False, + return_inverse: L[False] = False, + *, + return_counts: L[True], + axis: SupportsIndex | None = None, + equal_nan: bool = True, + sorted: bool = True, +) -> tuple[_AnyArray, _IntArray]: ... +@overload # known scalar-type, TTF +def unique( + ar: _ArrayLike[_ScalarT], + return_index: L[True], + return_inverse: L[True], + return_counts: L[False] = False, + axis: SupportsIndex | None = None, + *, + equal_nan: bool = True, + sorted: bool = True, +) -> tuple[NDArray[_ScalarT], _IntArray, _IntArray]: ... +@overload # unknown scalar-type, TTF +def unique( + ar: ArrayLike, + return_index: L[True], + return_inverse: L[True], + return_counts: L[False] = False, + axis: SupportsIndex | None = None, + *, + equal_nan: bool = True, + sorted: bool = True, +) -> tuple[_AnyArray, _IntArray, _IntArray]: ... +@overload # known scalar-type, TFT (positional) +def unique( + ar: _ArrayLike[_ScalarT], + return_index: L[True], + return_inverse: L[False], + return_counts: L[True], + axis: SupportsIndex | None = None, + *, + equal_nan: bool = True, + sorted: bool = True, +) -> tuple[NDArray[_ScalarT], _IntArray, _IntArray]: ... +@overload # known scalar-type, TFT (keyword) +def unique( + ar: _ArrayLike[_ScalarT], + return_index: L[True], + return_inverse: L[False] = False, + *, + return_counts: L[True], + axis: SupportsIndex | None = None, + equal_nan: bool = True, + sorted: bool = True, +) -> tuple[NDArray[_ScalarT], _IntArray, _IntArray]: ... +@overload # unknown scalar-type, TFT (positional) +def unique( + ar: ArrayLike, + return_index: L[True], + return_inverse: L[False], + return_counts: L[True], + axis: SupportsIndex | None = None, + *, + equal_nan: bool = True, + sorted: bool = True, +) -> tuple[_AnyArray, _IntArray, _IntArray]: ... +@overload # unknown scalar-type, TFT (keyword) +def unique( + ar: ArrayLike, + return_index: L[True], + return_inverse: L[False] = False, + *, + return_counts: L[True], + axis: SupportsIndex | None = None, + equal_nan: bool = True, + sorted: bool = True, +) -> tuple[_AnyArray, _IntArray, _IntArray]: ... +@overload # known scalar-type, FTT (positional) +def unique( + ar: _ArrayLike[_ScalarT], + return_index: L[False], + return_inverse: L[True], + return_counts: L[True], + axis: SupportsIndex | None = None, + *, + equal_nan: bool = True, + sorted: bool = True, +) -> tuple[NDArray[_ScalarT], _IntArray, _IntArray]: ... +@overload # known scalar-type, FTT (keyword) +def unique( + ar: _ArrayLike[_ScalarT], + return_index: L[False] = False, + *, + return_inverse: L[True], + return_counts: L[True], + axis: SupportsIndex | None = None, + equal_nan: bool = True, + sorted: bool = True, +) -> tuple[NDArray[_ScalarT], _IntArray, _IntArray]: ... +@overload # unknown scalar-type, FTT (positional) +def unique( + ar: ArrayLike, + return_index: L[False], + return_inverse: L[True], + return_counts: L[True], + axis: SupportsIndex | None = None, + *, + equal_nan: bool = True, + sorted: bool = True, +) -> tuple[_AnyArray, _IntArray, _IntArray]: ... +@overload # unknown scalar-type, FTT (keyword) +def unique( + ar: ArrayLike, + return_index: L[False] = False, + *, + return_inverse: L[True], + return_counts: L[True], + axis: SupportsIndex | None = None, + equal_nan: bool = True, + sorted: bool = True, +) -> tuple[_AnyArray, _IntArray, _IntArray]: ... +@overload # known scalar-type, TTT +def unique( + ar: _ArrayLike[_ScalarT], + return_index: L[True], + return_inverse: L[True], + return_counts: L[True], + axis: SupportsIndex | None = None, + *, + equal_nan: bool = True, + sorted: bool = True, +) -> tuple[NDArray[_ScalarT], _IntArray, _IntArray, _IntArray]: ... +@overload # unknown scalar-type, TTT +def unique( + ar: ArrayLike, + return_index: L[True], + return_inverse: L[True], + return_counts: L[True], + axis: SupportsIndex | None = None, + *, + equal_nan: bool = True, + sorted: bool = True, +) -> tuple[_AnyArray, _IntArray, _IntArray, _IntArray]: ... + +# +@overload +def unique_all(x: _ArrayLike[_ScalarT]) -> UniqueAllResult[_ScalarT]: ... +@overload +def unique_all(x: ArrayLike) -> UniqueAllResult[Any]: ... + +# +@overload +def unique_counts(x: _ArrayLike[_ScalarT]) -> UniqueCountsResult[_ScalarT]: ... +@overload +def unique_counts(x: ArrayLike) -> UniqueCountsResult[Any]: ... + +# +@overload +def unique_inverse(x: _ArrayLike[_ScalarT]) -> UniqueInverseResult[_ScalarT]: ... +@overload +def unique_inverse(x: ArrayLike) -> UniqueInverseResult[Any]: ... + +# +@overload +def unique_values(x: _ArrayLike[_ScalarT]) -> NDArray[_ScalarT]: ... +@overload +def unique_values(x: ArrayLike) -> _AnyArray: ... + +# +@overload # known scalar-type, return_indices=False (default) +def intersect1d( + ar1: _ArrayLike[_EitherSCT], + ar2: _ArrayLike[_EitherSCT], + assume_unique: bool = False, + return_indices: L[False] = False, +) -> NDArray[_EitherSCT]: ... +@overload # known scalar-type, return_indices=True (positional) +def intersect1d( + ar1: _ArrayLike[_EitherSCT], + ar2: _ArrayLike[_EitherSCT], + assume_unique: bool, + return_indices: L[True], +) -> tuple[NDArray[_EitherSCT], _IntArray, _IntArray]: ... +@overload # known scalar-type, return_indices=True (keyword) +def intersect1d( + ar1: _ArrayLike[_EitherSCT], + ar2: _ArrayLike[_EitherSCT], + assume_unique: bool = False, + *, + return_indices: L[True], +) -> tuple[NDArray[_EitherSCT], _IntArray, _IntArray]: ... +@overload # unknown scalar-type, return_indices=False (default) +def intersect1d( + ar1: ArrayLike, + ar2: ArrayLike, + assume_unique: bool = False, + return_indices: L[False] = False, +) -> _AnyArray: ... +@overload # unknown scalar-type, return_indices=True (positional) +def intersect1d( + ar1: ArrayLike, + ar2: ArrayLike, + assume_unique: bool, + return_indices: L[True], +) -> tuple[_AnyArray, _IntArray, _IntArray]: ... +@overload # unknown scalar-type, return_indices=True (keyword) +def intersect1d( + ar1: ArrayLike, + ar2: ArrayLike, + assume_unique: bool = False, + *, + return_indices: L[True], +) -> tuple[_AnyArray, _IntArray, _IntArray]: ... + +# +@overload +def setxor1d(ar1: _ArrayLike[_EitherSCT], ar2: _ArrayLike[_EitherSCT], assume_unique: bool = False) -> NDArray[_EitherSCT]: ... +@overload +def setxor1d(ar1: ArrayLike, ar2: ArrayLike, assume_unique: bool = False) -> _AnyArray: ... + +# +@overload +def union1d(ar1: _ArrayLike[_EitherSCT], ar2: _ArrayLike[_EitherSCT]) -> NDArray[_EitherSCT]: ... +@overload +def union1d(ar1: ArrayLike, ar2: ArrayLike) -> _AnyArray: ... + +# +@overload +def setdiff1d(ar1: _ArrayLike[_EitherSCT], ar2: _ArrayLike[_EitherSCT], assume_unique: bool = False) -> NDArray[_EitherSCT]: ... +@overload +def setdiff1d(ar1: ArrayLike, ar2: ArrayLike, assume_unique: bool = False) -> _AnyArray: ... + +# +def isin( + element: ArrayLike, + test_elements: ArrayLike, + assume_unique: bool = False, + invert: bool = False, + *, + kind: L["sort", "table"] | None = None, +) -> NDArray[np.bool]: ... diff --git a/python/user_packages/Python313/site-packages/numpy/lib/_arrayterator_impl.py b/python/user_packages/Python313/site-packages/numpy/lib/_arrayterator_impl.py new file mode 100644 index 0000000000000000000000000000000000000000..844c0633dae90e77d058ea69a5a69df0005f657b --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/lib/_arrayterator_impl.py @@ -0,0 +1,224 @@ +""" +A buffered iterator for big arrays. + +This module solves the problem of iterating over a big file-based array +without having to read it into memory. The `Arrayterator` class wraps +an array object, and when iterated it will return sub-arrays with at most +a user-specified number of elements. + +""" +from functools import reduce +from operator import mul + +__all__ = ['Arrayterator'] + + +class Arrayterator: + """ + Buffered iterator for big arrays. + + `Arrayterator` creates a buffered iterator for reading big arrays in small + contiguous blocks. The class is useful for objects stored in the + file system. It allows iteration over the object *without* reading + everything in memory; instead, small blocks are read and iterated over. + + `Arrayterator` can be used with any object that supports multidimensional + slices. This includes NumPy arrays, but also variables from + Scientific.IO.NetCDF or pynetcdf for example. + + Parameters + ---------- + var : array_like + The object to iterate over. + buf_size : int, optional + The buffer size. If `buf_size` is supplied, the maximum amount of + data that will be read into memory is `buf_size` elements. + Default is None, which will read as many element as possible + into memory. + + Attributes + ---------- + var + buf_size + start + stop + step + shape + flat + + See Also + -------- + numpy.ndenumerate : Multidimensional array iterator. + numpy.flatiter : Flat array iterator. + numpy.memmap : Create a memory-map to an array stored + in a binary file on disk. + + Notes + ----- + The algorithm works by first finding a "running dimension", along which + the blocks will be extracted. Given an array of dimensions + ``(d1, d2, ..., dn)``, e.g. if `buf_size` is smaller than ``d1``, the + first dimension will be used. If, on the other hand, + ``d1 < buf_size < d1*d2`` the second dimension will be used, and so on. + Blocks are extracted along this dimension, and when the last block is + returned the process continues from the next dimension, until all + elements have been read. + + Examples + -------- + >>> import numpy as np + >>> a = np.arange(3 * 4 * 5 * 6).reshape(3, 4, 5, 6) + >>> a_itor = np.lib.Arrayterator(a, 2) + >>> a_itor.shape + (3, 4, 5, 6) + + Now we can iterate over ``a_itor``, and it will return arrays of size + two. Since `buf_size` was smaller than any dimension, the first + dimension will be iterated over first: + + >>> for subarr in a_itor: + ... if not subarr.all(): + ... print(subarr, subarr.shape) # doctest: +SKIP + >>> # [[[[0 1]]]] (1, 1, 1, 2) + + """ + + __module__ = "numpy.lib" + + def __init__(self, var, buf_size=None): + self.var = var + self.buf_size = buf_size + + self.start = [0 for dim in var.shape] + self.stop = list(var.shape) + self.step = [1 for dim in var.shape] + + def __getattr__(self, attr): + return getattr(self.var, attr) + + def __getitem__(self, index): + """ + Return a new arrayterator. + + """ + # Fix index, handling ellipsis and incomplete slices. + if not isinstance(index, tuple): + index = (index,) + fixed = [] + length, dims = len(index), self.ndim + for slice_ in index: + if slice_ is Ellipsis: + fixed.extend([slice(None)] * (dims - length + 1)) + length = len(fixed) + elif isinstance(slice_, int): + fixed.append(slice(slice_, slice_ + 1, 1)) + else: + fixed.append(slice_) + index = tuple(fixed) + if len(index) < dims: + index += (slice(None),) * (dims - len(index)) + + # Return a new arrayterator object. + out = self.__class__(self.var, self.buf_size) + for i, (start, stop, step, slice_) in enumerate( + zip(self.start, self.stop, self.step, index)): + out.start[i] = start + (slice_.start or 0) + out.step[i] = step * (slice_.step or 1) + out.stop[i] = start + (slice_.stop or stop - start) + out.stop[i] = min(stop, out.stop[i]) + return out + + def __array__(self, dtype=None, copy=None): + """ + Return corresponding data. + + """ + slice_ = tuple(slice(*t) for t in zip( + self.start, self.stop, self.step)) + return self.var[slice_] + + @property + def flat(self): + """ + A 1-D flat iterator for Arrayterator objects. + + This iterator returns elements of the array to be iterated over in + `~lib.Arrayterator` one by one. + It is similar to `flatiter`. + + See Also + -------- + lib.Arrayterator + flatiter + + Examples + -------- + >>> a = np.arange(3 * 4 * 5 * 6).reshape(3, 4, 5, 6) + >>> a_itor = np.lib.Arrayterator(a, 2) + + >>> for subarr in a_itor.flat: + ... if not subarr: + ... print(subarr, type(subarr)) + ... + 0 + + """ + for block in self: + yield from block.flat + + @property + def shape(self): + """ + The shape of the array to be iterated over. + + For an example, see `Arrayterator`. + + """ + return tuple(((stop - start - 1) // step + 1) for start, stop, step in + zip(self.start, self.stop, self.step)) + + def __iter__(self): + # Skip arrays with degenerate dimensions + if [dim for dim in self.shape if dim <= 0]: + return + + start = self.start[:] + stop = self.stop[:] + step = self.step[:] + ndims = self.var.ndim + + while True: + count = self.buf_size or reduce(mul, self.shape) + + # iterate over each dimension, looking for the + # running dimension (ie, the dimension along which + # the blocks will be built from) + rundim = 0 + for i in range(ndims - 1, -1, -1): + # if count is zero we ran out of elements to read + # along higher dimensions, so we read only a single position + if count == 0: + stop[i] = start[i] + 1 + elif count <= self.shape[i]: + # limit along this dimension + stop[i] = start[i] + count * step[i] + rundim = i + else: + # read everything along this dimension + stop[i] = self.stop[i] + stop[i] = min(self.stop[i], stop[i]) + count = count // self.shape[i] + + # yield a block + slice_ = tuple(slice(*t) for t in zip(start, stop, step)) + yield self.var[slice_] + + # Update start position, taking care of overflow to + # other dimensions + start[rundim] = stop[rundim] # start where we stopped + for i in range(ndims - 1, 0, -1): + if start[i] >= self.stop[i]: + start[i] = self.start[i] + start[i - 1] += self.step[i - 1] + if start[0] >= self.stop[0]: + return diff --git a/python/user_packages/Python313/site-packages/numpy/lib/_arrayterator_impl.pyi b/python/user_packages/Python313/site-packages/numpy/lib/_arrayterator_impl.pyi new file mode 100644 index 0000000000000000000000000000000000000000..eeddcf301ad1f2c10493c4a927753015660ff230 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/lib/_arrayterator_impl.pyi @@ -0,0 +1,45 @@ +# pyright: reportIncompatibleMethodOverride=false + +from collections.abc import Generator +from types import EllipsisType +from typing import Any, Final, TypeAlias, overload +from typing_extensions import TypeVar + +import numpy as np +from numpy._typing import _AnyShape, _Shape + +__all__ = ["Arrayterator"] + +_ShapeT_co = TypeVar("_ShapeT_co", bound=_Shape, default=_AnyShape, covariant=True) +_DTypeT = TypeVar("_DTypeT", bound=np.dtype) +_DTypeT_co = TypeVar("_DTypeT_co", bound=np.dtype, default=np.dtype, covariant=True) +_ScalarT = TypeVar("_ScalarT", bound=np.generic) + +_AnyIndex: TypeAlias = EllipsisType | int | slice | tuple[EllipsisType | int | slice, ...] + +# NOTE: In reality `Arrayterator` does not actually inherit from `ndarray`, +# but its ``__getattr__` method does wrap around the former and thus has +# access to all its methods + +class Arrayterator(np.ndarray[_ShapeT_co, _DTypeT_co]): + var: np.ndarray[_ShapeT_co, _DTypeT_co] # type: ignore[assignment] + buf_size: Final[int | None] + start: Final[list[int]] + stop: Final[list[int]] + step: Final[list[int]] + + @property # type: ignore[misc] + def shape(self) -> _ShapeT_co: ... + @property + def flat(self: Arrayterator[Any, np.dtype[_ScalarT]]) -> Generator[_ScalarT]: ... # type: ignore[override] + + # + def __init__(self, /, var: np.ndarray[_ShapeT_co, _DTypeT_co], buf_size: int | None = None) -> None: ... + def __getitem__(self, index: _AnyIndex, /) -> Arrayterator[_AnyShape, _DTypeT_co]: ... # type: ignore[override] + def __iter__(self) -> Generator[np.ndarray[_AnyShape, _DTypeT_co]]: ... + + # + @overload # type: ignore[override] + def __array__(self, /, dtype: None = None, copy: bool | None = None) -> np.ndarray[_ShapeT_co, _DTypeT_co]: ... + @overload + def __array__(self, /, dtype: _DTypeT, copy: bool | None = None) -> np.ndarray[_ShapeT_co, _DTypeT]: ... diff --git a/python/user_packages/Python313/site-packages/numpy/lib/_datasource.py b/python/user_packages/Python313/site-packages/numpy/lib/_datasource.py new file mode 100644 index 0000000000000000000000000000000000000000..c36aa356bf4eb698ed5f616322e55bfab2104047 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/lib/_datasource.py @@ -0,0 +1,700 @@ +"""A file interface for handling local and remote data files. + +The goal of datasource is to abstract some of the file system operations +when dealing with data files so the researcher doesn't have to know all the +low-level details. Through datasource, a researcher can obtain and use a +file with one function call, regardless of location of the file. + +DataSource is meant to augment standard python libraries, not replace them. +It should work seamlessly with standard file IO operations and the os +module. + +DataSource files can originate locally or remotely: + +- local files : '/home/guido/src/local/data.txt' +- URLs (http, ftp, ...) : 'http://www.scipy.org/not/real/data.txt' + +DataSource files can also be compressed or uncompressed. Currently only +gzip, bz2 and xz are supported. + +Example:: + + >>> # Create a DataSource, use os.curdir (default) for local storage. + >>> from numpy import DataSource + >>> ds = DataSource() + >>> + >>> # Open a remote file. + >>> # DataSource downloads the file, stores it locally in: + >>> # './www.google.com/index.html' + >>> # opens the file and returns a file object. + >>> fp = ds.open('http://www.google.com/') # doctest: +SKIP + >>> + >>> # Use the file as you normally would + >>> fp.read() # doctest: +SKIP + >>> fp.close() # doctest: +SKIP + +""" +import os + +from numpy._utils import set_module + +_open = open + + +def _check_mode(mode, encoding, newline): + """Check mode and that encoding and newline are compatible. + + Parameters + ---------- + mode : str + File open mode. + encoding : str + File encoding. + newline : str + Newline for text files. + + """ + if "t" in mode: + if "b" in mode: + raise ValueError(f"Invalid mode: {mode!r}") + else: + if encoding is not None: + raise ValueError("Argument 'encoding' not supported in binary mode") + if newline is not None: + raise ValueError("Argument 'newline' not supported in binary mode") + + +# Using a class instead of a module-level dictionary +# to reduce the initial 'import numpy' overhead by +# deferring the import of lzma, bz2 and gzip until needed + +# TODO: .zip support, .tar support? +class _FileOpeners: + """ + Container for different methods to open (un-)compressed files. + + `_FileOpeners` contains a dictionary that holds one method for each + supported file format. Attribute lookup is implemented in such a way + that an instance of `_FileOpeners` itself can be indexed with the keys + of that dictionary. Currently uncompressed files as well as files + compressed with ``gzip``, ``bz2`` or ``xz`` compression are supported. + + Notes + ----- + `_file_openers`, an instance of `_FileOpeners`, is made available for + use in the `_datasource` module. + + Examples + -------- + >>> import gzip + >>> np.lib._datasource._file_openers.keys() + [None, '.bz2', '.gz', '.xz', '.lzma'] + >>> np.lib._datasource._file_openers['.gz'] is gzip.open + True + + """ + + def __init__(self): + self._loaded = False + self._file_openers = {None: open} + + def _load(self): + if self._loaded: + return + + try: + import bz2 + self._file_openers[".bz2"] = bz2.open + except ImportError: + pass + + try: + import gzip + self._file_openers[".gz"] = gzip.open + except ImportError: + pass + + try: + import lzma + self._file_openers[".xz"] = lzma.open + self._file_openers[".lzma"] = lzma.open + except (ImportError, AttributeError): + # There are incompatible backports of lzma that do not have the + # lzma.open attribute, so catch that as well as ImportError. + pass + + self._loaded = True + + def keys(self): + """ + Return the keys of currently supported file openers. + + Parameters + ---------- + None + + Returns + ------- + keys : list + The keys are None for uncompressed files and the file extension + strings (i.e. ``'.gz'``, ``'.xz'``) for supported compression + methods. + + """ + self._load() + return list(self._file_openers.keys()) + + def __getitem__(self, key): + self._load() + return self._file_openers[key] + + +_file_openers = _FileOpeners() + +def open(path, mode='r', destpath=os.curdir, encoding=None, newline=None): + """ + Open `path` with `mode` and return the file object. + + If ``path`` is an URL, it will be downloaded, stored in the + `DataSource` `destpath` directory and opened from there. + + Parameters + ---------- + path : str or pathlib.Path + Local file path or URL to open. + mode : str, optional + Mode to open `path`. Mode 'r' for reading, 'w' for writing, 'a' to + append. Available modes depend on the type of object specified by + path. Default is 'r'. + destpath : str, optional + Path to the directory where the source file gets downloaded to for + use. If `destpath` is None, a temporary directory will be created. + The default path is the current directory. + encoding : {None, str}, optional + Open text file with given encoding. The default encoding will be + what `open` uses. + newline : {None, str}, optional + Newline to use when reading text file. + + Returns + ------- + out : file object + The opened file. + + Notes + ----- + This is a convenience function that instantiates a `DataSource` and + returns the file object from ``DataSource.open(path)``. + + """ + + ds = DataSource(destpath) + return ds.open(path, mode, encoding=encoding, newline=newline) + + +@set_module('numpy.lib.npyio') +class DataSource: + """ + DataSource(destpath='.') + + A generic data source file (file, http, ftp, ...). + + DataSources can be local files or remote files/URLs. The files may + also be compressed or uncompressed. DataSource hides some of the + low-level details of downloading the file, allowing you to simply pass + in a valid file path (or URL) and obtain a file object. + + Parameters + ---------- + destpath : str or None, optional + Path to the directory where the source file gets downloaded to for + use. If `destpath` is None, a temporary directory will be created. + The default path is the current directory. + + Notes + ----- + URLs require a scheme string (``http://``) to be used, without it they + will fail:: + + >>> repos = np.lib.npyio.DataSource() + >>> repos.exists('www.google.com/index.html') + False + >>> repos.exists('http://www.google.com/index.html') + True + + Temporary directories are deleted when the DataSource is deleted. + + Examples + -------- + :: + + >>> ds = np.lib.npyio.DataSource('/home/guido') + >>> urlname = 'http://www.google.com/' + >>> gfile = ds.open('http://www.google.com/') + >>> ds.abspath(urlname) + '/home/guido/www.google.com/index.html' + + >>> ds = np.lib.npyio.DataSource(None) # use with temporary file + >>> ds.open('/home/guido/foobar.txt') + + >>> ds.abspath('/home/guido/foobar.txt') + '/tmp/.../home/guido/foobar.txt' + + """ + + def __init__(self, destpath=os.curdir): + """Create a DataSource with a local path at destpath.""" + if destpath: + self._destpath = os.path.abspath(destpath) + self._istmpdest = False + else: + import tempfile # deferring import to improve startup time + self._destpath = tempfile.mkdtemp() + self._istmpdest = True + + def __del__(self): + # Remove temp directories + if hasattr(self, '_istmpdest') and self._istmpdest: + import shutil + + shutil.rmtree(self._destpath) + + def _iszip(self, filename): + """Test if the filename is a zip file by looking at the file extension. + + """ + fname, ext = os.path.splitext(filename) + return ext in _file_openers.keys() + + def _iswritemode(self, mode): + """Test if the given mode will open a file for writing.""" + + # Currently only used to test the bz2 files. + _writemodes = ("w", "+") + return any(c in _writemodes for c in mode) + + def _splitzipext(self, filename): + """Split zip extension from filename and return filename. + + Returns + ------- + base, zip_ext : {tuple} + + """ + + if self._iszip(filename): + return os.path.splitext(filename) + else: + return filename, None + + def _possible_names(self, filename): + """Return a tuple containing compressed filename variations.""" + names = [filename] + if not self._iszip(filename): + for zipext in _file_openers.keys(): + if zipext: + names.append(filename + zipext) + return names + + def _isurl(self, path): + """Test if path is a net location. Tests the scheme and netloc.""" + + # We do this here to reduce the 'import numpy' initial import time. + from urllib.parse import urlparse + + # BUG : URLs require a scheme string ('http://') to be used. + # www.google.com will fail. + # Should we prepend the scheme for those that don't have it and + # test that also? Similar to the way we append .gz and test for + # for compressed versions of files. + + scheme, netloc, upath, uparams, uquery, ufrag = urlparse(path) + return bool(scheme and netloc) + + def _cache(self, path): + """Cache the file specified by path. + + Creates a copy of the file in the datasource cache. + + """ + # We import these here because importing them is slow and + # a significant fraction of numpy's total import time. + import shutil + from urllib.request import urlopen + + upath = self.abspath(path) + + # ensure directory exists + if not os.path.exists(os.path.dirname(upath)): + os.makedirs(os.path.dirname(upath)) + + # TODO: Doesn't handle compressed files! + if self._isurl(path): + with urlopen(path) as openedurl: + with _open(upath, 'wb') as f: + shutil.copyfileobj(openedurl, f) + else: + shutil.copyfile(path, upath) + return upath + + def _findfile(self, path): + """Searches for ``path`` and returns full path if found. + + If path is an URL, _findfile will cache a local copy and return the + path to the cached file. If path is a local file, _findfile will + return a path to that local file. + + The search will include possible compressed versions of the file + and return the first occurrence found. + + """ + + # Build list of possible local file paths + if not self._isurl(path): + # Valid local paths + filelist = self._possible_names(path) + # Paths in self._destpath + filelist += self._possible_names(self.abspath(path)) + else: + # Cached URLs in self._destpath + filelist = self._possible_names(self.abspath(path)) + # Remote URLs + filelist = filelist + self._possible_names(path) + + for name in filelist: + if self.exists(name): + if self._isurl(name): + name = self._cache(name) + return name + return None + + def abspath(self, path): + """ + Return absolute path of file in the DataSource directory. + + If `path` is an URL, then `abspath` will return either the location + the file exists locally or the location it would exist when opened + using the `open` method. + + Parameters + ---------- + path : str or pathlib.Path + Can be a local file or a remote URL. + + Returns + ------- + out : str + Complete path, including the `DataSource` destination directory. + + Notes + ----- + The functionality is based on `os.path.abspath`. + + """ + # We do this here to reduce the 'import numpy' initial import time. + from urllib.parse import urlparse + + # TODO: This should be more robust. Handles case where path includes + # the destpath, but not other sub-paths. Failing case: + # path = /home/guido/datafile.txt + # destpath = /home/alex/ + # upath = self.abspath(path) + # upath == '/home/alex/home/guido/datafile.txt' + + # handle case where path includes self._destpath + splitpath = path.split(self._destpath, 2) + if len(splitpath) > 1: + path = splitpath[1] + scheme, netloc, upath, uparams, uquery, ufrag = urlparse(path) + netloc = self._sanitize_relative_path(netloc) + upath = self._sanitize_relative_path(upath) + return os.path.join(self._destpath, netloc, upath) + + def _sanitize_relative_path(self, path): + """Return a sanitised relative path for which + os.path.abspath(os.path.join(base, path)).startswith(base) + """ + last = None + path = os.path.normpath(path) + while path != last: + last = path + # Note: os.path.join treats '/' as os.sep on Windows + path = path.lstrip(os.sep).lstrip('/') + path = path.lstrip(os.pardir).removeprefix('..') + drive, path = os.path.splitdrive(path) # for Windows + return path + + def exists(self, path): + """ + Test if path exists. + + Test if `path` exists as (and in this order): + + - a local file. + - a remote URL that has been downloaded and stored locally in the + `DataSource` directory. + - a remote URL that has not been downloaded, but is valid and + accessible. + + Parameters + ---------- + path : str or pathlib.Path + Can be a local file or a remote URL. + + Returns + ------- + out : bool + True if `path` exists. + + Notes + ----- + When `path` is an URL, `exists` will return True if it's either + stored locally in the `DataSource` directory, or is a valid remote + URL. `DataSource` does not discriminate between the two, the file + is accessible if it exists in either location. + + """ + + # First test for local path + if os.path.exists(path): + return True + + # We import this here because importing urllib is slow and + # a significant fraction of numpy's total import time. + from urllib.error import URLError + from urllib.request import urlopen + + # Test cached url + upath = self.abspath(path) + if os.path.exists(upath): + return True + + # Test remote url + if self._isurl(path): + try: + netfile = urlopen(path) + netfile.close() + del netfile + return True + except URLError: + return False + return False + + def open(self, path, mode='r', encoding=None, newline=None): + """ + Open and return file-like object. + + If `path` is an URL, it will be downloaded, stored in the + `DataSource` directory and opened from there. + + Parameters + ---------- + path : str or pathlib.Path + Local file path or URL to open. + mode : {'r', 'w', 'a'}, optional + Mode to open `path`. Mode 'r' for reading, 'w' for writing, + 'a' to append. Available modes depend on the type of object + specified by `path`. Default is 'r'. + encoding : {None, str}, optional + Open text file with given encoding. The default encoding will be + what `open` uses. + newline : {None, str}, optional + Newline to use when reading text file. + + Returns + ------- + out : file object + File object. + + """ + + # TODO: There is no support for opening a file for writing which + # doesn't exist yet (creating a file). Should there be? + + # TODO: Add a ``subdir`` parameter for specifying the subdirectory + # used to store URLs in self._destpath. + + if self._isurl(path) and self._iswritemode(mode): + raise ValueError("URLs are not writeable") + + # NOTE: _findfile will fail on a new file opened for writing. + found = self._findfile(path) + if found: + _fname, ext = self._splitzipext(found) + if ext == 'bz2': + mode.replace("+", "") + return _file_openers[ext](found, mode=mode, + encoding=encoding, newline=newline) + else: + raise FileNotFoundError(f"{path} not found.") + + +class Repository (DataSource): + """ + Repository(baseurl, destpath='.') + + A data repository where multiple DataSource's share a base + URL/directory. + + `Repository` extends `DataSource` by prepending a base URL (or + directory) to all the files it handles. Use `Repository` when you will + be working with multiple files from one base URL. Initialize + `Repository` with the base URL, then refer to each file by its filename + only. + + Parameters + ---------- + baseurl : str + Path to the local directory or remote location that contains the + data files. + destpath : str or None, optional + Path to the directory where the source file gets downloaded to for + use. If `destpath` is None, a temporary directory will be created. + The default path is the current directory. + + Examples + -------- + To analyze all files in the repository, do something like this + (note: this is not self-contained code):: + + >>> repos = np.lib._datasource.Repository('/home/user/data/dir/') + >>> for filename in filelist: + ... fp = repos.open(filename) + ... fp.analyze() + ... fp.close() + + Similarly you could use a URL for a repository:: + + >>> repos = np.lib._datasource.Repository('http://www.xyz.edu/data') + + """ + + def __init__(self, baseurl, destpath=os.curdir): + """Create a Repository with a shared url or directory of baseurl.""" + DataSource.__init__(self, destpath=destpath) + self._baseurl = baseurl + + def __del__(self): + DataSource.__del__(self) + + def _fullpath(self, path): + """Return complete path for path. Prepends baseurl if necessary.""" + splitpath = path.split(self._baseurl, 2) + if len(splitpath) == 1: + result = os.path.join(self._baseurl, path) + else: + result = path # path contains baseurl already + return result + + def _findfile(self, path): + """Extend DataSource method to prepend baseurl to ``path``.""" + return DataSource._findfile(self, self._fullpath(path)) + + def abspath(self, path): + """ + Return absolute path of file in the Repository directory. + + If `path` is an URL, then `abspath` will return either the location + the file exists locally or the location it would exist when opened + using the `open` method. + + Parameters + ---------- + path : str or pathlib.Path + Can be a local file or a remote URL. This may, but does not + have to, include the `baseurl` with which the `Repository` was + initialized. + + Returns + ------- + out : str + Complete path, including the `DataSource` destination directory. + + """ + return DataSource.abspath(self, self._fullpath(path)) + + def exists(self, path): + """ + Test if path exists prepending Repository base URL to path. + + Test if `path` exists as (and in this order): + + - a local file. + - a remote URL that has been downloaded and stored locally in the + `DataSource` directory. + - a remote URL that has not been downloaded, but is valid and + accessible. + + Parameters + ---------- + path : str or pathlib.Path + Can be a local file or a remote URL. This may, but does not + have to, include the `baseurl` with which the `Repository` was + initialized. + + Returns + ------- + out : bool + True if `path` exists. + + Notes + ----- + When `path` is an URL, `exists` will return True if it's either + stored locally in the `DataSource` directory, or is a valid remote + URL. `DataSource` does not discriminate between the two, the file + is accessible if it exists in either location. + + """ + return DataSource.exists(self, self._fullpath(path)) + + def open(self, path, mode='r', encoding=None, newline=None): + """ + Open and return file-like object prepending Repository base URL. + + If `path` is an URL, it will be downloaded, stored in the + DataSource directory and opened from there. + + Parameters + ---------- + path : str or pathlib.Path + Local file path or URL to open. This may, but does not have to, + include the `baseurl` with which the `Repository` was + initialized. + mode : {'r', 'w', 'a'}, optional + Mode to open `path`. Mode 'r' for reading, 'w' for writing, + 'a' to append. Available modes depend on the type of object + specified by `path`. Default is 'r'. + encoding : {None, str}, optional + Open text file with given encoding. The default encoding will be + what `open` uses. + newline : {None, str}, optional + Newline to use when reading text file. + + Returns + ------- + out : file object + File object. + + """ + return DataSource.open(self, self._fullpath(path), mode, + encoding=encoding, newline=newline) + + def listdir(self): + """ + List files in the source Repository. + + Returns + ------- + files : list of str or pathlib.Path + List of file names (not containing a directory part). + + Notes + ----- + Does not currently work for remote repositories. + + """ + if self._isurl(self._baseurl): + raise NotImplementedError( + "Directory listing of URLs, not supported yet.") + else: + return os.listdir(self._baseurl) diff --git a/python/user_packages/Python313/site-packages/numpy/lib/_datasource.pyi b/python/user_packages/Python313/site-packages/numpy/lib/_datasource.pyi new file mode 100644 index 0000000000000000000000000000000000000000..35631cf9f1f367107d89d3146f4e5bf4e6fd0ce2 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/lib/_datasource.pyi @@ -0,0 +1,30 @@ +from _typeshed import OpenBinaryMode, OpenTextMode +from pathlib import Path +from typing import IO, Any, TypeAlias + +_Mode: TypeAlias = OpenBinaryMode | OpenTextMode + +### + +# exported in numpy.lib.nppyio +class DataSource: + def __init__(self, /, destpath: Path | str | None = ".") -> None: ... + def __del__(self, /) -> None: ... + def abspath(self, /, path: str) -> str: ... + def exists(self, /, path: str) -> bool: ... + + # Whether the file-object is opened in string or bytes mode (by default) + # depends on the file-extension of `path` + def open(self, /, path: str, mode: _Mode = "r", encoding: str | None = None, newline: str | None = None) -> IO[Any]: ... + +class Repository(DataSource): + def __init__(self, /, baseurl: str, destpath: str | None = ".") -> None: ... + def listdir(self, /) -> list[str]: ... + +def open( + path: str, + mode: _Mode = "r", + destpath: str | None = ".", + encoding: str | None = None, + newline: str | None = None, +) -> IO[Any]: ... diff --git a/python/user_packages/Python313/site-packages/numpy/lib/_format_impl.py b/python/user_packages/Python313/site-packages/numpy/lib/_format_impl.py new file mode 100644 index 0000000000000000000000000000000000000000..047806a2f115f6eabdf8e6702345c1fbf40cdc2e --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/lib/_format_impl.py @@ -0,0 +1,1036 @@ +""" +Binary serialization + +NPY format +========== + +A simple format for saving numpy arrays to disk with the full +information about them. + +The ``.npy`` format is the standard binary file format in NumPy for +persisting a *single* arbitrary NumPy array on disk. The format stores all +of the shape and dtype information necessary to reconstruct the array +correctly even on another machine with a different architecture. +The format is designed to be as simple as possible while achieving +its limited goals. + +The ``.npz`` format is the standard format for persisting *multiple* NumPy +arrays on disk. A ``.npz`` file is a zip file containing multiple ``.npy`` +files, one for each array. + +Capabilities +------------ + +- Can represent all NumPy arrays including nested record arrays and + object arrays. + +- Represents the data in its native binary form. + +- Supports Fortran-contiguous arrays directly. + +- Stores all of the necessary information to reconstruct the array + including shape and dtype on a machine of a different + architecture. Both little-endian and big-endian arrays are + supported, and a file with little-endian numbers will yield + a little-endian array on any machine reading the file. The + types are described in terms of their actual sizes. For example, + if a machine with a 64-bit C "long int" writes out an array with + "long ints", a reading machine with 32-bit C "long ints" will yield + an array with 64-bit integers. + +- Is straightforward to reverse engineer. Datasets often live longer than + the programs that created them. A competent developer should be + able to create a solution in their preferred programming language to + read most ``.npy`` files that they have been given without much + documentation. + +- Allows memory-mapping of the data. See `open_memmap`. + +- Can be read from a filelike stream object instead of an actual file. + +- Stores object arrays, i.e. arrays containing elements that are arbitrary + Python objects. Files with object arrays are not to be mmapable, but + can be read and written to disk. + +Limitations +----------- + +- Arbitrary subclasses of numpy.ndarray are not completely preserved. + Subclasses will be accepted for writing, but only the array data will + be written out. A regular numpy.ndarray object will be created + upon reading the file. + +.. warning:: + + Due to limitations in the interpretation of structured dtypes, dtypes + with fields with empty names will have the names replaced by 'f0', 'f1', + etc. Such arrays will not round-trip through the format entirely + accurately. The data is intact; only the field names will differ. We are + working on a fix for this. This fix will not require a change in the + file format. The arrays with such structures can still be saved and + restored, and the correct dtype may be restored by using the + ``loadedarray.view(correct_dtype)`` method. + +File extensions +--------------- + +We recommend using the ``.npy`` and ``.npz`` extensions for files saved +in this format. This is by no means a requirement; applications may wish +to use these file formats but use an extension specific to the +application. In the absence of an obvious alternative, however, +we suggest using ``.npy`` and ``.npz``. + +Version numbering +----------------- + +The version numbering of these formats is independent of NumPy version +numbering. If the format is upgraded, the code in `numpy.io` will still +be able to read and write Version 1.0 files. + +Format Version 1.0 +------------------ + +The first 6 bytes are a magic string: exactly ``\\x93NUMPY``. + +The next 1 byte is an unsigned byte: the major version number of the file +format, e.g. ``\\x01``. + +The next 1 byte is an unsigned byte: the minor version number of the file +format, e.g. ``\\x00``. Note: the version of the file format is not tied +to the version of the numpy package. + +The next 2 bytes form a little-endian unsigned short int: the length of +the header data HEADER_LEN. + +The next HEADER_LEN bytes form the header data describing the array's +format. It is an ASCII string which contains a Python literal expression +of a dictionary. It is terminated by a newline (``\\n``) and padded with +spaces (``\\x20``) to make the total of +``len(magic string) + 2 + len(length) + HEADER_LEN`` be evenly divisible +by 64 for alignment purposes. + +The dictionary contains three keys: + + "descr" : dtype.descr + An object that can be passed as an argument to the `numpy.dtype` + constructor to create the array's dtype. + "fortran_order" : bool + Whether the array data is Fortran-contiguous or not. Since + Fortran-contiguous arrays are a common form of non-C-contiguity, + we allow them to be written directly to disk for efficiency. + "shape" : tuple of int + The shape of the array. + +For repeatability and readability, the dictionary keys are sorted in +alphabetic order. This is for convenience only. A writer SHOULD implement +this if possible. A reader MUST NOT depend on this. + +Following the header comes the array data. If the dtype contains Python +objects (i.e. ``dtype.hasobject is True``), then the data is a Python +pickle of the array. Otherwise the data is the contiguous (either C- +or Fortran-, depending on ``fortran_order``) bytes of the array. +Consumers can figure out the number of bytes by multiplying the number +of elements given by the shape (noting that ``shape=()`` means there is +1 element) by ``dtype.itemsize``. + +Format Version 2.0 +------------------ + +The version 1.0 format only allowed the array header to have a total size of +65535 bytes. This can be exceeded by structured arrays with a large number of +columns. The version 2.0 format extends the header size to 4 GiB. +`numpy.save` will automatically save in 2.0 format if the data requires it, +else it will always use the more compatible 1.0 format. + +The description of the fourth element of the header therefore has become: +"The next 4 bytes form a little-endian unsigned int: the length of the header +data HEADER_LEN." + +Format Version 3.0 +------------------ + +This version replaces the ASCII string (which in practice was latin1) with +a utf8-encoded string, so supports structured types with any unicode field +names. + +Notes +----- +The ``.npy`` format, including motivation for creating it and a comparison of +alternatives, is described in the +:doc:`"npy-format" NEP `, however details have +evolved with time and this document is more current. + +""" +import io +import os +import pickle +import warnings + +import numpy +from numpy._utils import set_module +from numpy.lib._utils_impl import drop_metadata + +__all__ = [] + +drop_metadata.__module__ = "numpy.lib.format" + +EXPECTED_KEYS = {'descr', 'fortran_order', 'shape'} +MAGIC_PREFIX = b'\x93NUMPY' +MAGIC_LEN = len(MAGIC_PREFIX) + 2 +ARRAY_ALIGN = 64 # plausible values are powers of 2 between 16 and 4096 +BUFFER_SIZE = 2**18 # size of buffer for reading npz files in bytes +# allow growth within the address space of a 64 bit machine along one axis +GROWTH_AXIS_MAX_DIGITS = 21 # = len(str(8*2**64-1)) hypothetical int1 dtype + +# difference between version 1.0 and 2.0 is a 4 byte (I) header length +# instead of 2 bytes (H) allowing storage of large structured arrays +_header_size_info = { + (1, 0): (' 255: + raise ValueError("major version must be 0 <= major < 256") + if minor < 0 or minor > 255: + raise ValueError("minor version must be 0 <= minor < 256") + return MAGIC_PREFIX + bytes([major, minor]) + + +@set_module("numpy.lib.format") +def read_magic(fp): + """ Read the magic string to get the version of the file format. + + Parameters + ---------- + fp : filelike object + + Returns + ------- + major : int + minor : int + """ + magic_str = _read_bytes(fp, MAGIC_LEN, "magic string") + if magic_str[:-2] != MAGIC_PREFIX: + msg = "the magic string is not correct; expected %r, got %r" + raise ValueError(msg % (MAGIC_PREFIX, magic_str[:-2])) + major, minor = magic_str[-2:] + return major, minor + + +@set_module("numpy.lib.format") +def dtype_to_descr(dtype): + """ + Get a serializable descriptor from the dtype. + + The .descr attribute of a dtype object cannot be round-tripped through + the dtype() constructor. Simple types, like dtype('float32'), have + a descr which looks like a record array with one field with '' as + a name. The dtype() constructor interprets this as a request to give + a default name. Instead, we construct descriptor that can be passed to + dtype(). + + Parameters + ---------- + dtype : dtype + The dtype of the array that will be written to disk. + + Returns + ------- + descr : object + An object that can be passed to `numpy.dtype()` in order to + replicate the input dtype. + + """ + # NOTE: that drop_metadata may not return the right dtype e.g. for user + # dtypes. In that case our code below would fail the same, though. + new_dtype = drop_metadata(dtype) + if new_dtype is not dtype: + warnings.warn("metadata on a dtype is not saved to an npy/npz. " + "Use another format (such as pickle) to store it.", + UserWarning, stacklevel=2) + dtype = new_dtype + + if dtype.names is not None: + # This is a record array. The .descr is fine. XXX: parts of the + # record array with an empty name, like padding bytes, still get + # fiddled with. This needs to be fixed in the C implementation of + # dtype(). + return dtype.descr + elif not type(dtype)._legacy: + # this must be a user-defined dtype since numpy does not yet expose any + # non-legacy dtypes in the public API + # + # non-legacy dtypes don't yet have __array_interface__ + # support. Instead, as a hack, we use pickle to save the array, and lie + # that the dtype is object. When the array is loaded, the descriptor is + # unpickled with the array and the object dtype in the header is + # discarded. + # + # a future NEP should define a way to serialize user-defined + # descriptors and ideally work out the possible security implications + warnings.warn("Custom dtypes are saved as python objects using the " + "pickle protocol. Loading this file requires " + "allow_pickle=True to be set.", + UserWarning, stacklevel=2) + return "|O" + else: + return dtype.str + + +@set_module("numpy.lib.format") +def descr_to_dtype(descr): + """ + Returns a dtype based off the given description. + + This is essentially the reverse of `~lib.format.dtype_to_descr`. It will + remove the valueless padding fields created by, i.e. simple fields like + dtype('float32'), and then convert the description to its corresponding + dtype. + + Parameters + ---------- + descr : object + The object retrieved by dtype.descr. Can be passed to + `numpy.dtype` in order to replicate the input dtype. + + Returns + ------- + dtype : dtype + The dtype constructed by the description. + + """ + if isinstance(descr, str): + # No padding removal needed + return numpy.dtype(descr) + elif isinstance(descr, tuple): + # subtype, will always have a shape descr[1] + dt = descr_to_dtype(descr[0]) + return numpy.dtype((dt, descr[1])) + + titles = [] + names = [] + formats = [] + offsets = [] + offset = 0 + for field in descr: + if len(field) == 2: + name, descr_str = field + dt = descr_to_dtype(descr_str) + else: + name, descr_str, shape = field + dt = numpy.dtype((descr_to_dtype(descr_str), shape)) + + # Ignore padding bytes, which will be void bytes with '' as name + # Once support for blank names is removed, only "if name == ''" needed) + is_pad = (name == '' and dt.type is numpy.void and dt.names is None) + if not is_pad: + title, name = name if isinstance(name, tuple) else (None, name) + titles.append(title) + names.append(name) + formats.append(dt) + offsets.append(offset) + offset += dt.itemsize + + return numpy.dtype({'names': names, 'formats': formats, 'titles': titles, + 'offsets': offsets, 'itemsize': offset}) + + +@set_module("numpy.lib.format") +def header_data_from_array_1_0(array): + """ Get the dictionary of header metadata from a numpy.ndarray. + + Parameters + ---------- + array : numpy.ndarray + + Returns + ------- + d : dict + This has the appropriate entries for writing its string representation + to the header of the file. + """ + d = {'shape': array.shape} + if array.flags.c_contiguous: + d['fortran_order'] = False + elif array.flags.f_contiguous: + d['fortran_order'] = True + else: + # Totally non-contiguous data. We will have to make it C-contiguous + # before writing. Note that we need to test for C_CONTIGUOUS first + # because a 1-D array is both C_CONTIGUOUS and F_CONTIGUOUS. + d['fortran_order'] = False + + d['descr'] = dtype_to_descr(array.dtype) + return d + + +def _wrap_header(header, version): + """ + Takes a stringified header, and attaches the prefix and padding to it + """ + import struct + assert version is not None + fmt, encoding = _header_size_info[version] + header = header.encode(encoding) + hlen = len(header) + 1 + padlen = ARRAY_ALIGN - ((MAGIC_LEN + struct.calcsize(fmt) + hlen) % ARRAY_ALIGN) + try: + header_prefix = magic(*version) + struct.pack(fmt, hlen + padlen) + except struct.error: + msg = f"Header length {hlen} too big for version={version}" + raise ValueError(msg) from None + + # Pad the header with spaces and a final newline such that the magic + # string, the header-length short and the header are aligned on a + # ARRAY_ALIGN byte boundary. This supports memory mapping of dtypes + # aligned up to ARRAY_ALIGN on systems like Linux where mmap() + # offset must be page-aligned (i.e. the beginning of the file). + return header_prefix + header + b' ' * padlen + b'\n' + + +def _wrap_header_guess_version(header): + """ + Like `_wrap_header`, but chooses an appropriate version given the contents + """ + try: + return _wrap_header(header, (1, 0)) + except ValueError: + pass + + try: + ret = _wrap_header(header, (2, 0)) + except UnicodeEncodeError: + pass + else: + warnings.warn("Stored array in format 2.0. It can only be" + "read by NumPy >= 1.9", UserWarning, stacklevel=2) + return ret + + header = _wrap_header(header, (3, 0)) + warnings.warn("Stored array in format 3.0. It can only be " + "read by NumPy >= 1.17", UserWarning, stacklevel=2) + return header + + +def _write_array_header(fp, d, version=None): + """ Write the header for an array and returns the version used + + Parameters + ---------- + fp : filelike object + d : dict + This has the appropriate entries for writing its string representation + to the header of the file. + version : tuple or None + None means use oldest that works. Providing an explicit version will + raise a ValueError if the format does not allow saving this data. + Default: None + """ + header = ["{"] + for key, value in sorted(d.items()): + # Need to use repr here, since we eval these when reading + header.append(f"'{key}': {repr(value)}, ") + header.append("}") + header = "".join(header) + + # Add some spare space so that the array header can be modified in-place + # when changing the array size, e.g. when growing it by appending data at + # the end. + shape = d['shape'] + header += " " * ((GROWTH_AXIS_MAX_DIGITS - len(repr( + shape[-1 if d['fortran_order'] else 0] + ))) if len(shape) > 0 else 0) + + if version is None: + header = _wrap_header_guess_version(header) + else: + header = _wrap_header(header, version) + fp.write(header) + + +@set_module("numpy.lib.format") +def write_array_header_1_0(fp, d): + """ Write the header for an array using the 1.0 format. + + Parameters + ---------- + fp : filelike object + d : dict + This has the appropriate entries for writing its string + representation to the header of the file. + """ + _write_array_header(fp, d, (1, 0)) + + +@set_module("numpy.lib.format") +def write_array_header_2_0(fp, d): + """ Write the header for an array using the 2.0 format. + The 2.0 format allows storing very large structured arrays. + + Parameters + ---------- + fp : filelike object + d : dict + This has the appropriate entries for writing its string + representation to the header of the file. + """ + _write_array_header(fp, d, (2, 0)) + + +@set_module("numpy.lib.format") +def read_array_header_1_0(fp, max_header_size=_MAX_HEADER_SIZE): + """ + Read an array header from a filelike object using the 1.0 file format + version. + + This will leave the file object located just after the header. + + Parameters + ---------- + fp : filelike object + A file object or something with a `.read()` method like a file. + + Returns + ------- + shape : tuple of int + The shape of the array. + fortran_order : bool + The array data will be written out directly if it is either + C-contiguous or Fortran-contiguous. Otherwise, it will be made + contiguous before writing it out. + dtype : dtype + The dtype of the file's data. + max_header_size : int, optional + Maximum allowed size of the header. Large headers may not be safe + to load securely and thus require explicitly passing a larger value. + See :py:func:`ast.literal_eval()` for details. + + Raises + ------ + ValueError + If the data is invalid. + + """ + return _read_array_header( + fp, version=(1, 0), max_header_size=max_header_size) + + +@set_module("numpy.lib.format") +def read_array_header_2_0(fp, max_header_size=_MAX_HEADER_SIZE): + """ + Read an array header from a filelike object using the 2.0 file format + version. + + This will leave the file object located just after the header. + + Parameters + ---------- + fp : filelike object + A file object or something with a `.read()` method like a file. + max_header_size : int, optional + Maximum allowed size of the header. Large headers may not be safe + to load securely and thus require explicitly passing a larger value. + See :py:func:`ast.literal_eval()` for details. + + Returns + ------- + shape : tuple of int + The shape of the array. + fortran_order : bool + The array data will be written out directly if it is either + C-contiguous or Fortran-contiguous. Otherwise, it will be made + contiguous before writing it out. + dtype : dtype + The dtype of the file's data. + + Raises + ------ + ValueError + If the data is invalid. + + """ + return _read_array_header( + fp, version=(2, 0), max_header_size=max_header_size) + + +def _filter_header(s): + """Clean up 'L' in npz header ints. + + Cleans up the 'L' in strings representing integers. Needed to allow npz + headers produced in Python2 to be read in Python3. + + Parameters + ---------- + s : string + Npy file header. + + Returns + ------- + header : str + Cleaned up header. + + """ + import tokenize + from io import StringIO + + tokens = [] + last_token_was_number = False + for token in tokenize.generate_tokens(StringIO(s).readline): + token_type = token[0] + token_string = token[1] + if (last_token_was_number and + token_type == tokenize.NAME and + token_string == "L"): + continue + else: + tokens.append(token) + last_token_was_number = (token_type == tokenize.NUMBER) + return tokenize.untokenize(tokens) + + +def _read_array_header(fp, version, max_header_size=_MAX_HEADER_SIZE): + """ + see read_array_header_1_0 + """ + # Read an unsigned, little-endian short int which has the length of the + # header. + import ast + import struct + hinfo = _header_size_info.get(version) + if hinfo is None: + raise ValueError(f"Invalid version {version!r}") + hlength_type, encoding = hinfo + + hlength_str = _read_bytes(fp, struct.calcsize(hlength_type), "array header length") + header_length = struct.unpack(hlength_type, hlength_str)[0] + header = _read_bytes(fp, header_length, "array header") + header = header.decode(encoding) + if len(header) > max_header_size: + raise ValueError( + f"Header info length ({len(header)}) is large and may not be safe " + "to load securely.\n" + "To allow loading, adjust `max_header_size` or fully trust " + "the `.npy` file using `allow_pickle=True`.\n" + "For safety against large resource use or crashes, sandboxing " + "may be necessary.") + + # The header is a pretty-printed string representation of a literal + # Python dictionary with trailing newlines padded to an ARRAY_ALIGN byte + # boundary. The keys are strings. + # "shape" : tuple of int + # "fortran_order" : bool + # "descr" : dtype.descr + # Versions (2, 0) and (1, 0) could have been created by a Python 2 + # implementation before header filtering was implemented. + # + # For performance reasons, we try without _filter_header first though + try: + d = ast.literal_eval(header) + except SyntaxError as e: + if version <= (2, 0): + header = _filter_header(header) + try: + d = ast.literal_eval(header) + except SyntaxError as e2: + msg = "Cannot parse header: {!r}" + raise ValueError(msg.format(header)) from e2 + else: + warnings.warn( + "Reading `.npy` or `.npz` file required additional " + "header parsing as it was created on Python 2. Save the " + "file again to speed up loading and avoid this warning.", + UserWarning, stacklevel=4) + else: + msg = "Cannot parse header: {!r}" + raise ValueError(msg.format(header)) from e + if not isinstance(d, dict): + msg = "Header is not a dictionary: {!r}" + raise ValueError(msg.format(d)) + + if EXPECTED_KEYS != d.keys(): + keys = sorted(d.keys()) + msg = "Header does not contain the correct keys: {!r}" + raise ValueError(msg.format(keys)) + + # Sanity-check the values. + if (not isinstance(d['shape'], tuple) or + not all(isinstance(x, int) for x in d['shape'])): + msg = "shape is not valid: {!r}" + raise ValueError(msg.format(d['shape'])) + if not isinstance(d['fortran_order'], bool): + msg = "fortran_order is not a valid bool: {!r}" + raise ValueError(msg.format(d['fortran_order'])) + try: + dtype = descr_to_dtype(d['descr']) + except TypeError as e: + msg = "descr is not a valid dtype descriptor: {!r}" + raise ValueError(msg.format(d['descr'])) from e + + return d['shape'], d['fortran_order'], dtype + + +@set_module("numpy.lib.format") +def write_array(fp, array, version=None, allow_pickle=True, pickle_kwargs=None): + """ + Write an array to an NPY file, including a header. + + If the array is neither C-contiguous nor Fortran-contiguous AND the + file_like object is not a real file object, this function will have to + copy data in memory. + + Parameters + ---------- + fp : file_like object + An open, writable file object, or similar object with a + ``.write()`` method. + array : ndarray + The array to write to disk. + version : (int, int) or None, optional + The version number of the format. None means use the oldest + supported version that is able to store the data. Default: None + allow_pickle : bool, optional + Whether to allow writing pickled data. Default: True + pickle_kwargs : dict, optional + Additional keyword arguments to pass to pickle.dump, excluding + 'protocol'. These are only useful when pickling objects in object + arrays to Python 2 compatible format. + + Raises + ------ + ValueError + If the array cannot be persisted. This includes the case of + allow_pickle=False and array being an object array. + Various other errors + If the array contains Python objects as part of its dtype, the + process of pickling them may raise various errors if the objects + are not picklable. + + """ + _check_version(version) + _write_array_header(fp, header_data_from_array_1_0(array), version) + + if array.itemsize == 0: + buffersize = 0 + else: + # Set buffer size to 16 MiB to hide the Python loop overhead. + buffersize = max(16 * 1024 ** 2 // array.itemsize, 1) + + dtype_class = type(array.dtype) + + if array.dtype.hasobject or not dtype_class._legacy: + # We contain Python objects so we cannot write out the data + # directly. Instead, we will pickle it out + if not allow_pickle: + if array.dtype.hasobject: + raise ValueError("Object arrays cannot be saved when " + "allow_pickle=False") + if not dtype_class._legacy: + raise ValueError("User-defined dtypes cannot be saved " + "when allow_pickle=False") + if pickle_kwargs is None: + pickle_kwargs = {} + pickle.dump(array, fp, protocol=4, **pickle_kwargs) + elif array.flags.f_contiguous and not array.flags.c_contiguous: + if isfileobj(fp): + array.T.tofile(fp) + else: + for chunk in numpy.nditer( + array, flags=['external_loop', 'buffered', 'zerosize_ok'], + buffersize=buffersize, order='F'): + fp.write(chunk.tobytes('C')) + elif isfileobj(fp): + array.tofile(fp) + else: + for chunk in numpy.nditer( + array, flags=['external_loop', 'buffered', 'zerosize_ok'], + buffersize=buffersize, order='C'): + fp.write(chunk.tobytes('C')) + + +@set_module("numpy.lib.format") +def read_array(fp, allow_pickle=False, pickle_kwargs=None, *, + max_header_size=_MAX_HEADER_SIZE): + """ + Read an array from an NPY file. + + Parameters + ---------- + fp : file_like object + If this is not a real file object, then this may take extra memory + and time. + allow_pickle : bool, optional + Whether to allow writing pickled data. Default: False + pickle_kwargs : dict + Additional keyword arguments to pass to pickle.load. These are only + useful when loading object arrays saved on Python 2. + max_header_size : int, optional + Maximum allowed size of the header. Large headers may not be safe + to load securely and thus require explicitly passing a larger value. + See :py:func:`ast.literal_eval()` for details. + This option is ignored when `allow_pickle` is passed. In that case + the file is by definition trusted and the limit is unnecessary. + + Returns + ------- + array : ndarray + The array from the data on disk. + + Raises + ------ + ValueError + If the data is invalid, or allow_pickle=False and the file contains + an object array. + + """ + if allow_pickle: + # Effectively ignore max_header_size, since `allow_pickle` indicates + # that the input is fully trusted. + max_header_size = 2**64 + + version = read_magic(fp) + _check_version(version) + shape, fortran_order, dtype = _read_array_header( + fp, version, max_header_size=max_header_size) + if len(shape) == 0: + count = 1 + else: + count = numpy.multiply.reduce(shape, dtype=numpy.int64) + + # Now read the actual data. + if dtype.hasobject: + # The array contained Python objects. We need to unpickle the data. + if not allow_pickle: + raise ValueError("Object arrays cannot be loaded when " + "allow_pickle=False") + if pickle_kwargs is None: + pickle_kwargs = {} + try: + array = pickle.load(fp, **pickle_kwargs) + except UnicodeError as err: + # Friendlier error message + raise UnicodeError("Unpickling a python object failed: %r\n" + "You may need to pass the encoding= option " + "to numpy.load" % (err,)) from err + else: + if isfileobj(fp): + # We can use the fast fromfile() function. + array = numpy.fromfile(fp, dtype=dtype, count=count) + else: + # This is not a real file. We have to read it the + # memory-intensive way. + # crc32 module fails on reads greater than 2 ** 32 bytes, + # breaking large reads from gzip streams. Chunk reads to + # BUFFER_SIZE bytes to avoid issue and reduce memory overhead + # of the read. In non-chunked case count < max_read_count, so + # only one read is performed. + + # Use np.ndarray instead of np.empty since the latter does + # not correctly instantiate zero-width string dtypes; see + # https://github.com/numpy/numpy/pull/6430 + array = numpy.ndarray(count, dtype=dtype) + + if dtype.itemsize > 0: + # If dtype.itemsize == 0 then there's nothing more to read + max_read_count = BUFFER_SIZE // min(BUFFER_SIZE, dtype.itemsize) + + for i in range(0, count, max_read_count): + read_count = min(max_read_count, count - i) + read_size = int(read_count * dtype.itemsize) + data = _read_bytes(fp, read_size, "array data") + array[i:i + read_count] = numpy.frombuffer(data, dtype=dtype, + count=read_count) + + if array.size != count: + raise ValueError( + "Failed to read all data for array. " + f"Expected {shape} = {count} elements, " + f"could only read {array.size} elements. " + "(file seems not fully written?)" + ) + + if fortran_order: + array = array.reshape(shape[::-1]) + array = array.transpose() + else: + array = array.reshape(shape) + + return array + + +@set_module("numpy.lib.format") +def open_memmap(filename, mode='r+', dtype=None, shape=None, + fortran_order=False, version=None, *, + max_header_size=_MAX_HEADER_SIZE): + """ + Open a .npy file as a memory-mapped array. + + This may be used to read an existing file or create a new one. + + Parameters + ---------- + filename : str or path-like + The name of the file on disk. This may *not* be a file-like + object. + mode : str, optional + The mode in which to open the file; the default is 'r+'. In + addition to the standard file modes, 'c' is also accepted to mean + "copy on write." See `memmap` for the available mode strings. + dtype : data-type, optional + The data type of the array if we are creating a new file in "write" + mode, if not, `dtype` is ignored. The default value is None, which + results in a data-type of `float64`. + shape : tuple of int + The shape of the array if we are creating a new file in "write" + mode, in which case this parameter is required. Otherwise, this + parameter is ignored and is thus optional. + fortran_order : bool, optional + Whether the array should be Fortran-contiguous (True) or + C-contiguous (False, the default) if we are creating a new file in + "write" mode. + version : tuple of int (major, minor) or None + If the mode is a "write" mode, then this is the version of the file + format used to create the file. None means use the oldest + supported version that is able to store the data. Default: None + max_header_size : int, optional + Maximum allowed size of the header. Large headers may not be safe + to load securely and thus require explicitly passing a larger value. + See :py:func:`ast.literal_eval()` for details. + + Returns + ------- + marray : memmap + The memory-mapped array. + + Raises + ------ + ValueError + If the data or the mode is invalid. + OSError + If the file is not found or cannot be opened correctly. + + See Also + -------- + numpy.memmap + + """ + if isfileobj(filename): + raise ValueError("Filename must be a string or a path-like object." + " Memmap cannot use existing file handles.") + + if 'w' in mode: + # We are creating the file, not reading it. + # Check if we ought to create the file. + _check_version(version) + # Ensure that the given dtype is an authentic dtype object rather + # than just something that can be interpreted as a dtype object. + dtype = numpy.dtype(dtype) + if dtype.hasobject: + msg = "Array can't be memory-mapped: Python objects in dtype." + raise ValueError(msg) + d = { + "descr": dtype_to_descr(dtype), + "fortran_order": fortran_order, + "shape": shape, + } + # If we got here, then it should be safe to create the file. + with open(os.fspath(filename), mode + 'b') as fp: + _write_array_header(fp, d, version) + offset = fp.tell() + else: + # Read the header of the file first. + with open(os.fspath(filename), 'rb') as fp: + version = read_magic(fp) + _check_version(version) + + shape, fortran_order, dtype = _read_array_header( + fp, version, max_header_size=max_header_size) + if dtype.hasobject: + msg = "Array can't be memory-mapped: Python objects in dtype." + raise ValueError(msg) + offset = fp.tell() + + if fortran_order: + order = 'F' + else: + order = 'C' + + # We need to change a write-only mode to a read-write mode since we've + # already written data to the file. + if mode == 'w+': + mode = 'r+' + + marray = numpy.memmap(filename, dtype=dtype, shape=shape, order=order, + mode=mode, offset=offset) + + return marray + + +def _read_bytes(fp, size, error_template="ran out of data"): + """ + Read from file-like object until size bytes are read. + Raises ValueError if not EOF is encountered before size bytes are read. + Non-blocking objects only supported if they derive from io objects. + + Required as e.g. ZipExtFile in python 2.6 can return less data than + requested. + """ + data = b"" + while True: + # io files (default in python3) return None or raise on + # would-block, python2 file will truncate, probably nothing can be + # done about that. note that regular files can't be non-blocking + try: + r = fp.read(size - len(data)) + data += r + if len(r) == 0 or len(data) == size: + break + except BlockingIOError: + pass + if len(data) != size: + msg = "EOF: reading %s, expected %d bytes got %d" + raise ValueError(msg % (error_template, size, len(data))) + else: + return data + + +@set_module("numpy.lib.format") +def isfileobj(f): + if not isinstance(f, (io.FileIO, io.BufferedReader, io.BufferedWriter)): + return False + try: + # BufferedReader/Writer may raise OSError when + # fetching `fileno()` (e.g. when wrapping BytesIO). + f.fileno() + return True + except OSError: + return False diff --git a/python/user_packages/Python313/site-packages/numpy/lib/_format_impl.pyi b/python/user_packages/Python313/site-packages/numpy/lib/_format_impl.pyi new file mode 100644 index 0000000000000000000000000000000000000000..06d49d3eaaf293f8fd7420d0309c3cfe890446f6 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/lib/_format_impl.pyi @@ -0,0 +1,56 @@ +import os +from _typeshed import SupportsRead, SupportsWrite +from typing import Any, BinaryIO, Final, TypeAlias, TypeGuard + +import numpy as np +import numpy.typing as npt +from numpy.lib._utils_impl import drop_metadata as drop_metadata + +__all__: list[str] = [] + +_DTypeDescr: TypeAlias = list[tuple[str, str]] | list[tuple[str, str, tuple[int, ...]]] + +### + +EXPECTED_KEYS: Final[set[str]] = ... +MAGIC_PREFIX: Final = b"\x93NUMPY" +MAGIC_LEN: Final = 8 +ARRAY_ALIGN: Final = 64 +BUFFER_SIZE: Final = 262_144 # 1 << 18 +GROWTH_AXIS_MAX_DIGITS: Final = 21 +_MAX_HEADER_SIZE: Final = 10_000 + +def magic(major: int, minor: int) -> bytes: ... +def read_magic(fp: SupportsRead[bytes]) -> tuple[int, int]: ... +def dtype_to_descr(dtype: np.dtype) -> _DTypeDescr: ... +def descr_to_dtype(descr: _DTypeDescr) -> np.dtype: ... +def header_data_from_array_1_0(array: np.ndarray) -> dict[str, Any]: ... +def write_array_header_1_0(fp: SupportsWrite[bytes], d: dict[str, Any]) -> None: ... +def write_array_header_2_0(fp: SupportsWrite[bytes], d: dict[str, Any]) -> None: ... +def read_array_header_1_0(fp: SupportsRead[bytes], max_header_size: int = 10_000) -> tuple[tuple[int, ...], bool, np.dtype]: ... +def read_array_header_2_0(fp: SupportsRead[bytes], max_header_size: int = 10_000) -> tuple[tuple[int, ...], bool, np.dtype]: ... +def write_array( + fp: SupportsWrite[bytes], + array: np.ndarray, + version: tuple[int, int] | None = None, + allow_pickle: bool = True, + pickle_kwargs: dict[str, Any] | None = None, +) -> None: ... +def read_array( + fp: SupportsRead[bytes], + allow_pickle: bool = False, + pickle_kwargs: dict[str, Any] | None = None, + *, + max_header_size: int = 10_000, +) -> np.ndarray: ... +def open_memmap( + filename: str | os.PathLike[Any], + mode: str = "r+", + dtype: npt.DTypeLike | None = None, + shape: tuple[int, ...] | None = None, + fortran_order: bool = False, + version: tuple[int, int] | None = None, + *, + max_header_size: int = 10_000, +) -> np.memmap: ... +def isfileobj(f: object) -> TypeGuard[BinaryIO]: ... # don't use `typing.TypeIs` diff --git a/python/user_packages/Python313/site-packages/numpy/lib/_function_base_impl.py b/python/user_packages/Python313/site-packages/numpy/lib/_function_base_impl.py new file mode 100644 index 0000000000000000000000000000000000000000..4daac6cb6f44b1f0a10da2c2b229e9a26fc87f68 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/lib/_function_base_impl.py @@ -0,0 +1,5760 @@ +import builtins +import collections.abc +import functools +import re +import warnings + +import numpy as np +import numpy._core.numeric as _nx +from numpy._core import overrides, transpose +from numpy._core._multiarray_umath import _array_converter +from numpy._core.fromnumeric import any, mean, nonzero, partition, ravel, sum +from numpy._core.multiarray import ( + _monotonicity, + _place, + bincount, + interp as compiled_interp, + interp_complex as compiled_interp_complex, + normalize_axis_index, +) +from numpy._core.numeric import ( + absolute, + arange, + array, + asanyarray, + asarray, + concatenate, + dot, + empty, + integer, + intp, + isscalar, + ndarray, + ones, + take, + where, + zeros_like, +) +from numpy._core.numerictypes import typecodes +from numpy._core.umath import ( + add, + arctan2, + cos, + exp, + floor, + frompyfunc, + less_equal, + minimum, + mod, + not_equal, + pi, + sin, + sqrt, + subtract, +) +from numpy._utils import set_module + +# needed in this module for compatibility +from numpy.lib._histograms_impl import histogram, histogramdd # noqa: F401 +from numpy.lib._twodim_base_impl import diag + +array_function_dispatch = functools.partial( + overrides.array_function_dispatch, module='numpy') + + +__all__ = [ + 'select', 'piecewise', 'trim_zeros', 'copy', 'iterable', 'percentile', + 'diff', 'gradient', 'angle', 'unwrap', 'sort_complex', 'flip', + 'rot90', 'extract', 'place', 'vectorize', 'asarray_chkfinite', 'average', + 'bincount', 'digitize', 'cov', 'corrcoef', + 'median', 'sinc', 'hamming', 'hanning', 'bartlett', + 'blackman', 'kaiser', 'trapezoid', 'i0', + 'meshgrid', 'delete', 'insert', 'append', 'interp', + 'quantile' + ] + +# _QuantileMethods is a dictionary listing all the supported methods to +# compute quantile/percentile. +# +# Below virtual_index refers to the index of the element where the percentile +# would be found in the sorted sample. +# When the sample contains exactly the percentile wanted, the virtual_index is +# an integer to the index of this element. +# When the percentile wanted is in between two elements, the virtual_index +# is made of a integer part (a.k.a 'i' or 'left') and a fractional part +# (a.k.a 'g' or 'gamma') +# +# Each method in _QuantileMethods has two properties +# get_virtual_index : Callable +# The function used to compute the virtual_index. +# fix_gamma : Callable +# A function used for discrete methods to force the index to a specific value. +_QuantileMethods = { + # --- HYNDMAN and FAN METHODS + # Discrete methods + 'inverted_cdf': { + 'get_virtual_index': lambda n, quantiles: _inverted_cdf(n, quantiles), # noqa: PLW0108 + 'fix_gamma': None, # should never be called + }, + 'averaged_inverted_cdf': { + 'get_virtual_index': lambda n, quantiles: (n * quantiles) - 1, + 'fix_gamma': lambda gamma, _: _get_gamma_mask( + shape=gamma.shape, + default_value=1., + conditioned_value=0.5, + where=gamma == 0), + }, + 'closest_observation': { + 'get_virtual_index': lambda n, quantiles: _closest_observation(n, quantiles), # noqa: PLW0108 + 'fix_gamma': None, # should never be called + }, + # Continuous methods + 'interpolated_inverted_cdf': { + 'get_virtual_index': lambda n, quantiles: + _compute_virtual_index(n, quantiles, 0, 1), + 'fix_gamma': lambda gamma, _: gamma, + }, + 'hazen': { + 'get_virtual_index': lambda n, quantiles: + _compute_virtual_index(n, quantiles, 0.5, 0.5), + 'fix_gamma': lambda gamma, _: gamma, + }, + 'weibull': { + 'get_virtual_index': lambda n, quantiles: + _compute_virtual_index(n, quantiles, 0, 0), + 'fix_gamma': lambda gamma, _: gamma, + }, + # Default method. + # To avoid some rounding issues, `(n-1) * quantiles` is preferred to + # `_compute_virtual_index(n, quantiles, 1, 1)`. + # They are mathematically equivalent. + 'linear': { + 'get_virtual_index': lambda n, quantiles: (n - 1) * quantiles, + 'fix_gamma': lambda gamma, _: gamma, + }, + 'median_unbiased': { + 'get_virtual_index': lambda n, quantiles: + _compute_virtual_index(n, quantiles, 1 / 3.0, 1 / 3.0), + 'fix_gamma': lambda gamma, _: gamma, + }, + 'normal_unbiased': { + 'get_virtual_index': lambda n, quantiles: + _compute_virtual_index(n, quantiles, 3 / 8.0, 3 / 8.0), + 'fix_gamma': lambda gamma, _: gamma, + }, + # --- OTHER METHODS + 'lower': { + 'get_virtual_index': lambda n, quantiles: np.floor( + (n - 1) * quantiles).astype(np.intp), + 'fix_gamma': None, # should never be called, index dtype is int + }, + 'higher': { + 'get_virtual_index': lambda n, quantiles: np.ceil( + (n - 1) * quantiles).astype(np.intp), + 'fix_gamma': None, # should never be called, index dtype is int + }, + 'midpoint': { + 'get_virtual_index': lambda n, quantiles: 0.5 * ( + np.floor((n - 1) * quantiles) + + np.ceil((n - 1) * quantiles)), + 'fix_gamma': lambda gamma, index: _get_gamma_mask( + shape=gamma.shape, + default_value=0.5, + conditioned_value=0., + where=index % 1 == 0), + }, + 'nearest': { + 'get_virtual_index': lambda n, quantiles: np.around( + (n - 1) * quantiles).astype(np.intp), + 'fix_gamma': None, + # should never be called, index dtype is int + }} + + +def _rot90_dispatcher(m, k=None, axes=None): + return (m,) + + +@array_function_dispatch(_rot90_dispatcher) +def rot90(m, k=1, axes=(0, 1)): + """ + Rotate an array by 90 degrees in the plane specified by axes. + + Rotation direction is from the first towards the second axis. + This means for a 2D array with the default `k` and `axes`, the + rotation will be counterclockwise. + + Parameters + ---------- + m : array_like + Array of two or more dimensions. + k : integer + Number of times the array is rotated by 90 degrees. + axes : (2,) array_like + The array is rotated in the plane defined by the axes. + Axes must be different. + + Returns + ------- + y : ndarray + A rotated view of `m`. + + See Also + -------- + flip : Reverse the order of elements in an array along the given axis. + fliplr : Flip an array horizontally. + flipud : Flip an array vertically. + + Notes + ----- + ``rot90(m, k=1, axes=(1,0))`` is the reverse of + ``rot90(m, k=1, axes=(0,1))`` + + ``rot90(m, k=1, axes=(1,0))`` is equivalent to + ``rot90(m, k=-1, axes=(0,1))`` + + Examples + -------- + >>> import numpy as np + >>> m = np.array([[1,2],[3,4]], int) + >>> m + array([[1, 2], + [3, 4]]) + >>> np.rot90(m) + array([[2, 4], + [1, 3]]) + >>> np.rot90(m, 2) + array([[4, 3], + [2, 1]]) + >>> m = np.arange(8).reshape((2,2,2)) + >>> np.rot90(m, 1, (1,2)) + array([[[1, 3], + [0, 2]], + [[5, 7], + [4, 6]]]) + + """ + axes = tuple(axes) + if len(axes) != 2: + raise ValueError("len(axes) must be 2.") + + m = asanyarray(m) + + if axes[0] == axes[1] or absolute(axes[0] - axes[1]) == m.ndim: + raise ValueError("Axes must be different.") + + if (axes[0] >= m.ndim or axes[0] < -m.ndim + or axes[1] >= m.ndim or axes[1] < -m.ndim): + raise ValueError(f"Axes={axes} out of range for array of ndim={m.ndim}.") + + k %= 4 + + if k == 0: + return m[:] + if k == 2: + return flip(flip(m, axes[0]), axes[1]) + + axes_list = arange(0, m.ndim) + (axes_list[axes[0]], axes_list[axes[1]]) = (axes_list[axes[1]], + axes_list[axes[0]]) + + if k == 1: + return transpose(flip(m, axes[1]), axes_list) + else: + # k == 3 + return flip(transpose(m, axes_list), axes[1]) + + +def _flip_dispatcher(m, axis=None): + return (m,) + + +@array_function_dispatch(_flip_dispatcher) +def flip(m, axis=None): + """ + Reverse the order of elements in an array along the given axis. + + The shape of the array is preserved, but the elements are reordered. + + Parameters + ---------- + m : array_like + Input array. + axis : None or int or tuple of ints, optional + Axis or axes along which to flip over. The default, + axis=None, will flip over all of the axes of the input array. + If axis is negative it counts from the last to the first axis. + + If axis is a tuple of ints, flipping is performed on all of the axes + specified in the tuple. + + Returns + ------- + out : array_like + A view of `m` with the entries of axis reversed. Since a view is + returned, this operation is done in constant time. + + See Also + -------- + flipud : Flip an array vertically (axis=0). + fliplr : Flip an array horizontally (axis=1). + + Notes + ----- + flip(m, 0) is equivalent to flipud(m). + + flip(m, 1) is equivalent to fliplr(m). + + flip(m, n) corresponds to ``m[...,::-1,...]`` with ``::-1`` at position n. + + flip(m) corresponds to ``m[::-1,::-1,...,::-1]`` with ``::-1`` at all + positions. + + flip(m, (0, 1)) corresponds to ``m[::-1,::-1,...]`` with ``::-1`` at + position 0 and position 1. + + Examples + -------- + >>> import numpy as np + >>> A = np.arange(8).reshape((2,2,2)) + >>> A + array([[[0, 1], + [2, 3]], + [[4, 5], + [6, 7]]]) + >>> np.flip(A, 0) + array([[[4, 5], + [6, 7]], + [[0, 1], + [2, 3]]]) + >>> np.flip(A, 1) + array([[[2, 3], + [0, 1]], + [[6, 7], + [4, 5]]]) + >>> np.flip(A) + array([[[7, 6], + [5, 4]], + [[3, 2], + [1, 0]]]) + >>> np.flip(A, (0, 2)) + array([[[5, 4], + [7, 6]], + [[1, 0], + [3, 2]]]) + >>> rng = np.random.default_rng() + >>> A = rng.normal(size=(3,4,5)) + >>> np.all(np.flip(A,2) == A[:,:,::-1,...]) + True + """ + if not hasattr(m, 'ndim'): + m = asarray(m) + if axis is None: + indexer = (np.s_[::-1],) * m.ndim + else: + axis = _nx.normalize_axis_tuple(axis, m.ndim) + indexer = [np.s_[:]] * m.ndim + for ax in axis: + indexer[ax] = np.s_[::-1] + indexer = tuple(indexer) + return m[indexer] + + +@set_module('numpy') +def iterable(y): + """ + Check whether or not an object can be iterated over. + + Parameters + ---------- + y : object + Input object. + + Returns + ------- + b : bool + Return ``True`` if the object has an iterator method or is a + sequence and ``False`` otherwise. + + + Examples + -------- + >>> import numpy as np + >>> np.iterable([1, 2, 3]) + True + >>> np.iterable(2) + False + + Notes + ----- + In most cases, the results of ``np.iterable(obj)`` are consistent with + ``isinstance(obj, collections.abc.Iterable)``. One notable exception is + the treatment of 0-dimensional arrays:: + + >>> from collections.abc import Iterable + >>> a = np.array(1.0) # 0-dimensional numpy array + >>> isinstance(a, Iterable) + True + >>> np.iterable(a) + False + + """ + try: + iter(y) + except TypeError: + return False + return True + + +def _weights_are_valid(weights, a, axis): + """Validate weights array. + + We assume, weights is not None. + """ + wgt = np.asanyarray(weights) + + # Sanity checks + if a.shape != wgt.shape: + if axis is None: + raise TypeError( + "Axis must be specified when shapes of a and weights " + "differ.") + if wgt.shape != tuple(a.shape[ax] for ax in axis): + raise ValueError( + "Shape of weights must be consistent with " + "shape of a along specified axis.") + + # setup wgt to broadcast along axis + wgt = wgt.transpose(np.argsort(axis)) + wgt = wgt.reshape(tuple((s if ax in axis else 1) + for ax, s in enumerate(a.shape))) + return wgt + + +def _average_dispatcher(a, axis=None, weights=None, returned=None, *, + keepdims=None): + return (a, weights) + + +@array_function_dispatch(_average_dispatcher) +def average(a, axis=None, weights=None, returned=False, *, + keepdims=np._NoValue): + """ + Compute the weighted average along the specified axis. + + Parameters + ---------- + a : array_like + Array containing data to be averaged. If `a` is not an array, a + conversion is attempted. + axis : None or int or tuple of ints, optional + Axis or axes along which to average `a`. The default, + `axis=None`, will average over all of the elements of the input array. + If axis is negative it counts from the last to the first axis. + If axis is a tuple of ints, averaging is performed on all of the axes + specified in the tuple instead of a single axis or all the axes as + before. + weights : array_like, optional + An array of weights associated with the values in `a`. Each value in + `a` contributes to the average according to its associated weight. + The array of weights must be the same shape as `a` if no axis is + specified, otherwise the weights must have dimensions and shape + consistent with `a` along the specified axis. + If `weights=None`, then all data in `a` are assumed to have a + weight equal to one. + The calculation is:: + + avg = sum(a * weights) / sum(weights) + + where the sum is over all included elements. + The only constraint on the values of `weights` is that `sum(weights)` + must not be 0. + returned : bool, optional + Default is `False`. If `True`, the tuple (`average`, `sum_of_weights`) + is returned, otherwise only the average is returned. + If `weights=None`, `sum_of_weights` is equivalent to the number of + elements over which the average is taken. + keepdims : bool, optional + If this is set to True, the axes which are reduced are left + in the result as dimensions with size one. With this option, + the result will broadcast correctly against the original `a`. + *Note:* `keepdims` will not work with instances of `numpy.matrix` + or other classes whose methods do not support `keepdims`. + + .. versionadded:: 1.23.0 + + Returns + ------- + retval, [sum_of_weights] : array_type or double + Return the average along the specified axis. When `returned` is `True`, + return a tuple with the average as the first element and the sum + of the weights as the second element. `sum_of_weights` is of the + same type as `retval`. The result dtype follows a general pattern. + If `weights` is None, the result dtype will be that of `a` , or ``float64`` + if `a` is integral. Otherwise, if `weights` is not None and `a` is non- + integral, the result type will be the type of lowest precision capable of + representing values of both `a` and `weights`. If `a` happens to be + integral, the previous rules still applies but the result dtype will + at least be ``float64``. + + Raises + ------ + ZeroDivisionError + When all weights along axis are zero. See `numpy.ma.average` for a + version robust to this type of error. + TypeError + When `weights` does not have the same shape as `a`, and `axis=None`. + ValueError + When `weights` does not have dimensions and shape consistent with `a` + along specified `axis`. + + See Also + -------- + mean + + ma.average : average for masked arrays -- useful if your data contains + "missing" values + numpy.result_type : Returns the type that results from applying the + numpy type promotion rules to the arguments. + + Examples + -------- + >>> import numpy as np + >>> data = np.arange(1, 5) + >>> data + array([1, 2, 3, 4]) + >>> np.average(data) + 2.5 + >>> np.average(np.arange(1, 11), weights=np.arange(10, 0, -1)) + 4.0 + + >>> data = np.arange(6).reshape((3, 2)) + >>> data + array([[0, 1], + [2, 3], + [4, 5]]) + >>> np.average(data, axis=1, weights=[1./4, 3./4]) + array([0.75, 2.75, 4.75]) + >>> np.average(data, weights=[1./4, 3./4]) + Traceback (most recent call last): + ... + TypeError: Axis must be specified when shapes of a and weights differ. + + With ``keepdims=True``, the following result has shape (3, 1). + + >>> np.average(data, axis=1, keepdims=True) + array([[0.5], + [2.5], + [4.5]]) + + >>> data = np.arange(8).reshape((2, 2, 2)) + >>> data + array([[[0, 1], + [2, 3]], + [[4, 5], + [6, 7]]]) + >>> np.average(data, axis=(0, 1), weights=[[1./4, 3./4], [1., 1./2]]) + array([3.4, 4.4]) + >>> np.average(data, axis=0, weights=[[1./4, 3./4], [1., 1./2]]) + Traceback (most recent call last): + ... + ValueError: Shape of weights must be consistent + with shape of a along specified axis. + """ + a = np.asanyarray(a) + + if axis is not None: + axis = _nx.normalize_axis_tuple(axis, a.ndim, argname="axis") + + if keepdims is np._NoValue: + # Don't pass on the keepdims argument if one wasn't given. + keepdims_kw = {} + else: + keepdims_kw = {'keepdims': keepdims} + + if weights is None: + avg = a.mean(axis, **keepdims_kw) + avg_as_array = np.asanyarray(avg) + scl = avg_as_array.dtype.type(a.size / avg_as_array.size) + else: + wgt = _weights_are_valid(weights=weights, a=a, axis=axis) + + if issubclass(a.dtype.type, (np.integer, np.bool)): + result_dtype = np.result_type(a.dtype, wgt.dtype, 'f8') + else: + result_dtype = np.result_type(a.dtype, wgt.dtype) + + scl = wgt.sum(axis=axis, dtype=result_dtype, **keepdims_kw) + if np.any(scl == 0.0): + raise ZeroDivisionError( + "Weights sum to zero, can't be normalized") + + avg = avg_as_array = np.multiply(a, wgt, + dtype=result_dtype).sum(axis, **keepdims_kw) / scl + + if returned: + if scl.shape != avg_as_array.shape: + scl = np.broadcast_to(scl, avg_as_array.shape, subok=True).copy() + return avg, scl + else: + return avg + + +@set_module('numpy') +def asarray_chkfinite(a, dtype=None, order=None): + """Convert the input to an array, checking for NaNs or Infs. + + Parameters + ---------- + a : array_like + Input data, in any form that can be converted to an array. This + includes lists, lists of tuples, tuples, tuples of tuples, tuples + of lists and ndarrays. Success requires no NaNs or Infs. + dtype : data-type, optional + By default, the data-type is inferred from the input data. + order : {'C', 'F', 'A', 'K'}, optional + The memory layout of the output. + 'C' gives a row-major layout (C-style), + 'F' gives a column-major layout (Fortran-style). + 'C' and 'F' will copy if needed to ensure the output format. + 'A' (any) is equivalent to 'F' if input a is non-contiguous or + Fortran-contiguous, otherwise, it is equivalent to 'C'. + Unlike 'C' or 'F', 'A' does not ensure that the result is contiguous. + 'K' (keep) preserves the input order for the output. + 'C' is the default. + + Returns + ------- + out : ndarray + Array interpretation of `a`. No copy is performed if the input + is already an ndarray. If `a` is a subclass of ndarray, a base + class ndarray is returned. + + Raises + ------ + ValueError + Raises ValueError if `a` contains NaN (Not a Number) or Inf (Infinity). + + See Also + -------- + asarray : Create and array. + asanyarray : Similar function which passes through subclasses. + ascontiguousarray : Convert input to a contiguous array. + asfortranarray : Convert input to an ndarray with column-major + memory order. + fromiter : Create an array from an iterator. + fromfunction : Construct an array by executing a function on grid + positions. + + Examples + -------- + >>> import numpy as np + + Convert a list into an array. If all elements are finite, then + ``asarray_chkfinite`` is identical to ``asarray``. + + >>> a = [1, 2] + >>> np.asarray_chkfinite(a, dtype=float) + array([1., 2.]) + + Raises ValueError if array_like contains Nans or Infs. + + >>> a = [1, 2, np.inf] + >>> try: + ... np.asarray_chkfinite(a) + ... except ValueError: + ... print('ValueError') + ... + ValueError + + """ + a = asarray(a, dtype=dtype, order=order) + if a.dtype.char in typecodes['AllFloat'] and not np.isfinite(a).all(): + raise ValueError( + "array must not contain infs or NaNs") + return a + + +def _piecewise_dispatcher(x, condlist, funclist, *args, **kw): + yield x + # support the undocumented behavior of allowing scalars + if np.iterable(condlist): + yield from condlist + + +@array_function_dispatch(_piecewise_dispatcher) +def piecewise(x, condlist, funclist, *args, **kw): + """ + Evaluate a piecewise-defined function. + + Given a set of conditions and corresponding functions, evaluate each + function on the input data wherever its condition is true. + + Parameters + ---------- + x : ndarray or scalar + The input domain. + condlist : list of bool arrays or bool scalars + Each boolean array corresponds to a function in `funclist`. Wherever + `condlist[i]` is True, `funclist[i](x)` is used as the output value. + + Each boolean array in `condlist` selects a piece of `x`, + and should therefore be of the same shape as `x`. + + The length of `condlist` must correspond to that of `funclist`. + If one extra function is given, i.e. if + ``len(funclist) == len(condlist) + 1``, then that extra function + is the default value, used wherever all conditions are false. + funclist : list of callables, f(x,*args,**kw), or scalars + Each function is evaluated over `x` wherever its corresponding + condition is True. It should take a 1d array as input and give a 1d + array or a scalar value as output. If, instead of a callable, + a scalar is provided then a constant function (``lambda x: scalar``) is + assumed. + args : tuple, optional + Any further arguments given to `piecewise` are passed to the functions + upon execution, i.e., if called ``piecewise(..., ..., 1, 'a')``, then + each function is called as ``f(x, 1, 'a')``. + kw : dict, optional + Keyword arguments used in calling `piecewise` are passed to the + functions upon execution, i.e., if called + ``piecewise(..., ..., alpha=1)``, then each function is called as + ``f(x, alpha=1)``. + + Returns + ------- + out : ndarray + The output is the same shape and type as x and is found by + calling the functions in `funclist` on the appropriate portions of `x`, + as defined by the boolean arrays in `condlist`. Portions not covered + by any condition have a default value of 0. + + + See Also + -------- + choose, select, where + + Notes + ----- + This is similar to choose or select, except that functions are + evaluated on elements of `x` that satisfy the corresponding condition from + `condlist`. + + The result is:: + + |-- + |funclist[0](x[condlist[0]]) + out = |funclist[1](x[condlist[1]]) + |... + |funclist[n2](x[condlist[n2]]) + |-- + + Examples + -------- + >>> import numpy as np + + Define the signum function, which is -1 for ``x < 0`` and +1 for ``x >= 0``. + + >>> x = np.linspace(-2.5, 2.5, 6) + >>> np.piecewise(x, [x < 0, x >= 0], [-1, 1]) + array([-1., -1., -1., 1., 1., 1.]) + + Define the absolute value, which is ``-x`` for ``x <0`` and ``x`` for + ``x >= 0``. + + >>> np.piecewise(x, [x < 0, x >= 0], [lambda x: -x, lambda x: x]) + array([2.5, 1.5, 0.5, 0.5, 1.5, 2.5]) + + Apply the same function to a scalar value. + + >>> y = -2 + >>> np.piecewise(y, [y < 0, y >= 0], [lambda x: -x, lambda x: x]) + array(2) + + """ + x = asanyarray(x) + n2 = len(funclist) + + # undocumented: single condition is promoted to a list of one condition + if isscalar(condlist) or ( + not isinstance(condlist[0], (list, ndarray)) and x.ndim != 0): + condlist = [condlist] + + condlist = asarray(condlist, dtype=bool) + n = len(condlist) + + if n == n2 - 1: # compute the "otherwise" condition. + condelse = ~np.any(condlist, axis=0, keepdims=True) + condlist = np.concatenate([condlist, condelse], axis=0) + n += 1 + elif n != n2: + raise ValueError( + f"with {n} condition(s), either {n} or {n + 1} functions are expected" + ) + + y = zeros_like(x) + for cond, func in zip(condlist, funclist): + if not isinstance(func, collections.abc.Callable): + y[cond] = func + else: + vals = x[cond] + if vals.size > 0: + y[cond] = func(vals, *args, **kw) + + return y + + +def _select_dispatcher(condlist, choicelist, default=None): + yield from condlist + yield from choicelist + + +@array_function_dispatch(_select_dispatcher) +def select(condlist, choicelist, default=0): + """ + Return an array drawn from elements in choicelist, depending on conditions. + + Parameters + ---------- + condlist : list of bool ndarrays + The list of conditions which determine from which array in `choicelist` + the output elements are taken. When multiple conditions are satisfied, + the first one encountered in `condlist` is used. + choicelist : list of ndarrays + The list of arrays from which the output elements are taken. It has + to be of the same length as `condlist`. + default : array_like, optional + The element inserted in `output` when all conditions evaluate to False. + + Returns + ------- + output : ndarray + The output at position m is the m-th element of the array in + `choicelist` where the m-th element of the corresponding array in + `condlist` is True. + + See Also + -------- + where : Return elements from one of two arrays depending on condition. + take, choose, compress, diag, diagonal + + Examples + -------- + >>> import numpy as np + + Beginning with an array of integers from 0 to 5 (inclusive), + elements less than ``3`` are negated, elements greater than ``3`` + are squared, and elements not meeting either of these conditions + (exactly ``3``) are replaced with a `default` value of ``42``. + + >>> x = np.arange(6) + >>> condlist = [x<3, x>3] + >>> choicelist = [-x, x**2] + >>> np.select(condlist, choicelist, 42) + array([ 0, -1, -2, 42, 16, 25]) + + When multiple conditions are satisfied, the first one encountered in + `condlist` is used. + + >>> condlist = [x<=4, x>3] + >>> choicelist = [x, x**2] + >>> np.select(condlist, choicelist, 55) + array([ 0, 1, 2, 3, 4, 25]) + + """ + # Check the size of condlist and choicelist are the same, or abort. + if len(condlist) != len(choicelist): + raise ValueError( + 'list of cases must be same length as list of conditions') + + # Now that the dtype is known, handle the deprecated select([], []) case + if len(condlist) == 0: + raise ValueError("select with an empty condition list is not possible") + + # TODO: This preserves the Python int, float, complex manually to get the + # right `result_type` with NEP 50. Most likely we will grow a better + # way to spell this (and this can be replaced). + choicelist = [ + choice if type(choice) in (int, float, complex) else np.asarray(choice) + for choice in choicelist] + choicelist.append(default if type(default) in (int, float, complex) + else np.asarray(default)) + + try: + dtype = np.result_type(*choicelist) + except TypeError as e: + msg = f'Choicelist and default value do not have a common dtype: {e}' + raise TypeError(msg) from None + + # Convert conditions to arrays and broadcast conditions and choices + # as the shape is needed for the result. Doing it separately optimizes + # for example when all choices are scalars. + condlist = np.broadcast_arrays(*condlist) + choicelist = np.broadcast_arrays(*choicelist) + + # If cond array is not an ndarray in boolean format or scalar bool, abort. + for i, cond in enumerate(condlist): + if cond.dtype.type is not np.bool: + raise TypeError( + f'invalid entry {i} in condlist: should be boolean ndarray') + + if choicelist[0].ndim == 0: + # This may be common, so avoid the call. + result_shape = condlist[0].shape + else: + result_shape = np.broadcast_arrays(condlist[0], choicelist[0])[0].shape + + result = np.full(result_shape, choicelist[-1], dtype) + + # Use np.copyto to burn each choicelist array onto result, using the + # corresponding condlist as a boolean mask. This is done in reverse + # order since the first choice should take precedence. + choicelist = choicelist[-2::-1] + condlist = condlist[::-1] + for choice, cond in zip(choicelist, condlist): + np.copyto(result, choice, where=cond) + + return result + + +def _copy_dispatcher(a, order=None, subok=None): + return (a,) + + +@array_function_dispatch(_copy_dispatcher) +def copy(a, order='K', subok=False): + """ + Return an array copy of the given object. + + Parameters + ---------- + a : array_like + Input data. + order : {'C', 'F', 'A', 'K'}, optional + Controls the memory layout of the copy. 'C' means C-order, + 'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous, + 'C' otherwise. 'K' means match the layout of `a` as closely + as possible. (Note that this function and :meth:`ndarray.copy` are very + similar, but have different default values for their order= + arguments.) + subok : bool, optional + If True, then sub-classes will be passed-through, otherwise the + returned array will be forced to be a base-class array (defaults to False). + + Returns + ------- + arr : ndarray + Array interpretation of `a`. + + See Also + -------- + ndarray.copy : Preferred method for creating an array copy + + Notes + ----- + This is equivalent to: + + >>> np.array(a, copy=True) #doctest: +SKIP + + The copy made of the data is shallow, i.e., for arrays with object dtype, + the new array will point to the same objects. + See Examples from `ndarray.copy`. + + Examples + -------- + >>> import numpy as np + + Create an array x, with a reference y and a copy z: + + >>> x = np.array([1, 2, 3]) + >>> y = x + >>> z = np.copy(x) + + Note that, when we modify x, y changes, but not z: + + >>> x[0] = 10 + >>> x[0] == y[0] + True + >>> x[0] == z[0] + False + + Note that, np.copy clears previously set WRITEABLE=False flag. + + >>> a = np.array([1, 2, 3]) + >>> a.flags["WRITEABLE"] = False + >>> b = np.copy(a) + >>> b.flags["WRITEABLE"] + True + >>> b[0] = 3 + >>> b + array([3, 2, 3]) + """ + return array(a, order=order, subok=subok, copy=True) + +# Basic operations + + +def _gradient_dispatcher(f, *varargs, axis=None, edge_order=None): + yield f + yield from varargs + + +@array_function_dispatch(_gradient_dispatcher) +def gradient(f, *varargs, axis=None, edge_order=1): + """ + Return the gradient of an N-dimensional array. + + The gradient is computed using second order accurate central differences + in the interior points and either first or second order accurate one-sides + (forward or backwards) differences at the boundaries. + The returned gradient hence has the same shape as the input array. + + Parameters + ---------- + f : array_like + An N-dimensional array containing samples of a scalar function. + varargs : list of scalar or array, optional + Spacing between f values. Default unitary spacing for all dimensions. + Spacing can be specified using: + + 1. single scalar to specify a sample distance for all dimensions. + 2. N scalars to specify a constant sample distance for each dimension. + i.e. `dx`, `dy`, `dz`, ... + 3. N arrays to specify the coordinates of the values along each + dimension of F. The length of the array must match the size of + the corresponding dimension + 4. Any combination of N scalars/arrays with the meaning of 2. and 3. + + If `axis` is given, the number of varargs must equal the number of axes + specified in the axis parameter. + Default: 1. (see Examples below). + + edge_order : {1, 2}, optional + Gradient is calculated using N-th order accurate differences + at the boundaries. Default: 1. + axis : None or int or tuple of ints, optional + Gradient is calculated only along the given axis or axes + The default (axis = None) is to calculate the gradient for all the axes + of the input array. axis may be negative, in which case it counts from + the last to the first axis. + + Returns + ------- + gradient : ndarray or tuple of ndarray + A tuple of ndarrays (or a single ndarray if there is only one + dimension) corresponding to the derivatives of f with respect + to each dimension. Each derivative has the same shape as f. + + Examples + -------- + >>> import numpy as np + >>> f = np.array([1, 2, 4, 7, 11, 16]) + >>> np.gradient(f) + array([1. , 1.5, 2.5, 3.5, 4.5, 5. ]) + >>> np.gradient(f, 2) + array([0.5 , 0.75, 1.25, 1.75, 2.25, 2.5 ]) + + Spacing can be also specified with an array that represents the coordinates + of the values F along the dimensions. + For instance a uniform spacing: + + >>> x = np.arange(f.size) + >>> np.gradient(f, x) + array([1. , 1.5, 2.5, 3.5, 4.5, 5. ]) + + Or a non uniform one: + + >>> x = np.array([0., 1., 1.5, 3.5, 4., 6.]) + >>> np.gradient(f, x) + array([1. , 3. , 3.5, 6.7, 6.9, 2.5]) + + For two dimensional arrays, the return will be two arrays ordered by + axis. In this example the first array stands for the gradient in + rows and the second one in columns direction: + + >>> np.gradient(np.array([[1, 2, 6], [3, 4, 5]])) + (array([[ 2., 2., -1.], + [ 2., 2., -1.]]), + array([[1. , 2.5, 4. ], + [1. , 1. , 1. ]])) + + In this example the spacing is also specified: + uniform for axis=0 and non uniform for axis=1 + + >>> dx = 2. + >>> y = [1., 1.5, 3.5] + >>> np.gradient(np.array([[1, 2, 6], [3, 4, 5]]), dx, y) + (array([[ 1. , 1. , -0.5], + [ 1. , 1. , -0.5]]), + array([[2. , 2. , 2. ], + [2. , 1.7, 0.5]])) + + It is possible to specify how boundaries are treated using `edge_order` + + >>> x = np.array([0, 1, 2, 3, 4]) + >>> f = x**2 + >>> np.gradient(f, edge_order=1) + array([1., 2., 4., 6., 7.]) + >>> np.gradient(f, edge_order=2) + array([0., 2., 4., 6., 8.]) + + The `axis` keyword can be used to specify a subset of axes of which the + gradient is calculated + + >>> np.gradient(np.array([[1, 2, 6], [3, 4, 5]]), axis=0) + array([[ 2., 2., -1.], + [ 2., 2., -1.]]) + + The `varargs` argument defines the spacing between sample points in the + input array. It can take two forms: + + 1. An array, specifying coordinates, which may be unevenly spaced: + + >>> x = np.array([0., 2., 3., 6., 8.]) + >>> y = x ** 2 + >>> np.gradient(y, x, edge_order=2) + array([ 0., 4., 6., 12., 16.]) + + 2. A scalar, representing the fixed sample distance: + + >>> dx = 2 + >>> x = np.array([0., 2., 4., 6., 8.]) + >>> y = x ** 2 + >>> np.gradient(y, dx, edge_order=2) + array([ 0., 4., 8., 12., 16.]) + + It's possible to provide different data for spacing along each dimension. + The number of arguments must match the number of dimensions in the input + data. + + >>> dx = 2 + >>> dy = 3 + >>> x = np.arange(0, 6, dx) + >>> y = np.arange(0, 9, dy) + >>> xs, ys = np.meshgrid(x, y) + >>> zs = xs + 2 * ys + >>> np.gradient(zs, dy, dx) # Passing two scalars + (array([[2., 2., 2.], + [2., 2., 2.], + [2., 2., 2.]]), + array([[1., 1., 1.], + [1., 1., 1.], + [1., 1., 1.]])) + + Mixing scalars and arrays is also allowed: + + >>> np.gradient(zs, y, dx) # Passing one array and one scalar + (array([[2., 2., 2.], + [2., 2., 2.], + [2., 2., 2.]]), + array([[1., 1., 1.], + [1., 1., 1.], + [1., 1., 1.]])) + + Notes + ----- + Assuming that :math:`f\\in C^{3}` (i.e., :math:`f` has at least 3 continuous + derivatives) and let :math:`h_{*}` be a non-homogeneous stepsize, we + minimize the "consistency error" :math:`\\eta_{i}` between the true gradient + and its estimate from a linear combination of the neighboring grid-points: + + .. math:: + + \\eta_{i} = f_{i}^{\\left(1\\right)} - + \\left[ \\alpha f\\left(x_{i}\\right) + + \\beta f\\left(x_{i} + h_{d}\\right) + + \\gamma f\\left(x_{i}-h_{s}\\right) + \\right] + + By substituting :math:`f(x_{i} + h_{d})` and :math:`f(x_{i} - h_{s})` + with their Taylor series expansion, this translates into solving + the following the linear system: + + .. math:: + + \\left\\{ + \\begin{array}{r} + \\alpha+\\beta+\\gamma=0 \\\\ + \\beta h_{d}-\\gamma h_{s}=1 \\\\ + \\beta h_{d}^{2}+\\gamma h_{s}^{2}=0 + \\end{array} + \\right. + + The resulting approximation of :math:`f_{i}^{(1)}` is the following: + + .. math:: + + \\hat f_{i}^{(1)} = + \\frac{ + h_{s}^{2}f\\left(x_{i} + h_{d}\\right) + + \\left(h_{d}^{2} - h_{s}^{2}\\right)f\\left(x_{i}\\right) + - h_{d}^{2}f\\left(x_{i}-h_{s}\\right)} + { h_{s}h_{d}\\left(h_{d} + h_{s}\\right)} + + \\mathcal{O}\\left(\\frac{h_{d}h_{s}^{2} + + h_{s}h_{d}^{2}}{h_{d} + + h_{s}}\\right) + + It is worth noting that if :math:`h_{s}=h_{d}` + (i.e., data are evenly spaced) + we find the standard second order approximation: + + .. math:: + + \\hat f_{i}^{(1)}= + \\frac{f\\left(x_{i+1}\\right) - f\\left(x_{i-1}\\right)}{2h} + + \\mathcal{O}\\left(h^{2}\\right) + + With a similar procedure the forward/backward approximations used for + boundaries can be derived. + + References + ---------- + .. [1] Quarteroni A., Sacco R., Saleri F. (2007) Numerical Mathematics + (Texts in Applied Mathematics). New York: Springer. + .. [2] Durran D. R. (1999) Numerical Methods for Wave Equations + in Geophysical Fluid Dynamics. New York: Springer. + .. [3] Fornberg B. (1988) Generation of Finite Difference Formulas on + Arbitrarily Spaced Grids, + Mathematics of Computation 51, no. 184 : 699-706. + `PDF `_. + """ + f = np.asanyarray(f) + N = f.ndim # number of dimensions + + if axis is None: + axes = tuple(range(N)) + else: + axes = _nx.normalize_axis_tuple(axis, N) + + len_axes = len(axes) + n = len(varargs) + if n == 0: + # no spacing argument - use 1 in all axes + dx = [1.0] * len_axes + elif n == 1 and np.ndim(varargs[0]) == 0: + # single scalar for all axes + dx = varargs * len_axes + elif n == len_axes: + # scalar or 1d array for each axis + dx = list(varargs) + for i, distances in enumerate(dx): + distances = np.asanyarray(distances) + if distances.ndim == 0: + continue + elif distances.ndim != 1: + raise ValueError("distances must be either scalars or 1d") + if len(distances) != f.shape[axes[i]]: + raise ValueError("when 1d, distances must match " + "the length of the corresponding dimension") + if np.issubdtype(distances.dtype, np.integer): + # Convert numpy integer types to float64 to avoid modular + # arithmetic in np.diff(distances). + distances = distances.astype(np.float64) + diffx = np.diff(distances) + # if distances are constant reduce to the scalar case + # since it brings a consistent speedup + if (diffx == diffx[0]).all(): + diffx = diffx[0] + dx[i] = diffx + else: + raise TypeError("invalid number of arguments") + + if edge_order > 2: + raise ValueError("'edge_order' greater than 2 not supported") + + # use central differences on interior and one-sided differences on the + # endpoints. This preserves second order-accuracy over the full domain. + + outvals = [] + + # create slice objects --- initially all are [:, :, ..., :] + slice1 = [slice(None)] * N + slice2 = [slice(None)] * N + slice3 = [slice(None)] * N + slice4 = [slice(None)] * N + + otype = f.dtype + if otype.type is np.datetime64: + # the timedelta dtype with the same unit information + otype = np.dtype(otype.name.replace('datetime', 'timedelta')) + # view as timedelta to allow addition + f = f.view(otype) + elif otype.type is np.timedelta64: + pass + elif np.issubdtype(otype, np.inexact): + pass + else: + # All other types convert to floating point. + # First check if f is a numpy integer type; if so, convert f to float64 + # to avoid modular arithmetic when computing the changes in f. + if np.issubdtype(otype, np.integer): + f = f.astype(np.float64) + otype = np.float64 + + for axis, ax_dx in zip(axes, dx): + if f.shape[axis] < edge_order + 1: + raise ValueError( + "Shape of array too small to calculate a numerical gradient, " + "at least (edge_order + 1) elements are required.") + # result allocation + out = np.empty_like(f, dtype=otype) + + # spacing for the current axis + uniform_spacing = np.ndim(ax_dx) == 0 + + # Numerical differentiation: 2nd order interior + slice1[axis] = slice(1, -1) + slice2[axis] = slice(None, -2) + slice3[axis] = slice(1, -1) + slice4[axis] = slice(2, None) + + if uniform_spacing: + out[tuple(slice1)] = (f[tuple(slice4)] - f[tuple(slice2)]) / (2. * ax_dx) + else: + dx1 = ax_dx[0:-1] + dx2 = ax_dx[1:] + a = -(dx2) / (dx1 * (dx1 + dx2)) + b = (dx2 - dx1) / (dx1 * dx2) + c = dx1 / (dx2 * (dx1 + dx2)) + # fix the shape for broadcasting + shape = np.ones(N, dtype=int) + shape[axis] = -1 + + a = a.reshape(shape) + b = b.reshape(shape) + c = c.reshape(shape) + # 1D equivalent -- out[1:-1] = a * f[:-2] + b * f[1:-1] + c * f[2:] + out[tuple(slice1)] = a * f[tuple(slice2)] + b * f[tuple(slice3)] \ + + c * f[tuple(slice4)] + + # Numerical differentiation: 1st order edges + if edge_order == 1: + slice1[axis] = 0 + slice2[axis] = 1 + slice3[axis] = 0 + dx_0 = ax_dx if uniform_spacing else ax_dx[0] + # 1D equivalent -- out[0] = (f[1] - f[0]) / (x[1] - x[0]) + out[tuple(slice1)] = (f[tuple(slice2)] - f[tuple(slice3)]) / dx_0 + + slice1[axis] = -1 + slice2[axis] = -1 + slice3[axis] = -2 + dx_n = ax_dx if uniform_spacing else ax_dx[-1] + # 1D equivalent -- out[-1] = (f[-1] - f[-2]) / (x[-1] - x[-2]) + out[tuple(slice1)] = (f[tuple(slice2)] - f[tuple(slice3)]) / dx_n + + # Numerical differentiation: 2nd order edges + else: + slice1[axis] = 0 + slice2[axis] = 0 + slice3[axis] = 1 + slice4[axis] = 2 + if uniform_spacing: + a = -1.5 / ax_dx + b = 2. / ax_dx + c = -0.5 / ax_dx + else: + dx1 = ax_dx[0] + dx2 = ax_dx[1] + a = -(2. * dx1 + dx2) / (dx1 * (dx1 + dx2)) + b = (dx1 + dx2) / (dx1 * dx2) + c = - dx1 / (dx2 * (dx1 + dx2)) + # 1D equivalent -- out[0] = a * f[0] + b * f[1] + c * f[2] + out[tuple(slice1)] = a * f[tuple(slice2)] + b * f[tuple(slice3)] \ + + c * f[tuple(slice4)] + + slice1[axis] = -1 + slice2[axis] = -3 + slice3[axis] = -2 + slice4[axis] = -1 + if uniform_spacing: + a = 0.5 / ax_dx + b = -2. / ax_dx + c = 1.5 / ax_dx + else: + dx1 = ax_dx[-2] + dx2 = ax_dx[-1] + a = (dx2) / (dx1 * (dx1 + dx2)) + b = - (dx2 + dx1) / (dx1 * dx2) + c = (2. * dx2 + dx1) / (dx2 * (dx1 + dx2)) + # 1D equivalent -- out[-1] = a * f[-3] + b * f[-2] + c * f[-1] + out[tuple(slice1)] = a * f[tuple(slice2)] + b * f[tuple(slice3)] \ + + c * f[tuple(slice4)] + + outvals.append(out) + + # reset the slice object in this dimension to ":" + slice1[axis] = slice(None) + slice2[axis] = slice(None) + slice3[axis] = slice(None) + slice4[axis] = slice(None) + + if len_axes == 1: + return outvals[0] + return tuple(outvals) + + +def _diff_dispatcher(a, n=None, axis=None, prepend=None, append=None): + return (a, prepend, append) + + +@array_function_dispatch(_diff_dispatcher) +def diff(a, n=1, axis=-1, prepend=np._NoValue, append=np._NoValue): + """ + Calculate the n-th discrete difference along the given axis. + + The first difference is given by ``out[i] = a[i+1] - a[i]`` along + the given axis, higher differences are calculated by using `diff` + recursively. + + Parameters + ---------- + a : array_like + Input array + n : int, optional + The number of times values are differenced. If zero, the input + is returned as-is. + axis : int, optional + The axis along which the difference is taken, default is the + last axis. + prepend, append : array_like, optional + Values to prepend or append to `a` along axis prior to + performing the difference. Scalar values are expanded to + arrays with length 1 in the direction of axis and the shape + of the input array in along all other axes. Otherwise the + dimension and shape must match `a` except along axis. + + Returns + ------- + diff : ndarray + The n-th differences. The shape of the output is the same as `a` + except along `axis` where the dimension is smaller by `n`. The + type of the output is the same as the type of the difference + between any two elements of `a`. This is the same as the type of + `a` in most cases. A notable exception is `datetime64`, which + results in a `timedelta64` output array. + + See Also + -------- + gradient, ediff1d, cumsum + + Notes + ----- + Type is preserved for boolean arrays, so the result will contain + `False` when consecutive elements are the same and `True` when they + differ. + + For unsigned integer arrays, the results will also be unsigned. This + should not be surprising, as the result is consistent with + calculating the difference directly: + + >>> u8_arr = np.array([1, 0], dtype=np.uint8) + >>> np.diff(u8_arr) + array([255], dtype=uint8) + >>> u8_arr[1,...] - u8_arr[0,...] + np.uint8(255) + + If this is not desirable, then the array should be cast to a larger + integer type first: + + >>> i16_arr = u8_arr.astype(np.int16) + >>> np.diff(i16_arr) + array([-1], dtype=int16) + + Examples + -------- + >>> import numpy as np + >>> x = np.array([1, 2, 4, 7, 0]) + >>> np.diff(x) + array([ 1, 2, 3, -7]) + >>> np.diff(x, n=2) + array([ 1, 1, -10]) + + >>> x = np.array([[1, 3, 6, 10], [0, 5, 6, 8]]) + >>> np.diff(x) + array([[2, 3, 4], + [5, 1, 2]]) + >>> np.diff(x, axis=0) + array([[-1, 2, 0, -2]]) + + >>> x = np.arange('1066-10-13', '1066-10-16', dtype=np.datetime64) + >>> np.diff(x) + array([1, 1], dtype='timedelta64[D]') + + """ + if n == 0: + return a + if n < 0: + raise ValueError( + "order must be non-negative but got " + repr(n)) + + a = asanyarray(a) + nd = a.ndim + if nd == 0: + raise ValueError("diff requires input that is at least one dimensional") + axis = normalize_axis_index(axis, nd) + + combined = [] + if prepend is not np._NoValue: + prepend = np.asanyarray(prepend) + if prepend.ndim == 0: + shape = list(a.shape) + shape[axis] = 1 + prepend = np.broadcast_to(prepend, tuple(shape)) + combined.append(prepend) + + combined.append(a) + + if append is not np._NoValue: + append = np.asanyarray(append) + if append.ndim == 0: + shape = list(a.shape) + shape[axis] = 1 + append = np.broadcast_to(append, tuple(shape)) + combined.append(append) + + if len(combined) > 1: + a = np.concatenate(combined, axis) + + slice1 = [slice(None)] * nd + slice2 = [slice(None)] * nd + slice1[axis] = slice(1, None) + slice2[axis] = slice(None, -1) + slice1 = tuple(slice1) + slice2 = tuple(slice2) + + op = not_equal if a.dtype == np.bool else subtract + for _ in range(n): + a = op(a[slice1], a[slice2]) + + return a + + +def _interp_dispatcher(x, xp, fp, left=None, right=None, period=None): + return (x, xp, fp) + + +@array_function_dispatch(_interp_dispatcher) +def interp(x, xp, fp, left=None, right=None, period=None): + """ + One-dimensional linear interpolation for monotonically increasing sample points. + + Returns the one-dimensional piecewise linear interpolant to a function + with given discrete data points (`xp`, `fp`), evaluated at `x`. + + Parameters + ---------- + x : array_like + The x-coordinates at which to evaluate the interpolated values. + + xp : 1-D sequence of floats + The x-coordinates of the data points, must be increasing if argument + `period` is not specified. Otherwise, `xp` is internally sorted after + normalizing the periodic boundaries with ``xp = xp % period``. + + fp : 1-D sequence of float or complex + The y-coordinates of the data points, same length as `xp`. + + left : optional float or complex corresponding to fp + Value to return for `x < xp[0]`, default is `fp[0]`. + + right : optional float or complex corresponding to fp + Value to return for `x > xp[-1]`, default is `fp[-1]`. + + period : None or float, optional + A period for the x-coordinates. This parameter allows the proper + interpolation of angular x-coordinates. Parameters `left` and `right` + are ignored if `period` is specified. + + Returns + ------- + y : float or complex (corresponding to fp) or ndarray + The interpolated values, same shape as `x`. + + Raises + ------ + ValueError + If `xp` and `fp` have different length + If `xp` or `fp` are not 1-D sequences + If `period == 0` + + See Also + -------- + scipy.interpolate + + Warnings + -------- + The x-coordinate sequence is expected to be increasing, but this is not + explicitly enforced. However, if the sequence `xp` is non-increasing, + interpolation results are meaningless. + + Note that, since NaN is unsortable, `xp` also cannot contain NaNs. + + A simple check for `xp` being strictly increasing is:: + + np.all(np.diff(xp) > 0) + + Examples + -------- + >>> import numpy as np + >>> xp = [1, 2, 3] + >>> fp = [3, 2, 0] + >>> np.interp(2.5, xp, fp) + 1.0 + >>> np.interp([0, 1, 1.5, 2.72, 3.14], xp, fp) + array([3. , 3. , 2.5 , 0.56, 0. ]) + >>> UNDEF = -99.0 + >>> np.interp(3.14, xp, fp, right=UNDEF) + -99.0 + + Plot an interpolant to the sine function: + + >>> x = np.linspace(0, 2*np.pi, 10) + >>> y = np.sin(x) + >>> xvals = np.linspace(0, 2*np.pi, 50) + >>> yinterp = np.interp(xvals, x, y) + >>> import matplotlib.pyplot as plt + >>> plt.plot(x, y, 'o') + [] + >>> plt.plot(xvals, yinterp, '-x') + [] + >>> plt.show() + + Interpolation with periodic x-coordinates: + + >>> x = [-180, -170, -185, 185, -10, -5, 0, 365] + >>> xp = [190, -190, 350, -350] + >>> fp = [5, 10, 3, 4] + >>> np.interp(x, xp, fp, period=360) + array([7.5 , 5. , 8.75, 6.25, 3. , 3.25, 3.5 , 3.75]) + + Complex interpolation: + + >>> x = [1.5, 4.0] + >>> xp = [2,3,5] + >>> fp = [1.0j, 0, 2+3j] + >>> np.interp(x, xp, fp) + array([0.+1.j , 1.+1.5j]) + + """ + + fp = np.asarray(fp) + + if np.iscomplexobj(fp): + interp_func = compiled_interp_complex + input_dtype = np.complex128 + else: + interp_func = compiled_interp + input_dtype = np.float64 + + if period is not None: + if period == 0: + raise ValueError("period must be a non-zero value") + period = abs(period) + left = None + right = None + + x = np.asarray(x, dtype=np.float64) + xp = np.asarray(xp, dtype=np.float64) + fp = np.asarray(fp, dtype=input_dtype) + + if xp.ndim != 1 or fp.ndim != 1: + raise ValueError("Data points must be 1-D sequences") + if xp.shape[0] != fp.shape[0]: + raise ValueError("fp and xp are not of the same length") + # normalizing periodic boundaries + x = x % period + xp = xp % period + asort_xp = np.argsort(xp) + xp = xp[asort_xp] + fp = fp[asort_xp] + xp = np.concatenate((xp[-1:] - period, xp, xp[0:1] + period)) + fp = np.concatenate((fp[-1:], fp, fp[0:1])) + + return interp_func(x, xp, fp, left, right) + + +def _angle_dispatcher(z, deg=None): + return (z,) + + +@array_function_dispatch(_angle_dispatcher) +def angle(z, deg=False): + """ + Return the angle of the complex argument. + + Parameters + ---------- + z : array_like + A complex number or sequence of complex numbers. + deg : bool, optional + Return angle in degrees if True, radians if False (default). + + Returns + ------- + angle : ndarray or scalar + The counterclockwise angle from the positive real axis on the complex + plane in the range ``(-pi, pi]``, with dtype as numpy.float64. + + See Also + -------- + arctan2 + absolute + + Notes + ----- + This function passes the imaginary and real parts of the argument to + `arctan2` to compute the result; consequently, it follows the convention + of `arctan2` when the magnitude of the argument is zero. See example. + + Examples + -------- + >>> import numpy as np + >>> np.angle([1.0, 1.0j, 1+1j]) # in radians + array([ 0. , 1.57079633, 0.78539816]) # may vary + >>> np.angle(1+1j, deg=True) # in degrees + 45.0 + >>> np.angle([0., -0., complex(0., -0.), complex(-0., -0.)]) # convention + array([ 0. , 3.14159265, -0. , -3.14159265]) + + """ + z = asanyarray(z) + if issubclass(z.dtype.type, _nx.complexfloating): + zimag = z.imag + zreal = z.real + else: + zimag = 0 + zreal = z + + a = arctan2(zimag, zreal) + if deg: + a *= 180 / pi + return a + + +def _unwrap_dispatcher(p, discont=None, axis=None, *, period=None): + return (p,) + + +@array_function_dispatch(_unwrap_dispatcher) +def unwrap(p, discont=None, axis=-1, *, period=2 * pi): + r""" + Unwrap by taking the complement of large deltas with respect to the period. + + This unwraps a signal `p` by changing elements which have an absolute + difference from their predecessor of more than ``max(discont, period/2)`` + to their `period`-complementary values. + + For the default case where `period` is :math:`2\pi` and `discont` is + :math:`\pi`, this unwraps a radian phase `p` such that adjacent differences + are never greater than :math:`\pi` by adding :math:`2k\pi` for some + integer :math:`k`. + + Parameters + ---------- + p : array_like + Input array. + discont : float, optional + Maximum discontinuity between values, default is ``period/2``. + Values below ``period/2`` are treated as if they were ``period/2``. + To have an effect different from the default, `discont` should be + larger than ``period/2``. + axis : int, optional + Axis along which unwrap will operate, default is the last axis. + period : float, optional + Size of the range over which the input wraps. By default, it is + ``2 pi``. + + .. versionadded:: 1.21.0 + + Returns + ------- + out : ndarray + Output array. + + See Also + -------- + rad2deg, deg2rad + + Notes + ----- + If the discontinuity in `p` is smaller than ``period/2``, + but larger than `discont`, no unwrapping is done because taking + the complement would only make the discontinuity larger. + + Examples + -------- + >>> import numpy as np + + >>> phase = np.linspace(0, np.pi, num=5) + >>> phase[3:] += np.pi + >>> phase + array([ 0. , 0.78539816, 1.57079633, 5.49778714, 6.28318531]) # may vary + >>> np.unwrap(phase) + array([ 0. , 0.78539816, 1.57079633, -0.78539816, 0. ]) # may vary + >>> np.unwrap([0, 1, 2, -1, 0], period=4) + array([0, 1, 2, 3, 4]) + >>> np.unwrap([ 1, 2, 3, 4, 5, 6, 1, 2, 3], period=6) + array([1, 2, 3, 4, 5, 6, 7, 8, 9]) + >>> np.unwrap([2, 3, 4, 5, 2, 3, 4, 5], period=4) + array([2, 3, 4, 5, 6, 7, 8, 9]) + >>> phase_deg = np.mod(np.linspace(0 ,720, 19), 360) - 180 + >>> np.unwrap(phase_deg, period=360) + array([-180., -140., -100., -60., -20., 20., 60., 100., 140., + 180., 220., 260., 300., 340., 380., 420., 460., 500., + 540.]) + + This example plots the unwrapping of the wrapped input signal `w`. + First generate `w`, then apply `unwrap` to get `u`. + + >>> t = np.linspace(0, 25, 801) + >>> w = np.mod(1.5 * np.sin(1.1 * t + 0.26) * (1 - t / 6 + (t / 23) ** 3), 2.0) - 1 + >>> u = np.unwrap(w, period=2.0) + + Plot `w` and `u`. + + >>> import matplotlib.pyplot as plt + >>> plt.plot(t, w, label='w (a signal wrapped to [-1, 1])') + >>> plt.plot(t, u, linewidth=2.5, alpha=0.5, label='unwrap(w, period=2)') + >>> plt.xlabel('t') + >>> plt.grid(alpha=0.6) + >>> plt.legend(framealpha=1, shadow=True) + >>> plt.show() + """ + p = asarray(p) + nd = p.ndim + dd = diff(p, axis=axis) + if discont is None: + discont = period / 2 + slice1 = [slice(None, None)] * nd # full slices + slice1[axis] = slice(1, None) + slice1 = tuple(slice1) + dtype = np.result_type(dd, period) + if _nx.issubdtype(dtype, _nx.integer): + interval_high, rem = divmod(period, 2) + boundary_ambiguous = rem == 0 + else: + interval_high = period / 2 + boundary_ambiguous = True + interval_low = -interval_high + ddmod = mod(dd - interval_low, period) + interval_low + if boundary_ambiguous: + # for `mask = (abs(dd) == period/2)`, the above line made + # `ddmod[mask] == -period/2`. correct these such that + # `ddmod[mask] == sign(dd[mask])*period/2`. + _nx.copyto(ddmod, interval_high, + where=(ddmod == interval_low) & (dd > 0)) + ph_correct = ddmod - dd + _nx.copyto(ph_correct, 0, where=abs(dd) < discont) + up = array(p, copy=True, dtype=dtype) + up[slice1] = p[slice1] + ph_correct.cumsum(axis) + return up + + +def _sort_complex(a): + return (a,) + + +@array_function_dispatch(_sort_complex) +def sort_complex(a): + """ + Sort a complex array using the real part first, then the imaginary part. + + Parameters + ---------- + a : array_like + Input array + + Returns + ------- + out : complex ndarray + Always returns a sorted complex array. + + Examples + -------- + >>> import numpy as np + >>> np.sort_complex([5, 3, 6, 2, 1]) + array([1.+0.j, 2.+0.j, 3.+0.j, 5.+0.j, 6.+0.j]) + + >>> np.sort_complex([1 + 2j, 2 - 1j, 3 - 2j, 3 - 3j, 3 + 5j]) + array([1.+2.j, 2.-1.j, 3.-3.j, 3.-2.j, 3.+5.j]) + + """ + b = array(a, copy=True) + b.sort() + if not issubclass(b.dtype.type, _nx.complexfloating): + if b.dtype.char in 'bhBH': + return b.astype('F') + elif b.dtype.char == 'g': + return b.astype('G') + else: + return b.astype('D') + else: + return b + + +def _arg_trim_zeros(filt): + """Return indices of the first and last non-zero element. + + Parameters + ---------- + filt : array_like + Input array. + + Returns + ------- + start, stop : ndarray + Two arrays containing the indices of the first and last non-zero + element in each dimension. + + See also + -------- + trim_zeros + + Examples + -------- + >>> import numpy as np + >>> _arg_trim_zeros(np.array([0, 0, 1, 1, 0])) + (array([2]), array([3])) + """ + nonzero = ( + np.argwhere(filt) + if filt.dtype != np.object_ + # Historically, `trim_zeros` treats `None` in an object array + # as non-zero while argwhere doesn't, account for that + else np.argwhere(filt != 0) + ) + if nonzero.size == 0: + start = stop = np.array([], dtype=np.intp) + else: + start = nonzero.min(axis=0) + stop = nonzero.max(axis=0) + return start, stop + + +def _trim_zeros(filt, trim=None, axis=None): + return (filt,) + + +@array_function_dispatch(_trim_zeros) +def trim_zeros(filt, trim='fb', axis=None): + """Remove values along a dimension which are zero along all other. + + Parameters + ---------- + filt : array_like + Input array. + trim : {"fb", "f", "b"}, optional + A string with 'f' representing trim from front and 'b' to trim from + back. By default, zeros are trimmed on both sides. + Front and back refer to the edges of a dimension, with "front" referring + to the side with the lowest index 0, and "back" referring to the highest + index (or index -1). + axis : int or sequence, optional + If None, `filt` is cropped such that the smallest bounding box is + returned that still contains all values which are not zero. + If an axis is specified, `filt` will be sliced in that dimension only + on the sides specified by `trim`. The remaining area will be the + smallest that still contains all values wich are not zero. + + .. versionadded:: 2.2.0 + + Returns + ------- + trimmed : ndarray or sequence + The result of trimming the input. The number of dimensions and the + input data type are preserved. + + Notes + ----- + For all-zero arrays, the first axis is trimmed first. + + Examples + -------- + >>> import numpy as np + >>> a = np.array((0, 0, 0, 1, 2, 3, 0, 2, 1, 0)) + >>> np.trim_zeros(a) + array([1, 2, 3, 0, 2, 1]) + + >>> np.trim_zeros(a, trim='b') + array([0, 0, 0, ..., 0, 2, 1]) + + Multiple dimensions are supported. + + >>> b = np.array([[0, 0, 2, 3, 0, 0], + ... [0, 1, 0, 3, 0, 0], + ... [0, 0, 0, 0, 0, 0]]) + >>> np.trim_zeros(b) + array([[0, 2, 3], + [1, 0, 3]]) + + >>> np.trim_zeros(b, axis=-1) + array([[0, 2, 3], + [1, 0, 3], + [0, 0, 0]]) + + The input data type is preserved, list/tuple in means list/tuple out. + + >>> np.trim_zeros([0, 1, 2, 0]) + [1, 2] + + """ + filt_ = np.asarray(filt) + + trim = trim.lower() + if trim not in {"fb", "bf", "f", "b"}: + raise ValueError(f"unexpected character(s) in `trim`: {trim!r}") + if axis is None: + axis_tuple = tuple(range(filt_.ndim)) + else: + axis_tuple = _nx.normalize_axis_tuple(axis, filt_.ndim, argname="axis") + + if not axis_tuple: + # No trimming requested -> return input unmodified. + return filt + + start, stop = _arg_trim_zeros(filt_) + stop += 1 # Adjust for slicing + + if start.size == 0: + # filt is all-zero -> assign same values to start and stop so that + # resulting slice will be empty + start = stop = np.zeros(filt_.ndim, dtype=np.intp) + else: + if 'f' not in trim: + start = (None,) * filt_.ndim + if 'b' not in trim: + stop = (None,) * filt_.ndim + + sl = tuple(slice(start[ax], stop[ax]) if ax in axis_tuple else slice(None) + for ax in range(filt_.ndim)) + if len(sl) == 1: + # filt is 1D -> avoid multi-dimensional slicing to preserve + # non-array input types + return filt[sl[0]] + return filt[sl] + + +def _extract_dispatcher(condition, arr): + return (condition, arr) + + +@array_function_dispatch(_extract_dispatcher) +def extract(condition, arr): + """ + Return the elements of an array that satisfy some condition. + + This is equivalent to ``np.compress(ravel(condition), ravel(arr))``. If + `condition` is boolean ``np.extract`` is equivalent to ``arr[condition]``. + + Note that `place` does the exact opposite of `extract`. + + Parameters + ---------- + condition : array_like + An array whose nonzero or True entries indicate the elements of `arr` + to extract. + arr : array_like + Input array of the same size as `condition`. + + Returns + ------- + extract : ndarray + Rank 1 array of values from `arr` where `condition` is True. + + See Also + -------- + take, put, copyto, compress, place + + Examples + -------- + >>> import numpy as np + >>> arr = np.arange(12).reshape((3, 4)) + >>> arr + array([[ 0, 1, 2, 3], + [ 4, 5, 6, 7], + [ 8, 9, 10, 11]]) + >>> condition = np.mod(arr, 3)==0 + >>> condition + array([[ True, False, False, True], + [False, False, True, False], + [False, True, False, False]]) + >>> np.extract(condition, arr) + array([0, 3, 6, 9]) + + + If `condition` is boolean: + + >>> arr[condition] + array([0, 3, 6, 9]) + + """ + return _nx.take(ravel(arr), nonzero(ravel(condition))[0]) + + +def _place_dispatcher(arr, mask, vals): + return (arr, mask, vals) + + +@array_function_dispatch(_place_dispatcher) +def place(arr, mask, vals): + """ + Change elements of an array based on conditional and input values. + + Similar to ``np.copyto(arr, vals, where=mask)``, the difference is that + `place` uses the first N elements of `vals`, where N is the number of + True values in `mask`, while `copyto` uses the elements where `mask` + is True. + + Note that `extract` does the exact opposite of `place`. + + Parameters + ---------- + arr : ndarray + Array to put data into. + mask : array_like + Boolean mask array. Must have the same size as `a`. + vals : 1-D sequence + Values to put into `a`. Only the first N elements are used, where + N is the number of True values in `mask`. If `vals` is smaller + than N, it will be repeated, and if elements of `a` are to be masked, + this sequence must be non-empty. + + See Also + -------- + copyto, put, take, extract + + Examples + -------- + >>> import numpy as np + >>> arr = np.arange(6).reshape(2, 3) + >>> np.place(arr, arr>2, [44, 55]) + >>> arr + array([[ 0, 1, 2], + [44, 55, 44]]) + + """ + return _place(arr, mask, vals) + + +# See https://docs.scipy.org/doc/numpy/reference/c-api.generalized-ufuncs.html +_DIMENSION_NAME = r'\w+' +_CORE_DIMENSION_LIST = f'(?:{_DIMENSION_NAME}(?:,{_DIMENSION_NAME})*)?' +_ARGUMENT = fr'\({_CORE_DIMENSION_LIST}\)' +_ARGUMENT_LIST = f'{_ARGUMENT}(?:,{_ARGUMENT})*' +_SIGNATURE = f'^{_ARGUMENT_LIST}->{_ARGUMENT_LIST}$' + + +def _parse_gufunc_signature(signature): + """ + Parse string signatures for a generalized universal function. + + Arguments + --------- + signature : string + Generalized universal function signature, e.g., ``(m,n),(n,p)->(m,p)`` + for ``np.matmul``. + + Returns + ------- + Tuple of input and output core dimensions parsed from the signature, each + of the form List[Tuple[str, ...]]. + """ + signature = re.sub(r'\s+', '', signature) + + if not re.match(_SIGNATURE, signature): + raise ValueError( + f'not a valid gufunc signature: {signature}') + return tuple([tuple(re.findall(_DIMENSION_NAME, arg)) + for arg in re.findall(_ARGUMENT, arg_list)] + for arg_list in signature.split('->')) + + +def _update_dim_sizes(dim_sizes, arg, core_dims): + """ + Incrementally check and update core dimension sizes for a single argument. + + Arguments + --------- + dim_sizes : Dict[str, int] + Sizes of existing core dimensions. Will be updated in-place. + arg : ndarray + Argument to examine. + core_dims : Tuple[str, ...] + Core dimensions for this argument. + """ + if not core_dims: + return + + num_core_dims = len(core_dims) + if arg.ndim < num_core_dims: + raise ValueError( + '%d-dimensional argument does not have enough ' + 'dimensions for all core dimensions %r' + % (arg.ndim, core_dims)) + + core_shape = arg.shape[-num_core_dims:] + for dim, size in zip(core_dims, core_shape): + if dim in dim_sizes: + if size != dim_sizes[dim]: + raise ValueError( + 'inconsistent size for core dimension %r: %r vs %r' + % (dim, size, dim_sizes[dim])) + else: + dim_sizes[dim] = size + + +def _parse_input_dimensions(args, input_core_dims): + """ + Parse broadcast and core dimensions for vectorize with a signature. + + Arguments + --------- + args : Tuple[ndarray, ...] + Tuple of input arguments to examine. + input_core_dims : List[Tuple[str, ...]] + List of core dimensions corresponding to each input. + + Returns + ------- + broadcast_shape : Tuple[int, ...] + Common shape to broadcast all non-core dimensions to. + dim_sizes : Dict[str, int] + Common sizes for named core dimensions. + """ + broadcast_args = [] + dim_sizes = {} + for arg, core_dims in zip(args, input_core_dims): + _update_dim_sizes(dim_sizes, arg, core_dims) + ndim = arg.ndim - len(core_dims) + dummy_array = np.lib.stride_tricks.as_strided(0, arg.shape[:ndim]) + broadcast_args.append(dummy_array) + broadcast_shape = np.lib._stride_tricks_impl._broadcast_shape( + *broadcast_args + ) + return broadcast_shape, dim_sizes + + +def _calculate_shapes(broadcast_shape, dim_sizes, list_of_core_dims): + """Helper for calculating broadcast shapes with core dimensions.""" + return [broadcast_shape + tuple(dim_sizes[dim] for dim in core_dims) + for core_dims in list_of_core_dims] + + +def _create_arrays(broadcast_shape, dim_sizes, list_of_core_dims, dtypes, + results=None): + """Helper for creating output arrays in vectorize.""" + shapes = _calculate_shapes(broadcast_shape, dim_sizes, list_of_core_dims) + if dtypes is None: + dtypes = [None] * len(shapes) + if results is None: + arrays = tuple(np.empty(shape=shape, dtype=dtype) + for shape, dtype in zip(shapes, dtypes)) + else: + arrays = tuple(np.empty_like(result, shape=shape, dtype=dtype) + for result, shape, dtype + in zip(results, shapes, dtypes)) + return arrays + + +def _get_vectorize_dtype(dtype): + if dtype.char in "SU": + return dtype.char + return dtype + + +@set_module('numpy') +class vectorize: + """ + vectorize(pyfunc=np._NoValue, otypes=None, doc=None, excluded=None, + cache=False, signature=None) + + Returns an object that acts like pyfunc, but takes arrays as input. + + Define a vectorized function which takes a nested sequence of objects or + numpy arrays as inputs and returns a single numpy array or a tuple of numpy + arrays. The vectorized function evaluates `pyfunc` over successive tuples + of the input arrays like the python map function, except it uses the + broadcasting rules of numpy. + + The data type of the output of `vectorized` is determined by calling + the function with the first element of the input. This can be avoided + by specifying the `otypes` argument. + + Parameters + ---------- + pyfunc : callable, optional + A python function or method. + Can be omitted to produce a decorator with keyword arguments. + otypes : str or list of dtypes, optional + The output data type. It must be specified as either a string of + typecode characters or a list of data type specifiers. There should + be one data type specifier for each output. + doc : str, optional + The docstring for the function. If None, the docstring will be the + ``pyfunc.__doc__``. + excluded : set, optional + Set of strings or integers representing the positional or keyword + arguments for which the function will not be vectorized. These will be + passed directly to `pyfunc` unmodified. + + cache : bool, optional + If neither `otypes` nor `signature` are provided, and `cache` is ``True``, then + cache the number of outputs. + + signature : string, optional + Generalized universal function signature, e.g., ``(m,n),(n)->(m)`` for + vectorized matrix-vector multiplication. If provided, ``pyfunc`` will + be called with (and expected to return) arrays with shapes given by the + size of corresponding core dimensions. By default, ``pyfunc`` is + assumed to take scalars as input and output. + + Returns + ------- + out : callable + A vectorized function if ``pyfunc`` was provided, + a decorator otherwise. + + See Also + -------- + frompyfunc : Takes an arbitrary Python function and returns a ufunc + + Notes + ----- + The `vectorize` function is provided primarily for convenience, not for + performance. The implementation is essentially a for loop. + + If neither `otypes` nor `signature` are specified, then a call to the function with + the first argument will be used to determine the number of outputs. The results of + this call will be cached if `cache` is `True` to prevent calling the function + twice. However, to implement the cache, the original function must be wrapped + which will slow down subsequent calls, so only do this if your function is + expensive. + + The new keyword argument interface and `excluded` argument support + further degrades performance. + + References + ---------- + .. [1] :doc:`/reference/c-api/generalized-ufuncs` + + Examples + -------- + >>> import numpy as np + >>> def myfunc(a, b): + ... "Return a-b if a>b, otherwise return a+b" + ... if a > b: + ... return a - b + ... else: + ... return a + b + + >>> vfunc = np.vectorize(myfunc) + >>> vfunc([1, 2, 3, 4], 2) + array([3, 4, 1, 2]) + + The docstring is taken from the input function to `vectorize` unless it + is specified: + + >>> vfunc.__doc__ + 'Return a-b if a>b, otherwise return a+b' + >>> vfunc = np.vectorize(myfunc, doc='Vectorized `myfunc`') + >>> vfunc.__doc__ + 'Vectorized `myfunc`' + + The output type is determined by evaluating the first element of the input, + unless it is specified: + + >>> out = vfunc([1, 2, 3, 4], 2) + >>> type(out[0]) + + >>> vfunc = np.vectorize(myfunc, otypes=[float]) + >>> out = vfunc([1, 2, 3, 4], 2) + >>> type(out[0]) + + + The `excluded` argument can be used to prevent vectorizing over certain + arguments. This can be useful for array-like arguments of a fixed length + such as the coefficients for a polynomial as in `polyval`: + + >>> def mypolyval(p, x): + ... _p = list(p) + ... res = _p.pop(0) + ... while _p: + ... res = res*x + _p.pop(0) + ... return res + + Here, we exclude the zeroth argument from vectorization whether it is + passed by position or keyword. + + >>> vpolyval = np.vectorize(mypolyval, excluded={0, 'p'}) + >>> vpolyval([1, 2, 3], x=[0, 1]) + array([3, 6]) + >>> vpolyval(p=[1, 2, 3], x=[0, 1]) + array([3, 6]) + + The `signature` argument allows for vectorizing functions that act on + non-scalar arrays of fixed length. For example, you can use it for a + vectorized calculation of Pearson correlation coefficient and its p-value: + + >>> import scipy.stats + >>> pearsonr = np.vectorize(scipy.stats.pearsonr, + ... signature='(n),(n)->(),()') + >>> pearsonr([[0, 1, 2, 3]], [[1, 2, 3, 4], [4, 3, 2, 1]]) + (array([ 1., -1.]), array([ 0., 0.])) + + Or for a vectorized convolution: + + >>> convolve = np.vectorize(np.convolve, signature='(n),(m)->(k)') + >>> convolve(np.eye(4), [1, 2, 1]) + array([[1., 2., 1., 0., 0., 0.], + [0., 1., 2., 1., 0., 0.], + [0., 0., 1., 2., 1., 0.], + [0., 0., 0., 1., 2., 1.]]) + + Decorator syntax is supported. The decorator can be called as + a function to provide keyword arguments: + + >>> @np.vectorize + ... def identity(x): + ... return x + ... + >>> identity([0, 1, 2]) + array([0, 1, 2]) + >>> @np.vectorize(otypes=[float]) + ... def as_float(x): + ... return x + ... + >>> as_float([0, 1, 2]) + array([0., 1., 2.]) + """ + def __init__(self, pyfunc=np._NoValue, otypes=None, doc=None, + excluded=None, cache=False, signature=None): + + if (pyfunc != np._NoValue) and (not callable(pyfunc)): + # Splitting the error message to keep + # the length below 79 characters. + part1 = "When used as a decorator, " + part2 = "only accepts keyword arguments." + raise TypeError(part1 + part2) + + self.pyfunc = pyfunc + self.cache = cache + self.signature = signature + if pyfunc != np._NoValue and hasattr(pyfunc, '__name__'): + self.__name__ = pyfunc.__name__ + + self._ufunc = {} # Caching to improve default performance + self._doc = None + self.__doc__ = doc + if doc is None and hasattr(pyfunc, '__doc__'): + self.__doc__ = pyfunc.__doc__ + else: + self._doc = doc + + if isinstance(otypes, str): + for char in otypes: + if char not in typecodes['All']: + raise ValueError(f"Invalid otype specified: {char}") + elif iterable(otypes): + otypes = [_get_vectorize_dtype(_nx.dtype(x)) for x in otypes] + elif otypes is not None: + raise ValueError("Invalid otype specification") + self.otypes = otypes + + # Excluded variable support + if excluded is None: + excluded = set() + self.excluded = set(excluded) + + if signature is not None: + self._in_and_out_core_dims = _parse_gufunc_signature(signature) + else: + self._in_and_out_core_dims = None + + def _init_stage_2(self, pyfunc, *args, **kwargs): + self.__name__ = pyfunc.__name__ + self.pyfunc = pyfunc + if self._doc is None: + self.__doc__ = pyfunc.__doc__ + else: + self.__doc__ = self._doc + + def _call_as_normal(self, *args, **kwargs): + """ + Return arrays with the results of `pyfunc` broadcast (vectorized) over + `args` and `kwargs` not in `excluded`. + """ + excluded = self.excluded + if not kwargs and not excluded: + func = self.pyfunc + vargs = args + else: + # The wrapper accepts only positional arguments: we use `names` and + # `inds` to mutate `the_args` and `kwargs` to pass to the original + # function. + nargs = len(args) + + names = [_n for _n in kwargs if _n not in excluded] + inds = [_i for _i in range(nargs) if _i not in excluded] + the_args = list(args) + + def func(*vargs): + for _n, _i in enumerate(inds): + the_args[_i] = vargs[_n] + kwargs.update(zip(names, vargs[len(inds):])) + return self.pyfunc(*the_args, **kwargs) + + vargs = [args[_i] for _i in inds] + vargs.extend([kwargs[_n] for _n in names]) + + return self._vectorize_call(func=func, args=vargs) + + def __call__(self, *args, **kwargs): + if self.pyfunc is np._NoValue: + self._init_stage_2(*args, **kwargs) + return self + + return self._call_as_normal(*args, **kwargs) + + def _get_ufunc_and_otypes(self, func, args): + """Return (ufunc, otypes).""" + # frompyfunc will fail if args is empty + if not args: + raise ValueError('args can not be empty') + + if self.otypes is not None: + otypes = self.otypes + + # self._ufunc is a dictionary whose keys are the number of + # arguments (i.e. len(args)) and whose values are ufuncs created + # by frompyfunc. len(args) can be different for different calls if + # self.pyfunc has parameters with default values. We only use the + # cache when func is self.pyfunc, which occurs when the call uses + # only positional arguments and no arguments are excluded. + + nin = len(args) + nout = len(self.otypes) + if func is not self.pyfunc or nin not in self._ufunc: + ufunc = frompyfunc(func, nin, nout) + else: + ufunc = None # We'll get it from self._ufunc + if func is self.pyfunc: + ufunc = self._ufunc.setdefault(nin, ufunc) + else: + # Get number of outputs and output types by calling the function on + # the first entries of args. We also cache the result to prevent + # the subsequent call when the ufunc is evaluated. + # Assumes that ufunc first evaluates the 0th elements in the input + # arrays (the input values are not checked to ensure this) + args = [asarray(a) for a in args] + if builtins.any(arg.size == 0 for arg in args): + raise ValueError('cannot call `vectorize` on size 0 inputs ' + 'unless `otypes` is set') + + inputs = [arg.flat[0] for arg in args] + outputs = func(*inputs) + + # Performance note: profiling indicates that -- for simple + # functions at least -- this wrapping can almost double the + # execution time. + # Hence we make it optional. + if self.cache: + _cache = [outputs] + + def _func(*vargs): + if _cache: + return _cache.pop() + else: + return func(*vargs) + else: + _func = func + + if isinstance(outputs, tuple): + nout = len(outputs) + else: + nout = 1 + outputs = (outputs,) + + otypes = ''.join([asarray(outputs[_k]).dtype.char + for _k in range(nout)]) + + # Performance note: profiling indicates that creating the ufunc is + # not a significant cost compared with wrapping so it seems not + # worth trying to cache this. + ufunc = frompyfunc(_func, len(args), nout) + + return ufunc, otypes + + def _vectorize_call(self, func, args): + """Vectorized call to `func` over positional `args`.""" + if self.signature is not None: + res = self._vectorize_call_with_signature(func, args) + elif not args: + res = func() + else: + ufunc, otypes = self._get_ufunc_and_otypes(func=func, args=args) + # gh-29196: `dtype=object` should eventually be removed + args = [asanyarray(a, dtype=object) for a in args] + outputs = ufunc(*args, out=...) + + if ufunc.nout == 1: + res = asanyarray(outputs, dtype=otypes[0]) + else: + res = tuple(asanyarray(x, dtype=t) + for x, t in zip(outputs, otypes)) + return res + + def _vectorize_call_with_signature(self, func, args): + """Vectorized call over positional arguments with a signature.""" + input_core_dims, output_core_dims = self._in_and_out_core_dims + + if len(args) != len(input_core_dims): + raise TypeError('wrong number of positional arguments: ' + 'expected %r, got %r' + % (len(input_core_dims), len(args))) + args = tuple(asanyarray(arg) for arg in args) + + broadcast_shape, dim_sizes = _parse_input_dimensions( + args, input_core_dims) + input_shapes = _calculate_shapes(broadcast_shape, dim_sizes, + input_core_dims) + args = [np.broadcast_to(arg, shape, subok=True) + for arg, shape in zip(args, input_shapes)] + + outputs = None + otypes = self.otypes + nout = len(output_core_dims) + + for index in np.ndindex(*broadcast_shape): + results = func(*(arg[index] for arg in args)) + + n_results = len(results) if isinstance(results, tuple) else 1 + + if nout != n_results: + raise ValueError( + 'wrong number of outputs from pyfunc: expected %r, got %r' + % (nout, n_results)) + + if nout == 1: + results = (results,) + + if outputs is None: + for result, core_dims in zip(results, output_core_dims): + _update_dim_sizes(dim_sizes, result, core_dims) + + outputs = _create_arrays(broadcast_shape, dim_sizes, + output_core_dims, otypes, results) + + for output, result in zip(outputs, results): + output[index] = result + + if outputs is None: + # did not call the function even once + if otypes is None: + raise ValueError('cannot call `vectorize` on size 0 inputs ' + 'unless `otypes` is set') + if builtins.any(dim not in dim_sizes + for dims in output_core_dims + for dim in dims): + raise ValueError('cannot call `vectorize` with a signature ' + 'including new output dimensions on size 0 ' + 'inputs') + outputs = _create_arrays(broadcast_shape, dim_sizes, + output_core_dims, otypes) + + return outputs[0] if nout == 1 else outputs + + +def _cov_dispatcher(m, y=None, rowvar=None, bias=None, ddof=None, + fweights=None, aweights=None, *, dtype=None): + return (m, y, fweights, aweights) + + +@array_function_dispatch(_cov_dispatcher) +def cov(m, y=None, rowvar=True, bias=False, ddof=None, fweights=None, + aweights=None, *, dtype=None): + """ + Estimate a covariance matrix, given data and weights. + + Covariance indicates the level to which two variables vary together. + If we examine N-dimensional samples, :math:`X = [x_1, x_2, ..., x_N]^T`, + then the covariance matrix element :math:`C_{ij}` is the covariance of + :math:`x_i` and :math:`x_j`. The element :math:`C_{ii}` is the variance + of :math:`x_i`. + + See the notes for an outline of the algorithm. + + Parameters + ---------- + m : array_like + A 1-D or 2-D array containing multiple variables and observations. + Each row of `m` represents a variable, and each column a single + observation of all those variables. Also see `rowvar` below. + y : array_like, optional + An additional set of variables and observations. `y` has the same form + as that of `m`. + rowvar : bool, optional + If `rowvar` is True (default), then each row represents a + variable, with observations in the columns. Otherwise, the relationship + is transposed: each column represents a variable, while the rows + contain observations. + bias : bool, optional + Default normalization (False) is by ``(N - 1)``, where ``N`` is the + number of observations given (unbiased estimate). If `bias` is True, + then normalization is by ``N``. These values can be overridden by using + the keyword ``ddof`` in numpy versions >= 1.5. + ddof : int, optional + If not ``None`` the default value implied by `bias` is overridden. + Note that ``ddof=1`` will return the unbiased estimate, even if both + `fweights` and `aweights` are specified, and ``ddof=0`` will return + the simple average. See the notes for the details. The default value + is ``None``. + fweights : array_like, int, optional + 1-D array of integer frequency weights; the number of times each + observation vector should be repeated. + aweights : array_like, optional + 1-D array of observation vector weights. These relative weights are + typically large for observations considered "important" and smaller for + observations considered less "important". If ``ddof=0`` the array of + weights can be used to assign probabilities to observation vectors. + dtype : data-type, optional + Data-type of the result. By default, the return data-type will have + at least `numpy.float64` precision. + + .. versionadded:: 1.20 + + Returns + ------- + out : ndarray + The covariance matrix of the variables. + + See Also + -------- + corrcoef : Normalized covariance matrix + + Notes + ----- + Assume that the observations are in the columns of the observation + array `m` and let ``f = fweights`` and ``a = aweights`` for brevity. The + steps to compute the weighted covariance are as follows:: + + >>> m = np.arange(10, dtype=np.float64) + >>> f = np.arange(10) * 2 + >>> a = np.arange(10) ** 2. + >>> ddof = 1 + >>> w = f * a + >>> v1 = np.sum(w) + >>> v2 = np.sum(w * a) + >>> m -= np.sum(m * w, axis=None, keepdims=True) / v1 + >>> cov = np.dot(m * w, m.T) * v1 / (v1**2 - ddof * v2) + + Note that when ``a == 1``, the normalization factor + ``v1 / (v1**2 - ddof * v2)`` goes over to ``1 / (np.sum(f) - ddof)`` + as it should. + + Examples + -------- + >>> import numpy as np + + Consider two variables, :math:`x_0` and :math:`x_1`, which + correlate perfectly, but in opposite directions: + + >>> x = np.array([[0, 2], [1, 1], [2, 0]]).T + >>> x + array([[0, 1, 2], + [2, 1, 0]]) + + Note how :math:`x_0` increases while :math:`x_1` decreases. The covariance + matrix shows this clearly: + + >>> np.cov(x) + array([[ 1., -1.], + [-1., 1.]]) + + Note that element :math:`C_{0,1}`, which shows the correlation between + :math:`x_0` and :math:`x_1`, is negative. + + Further, note how `x` and `y` are combined: + + >>> x = [-2.1, -1, 4.3] + >>> y = [3, 1.1, 0.12] + >>> X = np.stack((x, y), axis=0) + >>> np.cov(X) + array([[11.71 , -4.286 ], # may vary + [-4.286 , 2.144133]]) + >>> np.cov(x, y) + array([[11.71 , -4.286 ], # may vary + [-4.286 , 2.144133]]) + >>> np.cov(x) + array(11.71) + + """ + # Check inputs + if ddof is not None and ddof != int(ddof): + raise ValueError( + "ddof must be integer") + + # Handles complex arrays too + m = np.asarray(m) + if m.ndim > 2: + raise ValueError("m has more than 2 dimensions") + + if y is not None: + y = np.asarray(y) + if y.ndim > 2: + raise ValueError("y has more than 2 dimensions") + + if dtype is None: + if y is None: + dtype = np.result_type(m, np.float64) + else: + dtype = np.result_type(m, y, np.float64) + + X = array(m, ndmin=2, dtype=dtype) + if not rowvar and m.ndim != 1: + X = X.T + if X.shape[0] == 0: + return np.array([]).reshape(0, 0) + if y is not None: + y = array(y, copy=None, ndmin=2, dtype=dtype) + if not rowvar and y.shape[0] != 1: + y = y.T + X = np.concatenate((X, y), axis=0) + + if ddof is None: + if bias == 0: + ddof = 1 + else: + ddof = 0 + + # Get the product of frequencies and weights + w = None + if fweights is not None: + fweights = np.asarray(fweights, dtype=float) + if not np.all(fweights == np.around(fweights)): + raise TypeError( + "fweights must be integer") + if fweights.ndim > 1: + raise RuntimeError( + "cannot handle multidimensional fweights") + if fweights.shape[0] != X.shape[1]: + raise RuntimeError( + "incompatible numbers of samples and fweights") + if any(fweights < 0): + raise ValueError( + "fweights cannot be negative") + w = fweights + if aweights is not None: + aweights = np.asarray(aweights, dtype=float) + if aweights.ndim > 1: + raise RuntimeError( + "cannot handle multidimensional aweights") + if aweights.shape[0] != X.shape[1]: + raise RuntimeError( + "incompatible numbers of samples and aweights") + if any(aweights < 0): + raise ValueError( + "aweights cannot be negative") + if w is None: + w = aweights + else: + w *= aweights + + avg, w_sum = average(X, axis=1, weights=w, returned=True) + w_sum = w_sum[0] + + # Determine the normalization + if w is None: + fact = X.shape[1] - ddof + elif ddof == 0: + fact = w_sum + elif aweights is None: + fact = w_sum - ddof + else: + fact = w_sum - ddof * sum(w * aweights) / w_sum + + if fact <= 0: + warnings.warn("Degrees of freedom <= 0 for slice", + RuntimeWarning, stacklevel=2) + fact = 0.0 + + X -= avg[:, None] + if w is None: + X_T = X.T + else: + X_T = (X * w).T + c = dot(X, X_T.conj()) + c *= np.true_divide(1, fact) + return c.squeeze() + + +def _corrcoef_dispatcher(x, y=None, rowvar=None, *, + dtype=None): + return (x, y) + + +@array_function_dispatch(_corrcoef_dispatcher) +def corrcoef(x, y=None, rowvar=True, *, + dtype=None): + """ + Return Pearson product-moment correlation coefficients. + + Please refer to the documentation for `cov` for more detail. The + relationship between the correlation coefficient matrix, `R`, and the + covariance matrix, `C`, is + + .. math:: R_{ij} = \\frac{ C_{ij} } { \\sqrt{ C_{ii} C_{jj} } } + + The values of `R` are between -1 and 1, inclusive. + + Parameters + ---------- + x : array_like + A 1-D or 2-D array containing multiple variables and observations. + Each row of `x` represents a variable, and each column a single + observation of all those variables. Also see `rowvar` below. + y : array_like, optional + An additional set of variables and observations. `y` has the same + shape as `x`. + rowvar : bool, optional + If `rowvar` is True (default), then each row represents a + variable, with observations in the columns. Otherwise, the relationship + is transposed: each column represents a variable, while the rows + contain observations. + + dtype : data-type, optional + Data-type of the result. By default, the return data-type will have + at least `numpy.float64` precision. + + .. versionadded:: 1.20 + + Returns + ------- + R : ndarray + The correlation coefficient matrix of the variables. + + See Also + -------- + cov : Covariance matrix + + Notes + ----- + Due to floating point rounding the resulting array may not be Hermitian, + the diagonal elements may not be 1, and the elements may not satisfy the + inequality abs(a) <= 1. The real and imaginary parts are clipped to the + interval [-1, 1] in an attempt to improve on that situation but is not + much help in the complex case. + + Examples + -------- + >>> import numpy as np + + In this example we generate two random arrays, ``xarr`` and ``yarr``, and + compute the row-wise and column-wise Pearson correlation coefficients, + ``R``. Since ``rowvar`` is true by default, we first find the row-wise + Pearson correlation coefficients between the variables of ``xarr``. + + >>> import numpy as np + >>> rng = np.random.default_rng(seed=42) + >>> xarr = rng.random((3, 3)) + >>> xarr + array([[0.77395605, 0.43887844, 0.85859792], + [0.69736803, 0.09417735, 0.97562235], + [0.7611397 , 0.78606431, 0.12811363]]) + >>> R1 = np.corrcoef(xarr) + >>> R1 + array([[ 1. , 0.99256089, -0.68080986], + [ 0.99256089, 1. , -0.76492172], + [-0.68080986, -0.76492172, 1. ]]) + + If we add another set of variables and observations ``yarr``, we can + compute the row-wise Pearson correlation coefficients between the + variables in ``xarr`` and ``yarr``. + + >>> yarr = rng.random((3, 3)) + >>> yarr + array([[0.45038594, 0.37079802, 0.92676499], + [0.64386512, 0.82276161, 0.4434142 ], + [0.22723872, 0.55458479, 0.06381726]]) + >>> R2 = np.corrcoef(xarr, yarr) + >>> R2 + array([[ 1. , 0.99256089, -0.68080986, 0.75008178, -0.934284 , + -0.99004057], + [ 0.99256089, 1. , -0.76492172, 0.82502011, -0.97074098, + -0.99981569], + [-0.68080986, -0.76492172, 1. , -0.99507202, 0.89721355, + 0.77714685], + [ 0.75008178, 0.82502011, -0.99507202, 1. , -0.93657855, + -0.83571711], + [-0.934284 , -0.97074098, 0.89721355, -0.93657855, 1. , + 0.97517215], + [-0.99004057, -0.99981569, 0.77714685, -0.83571711, 0.97517215, + 1. ]]) + + Finally if we use the option ``rowvar=False``, the columns are now + being treated as the variables and we will find the column-wise Pearson + correlation coefficients between variables in ``xarr`` and ``yarr``. + + >>> R3 = np.corrcoef(xarr, yarr, rowvar=False) + >>> R3 + array([[ 1. , 0.77598074, -0.47458546, -0.75078643, -0.9665554 , + 0.22423734], + [ 0.77598074, 1. , -0.92346708, -0.99923895, -0.58826587, + -0.44069024], + [-0.47458546, -0.92346708, 1. , 0.93773029, 0.23297648, + 0.75137473], + [-0.75078643, -0.99923895, 0.93773029, 1. , 0.55627469, + 0.47536961], + [-0.9665554 , -0.58826587, 0.23297648, 0.55627469, 1. , + -0.46666491], + [ 0.22423734, -0.44069024, 0.75137473, 0.47536961, -0.46666491, + 1. ]]) + + """ + c = cov(x, y, rowvar, dtype=dtype) + try: + d = diag(c) + except ValueError: + # scalar covariance + # nan if incorrect value (nan, inf, 0), 1 otherwise + return c / c + stddev = sqrt(d.real) + c /= stddev[:, None] + c /= stddev[None, :] + + # Clip real and imaginary parts to [-1, 1]. This does not guarantee + # abs(a[i,j]) <= 1 for complex arrays, but is the best we can do without + # excessive work. + np.clip(c.real, -1, 1, out=c.real) + if np.iscomplexobj(c): + np.clip(c.imag, -1, 1, out=c.imag) + + return c + + +@set_module('numpy') +def blackman(M): + """ + Return the Blackman window. + + The Blackman window is a taper formed by using the first three + terms of a summation of cosines. It was designed to have close to the + minimal leakage possible. It is close to optimal, only slightly worse + than a Kaiser window. + + Parameters + ---------- + M : int + Number of points in the output window. If zero or less, an empty + array is returned. + + Returns + ------- + out : ndarray + The window, with the maximum value normalized to one (the value one + appears only if the number of samples is odd). + + See Also + -------- + bartlett, hamming, hanning, kaiser + + Notes + ----- + The Blackman window is defined as + + .. math:: w(n) = 0.42 - 0.5 \\cos(2\\pi n/M) + 0.08 \\cos(4\\pi n/M) + + Most references to the Blackman window come from the signal processing + literature, where it is used as one of many windowing functions for + smoothing values. It is also known as an apodization (which means + "removing the foot", i.e. smoothing discontinuities at the beginning + and end of the sampled signal) or tapering function. It is known as a + "near optimal" tapering function, almost as good (by some measures) + as the kaiser window. + + References + ---------- + Blackman, R.B. and Tukey, J.W., (1958) The measurement of power spectra, + Dover Publications, New York. + + Oppenheim, A.V., and R.W. Schafer. Discrete-Time Signal Processing. + Upper Saddle River, NJ: Prentice-Hall, 1999, pp. 468-471. + + Examples + -------- + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> np.blackman(12) + array([-1.38777878e-17, 3.26064346e-02, 1.59903635e-01, # may vary + 4.14397981e-01, 7.36045180e-01, 9.67046769e-01, + 9.67046769e-01, 7.36045180e-01, 4.14397981e-01, + 1.59903635e-01, 3.26064346e-02, -1.38777878e-17]) + + Plot the window and the frequency response. + + .. plot:: + :include-source: + + import matplotlib.pyplot as plt + from numpy.fft import fft, fftshift + window = np.blackman(51) + plt.plot(window) + plt.title("Blackman window") + plt.ylabel("Amplitude") + plt.xlabel("Sample") + plt.show() # doctest: +SKIP + + plt.figure() + A = fft(window, 2048) / 25.5 + mag = np.abs(fftshift(A)) + freq = np.linspace(-0.5, 0.5, len(A)) + with np.errstate(divide='ignore', invalid='ignore'): + response = 20 * np.log10(mag) + response = np.clip(response, -100, 100) + plt.plot(freq, response) + plt.title("Frequency response of Blackman window") + plt.ylabel("Magnitude [dB]") + plt.xlabel("Normalized frequency [cycles per sample]") + plt.axis('tight') + plt.show() + + """ + # Ensures at least float64 via 0.0. M should be an integer, but conversion + # to double is safe for a range. + values = np.array([0.0, M]) + M = values[1] + + if M < 1: + return array([], dtype=values.dtype) + if M == 1: + return ones(1, dtype=values.dtype) + n = arange(1 - M, M, 2) + return 0.42 + 0.5 * cos(pi * n / (M - 1)) + 0.08 * cos(2.0 * pi * n / (M - 1)) + + +@set_module('numpy') +def bartlett(M): + """ + Return the Bartlett window. + + The Bartlett window is very similar to a triangular window, except + that the end points are at zero. It is often used in signal + processing for tapering a signal, without generating too much + ripple in the frequency domain. + + Parameters + ---------- + M : int + Number of points in the output window. If zero or less, an + empty array is returned. + + Returns + ------- + out : array + The triangular window, with the maximum value normalized to one + (the value one appears only if the number of samples is odd), with + the first and last samples equal to zero. + + See Also + -------- + blackman, hamming, hanning, kaiser + + Notes + ----- + The Bartlett window is defined as + + .. math:: w(n) = \\frac{2}{M-1} \\left( + \\frac{M-1}{2} - \\left|n - \\frac{M-1}{2}\\right| + \\right) + + Most references to the Bartlett window come from the signal processing + literature, where it is used as one of many windowing functions for + smoothing values. Note that convolution with this window produces linear + interpolation. It is also known as an apodization (which means "removing + the foot", i.e. smoothing discontinuities at the beginning and end of the + sampled signal) or tapering function. The Fourier transform of the + Bartlett window is the product of two sinc functions. Note the excellent + discussion in Kanasewich [2]_. + + References + ---------- + .. [1] M.S. Bartlett, "Periodogram Analysis and Continuous Spectra", + Biometrika 37, 1-16, 1950. + .. [2] E.R. Kanasewich, "Time Sequence Analysis in Geophysics", + The University of Alberta Press, 1975, pp. 109-110. + .. [3] A.V. Oppenheim and R.W. Schafer, "Discrete-Time Signal + Processing", Prentice-Hall, 1999, pp. 468-471. + .. [4] Wikipedia, "Window function", + https://en.wikipedia.org/wiki/Window_function + .. [5] W.H. Press, B.P. Flannery, S.A. Teukolsky, and W.T. Vetterling, + "Numerical Recipes", Cambridge University Press, 1986, page 429. + + Examples + -------- + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> np.bartlett(12) + array([ 0. , 0.18181818, 0.36363636, 0.54545455, 0.72727273, # may vary + 0.90909091, 0.90909091, 0.72727273, 0.54545455, 0.36363636, + 0.18181818, 0. ]) + + Plot the window and its frequency response (requires SciPy and matplotlib). + + .. plot:: + :include-source: + + import matplotlib.pyplot as plt + from numpy.fft import fft, fftshift + window = np.bartlett(51) + plt.plot(window) + plt.title("Bartlett window") + plt.ylabel("Amplitude") + plt.xlabel("Sample") + plt.show() + plt.figure() + A = fft(window, 2048) / 25.5 + mag = np.abs(fftshift(A)) + freq = np.linspace(-0.5, 0.5, len(A)) + with np.errstate(divide='ignore', invalid='ignore'): + response = 20 * np.log10(mag) + response = np.clip(response, -100, 100) + plt.plot(freq, response) + plt.title("Frequency response of Bartlett window") + plt.ylabel("Magnitude [dB]") + plt.xlabel("Normalized frequency [cycles per sample]") + plt.axis('tight') + plt.show() + + """ + # Ensures at least float64 via 0.0. M should be an integer, but conversion + # to double is safe for a range. + values = np.array([0.0, M]) + M = values[1] + + if M < 1: + return array([], dtype=values.dtype) + if M == 1: + return ones(1, dtype=values.dtype) + n = arange(1 - M, M, 2) + return where(less_equal(n, 0), 1 + n / (M - 1), 1 - n / (M - 1)) + + +@set_module('numpy') +def hanning(M): + """ + Return the Hanning window. + + The Hanning window is a taper formed by using a weighted cosine. + + Parameters + ---------- + M : int + Number of points in the output window. If zero or less, an + empty array is returned. + + Returns + ------- + out : ndarray, shape(M,) + The window, with the maximum value normalized to one (the value + one appears only if `M` is odd). + + See Also + -------- + bartlett, blackman, hamming, kaiser + + Notes + ----- + The Hanning window is defined as + + .. math:: w(n) = 0.5 - 0.5\\cos\\left(\\frac{2\\pi{n}}{M-1}\\right) + \\qquad 0 \\leq n \\leq M-1 + + The Hanning was named for Julius von Hann, an Austrian meteorologist. + It is also known as the Cosine Bell. Some authors prefer that it be + called a Hann window, to help avoid confusion with the very similar + Hamming window. + + Most references to the Hanning window come from the signal processing + literature, where it is used as one of many windowing functions for + smoothing values. It is also known as an apodization (which means + "removing the foot", i.e. smoothing discontinuities at the beginning + and end of the sampled signal) or tapering function. + + References + ---------- + .. [1] Blackman, R.B. and Tukey, J.W., (1958) The measurement of power + spectra, Dover Publications, New York. + .. [2] E.R. Kanasewich, "Time Sequence Analysis in Geophysics", + The University of Alberta Press, 1975, pp. 106-108. + .. [3] Wikipedia, "Window function", + https://en.wikipedia.org/wiki/Window_function + .. [4] W.H. Press, B.P. Flannery, S.A. Teukolsky, and W.T. Vetterling, + "Numerical Recipes", Cambridge University Press, 1986, page 425. + + Examples + -------- + >>> import numpy as np + >>> np.hanning(12) + array([0. , 0.07937323, 0.29229249, 0.57115742, 0.82743037, + 0.97974649, 0.97974649, 0.82743037, 0.57115742, 0.29229249, + 0.07937323, 0. ]) + + Plot the window and its frequency response. + + .. plot:: + :include-source: + + import matplotlib.pyplot as plt + from numpy.fft import fft, fftshift + window = np.hanning(51) + plt.plot(window) + plt.title("Hann window") + plt.ylabel("Amplitude") + plt.xlabel("Sample") + plt.show() + + plt.figure() + A = fft(window, 2048) / 25.5 + mag = np.abs(fftshift(A)) + freq = np.linspace(-0.5, 0.5, len(A)) + with np.errstate(divide='ignore', invalid='ignore'): + response = 20 * np.log10(mag) + response = np.clip(response, -100, 100) + plt.plot(freq, response) + plt.title("Frequency response of the Hann window") + plt.ylabel("Magnitude [dB]") + plt.xlabel("Normalized frequency [cycles per sample]") + plt.axis('tight') + plt.show() + + """ + # Ensures at least float64 via 0.0. M should be an integer, but conversion + # to double is safe for a range. + values = np.array([0.0, M]) + M = values[1] + + if M < 1: + return array([], dtype=values.dtype) + if M == 1: + return ones(1, dtype=values.dtype) + n = arange(1 - M, M, 2) + return 0.5 + 0.5 * cos(pi * n / (M - 1)) + + +@set_module('numpy') +def hamming(M): + """ + Return the Hamming window. + + The Hamming window is a taper formed by using a weighted cosine. + + Parameters + ---------- + M : int + Number of points in the output window. If zero or less, an + empty array is returned. + + Returns + ------- + out : ndarray + The window, with the maximum value normalized to one (the value + one appears only if the number of samples is odd). + + See Also + -------- + bartlett, blackman, hanning, kaiser + + Notes + ----- + The Hamming window is defined as + + .. math:: w(n) = 0.54 - 0.46\\cos\\left(\\frac{2\\pi{n}}{M-1}\\right) + \\qquad 0 \\leq n \\leq M-1 + + The Hamming was named for R. W. Hamming, an associate of J. W. Tukey + and is described in Blackman and Tukey. It was recommended for + smoothing the truncated autocovariance function in the time domain. + Most references to the Hamming window come from the signal processing + literature, where it is used as one of many windowing functions for + smoothing values. It is also known as an apodization (which means + "removing the foot", i.e. smoothing discontinuities at the beginning + and end of the sampled signal) or tapering function. + + References + ---------- + .. [1] Blackman, R.B. and Tukey, J.W., (1958) The measurement of power + spectra, Dover Publications, New York. + .. [2] E.R. Kanasewich, "Time Sequence Analysis in Geophysics", The + University of Alberta Press, 1975, pp. 109-110. + .. [3] Wikipedia, "Window function", + https://en.wikipedia.org/wiki/Window_function + .. [4] W.H. Press, B.P. Flannery, S.A. Teukolsky, and W.T. Vetterling, + "Numerical Recipes", Cambridge University Press, 1986, page 425. + + Examples + -------- + >>> import numpy as np + >>> np.hamming(12) + array([ 0.08 , 0.15302337, 0.34890909, 0.60546483, 0.84123594, # may vary + 0.98136677, 0.98136677, 0.84123594, 0.60546483, 0.34890909, + 0.15302337, 0.08 ]) + + Plot the window and the frequency response. + + .. plot:: + :include-source: + + import matplotlib.pyplot as plt + from numpy.fft import fft, fftshift + window = np.hamming(51) + plt.plot(window) + plt.title("Hamming window") + plt.ylabel("Amplitude") + plt.xlabel("Sample") + plt.show() + + plt.figure() + A = fft(window, 2048) / 25.5 + mag = np.abs(fftshift(A)) + freq = np.linspace(-0.5, 0.5, len(A)) + response = 20 * np.log10(mag) + response = np.clip(response, -100, 100) + plt.plot(freq, response) + plt.title("Frequency response of Hamming window") + plt.ylabel("Magnitude [dB]") + plt.xlabel("Normalized frequency [cycles per sample]") + plt.axis('tight') + plt.show() + + """ + # Ensures at least float64 via 0.0. M should be an integer, but conversion + # to double is safe for a range. + values = np.array([0.0, M]) + M = values[1] + + if M < 1: + return array([], dtype=values.dtype) + if M == 1: + return ones(1, dtype=values.dtype) + n = arange(1 - M, M, 2) + return 0.54 + 0.46 * cos(pi * n / (M - 1)) + + +## Code from cephes for i0 + +_i0A = [ + -4.41534164647933937950E-18, + 3.33079451882223809783E-17, + -2.43127984654795469359E-16, + 1.71539128555513303061E-15, + -1.16853328779934516808E-14, + 7.67618549860493561688E-14, + -4.85644678311192946090E-13, + 2.95505266312963983461E-12, + -1.72682629144155570723E-11, + 9.67580903537323691224E-11, + -5.18979560163526290666E-10, + 2.65982372468238665035E-9, + -1.30002500998624804212E-8, + 6.04699502254191894932E-8, + -2.67079385394061173391E-7, + 1.11738753912010371815E-6, + -4.41673835845875056359E-6, + 1.64484480707288970893E-5, + -5.75419501008210370398E-5, + 1.88502885095841655729E-4, + -5.76375574538582365885E-4, + 1.63947561694133579842E-3, + -4.32430999505057594430E-3, + 1.05464603945949983183E-2, + -2.37374148058994688156E-2, + 4.93052842396707084878E-2, + -9.49010970480476444210E-2, + 1.71620901522208775349E-1, + -3.04682672343198398683E-1, + 6.76795274409476084995E-1 + ] + +_i0B = [ + -7.23318048787475395456E-18, + -4.83050448594418207126E-18, + 4.46562142029675999901E-17, + 3.46122286769746109310E-17, + -2.82762398051658348494E-16, + -3.42548561967721913462E-16, + 1.77256013305652638360E-15, + 3.81168066935262242075E-15, + -9.55484669882830764870E-15, + -4.15056934728722208663E-14, + 1.54008621752140982691E-14, + 3.85277838274214270114E-13, + 7.18012445138366623367E-13, + -1.79417853150680611778E-12, + -1.32158118404477131188E-11, + -3.14991652796324136454E-11, + 1.18891471078464383424E-11, + 4.94060238822496958910E-10, + 3.39623202570838634515E-9, + 2.26666899049817806459E-8, + 2.04891858946906374183E-7, + 2.89137052083475648297E-6, + 6.88975834691682398426E-5, + 3.36911647825569408990E-3, + 8.04490411014108831608E-1 + ] + + +def _chbevl(x, vals): + b0 = vals[0] + b1 = 0.0 + + for i in range(1, len(vals)): + b2 = b1 + b1 = b0 + b0 = x * b1 - b2 + vals[i] + + return 0.5 * (b0 - b2) + + +def _i0_1(x): + return exp(x) * _chbevl(x / 2.0 - 2, _i0A) + + +def _i0_2(x): + return exp(x) * _chbevl(32.0 / x - 2.0, _i0B) / sqrt(x) + + +def _i0_dispatcher(x): + return (x,) + + +@array_function_dispatch(_i0_dispatcher) +def i0(x): + """ + Modified Bessel function of the first kind, order 0. + + Usually denoted :math:`I_0`. + + Parameters + ---------- + x : array_like of float + Argument of the Bessel function. + + Returns + ------- + out : ndarray, shape = x.shape, dtype = float + The modified Bessel function evaluated at each of the elements of `x`. + + See Also + -------- + scipy.special.i0, scipy.special.iv, scipy.special.ive + + Notes + ----- + The scipy implementation is recommended over this function: it is a + proper ufunc written in C, and more than an order of magnitude faster. + + We use the algorithm published by Clenshaw [1]_ and referenced by + Abramowitz and Stegun [2]_, for which the function domain is + partitioned into the two intervals [0,8] and (8,inf), and Chebyshev + polynomial expansions are employed in each interval. Relative error on + the domain [0,30] using IEEE arithmetic is documented [3]_ as having a + peak of 5.8e-16 with an rms of 1.4e-16 (n = 30000). + + References + ---------- + .. [1] C. W. Clenshaw, "Chebyshev series for mathematical functions", in + *National Physical Laboratory Mathematical Tables*, vol. 5, London: + Her Majesty's Stationery Office, 1962. + .. [2] M. Abramowitz and I. A. Stegun, *Handbook of Mathematical + Functions*, 10th printing, New York: Dover, 1964, pp. 379. + https://personal.math.ubc.ca/~cbm/aands/page_379.htm + .. [3] https://metacpan.org/pod/distribution/Math-Cephes/lib/Math/Cephes.pod#i0:-Modified-Bessel-function-of-order-zero + + Examples + -------- + >>> import numpy as np + >>> np.i0(0.) + array(1.0) + >>> np.i0([0, 1, 2, 3]) + array([1. , 1.26606588, 2.2795853 , 4.88079259]) + + """ + x = np.asanyarray(x) + if x.dtype.kind == 'c': + raise TypeError("i0 not supported for complex values") + if x.dtype.kind != 'f': + x = x.astype(float) + x = np.abs(x) + return piecewise(x, [x <= 8.0], [_i0_1, _i0_2]) + +## End of cephes code for i0 + + +@set_module('numpy') +def kaiser(M, beta): + """ + Return the Kaiser window. + + The Kaiser window is a taper formed by using a Bessel function. + + Parameters + ---------- + M : int + Number of points in the output window. If zero or less, an + empty array is returned. + beta : float + Shape parameter for window. + + Returns + ------- + out : array + The window, with the maximum value normalized to one (the value + one appears only if the number of samples is odd). + + See Also + -------- + bartlett, blackman, hamming, hanning + + Notes + ----- + The Kaiser window is defined as + + .. math:: w(n) = I_0\\left( \\beta \\sqrt{1-\\frac{4n^2}{(M-1)^2}} + \\right)/I_0(\\beta) + + with + + .. math:: \\quad -\\frac{M-1}{2} \\leq n \\leq \\frac{M-1}{2}, + + where :math:`I_0` is the modified zeroth-order Bessel function. + + The Kaiser was named for Jim Kaiser, who discovered a simple + approximation to the DPSS window based on Bessel functions. The Kaiser + window is a very good approximation to the Digital Prolate Spheroidal + Sequence, or Slepian window, which is the transform which maximizes the + energy in the main lobe of the window relative to total energy. + + The Kaiser can approximate many other windows by varying the beta + parameter. + + ==== ======================= + beta Window shape + ==== ======================= + 0 Rectangular + 5 Similar to a Hamming + 6 Similar to a Hanning + 8.6 Similar to a Blackman + ==== ======================= + + A beta value of 14 is probably a good starting point. Note that as beta + gets large, the window narrows, and so the number of samples needs to be + large enough to sample the increasingly narrow spike, otherwise NaNs will + get returned. + + Most references to the Kaiser window come from the signal processing + literature, where it is used as one of many windowing functions for + smoothing values. It is also known as an apodization (which means + "removing the foot", i.e. smoothing discontinuities at the beginning + and end of the sampled signal) or tapering function. + + References + ---------- + .. [1] J. F. Kaiser, "Digital Filters" - Ch 7 in "Systems analysis by + digital computer", Editors: F.F. Kuo and J.F. Kaiser, p 218-285. + John Wiley and Sons, New York, (1966). + .. [2] E.R. Kanasewich, "Time Sequence Analysis in Geophysics", The + University of Alberta Press, 1975, pp. 177-178. + .. [3] Wikipedia, "Window function", + https://en.wikipedia.org/wiki/Window_function + + Examples + -------- + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> np.kaiser(12, 14) + array([7.72686684e-06, 3.46009194e-03, 4.65200189e-02, # may vary + 2.29737120e-01, 5.99885316e-01, 9.45674898e-01, + 9.45674898e-01, 5.99885316e-01, 2.29737120e-01, + 4.65200189e-02, 3.46009194e-03, 7.72686684e-06]) + + + Plot the window and the frequency response. + + .. plot:: + :include-source: + + import matplotlib.pyplot as plt + from numpy.fft import fft, fftshift + window = np.kaiser(51, 14) + plt.plot(window) + plt.title("Kaiser window") + plt.ylabel("Amplitude") + plt.xlabel("Sample") + plt.show() + + plt.figure() + A = fft(window, 2048) / 25.5 + mag = np.abs(fftshift(A)) + freq = np.linspace(-0.5, 0.5, len(A)) + response = 20 * np.log10(mag) + response = np.clip(response, -100, 100) + plt.plot(freq, response) + plt.title("Frequency response of Kaiser window") + plt.ylabel("Magnitude [dB]") + plt.xlabel("Normalized frequency [cycles per sample]") + plt.axis('tight') + plt.show() + + """ + # Ensures at least float64 via 0.0. M should be an integer, but conversion + # to double is safe for a range. (Simplified result_type with 0.0 + # strongly typed. result-type is not/less order sensitive, but that mainly + # matters for integers anyway.) + values = np.array([0.0, M, beta]) + M = values[1] + beta = values[2] + + if M == 1: + return np.ones(1, dtype=values.dtype) + n = arange(0, M) + alpha = (M - 1) / 2.0 + return i0(beta * sqrt(1 - ((n - alpha) / alpha)**2.0)) / i0(beta) + + +def _sinc_dispatcher(x): + return (x,) + + +@array_function_dispatch(_sinc_dispatcher) +def sinc(x): + r""" + Return the normalized sinc function. + + The sinc function is equal to :math:`\sin(\pi x)/(\pi x)` for any argument + :math:`x\ne 0`. ``sinc(0)`` takes the limit value 1, making ``sinc`` not + only everywhere continuous but also infinitely differentiable. + + .. note:: + + Note the normalization factor of ``pi`` used in the definition. + This is the most commonly used definition in signal processing. + Use ``sinc(x / np.pi)`` to obtain the unnormalized sinc function + :math:`\sin(x)/x` that is more common in mathematics. + + Parameters + ---------- + x : ndarray + Array (possibly multi-dimensional) of values for which to calculate + ``sinc(x)``. + + Returns + ------- + out : ndarray + ``sinc(x)``, which has the same shape as the input. + + Notes + ----- + The name sinc is short for "sine cardinal" or "sinus cardinalis". + + The sinc function is used in various signal processing applications, + including in anti-aliasing, in the construction of a Lanczos resampling + filter, and in interpolation. + + For bandlimited interpolation of discrete-time signals, the ideal + interpolation kernel is proportional to the sinc function. + + References + ---------- + .. [1] Weisstein, Eric W. "Sinc Function." From MathWorld--A Wolfram Web + Resource. https://mathworld.wolfram.com/SincFunction.html + .. [2] Wikipedia, "Sinc function", + https://en.wikipedia.org/wiki/Sinc_function + + Examples + -------- + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> x = np.linspace(-4, 4, 41) + >>> np.sinc(x) + array([-3.89804309e-17, -4.92362781e-02, -8.40918587e-02, # may vary + -8.90384387e-02, -5.84680802e-02, 3.89804309e-17, + 6.68206631e-02, 1.16434881e-01, 1.26137788e-01, + 8.50444803e-02, -3.89804309e-17, -1.03943254e-01, + -1.89206682e-01, -2.16236208e-01, -1.55914881e-01, + 3.89804309e-17, 2.33872321e-01, 5.04551152e-01, + 7.56826729e-01, 9.35489284e-01, 1.00000000e+00, + 9.35489284e-01, 7.56826729e-01, 5.04551152e-01, + 2.33872321e-01, 3.89804309e-17, -1.55914881e-01, + -2.16236208e-01, -1.89206682e-01, -1.03943254e-01, + -3.89804309e-17, 8.50444803e-02, 1.26137788e-01, + 1.16434881e-01, 6.68206631e-02, 3.89804309e-17, + -5.84680802e-02, -8.90384387e-02, -8.40918587e-02, + -4.92362781e-02, -3.89804309e-17]) + + >>> plt.plot(x, np.sinc(x)) + [] + >>> plt.title("Sinc Function") + Text(0.5, 1.0, 'Sinc Function') + >>> plt.ylabel("Amplitude") + Text(0, 0.5, 'Amplitude') + >>> plt.xlabel("X") + Text(0.5, 0, 'X') + >>> plt.show() + + """ + x = np.asanyarray(x) + x = pi * x + # Hope that 1e-20 is sufficient for objects... + eps = np.finfo(x.dtype).eps if x.dtype.kind == "f" else 1e-20 + y = where(x, x, eps) + return sin(y) / y + + +def _ureduce(a, func, keepdims=False, **kwargs): + """ + Internal Function. + Call `func` with `a` as first argument swapping the axes to use extended + axis on functions that don't support it natively. + + Returns result and a.shape with axis dims set to 1. + + Parameters + ---------- + a : array_like + Input array or object that can be converted to an array. + func : callable + Reduction function capable of receiving a single axis argument. + It is called with `a` as first argument followed by `kwargs`. + kwargs : keyword arguments + additional keyword arguments to pass to `func`. + + Returns + ------- + result : tuple + Result of func(a, **kwargs) and a.shape with axis dims set to 1 + which can be used to reshape the result to the same shape a ufunc with + keepdims=True would produce. + + """ + a = np.asanyarray(a) + axis = kwargs.get('axis') + out = kwargs.get('out') + + if keepdims is np._NoValue: + keepdims = False + + nd = a.ndim + if axis is not None: + axis = _nx.normalize_axis_tuple(axis, nd) + + if keepdims and out is not None: + index_out = tuple( + 0 if i in axis else slice(None) for i in range(nd)) + kwargs['out'] = out[(Ellipsis, ) + index_out] + + if len(axis) == 1: + kwargs['axis'] = axis[0] + else: + keep = sorted(set(range(nd)) - set(axis)) + nkeep = len(keep) + + def reshape_arr(a): + # move axis that should not be reduced to front + a = np.moveaxis(a, keep, range(nkeep)) + # merge reduced axis + return a.reshape(a.shape[:nkeep] + (-1,)) + + a = reshape_arr(a) + + weights = kwargs.get("weights") + if weights is not None: + kwargs["weights"] = reshape_arr(weights) + + kwargs['axis'] = -1 + elif keepdims and out is not None: + index_out = (0, ) * nd + kwargs['out'] = out[(Ellipsis, ) + index_out] + + r = func(a, **kwargs) + + if out is not None: + return out + + if keepdims: + if axis is None: + index_r = (np.newaxis, ) * nd + else: + index_r = tuple( + np.newaxis if i in axis else slice(None) + for i in range(nd)) + r = r[(Ellipsis, ) + index_r] + + return r + + +def _median_dispatcher( + a, axis=None, out=None, overwrite_input=None, keepdims=None): + return (a, out) + + +@array_function_dispatch(_median_dispatcher) +def median(a, axis=None, out=None, overwrite_input=False, keepdims=False): + """ + Compute the median along the specified axis. + + Returns the median of the array elements. + + Parameters + ---------- + a : array_like + Input array or object that can be converted to an array. + axis : {int, sequence of int, None}, optional + Axis or axes along which the medians are computed. The default, + axis=None, will compute the median along a flattened version of + the array. If a sequence of axes, the array is first flattened + along the given axes, then the median is computed along the + resulting flattened axis. + out : ndarray, optional + Alternative output array in which to place the result. It must + have the same shape and buffer length as the expected output, + but the type (of the output) will be cast if necessary. + overwrite_input : bool, optional + If True, then allow use of memory of input array `a` for + calculations. The input array will be modified by the call to + `median`. This will save memory when you do not need to preserve + the contents of the input array. Treat the input as undefined, + but it will probably be fully or partially sorted. Default is + False. If `overwrite_input` is ``True`` and `a` is not already an + `ndarray`, an error will be raised. + keepdims : bool, optional + If this is set to True, the axes which are reduced are left + in the result as dimensions with size one. With this option, + the result will broadcast correctly against the original `arr`. + + Returns + ------- + median : ndarray + A new array holding the result. If the input contains integers + or floats smaller than ``float64``, then the output data-type is + ``np.float64``. Otherwise, the data-type of the output is the + same as that of the input. If `out` is specified, that array is + returned instead. + + See Also + -------- + mean, percentile + + Notes + ----- + Given a vector ``V`` of length ``N``, the median of ``V`` is the + middle value of a sorted copy of ``V``, ``V_sorted`` - i + e., ``V_sorted[(N-1)/2]``, when ``N`` is odd, and the average of the + two middle values of ``V_sorted`` when ``N`` is even. + + Examples + -------- + >>> import numpy as np + >>> a = np.array([[10, 7, 4], [3, 2, 1]]) + >>> a + array([[10, 7, 4], + [ 3, 2, 1]]) + >>> np.median(a) + np.float64(3.5) + >>> np.median(a, axis=0) + array([6.5, 4.5, 2.5]) + >>> np.median(a, axis=1) + array([7., 2.]) + >>> np.median(a, axis=(0, 1)) + np.float64(3.5) + >>> m = np.median(a, axis=0) + >>> out = np.zeros_like(m) + >>> np.median(a, axis=0, out=m) + array([6.5, 4.5, 2.5]) + >>> m + array([6.5, 4.5, 2.5]) + >>> b = a.copy() + >>> np.median(b, axis=1, overwrite_input=True) + array([7., 2.]) + >>> assert not np.all(a==b) + >>> b = a.copy() + >>> np.median(b, axis=None, overwrite_input=True) + np.float64(3.5) + >>> assert not np.all(a==b) + + """ + return _ureduce(a, func=_median, keepdims=keepdims, axis=axis, out=out, + overwrite_input=overwrite_input) + + +def _median(a, axis=None, out=None, overwrite_input=False): + # can't be reasonably be implemented in terms of percentile as we have to + # call mean to not break astropy + a = np.asanyarray(a) + + # Set the partition indexes + if axis is None: + sz = a.size + else: + sz = a.shape[axis] + if sz % 2 == 0: + szh = sz // 2 + kth = [szh - 1, szh] + else: + kth = [(sz - 1) // 2] + + # We have to check for NaNs (as of writing 'M' doesn't actually work). + supports_nans = np.issubdtype(a.dtype, np.inexact) or a.dtype.kind in 'Mm' + if supports_nans: + kth.append(-1) + + if overwrite_input: + if axis is None: + part = a.ravel() + part.partition(kth) + else: + a.partition(kth, axis=axis) + part = a + else: + part = partition(a, kth, axis=axis) + + if part.shape == (): + # make 0-D arrays work + return part.item() + if axis is None: + axis = 0 + + indexer = [slice(None)] * part.ndim + index = part.shape[axis] // 2 + if part.shape[axis] % 2 == 1: + # index with slice to allow mean (below) to work + indexer[axis] = slice(index, index + 1) + else: + indexer[axis] = slice(index - 1, index + 1) + indexer = tuple(indexer) + + # Use mean in both odd and even case to coerce data type, + # using out array if needed. + rout = mean(part[indexer], axis=axis, out=out) + if supports_nans and sz > 0: + # If nans are possible, warn and replace by nans like mean would. + rout = np.lib._utils_impl._median_nancheck(part, rout, axis) + + return rout + + +def _percentile_dispatcher(a, q, axis=None, out=None, overwrite_input=None, + method=None, keepdims=None, *, weights=None): + return (a, q, out, weights) + + +@array_function_dispatch(_percentile_dispatcher) +def percentile(a, + q, + axis=None, + out=None, + overwrite_input=False, + method="linear", + keepdims=False, + *, + weights=None): + """ + Compute the q-th percentile of the data along the specified axis. + + Returns the q-th percentile(s) of the array elements. + + Parameters + ---------- + a : array_like of real numbers + Input array or object that can be converted to an array. + q : array_like of float + Percentage or sequence of percentages for the percentiles to compute. + Values must be between 0 and 100 inclusive. + axis : {int, tuple of int, None}, optional + Axis or axes along which the percentiles are computed. The + default is to compute the percentile(s) along a flattened + version of the array. + out : ndarray, optional + Alternative output array in which to place the result. It must + have the same shape and buffer length as the expected output, + but the type (of the output) will be cast if necessary. + overwrite_input : bool, optional + If True, then allow the input array `a` to be modified by intermediate + calculations, to save memory. In this case, the contents of the input + `a` after this function completes is undefined. + method : str, optional + This parameter specifies the method to use for estimating the + percentile. There are many different methods, some unique to NumPy. + See the notes for explanation. The options sorted by their R type + as summarized in the H&F paper [1]_ are: + + 1. 'inverted_cdf' + 2. 'averaged_inverted_cdf' + 3. 'closest_observation' + 4. 'interpolated_inverted_cdf' + 5. 'hazen' + 6. 'weibull' + 7. 'linear' (default) + 8. 'median_unbiased' + 9. 'normal_unbiased' + + The first three methods are discontinuous. NumPy further defines the + following discontinuous variations of the default 'linear' (7.) option: + + * 'lower' + * 'higher', + * 'midpoint' + * 'nearest' + + .. versionchanged:: 1.22.0 + This argument was previously called "interpolation" and only + offered the "linear" default and last four options. + + keepdims : bool, optional + If this is set to True, the axes which are reduced are left in + the result as dimensions with size one. With this option, the + result will broadcast correctly against the original array `a`. + + weights : array_like, optional + An array of weights associated with the values in `a`. Each value in + `a` contributes to the percentile according to its associated weight. + The weights array can either be 1-D (in which case its length must be + the size of `a` along the given axis) or of the same shape as `a`. + If `weights=None`, then all data in `a` are assumed to have a + weight equal to one. + Only `method="inverted_cdf"` supports weights. + See the notes for more details. + + .. versionadded:: 2.0.0 + + Returns + ------- + percentile : scalar or ndarray + If `q` is a single percentile and `axis=None`, then the result + is a scalar. If multiple percentiles are given, first axis of + the result corresponds to the percentiles. The other axes are + the axes that remain after the reduction of `a`. If the input + contains integers or floats smaller than ``float64``, the output + data-type is ``float64``. Otherwise, the output data-type is the + same as that of the input. If `out` is specified, that array is + returned instead. + + See Also + -------- + mean + median : equivalent to ``percentile(..., 50)`` + nanpercentile + quantile : equivalent to percentile, except q in the range [0, 1]. + + Notes + ----- + The behavior of `numpy.percentile` with percentage `q` is + that of `numpy.quantile` with argument ``q/100``. + For more information, please see `numpy.quantile`. + + Examples + -------- + >>> import numpy as np + >>> a = np.array([[10, 7, 4], [3, 2, 1]]) + >>> a + array([[10, 7, 4], + [ 3, 2, 1]]) + >>> np.percentile(a, 50) + 3.5 + >>> np.percentile(a, 50, axis=0) + array([6.5, 4.5, 2.5]) + >>> np.percentile(a, 50, axis=1) + array([7., 2.]) + >>> np.percentile(a, 50, axis=1, keepdims=True) + array([[7.], + [2.]]) + + >>> m = np.percentile(a, 50, axis=0) + >>> out = np.zeros_like(m) + >>> np.percentile(a, 50, axis=0, out=out) + array([6.5, 4.5, 2.5]) + >>> m + array([6.5, 4.5, 2.5]) + + >>> b = a.copy() + >>> np.percentile(b, 50, axis=1, overwrite_input=True) + array([7., 2.]) + >>> assert not np.all(a == b) + + The different methods can be visualized graphically: + + .. plot:: + + import matplotlib.pyplot as plt + + a = np.arange(4) + p = np.linspace(0, 100, 6001) + ax = plt.gca() + lines = [ + ('linear', '-', 'C0'), + ('inverted_cdf', ':', 'C1'), + # Almost the same as `inverted_cdf`: + ('averaged_inverted_cdf', '-.', 'C1'), + ('closest_observation', ':', 'C2'), + ('interpolated_inverted_cdf', '--', 'C1'), + ('hazen', '--', 'C3'), + ('weibull', '-.', 'C4'), + ('median_unbiased', '--', 'C5'), + ('normal_unbiased', '-.', 'C6'), + ] + for method, style, color in lines: + ax.plot( + p, np.percentile(a, p, method=method), + label=method, linestyle=style, color=color) + ax.set( + title='Percentiles for different methods and data: ' + str(a), + xlabel='Percentile', + ylabel='Estimated percentile value', + yticks=a) + ax.legend(bbox_to_anchor=(1.03, 1)) + plt.tight_layout() + plt.show() + + References + ---------- + .. [1] R. J. Hyndman and Y. Fan, + "Sample quantiles in statistical packages," + The American Statistician, 50(4), pp. 361-365, 1996 + + """ + a = np.asanyarray(a) + if a.dtype.kind == "c": + raise TypeError("a must be an array of real numbers") + + weak_q = type(q) in (int, float) # use weak promotion for final result type + q = np.true_divide(q, 100, out=...) + if not _quantile_is_valid(q): + raise ValueError("Percentiles must be in the range [0, 100]") + + if weights is not None: + if method != "inverted_cdf": + msg = ("Only method 'inverted_cdf' supports weights. " + f"Got: {method}.") + raise ValueError(msg) + if axis is not None: + axis = _nx.normalize_axis_tuple(axis, a.ndim, argname="axis") + weights = _weights_are_valid(weights=weights, a=a, axis=axis) + if np.any(weights < 0): + raise ValueError("Weights must be non-negative.") + + return _quantile_unchecked( + a, q, axis, out, overwrite_input, method, keepdims, weights, weak_q) + + +def _quantile_dispatcher(a, q, axis=None, out=None, overwrite_input=None, + method=None, keepdims=None, *, weights=None): + return (a, q, out, weights) + + +@array_function_dispatch(_quantile_dispatcher) +def quantile(a, + q, + axis=None, + out=None, + overwrite_input=False, + method="linear", + keepdims=False, + *, + weights=None): + """ + Compute the q-th quantile of the data along the specified axis. + + Parameters + ---------- + a : array_like of real numbers + Input array or object that can be converted to an array. + q : array_like of float + Probability or sequence of probabilities of the quantiles to compute. + Values must be between 0 and 1 inclusive. + axis : {int, tuple of int, None}, optional + Axis or axes along which the quantiles are computed. The default is + to compute the quantile(s) along a flattened version of the array. + out : ndarray, optional + Alternative output array in which to place the result. It must have + the same shape and buffer length as the expected output, but the + type (of the output) will be cast if necessary. + overwrite_input : bool, optional + If True, then allow the input array `a` to be modified by + intermediate calculations, to save memory. In this case, the + contents of the input `a` after this function completes is + undefined. + method : str, optional + This parameter specifies the method to use for estimating the + quantile. There are many different methods, some unique to NumPy. + The recommended options, numbered as they appear in [1]_, are: + + 1. 'inverted_cdf' + 2. 'averaged_inverted_cdf' + 3. 'closest_observation' + 4. 'interpolated_inverted_cdf' + 5. 'hazen' + 6. 'weibull' + 7. 'linear' (default) + 8. 'median_unbiased' + 9. 'normal_unbiased' + + The first three methods are discontinuous. For backward compatibility + with previous versions of NumPy, the following discontinuous variations + of the default 'linear' (7.) option are available: + + * 'lower' + * 'higher', + * 'midpoint' + * 'nearest' + + See Notes for details. + + .. versionchanged:: 1.22.0 + This argument was previously called "interpolation" and only + offered the "linear" default and last four options. + + keepdims : bool, optional + If this is set to True, the axes which are reduced are left in + the result as dimensions with size one. With this option, the + result will broadcast correctly against the original array `a`. + + weights : array_like, optional + An array of weights associated with the values in `a`. Each value in + `a` contributes to the quantile according to its associated weight. + The weights array can either be 1-D (in which case its length must be + the size of `a` along the given axis) or of the same shape as `a`. + If `weights=None`, then all data in `a` are assumed to have a + weight equal to one. + Only `method="inverted_cdf"` supports weights. + See the notes for more details. + + .. versionadded:: 2.0.0 + + Returns + ------- + quantile : scalar or ndarray + If `q` is a single probability and `axis=None`, then the result + is a scalar. If multiple probability levels are given, first axis + of the result corresponds to the quantiles. The other axes are + the axes that remain after the reduction of `a`. If the input + contains integers or floats smaller than ``float64``, the output + data-type is ``float64``. Otherwise, the output data-type is the + same as that of the input. If `out` is specified, that array is + returned instead. + + See Also + -------- + mean + percentile : equivalent to quantile, but with q in the range [0, 100]. + median : equivalent to ``quantile(..., 0.5)`` + nanquantile + + Notes + ----- + Given a sample `a` from an underlying distribution, `quantile` provides a + nonparametric estimate of the inverse cumulative distribution function. + + By default, this is done by interpolating between adjacent elements in + ``y``, a sorted copy of `a`:: + + (1-g)*y[j] + g*y[j+1] + + where the index ``j`` and coefficient ``g`` are the integral and + fractional components of ``q * (n-1)``, and ``n`` is the number of + elements in the sample. + + This is a special case of Equation 1 of H&F [1]_. More generally, + + - ``j = (q*n + m - 1) // 1``, and + - ``g = (q*n + m - 1) % 1``, + + where ``m`` may be defined according to several different conventions. + The preferred convention may be selected using the ``method`` parameter: + + =============================== =============== =============== + ``method`` number in H&F ``m`` + =============================== =============== =============== + ``interpolated_inverted_cdf`` 4 ``0`` + ``hazen`` 5 ``1/2`` + ``weibull`` 6 ``q`` + ``linear`` (default) 7 ``1 - q`` + ``median_unbiased`` 8 ``q/3 + 1/3`` + ``normal_unbiased`` 9 ``q/4 + 3/8`` + =============================== =============== =============== + + Note that indices ``j`` and ``j + 1`` are clipped to the range ``0`` to + ``n - 1`` when the results of the formula would be outside the allowed + range of non-negative indices. The ``- 1`` in the formulas for ``j`` and + ``g`` accounts for Python's 0-based indexing. + + The table above includes only the estimators from H&F that are continuous + functions of probability `q` (estimators 4-9). NumPy also provides the + three discontinuous estimators from H&F (estimators 1-3), where ``j`` is + defined as above, ``m`` is defined as follows, and ``g`` is a function + of the real-valued ``index = q*n + m - 1`` and ``j``. + + 1. ``inverted_cdf``: ``m = 0`` and ``g = int(index - j > 0)`` + 2. ``averaged_inverted_cdf``: ``m = 0`` and + ``g = (1 + int(index - j > 0)) / 2`` + 3. ``closest_observation``: ``m = -1/2`` and + ``g = 1 - int((index == j) & (j%2 == 1))`` + + For backward compatibility with previous versions of NumPy, `quantile` + provides four additional discontinuous estimators. Like + ``method='linear'``, all have ``m = 1 - q`` so that ``j = q*(n-1) // 1``, + but ``g`` is defined as follows. + + - ``lower``: ``g = 0`` + - ``midpoint``: ``g = 0.5`` + - ``higher``: ``g = 1`` + - ``nearest``: ``g = (q*(n-1) % 1) > 0.5`` + + **Weighted quantiles:** + More formally, the quantile at probability level :math:`q` of a cumulative + distribution function :math:`F(y)=P(Y \\leq y)` with probability measure + :math:`P` is defined as any number :math:`x` that fulfills the + *coverage conditions* + + .. math:: P(Y < x) \\leq q \\quad\\text{and}\\quad P(Y \\leq x) \\geq q + + with random variable :math:`Y\\sim P`. + Sample quantiles, the result of `quantile`, provide nonparametric + estimation of the underlying population counterparts, represented by the + unknown :math:`F`, given a data vector `a` of length ``n``. + + Some of the estimators above arise when one considers :math:`F` as the + empirical distribution function of the data, i.e. + :math:`F(y) = \\frac{1}{n} \\sum_i 1_{a_i \\leq y}`. + Then, different methods correspond to different choices of :math:`x` that + fulfill the above coverage conditions. Methods that follow this approach + are ``inverted_cdf`` and ``averaged_inverted_cdf``. + + For weighted quantiles, the coverage conditions still hold. The + empirical cumulative distribution is simply replaced by its weighted + version, i.e. + :math:`P(Y \\leq t) = \\frac{1}{\\sum_i w_i} \\sum_i w_i 1_{x_i \\leq t}`. + Only ``method="inverted_cdf"`` supports weights. + + Examples + -------- + >>> import numpy as np + >>> a = np.array([[10, 7, 4], [3, 2, 1]]) + >>> a + array([[10, 7, 4], + [ 3, 2, 1]]) + >>> np.quantile(a, 0.5) + 3.5 + >>> np.quantile(a, 0.5, axis=0) + array([6.5, 4.5, 2.5]) + >>> np.quantile(a, 0.5, axis=1) + array([7., 2.]) + >>> np.quantile(a, 0.5, axis=1, keepdims=True) + array([[7.], + [2.]]) + >>> m = np.quantile(a, 0.5, axis=0) + >>> out = np.zeros_like(m) + >>> np.quantile(a, 0.5, axis=0, out=out) + array([6.5, 4.5, 2.5]) + >>> m + array([6.5, 4.5, 2.5]) + >>> b = a.copy() + >>> np.quantile(b, 0.5, axis=1, overwrite_input=True) + array([7., 2.]) + >>> assert not np.all(a == b) + + See also `numpy.percentile` for a visualization of most methods. + + References + ---------- + .. [1] R. J. Hyndman and Y. Fan, + "Sample quantiles in statistical packages," + The American Statistician, 50(4), pp. 361-365, 1996 + + """ + a = np.asanyarray(a) + if a.dtype.kind == "c": + raise TypeError("a must be an array of real numbers") + + weak_q = type(q) in (int, float) # use weak promotion for final result type + q = np.asanyarray(q) + + if not _quantile_is_valid(q): + raise ValueError("Quantiles must be in the range [0, 1]") + + if weights is not None: + if method != "inverted_cdf": + msg = ("Only method 'inverted_cdf' supports weights. " + f"Got: {method}.") + raise ValueError(msg) + if axis is not None: + axis = _nx.normalize_axis_tuple(axis, a.ndim, argname="axis") + weights = _weights_are_valid(weights=weights, a=a, axis=axis) + if np.any(weights < 0): + raise ValueError("Weights must be non-negative.") + + return _quantile_unchecked( + a, q, axis, out, overwrite_input, method, keepdims, weights, weak_q) + + +def _quantile_unchecked(a, + q, + axis=None, + out=None, + overwrite_input=False, + method="linear", + keepdims=False, + weights=None, + weak_q=False): + """Assumes that q is in [0, 1], and is an ndarray""" + return _ureduce(a, + func=_quantile_ureduce_func, + q=q, + weights=weights, + keepdims=keepdims, + axis=axis, + out=out, + overwrite_input=overwrite_input, + method=method, + weak_q=weak_q) + + +def _quantile_is_valid(q): + # avoid expensive reductions, relevant for arrays with < O(1000) elements + if q.ndim == 1 and q.size < 10: + for i in range(q.size): + if not (0.0 <= q[i] <= 1.0): + return False + elif not (q.min() >= 0 and q.max() <= 1): + return False + return True + + +def _compute_virtual_index(n, quantiles, alpha: float, beta: float): + """ + Compute the floating point indexes of an array for the linear + interpolation of quantiles. + n : array_like + The sample sizes. + quantiles : array_like + The quantiles values. + alpha : float + A constant used to correct the index computed. + beta : float + A constant used to correct the index computed. + + alpha and beta values depend on the chosen method + (see quantile documentation) + + Reference: + Hyndman&Fan paper "Sample Quantiles in Statistical Packages", + DOI: 10.1080/00031305.1996.10473566 + """ + return n * quantiles + ( + alpha + quantiles * (1 - alpha - beta) + ) - 1 + + +def _get_gamma(virtual_indexes, previous_indexes, method): + """ + Compute gamma (a.k.a 'm' or 'weight') for the linear interpolation + of quantiles. + + virtual_indexes : array_like + The indexes where the percentile is supposed to be found in the sorted + sample. + previous_indexes : array_like + The floor values of virtual_indexes. + method : dict + The interpolation method chosen, which may have a specific rule + modifying gamma. + + gamma is usually the fractional part of virtual_indexes but can be modified + by the interpolation method. + """ + gamma = np.asanyarray(virtual_indexes - previous_indexes) + gamma = method["fix_gamma"](gamma, virtual_indexes) + # Ensure both that we have an array, and that we keep the dtype + # (which may have been matched to the input array). + return np.asanyarray(gamma, dtype=virtual_indexes.dtype) + + +def _lerp(a, b, t, out=None): + """ + Compute the linear interpolation weighted by gamma on each point of + two same shape array. + + a : array_like + Left bound. + b : array_like + Right bound. + t : array_like + The interpolation weight. + out : array_like + Output array. + """ + diff_b_a = b - a + lerp_interpolation = add(a, diff_b_a * t, out=... if out is None else out) + subtract(b, diff_b_a * (1 - t), out=lerp_interpolation, where=t >= 0.5, + casting='unsafe', dtype=type(lerp_interpolation.dtype)) + if lerp_interpolation.ndim == 0 and out is None: + lerp_interpolation = lerp_interpolation[()] # unpack 0d arrays + return lerp_interpolation + + +def _get_gamma_mask(shape, default_value, conditioned_value, where): + out = np.full(shape, default_value) + np.copyto(out, conditioned_value, where=where, casting="unsafe") + return out + + +def _discrete_interpolation_to_boundaries(index, gamma_condition_fun): + previous = np.floor(index) + next = previous + 1 + gamma = index - previous + res = _get_gamma_mask(shape=index.shape, + default_value=next, + conditioned_value=previous, + where=gamma_condition_fun(gamma, index) + ).astype(np.intp) + # Some methods can lead to out-of-bound integers, clip them: + res[res < 0] = 0 + return res + + +def _closest_observation(n, quantiles): + # "choose the nearest even order statistic at g=0" (H&F (1996) pp. 362). + # Order is 1-based so for zero-based indexing round to nearest odd index. + gamma_fun = lambda gamma, index: (gamma == 0) & (np.floor(index) % 2 == 1) + return _discrete_interpolation_to_boundaries((n * quantiles) - 1 - 0.5, + gamma_fun) + + +def _inverted_cdf(n, quantiles): + gamma_fun = lambda gamma, _: (gamma == 0) + return _discrete_interpolation_to_boundaries((n * quantiles) - 1, + gamma_fun) + + +def _quantile_ureduce_func( + a: np.ndarray, + q: np.ndarray, + weights: np.ndarray | None, + axis: int | None = None, + out: np.ndarray | None = None, + overwrite_input: bool = False, + method: str = "linear", + weak_q: bool = False, +) -> np.ndarray: + if q.ndim > 2: + # The code below works fine for nd, but it might not have useful + # semantics. For now, keep the supported dimensions the same as it was + # before. + raise ValueError("q must be a scalar or 1d") + if overwrite_input: + if axis is None: + axis = 0 + arr = a.ravel() + wgt = None if weights is None else weights.ravel() + else: + arr = a + wgt = weights + elif axis is None: + axis = 0 + arr = a.flatten() + wgt = None if weights is None else weights.flatten() + else: + arr = a.copy() + wgt = weights + result = _quantile(arr, + quantiles=q, + axis=axis, + method=method, + out=out, + weights=wgt, + weak_q=weak_q) + return result + + +def _get_indexes(arr, virtual_indexes, valid_values_count): + """ + Get the valid indexes of arr neighbouring virtual_indexes. + Note + This is a companion function to linear interpolation of + Quantiles + + Returns + ------- + (previous_indexes, next_indexes): Tuple + A Tuple of virtual_indexes neighbouring indexes + """ + previous_indexes = floor(virtual_indexes, out=...) + next_indexes = add(previous_indexes, 1, out=...) + indexes_above_bounds = virtual_indexes >= valid_values_count - 1 + # When indexes is above max index, take the max value of the array + if indexes_above_bounds.any(): + previous_indexes[indexes_above_bounds] = -1 + next_indexes[indexes_above_bounds] = -1 + # When indexes is below min index, take the min value of the array + indexes_below_bounds = virtual_indexes < 0 + if indexes_below_bounds.any(): + previous_indexes[indexes_below_bounds] = 0 + next_indexes[indexes_below_bounds] = 0 + if np.issubdtype(arr.dtype, np.inexact): + # After the sort, slices having NaNs will have for last element a NaN + virtual_indexes_nans = np.isnan(virtual_indexes) + if virtual_indexes_nans.any(): + previous_indexes[virtual_indexes_nans] = -1 + next_indexes[virtual_indexes_nans] = -1 + previous_indexes = previous_indexes.astype(np.intp) + next_indexes = next_indexes.astype(np.intp) + return previous_indexes, next_indexes + + +def _quantile( + arr: "np.typing.ArrayLike", + quantiles: np.ndarray, + axis: int = -1, + method: str = "linear", + out: np.ndarray | None = None, + weights: "np.typing.ArrayLike | None" = None, + weak_q: bool = False, +) -> np.ndarray: + """ + Private function that doesn't support extended axis or keepdims. + These methods are extended to this function using _ureduce + See nanpercentile for parameter usage + It computes the quantiles of the array for the given axis. + A linear interpolation is performed based on the `method`. + + By default, the method is "linear" where alpha == beta == 1 which + performs the 7th method of Hyndman&Fan. + With "median_unbiased" we get alpha == beta == 1/3 + thus the 8th method of Hyndman&Fan. + """ + # --- Setup + arr = np.asanyarray(arr) + values_count = arr.shape[axis] + # The dimensions of `q` are prepended to the output shape, so we need the + # axis being sampled from `arr` to be last. + if axis != 0: # But moveaxis is slow, so only call it if necessary. + arr = np.moveaxis(arr, axis, destination=0) + supports_nans = ( + np.issubdtype(arr.dtype, np.inexact) or arr.dtype.kind in 'Mm' + ) + + if weights is None: + # --- Computation of indexes + # Index where to find the value in the sorted array. + # Virtual because it is a floating point value, not a valid index. + # The nearest neighbours are used for interpolation + try: + method_props = _QuantileMethods[method] + except KeyError: + raise ValueError( + f"{method!r} is not a valid method. Use one of: " + f"{_QuantileMethods.keys()}") from None + virtual_indexes = method_props["get_virtual_index"](values_count, + quantiles) + virtual_indexes = np.asanyarray(virtual_indexes) + + if method_props["fix_gamma"] is None: + supports_integers = True + else: + int_virtual_indices = np.issubdtype(virtual_indexes.dtype, + np.integer) + supports_integers = method == 'linear' and int_virtual_indices + + if supports_integers: + # No interpolation needed, take the points along axis + if supports_nans: + # may contain nan, which would sort to the end + arr.partition( + concatenate((virtual_indexes.ravel(), [-1])), axis=0, + ) + slices_having_nans = np.isnan(arr[-1, ...]) + else: + # cannot contain nan + arr.partition(virtual_indexes.ravel(), axis=0) + slices_having_nans = np.array(False, dtype=bool) + result = take(arr, virtual_indexes, axis=0, out=out) + else: + previous_indexes, next_indexes = _get_indexes(arr, + virtual_indexes, + values_count) + # --- Sorting + arr.partition( + np.unique(np.concatenate(([0, -1], + previous_indexes.ravel(), + next_indexes.ravel(), + ))), + axis=0) + if supports_nans: + slices_having_nans = np.isnan(arr[-1, ...]) + else: + slices_having_nans = None + # --- Get values from indexes + previous = arr[previous_indexes] + next = arr[next_indexes] + # --- Linear interpolation + gamma = _get_gamma(virtual_indexes, previous_indexes, + method_props) + if weak_q: + gamma = float(gamma) + else: + result_shape = virtual_indexes.shape + (1,) * (arr.ndim - 1) + gamma = gamma.reshape(result_shape) + result = _lerp(previous, + next, + gamma, + out=out) + else: + # Weighted case + # This implements method="inverted_cdf", the only supported weighted + # method, which needs to sort anyway. + weights = np.asanyarray(weights) + if axis != 0: + weights = np.moveaxis(weights, axis, destination=0) + index_array = np.argsort(arr, axis=0) + + # arr = arr[index_array, ...] # but this adds trailing dimensions of + # 1. + arr = np.take_along_axis(arr, index_array, axis=0) + if weights.shape == arr.shape: + weights = np.take_along_axis(weights, index_array, axis=0) + else: + # weights is 1d + weights = weights.reshape(-1)[index_array, ...] + + if supports_nans: + # may contain nan, which would sort to the end + slices_having_nans = np.isnan(arr[-1, ...]) + else: + # cannot contain nan + slices_having_nans = np.array(False, dtype=bool) + + # We use the weights to calculate the empirical cumulative + # distribution function cdf + cdf = weights.cumsum(axis=0, dtype=np.float64) + cdf /= cdf[-1, ...] # normalization to 1 + if np.isnan(cdf[-1]).any(): + # Above calculations should normally warn for the zero/inf case. + raise ValueError("Weights included NaN, inf or were all zero.") + # Search index i such that + # sum(weights[j], j=0..i-1) < quantile <= sum(weights[j], j=0..i) + # is then equivalent to + # cdf[i-1] < quantile <= cdf[i] + # Unfortunately, searchsorted only accepts 1-d arrays as first + # argument, so we will need to iterate over dimensions. + + # Without the following cast, searchsorted can return surprising + # results, e.g. + # np.searchsorted(np.array([0.2, 0.4, 0.6, 0.8, 1.]), + # np.array(0.4, dtype=np.float32), side="left") + # returns 2 instead of 1 because 0.4 is not binary representable. + if quantiles.dtype.kind == "f": + cdf = cdf.astype(quantiles.dtype) + # Weights must be non-negative, so we might have zero weights at the + # beginning leading to some leading zeros in cdf. The call to + # np.searchsorted for quantiles=0 will then pick the first element, + # but should pick the first one larger than zero. We + # therefore simply set 0 values in cdf to -1. + if np.any(cdf[0, ...] == 0): + cdf[cdf == 0] = -1 + + def find_cdf_1d(arr, cdf): + indices = np.searchsorted(cdf, quantiles, side="left") + # We might have reached the maximum with i = len(arr), e.g. for + # quantiles = 1, and need to cut it to len(arr) - 1. + indices = minimum(indices, values_count - 1) + result = take(arr, indices, axis=0) + return result + + r_shape = arr.shape[1:] + if quantiles.ndim > 0: + r_shape = quantiles.shape + r_shape + if out is None: + result = np.empty_like(arr, shape=r_shape) + else: + if out.shape != r_shape: + msg = (f"Wrong shape of argument 'out', shape={r_shape} is " + f"required; got shape={out.shape}.") + raise ValueError(msg) + result = out + + # See apply_along_axis, which we do for axis=0. Note that Ni = (,) + # always, so we remove it here. + Nk = arr.shape[1:] + for kk in np.ndindex(Nk): + result[(...,) + kk] = find_cdf_1d( + arr[np.s_[:, ] + kk], cdf[np.s_[:, ] + kk] + ) + + # Make result the same as in unweighted inverted_cdf. + if result.shape == () and result.dtype == np.dtype("O"): + result = result.item() + + if np.any(slices_having_nans): + if result.ndim == 0 and out is None: + # can't write to a scalar, but indexing will be correct + result = arr[-1] + else: + np.copyto(result, arr[-1, ...], where=slices_having_nans) + return result + + +def _trapezoid_dispatcher(y, x=None, dx=None, axis=None): + return (y, x) + + +@array_function_dispatch(_trapezoid_dispatcher) +def trapezoid(y, x=None, dx=1.0, axis=-1): + r""" + Integrate along the given axis using the composite trapezoidal rule. + + If `x` is provided, the integration happens in sequence along its + elements - they are not sorted. + + Integrate `y` (`x`) along each 1d slice on the given axis, compute + :math:`\int y(x) dx`. + When `x` is specified, this integrates along the parametric curve, + computing :math:`\int_t y(t) dt = + \int_t y(t) \left.\frac{dx}{dt}\right|_{x=x(t)} dt`. + + .. versionadded:: 2.0.0 + + Parameters + ---------- + y : array_like + Input array to integrate. + x : array_like, optional + The sample points corresponding to the `y` values. If `x` is None, + the sample points are assumed to be evenly spaced `dx` apart. The + default is None. + dx : scalar, optional + The spacing between sample points when `x` is None. The default is 1. + axis : int, optional + The axis along which to integrate. + + Returns + ------- + trapezoid : float or ndarray + Definite integral of `y` = n-dimensional array as approximated along + a single axis by the trapezoidal rule. If `y` is a 1-dimensional array, + then the result is a float. If `n` is greater than 1, then the result + is an `n`-1 dimensional array. + + See Also + -------- + sum, cumsum + + Notes + ----- + Image [2]_ illustrates trapezoidal rule -- y-axis locations of points + will be taken from `y` array, by default x-axis distances between + points will be 1.0, alternatively they can be provided with `x` array + or with `dx` scalar. Return value will be equal to combined area under + the red lines. + + + References + ---------- + .. [1] Wikipedia page: https://en.wikipedia.org/wiki/Trapezoidal_rule + + .. [2] Illustration image: + https://en.wikipedia.org/wiki/File:Composite_trapezoidal_rule_illustration.png + + Examples + -------- + >>> import numpy as np + + Use the trapezoidal rule on evenly spaced points: + + >>> np.trapezoid([1, 2, 3]) + 4.0 + + The spacing between sample points can be selected by either the + ``x`` or ``dx`` arguments: + + >>> np.trapezoid([1, 2, 3], x=[4, 6, 8]) + 8.0 + >>> np.trapezoid([1, 2, 3], dx=2) + 8.0 + + Using a decreasing ``x`` corresponds to integrating in reverse: + + >>> np.trapezoid([1, 2, 3], x=[8, 6, 4]) + -8.0 + + More generally ``x`` is used to integrate along a parametric curve. We can + estimate the integral :math:`\int_0^1 x^2 = 1/3` using: + + >>> x = np.linspace(0, 1, num=50) + >>> y = x**2 + >>> np.trapezoid(y, x) + 0.33340274885464394 + + Or estimate the area of a circle, noting we repeat the sample which closes + the curve: + + >>> theta = np.linspace(0, 2 * np.pi, num=1000, endpoint=True) + >>> np.trapezoid(np.cos(theta), x=np.sin(theta)) + 3.141571941375841 + + ``np.trapezoid`` can be applied along a specified axis to do multiple + computations in one call: + + >>> a = np.arange(6).reshape(2, 3) + >>> a + array([[0, 1, 2], + [3, 4, 5]]) + >>> np.trapezoid(a, axis=0) + array([1.5, 2.5, 3.5]) + >>> np.trapezoid(a, axis=1) + array([2., 8.]) + """ + + y = asanyarray(y) + if x is None: + d = dx + else: + x = asanyarray(x) + if x.ndim == 1: + d = diff(x) + # reshape to correct shape + shape = [1] * y.ndim + shape[axis] = d.shape[0] + d = d.reshape(shape) + else: + d = diff(x, axis=axis) + nd = y.ndim + slice1 = [slice(None)] * nd + slice2 = [slice(None)] * nd + slice1[axis] = slice(1, None) + slice2[axis] = slice(None, -1) + try: + ret = (d * (y[tuple(slice1)] + y[tuple(slice2)]) / 2.0).sum(axis) + except ValueError: + # Operations didn't work, cast to ndarray + d = np.asarray(d) + y = np.asarray(y) + ret = add.reduce(d * (y[tuple(slice1)] + y[tuple(slice2)]) / 2.0, axis) + return ret + + +def _meshgrid_dispatcher(*xi, copy=None, sparse=None, indexing=None): + return xi + + +# Based on scitools meshgrid +@array_function_dispatch(_meshgrid_dispatcher) +def meshgrid(*xi, copy=True, sparse=False, indexing='xy'): + """ + Return a tuple of coordinate matrices from coordinate vectors. + + Make N-D coordinate arrays for vectorized evaluations of + N-D scalar/vector fields over N-D grids, given + one-dimensional coordinate arrays x1, x2,..., xn. + + Parameters + ---------- + x1, x2,..., xn : array_like + 1-D arrays representing the coordinates of a grid. + indexing : {'xy', 'ij'}, optional + Cartesian ('xy', default) or matrix ('ij') indexing of output. + See Notes for more details. + sparse : bool, optional + If True the shape of the returned coordinate array for dimension *i* + is reduced from ``(N1, ..., Ni, ... Nn)`` to + ``(1, ..., 1, Ni, 1, ..., 1)``. These sparse coordinate grids are + intended to be used with :ref:`basics.broadcasting`. When all + coordinates are used in an expression, broadcasting still leads to a + fully-dimensonal result array. + + Default is False. + + copy : bool, optional + If False, a view into the original arrays are returned in order to + conserve memory. Default is True. Please note that + ``sparse=False, copy=False`` will likely return non-contiguous + arrays. Furthermore, more than one element of a broadcast array + may refer to a single memory location. If you need to write to the + arrays, make copies first. + + Returns + ------- + X1, X2,..., XN : tuple of ndarrays + For vectors `x1`, `x2`,..., `xn` with lengths ``Ni=len(xi)``, + returns ``(N1, N2, N3,..., Nn)`` shaped arrays if indexing='ij' + or ``(N2, N1, N3,..., Nn)`` shaped arrays if indexing='xy' + with the elements of `xi` repeated to fill the matrix along + the first dimension for `x1`, the second for `x2` and so on. + + Notes + ----- + This function supports both indexing conventions through the indexing + keyword argument. Giving the string 'ij' returns a meshgrid with + matrix indexing, while 'xy' returns a meshgrid with Cartesian indexing. + In the 2-D case with inputs of length M and N, the outputs are of shape + (N, M) for 'xy' indexing and (M, N) for 'ij' indexing. In the 3-D case + with inputs of length M, N and P, outputs are of shape (N, M, P) for + 'xy' indexing and (M, N, P) for 'ij' indexing. The difference is + illustrated by the following code snippet:: + + xv, yv = np.meshgrid(x, y, indexing='ij') + for i in range(nx): + for j in range(ny): + # treat xv[i,j], yv[i,j] + + xv, yv = np.meshgrid(x, y, indexing='xy') + for i in range(nx): + for j in range(ny): + # treat xv[j,i], yv[j,i] + + In the 1-D and 0-D case, the indexing and sparse keywords have no effect. + + See Also + -------- + mgrid : Construct a multi-dimensional "meshgrid" using indexing notation. + ogrid : Construct an open multi-dimensional "meshgrid" using indexing + notation. + :ref:`how-to-index` + + Examples + -------- + >>> import numpy as np + >>> nx, ny = (3, 2) + >>> x = np.linspace(0, 1, nx) + >>> y = np.linspace(0, 1, ny) + >>> xv, yv = np.meshgrid(x, y) + >>> xv + array([[0. , 0.5, 1. ], + [0. , 0.5, 1. ]]) + >>> yv + array([[0., 0., 0.], + [1., 1., 1.]]) + + The result of `meshgrid` is a coordinate grid: + + >>> import matplotlib.pyplot as plt + >>> plt.plot(xv, yv, marker='o', color='k', linestyle='none') + >>> plt.show() + + You can create sparse output arrays to save memory and computation time. + + >>> xv, yv = np.meshgrid(x, y, sparse=True) + >>> xv + array([[0. , 0.5, 1. ]]) + >>> yv + array([[0.], + [1.]]) + + `meshgrid` is very useful to evaluate functions on a grid. If the + function depends on all coordinates, both dense and sparse outputs can be + used. + + >>> x = np.linspace(-5, 5, 101) + >>> y = np.linspace(-5, 5, 101) + >>> # full coordinate arrays + >>> xx, yy = np.meshgrid(x, y) + >>> zz = np.sqrt(xx**2 + yy**2) + >>> xx.shape, yy.shape, zz.shape + ((101, 101), (101, 101), (101, 101)) + >>> # sparse coordinate arrays + >>> xs, ys = np.meshgrid(x, y, sparse=True) + >>> zs = np.sqrt(xs**2 + ys**2) + >>> xs.shape, ys.shape, zs.shape + ((1, 101), (101, 1), (101, 101)) + >>> np.array_equal(zz, zs) + True + + >>> h = plt.contourf(x, y, zs) + >>> plt.axis('scaled') + >>> plt.colorbar() + >>> plt.show() + """ + ndim = len(xi) + + if indexing not in ['xy', 'ij']: + raise ValueError( + "Valid values for `indexing` are 'xy' and 'ij'.") + + s0 = (1,) * ndim + output = [np.asanyarray(x).reshape(s0[:i] + (-1,) + s0[i + 1:]) + for i, x in enumerate(xi)] + + if indexing == 'xy' and ndim > 1: + # switch first and second axis + output[0].shape = (1, -1) + s0[2:] + output[1].shape = (-1, 1) + s0[2:] + + if not sparse: + # Return the full N-D matrix (not only the 1-D vector) + output = np.broadcast_arrays(*output, subok=True) + + if copy: + output = tuple(x.copy() for x in output) + + return output + + +def _delete_dispatcher(arr, obj, axis=None): + return (arr, obj) + + +@array_function_dispatch(_delete_dispatcher) +def delete(arr, obj, axis=None): + """ + Return a new array with sub-arrays along an axis deleted. For a one + dimensional array, this returns those entries not returned by + `arr[obj]`. + + Parameters + ---------- + arr : array_like + Input array. + obj : slice, int, array-like of ints or bools + Indicate indices of sub-arrays to remove along the specified axis. + + .. versionchanged:: 1.19.0 + Boolean indices are now treated as a mask of elements to remove, + rather than being cast to the integers 0 and 1. + + axis : int, optional + The axis along which to delete the subarray defined by `obj`. + If `axis` is None, `obj` is applied to the flattened array. + + Returns + ------- + out : ndarray + A copy of `arr` with the elements specified by `obj` removed. Note + that `delete` does not occur in-place. If `axis` is None, `out` is + a flattened array. + + See Also + -------- + insert : Insert elements into an array. + append : Append elements at the end of an array. + + Notes + ----- + Often it is preferable to use a boolean mask. For example: + + >>> arr = np.arange(12) + 1 + >>> mask = np.ones(len(arr), dtype=bool) + >>> mask[[0,2,4]] = False + >>> result = arr[mask,...] + + Is equivalent to ``np.delete(arr, [0,2,4], axis=0)``, but allows further + use of `mask`. + + Examples + -------- + >>> import numpy as np + >>> arr = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]]) + >>> arr + array([[ 1, 2, 3, 4], + [ 5, 6, 7, 8], + [ 9, 10, 11, 12]]) + >>> np.delete(arr, 1, 0) + array([[ 1, 2, 3, 4], + [ 9, 10, 11, 12]]) + + >>> np.delete(arr, np.s_[::2], 1) + array([[ 2, 4], + [ 6, 8], + [10, 12]]) + >>> np.delete(arr, [1,3,5], None) + array([ 1, 3, 5, 7, 8, 9, 10, 11, 12]) + + """ + conv = _array_converter(arr) + arr, = conv.as_arrays(subok=False) + + ndim = arr.ndim + arrorder = 'F' if arr.flags.fnc else 'C' + if axis is None: + if ndim != 1: + arr = arr.ravel() + # needed for np.matrix, which is still not 1d after being ravelled + ndim = arr.ndim + axis = ndim - 1 + else: + axis = normalize_axis_index(axis, ndim) + + slobj = [slice(None)] * ndim + N = arr.shape[axis] + newshape = list(arr.shape) + + if isinstance(obj, slice): + start, stop, step = obj.indices(N) + xr = range(start, stop, step) + numtodel = len(xr) + + if numtodel <= 0: + return conv.wrap(arr.copy(order=arrorder), to_scalar=False) + + # Invert if step is negative: + if step < 0: + step = -step + start = xr[-1] + stop = xr[0] + 1 + + newshape[axis] -= numtodel + new = empty(newshape, arr.dtype, arrorder) + # copy initial chunk + if start == 0: + pass + else: + slobj[axis] = slice(None, start) + new[tuple(slobj)] = arr[tuple(slobj)] + # copy end chunk + if stop == N: + pass + else: + slobj[axis] = slice(stop - numtodel, None) + slobj2 = [slice(None)] * ndim + slobj2[axis] = slice(stop, None) + new[tuple(slobj)] = arr[tuple(slobj2)] + # copy middle pieces + if step == 1: + pass + else: # use array indexing. + keep = ones(stop - start, dtype=bool) + keep[:stop - start:step] = False + slobj[axis] = slice(start, stop - numtodel) + slobj2 = [slice(None)] * ndim + slobj2[axis] = slice(start, stop) + arr = arr[tuple(slobj2)] + slobj2[axis] = keep + new[tuple(slobj)] = arr[tuple(slobj2)] + + return conv.wrap(new, to_scalar=False) + + if isinstance(obj, (int, integer)) and not isinstance(obj, bool): + single_value = True + else: + single_value = False + _obj = obj + obj = np.asarray(obj) + # `size == 0` to allow empty lists similar to indexing, but (as there) + # is really too generic: + if obj.size == 0 and not isinstance(_obj, np.ndarray): + obj = obj.astype(intp) + elif obj.size == 1 and obj.dtype.kind in "ui": + # For a size 1 integer array we can use the single-value path + # (most dtypes, except boolean, should just fail later). + obj = obj.item() + single_value = True + + if single_value: + # optimization for a single value + if (obj < -N or obj >= N): + raise IndexError( + f"index {obj} is out of bounds for axis {axis} with " + f"size {N}") + if (obj < 0): + obj += N + newshape[axis] -= 1 + new = empty(newshape, arr.dtype, arrorder) + slobj[axis] = slice(None, obj) + new[tuple(slobj)] = arr[tuple(slobj)] + slobj[axis] = slice(obj, None) + slobj2 = [slice(None)] * ndim + slobj2[axis] = slice(obj + 1, None) + new[tuple(slobj)] = arr[tuple(slobj2)] + else: + if obj.dtype == bool: + if obj.shape != (N,): + raise ValueError('boolean array argument obj to delete ' + 'must be one dimensional and match the axis ' + f'length of {N}') + + # optimization, the other branch is slower + keep = ~obj + else: + keep = ones(N, dtype=bool) + keep[obj,] = False + + slobj[axis] = keep + new = arr[tuple(slobj)] + + return conv.wrap(new, to_scalar=False) + + +def _insert_dispatcher(arr, obj, values, axis=None): + return (arr, obj, values) + + +@array_function_dispatch(_insert_dispatcher) +def insert(arr, obj, values, axis=None): + """ + Insert values along the given axis before the given indices. + + Parameters + ---------- + arr : array_like + Input array. + obj : slice, int, array-like of ints or bools + Object that defines the index or indices before which `values` is + inserted. + + .. versionchanged:: 2.1.2 + Boolean indices are now treated as a mask of elements to insert, + rather than being cast to the integers 0 and 1. + + Support for multiple insertions when `obj` is a single scalar or a + sequence with one element (similar to calling insert multiple + times). + values : array_like + Values to insert into `arr`. If the type of `values` is different + from that of `arr`, `values` is converted to the type of `arr`. + `values` should be shaped so that ``arr[...,obj,...] = values`` + is legal. + axis : int, optional + Axis along which to insert `values`. If `axis` is None then `arr` + is flattened first. + + Returns + ------- + out : ndarray + A copy of `arr` with `values` inserted. Note that `insert` + does not occur in-place: a new array is returned. If + `axis` is None, `out` is a flattened array. + + See Also + -------- + append : Append elements at the end of an array. + concatenate : Join a sequence of arrays along an existing axis. + delete : Delete elements from an array. + + Notes + ----- + Note that for higher dimensional inserts ``obj=0`` behaves very different + from ``obj=[0]`` just like ``arr[:,0,:] = values`` is different from + ``arr[:,[0],:] = values``. This is because of the difference between basic + and advanced :ref:`indexing `. + + Examples + -------- + >>> import numpy as np + >>> a = np.arange(6).reshape(3, 2) + >>> a + array([[0, 1], + [2, 3], + [4, 5]]) + >>> np.insert(a, 1, 6) + array([0, 6, 1, 2, 3, 4, 5]) + >>> np.insert(a, 1, 6, axis=1) + array([[0, 6, 1], + [2, 6, 3], + [4, 6, 5]]) + + Difference between sequence and scalars, + showing how ``obj=[1]`` behaves different from ``obj=1``: + + >>> np.insert(a, [1], [[7],[8],[9]], axis=1) + array([[0, 7, 1], + [2, 8, 3], + [4, 9, 5]]) + >>> np.insert(a, 1, [[7],[8],[9]], axis=1) + array([[0, 7, 8, 9, 1], + [2, 7, 8, 9, 3], + [4, 7, 8, 9, 5]]) + >>> np.array_equal(np.insert(a, 1, [7, 8, 9], axis=1), + ... np.insert(a, [1], [[7],[8],[9]], axis=1)) + True + + >>> b = a.flatten() + >>> b + array([0, 1, 2, 3, 4, 5]) + >>> np.insert(b, [2, 2], [6, 7]) + array([0, 1, 6, 7, 2, 3, 4, 5]) + + >>> np.insert(b, slice(2, 4), [7, 8]) + array([0, 1, 7, 2, 8, 3, 4, 5]) + + >>> np.insert(b, [2, 2], [7.13, False]) # type casting + array([0, 1, 7, 0, 2, 3, 4, 5]) + + >>> x = np.arange(8).reshape(2, 4) + >>> idx = (1, 3) + >>> np.insert(x, idx, 999, axis=1) + array([[ 0, 999, 1, 2, 999, 3], + [ 4, 999, 5, 6, 999, 7]]) + + """ + conv = _array_converter(arr) + arr, = conv.as_arrays(subok=False) + + ndim = arr.ndim + arrorder = 'F' if arr.flags.fnc else 'C' + if axis is None: + if ndim != 1: + arr = arr.ravel() + # needed for np.matrix, which is still not 1d after being ravelled + ndim = arr.ndim + axis = ndim - 1 + else: + axis = normalize_axis_index(axis, ndim) + slobj = [slice(None)] * ndim + N = arr.shape[axis] + newshape = list(arr.shape) + + if isinstance(obj, slice): + # turn it into a range object + indices = arange(*obj.indices(N), dtype=intp) + else: + # need to copy obj, because indices will be changed in-place + indices = np.array(obj) + if indices.dtype == bool: + if obj.ndim != 1: + raise ValueError('boolean array argument obj to insert ' + 'must be one dimensional') + indices = np.flatnonzero(obj) + elif indices.ndim > 1: + raise ValueError( + "index array argument obj to insert must be one dimensional " + "or scalar") + if indices.size == 1: + index = indices.item() + if index < -N or index > N: + raise IndexError(f"index {obj} is out of bounds for axis {axis} " + f"with size {N}") + if (index < 0): + index += N + + # There are some object array corner cases here, but we cannot avoid + # that: + values = array(values, copy=None, ndmin=arr.ndim, dtype=arr.dtype) + if indices.ndim == 0: + # broadcasting is very different here, since a[:,0,:] = ... behaves + # very different from a[:,[0],:] = ...! This changes values so that + # it works likes the second case. (here a[:,0:1,:]) + values = np.moveaxis(values, 0, axis) + numnew = values.shape[axis] + newshape[axis] += numnew + new = empty(newshape, arr.dtype, arrorder) + slobj[axis] = slice(None, index) + new[tuple(slobj)] = arr[tuple(slobj)] + slobj[axis] = slice(index, index + numnew) + new[tuple(slobj)] = values + slobj[axis] = slice(index + numnew, None) + slobj2 = [slice(None)] * ndim + slobj2[axis] = slice(index, None) + new[tuple(slobj)] = arr[tuple(slobj2)] + + return conv.wrap(new, to_scalar=False) + + elif indices.size == 0 and not isinstance(obj, np.ndarray): + # Can safely cast the empty list to intp + indices = indices.astype(intp) + + indices[indices < 0] += N + + numnew = len(indices) + order = indices.argsort(kind='mergesort') # stable sort + indices[order] += np.arange(numnew) + + newshape[axis] += numnew + old_mask = ones(newshape[axis], dtype=bool) + old_mask[indices] = False + + new = empty(newshape, arr.dtype, arrorder) + slobj2 = [slice(None)] * ndim + slobj[axis] = indices + slobj2[axis] = old_mask + new[tuple(slobj)] = values + new[tuple(slobj2)] = arr + + return conv.wrap(new, to_scalar=False) + + +def _append_dispatcher(arr, values, axis=None): + return (arr, values) + + +@array_function_dispatch(_append_dispatcher) +def append(arr, values, axis=None): + """ + Append values to the end of an array. + + Parameters + ---------- + arr : array_like + Values are appended to a copy of this array. + values : array_like + These values are appended to a copy of `arr`. It must be of the + correct shape (the same shape as `arr`, excluding `axis`). If + `axis` is not specified, `values` can be any shape and will be + flattened before use. + axis : int, optional + The axis along which `values` are appended. If `axis` is not + given, both `arr` and `values` are flattened before use. + + Returns + ------- + append : ndarray + A copy of `arr` with `values` appended to `axis`. Note that + `append` does not occur in-place: a new array is allocated and + filled. If `axis` is None, `out` is a flattened array. + + See Also + -------- + insert : Insert elements into an array. + delete : Delete elements from an array. + + Examples + -------- + >>> import numpy as np + >>> np.append([1, 2, 3], [[4, 5, 6], [7, 8, 9]]) + array([1, 2, 3, ..., 7, 8, 9]) + + When `axis` is specified, `values` must have the correct shape. + + >>> np.append([[1, 2, 3], [4, 5, 6]], [[7, 8, 9]], axis=0) + array([[1, 2, 3], + [4, 5, 6], + [7, 8, 9]]) + + >>> np.append([[1, 2, 3], [4, 5, 6]], [7, 8, 9], axis=0) + Traceback (most recent call last): + ... + ValueError: all the input arrays must have same number of dimensions, but + the array at index 0 has 2 dimension(s) and the array at index 1 has 1 + dimension(s) + + >>> a = np.array([1, 2], dtype=int) + >>> c = np.append(a, []) + >>> c + array([1., 2.]) + >>> c.dtype + float64 + + Default dtype for empty ndarrays is `float64` thus making the output of dtype + `float64` when appended with dtype `int64` + + """ + arr = asanyarray(arr) + if axis is None: + if arr.ndim != 1: + arr = arr.ravel() + values = ravel(values) + axis = arr.ndim - 1 + return concatenate((arr, values), axis=axis) + + +def _digitize_dispatcher(x, bins, right=None): + return (x, bins) + + +@array_function_dispatch(_digitize_dispatcher) +def digitize(x, bins, right=False): + """ + Return the indices of the bins to which each value in input array belongs. + + ========= ============= ============================ + `right` order of bins returned index `i` satisfies + ========= ============= ============================ + ``False`` increasing ``bins[i-1] <= x < bins[i]`` + ``True`` increasing ``bins[i-1] < x <= bins[i]`` + ``False`` decreasing ``bins[i-1] > x >= bins[i]`` + ``True`` decreasing ``bins[i-1] >= x > bins[i]`` + ========= ============= ============================ + + If values in `x` are beyond the bounds of `bins`, 0 or ``len(bins)`` is + returned as appropriate. + + Parameters + ---------- + x : array_like + Input array to be binned. Prior to NumPy 1.10.0, this array had to + be 1-dimensional, but can now have any shape. + bins : array_like + Array of bins. It has to be 1-dimensional and monotonic. + right : bool, optional + Indicating whether the intervals include the right or the left bin + edge. Default behavior is (right==False) indicating that the interval + does not include the right edge. The left bin end is open in this + case, i.e., bins[i-1] <= x < bins[i] is the default behavior for + monotonically increasing bins. + + Returns + ------- + indices : ndarray of ints + Output array of indices, of same shape as `x`. + + Raises + ------ + ValueError + If `bins` is not monotonic. + TypeError + If the type of the input is complex. + + See Also + -------- + bincount, histogram, unique, searchsorted + + Notes + ----- + If values in `x` are such that they fall outside the bin range, + attempting to index `bins` with the indices that `digitize` returns + will result in an IndexError. + + .. versionadded:: 1.10.0 + + `numpy.digitize` is implemented in terms of `numpy.searchsorted`. + This means that a binary search is used to bin the values, which scales + much better for larger number of bins than the previous linear search. + It also removes the requirement for the input array to be 1-dimensional. + + For monotonically *increasing* `bins`, the following are equivalent:: + + np.digitize(x, bins, right=True) + np.searchsorted(bins, x, side='left') + + Note that as the order of the arguments are reversed, the side must be too. + The `searchsorted` call is marginally faster, as it does not do any + monotonicity checks. Perhaps more importantly, it supports all dtypes. + + Examples + -------- + >>> import numpy as np + >>> x = np.array([0.2, 6.4, 3.0, 1.6]) + >>> bins = np.array([0.0, 1.0, 2.5, 4.0, 10.0]) + >>> inds = np.digitize(x, bins) + >>> inds + array([1, 4, 3, 2]) + >>> for n in range(x.size): + ... print(bins[inds[n]-1], "<=", x[n], "<", bins[inds[n]]) + ... + 0.0 <= 0.2 < 1.0 + 4.0 <= 6.4 < 10.0 + 2.5 <= 3.0 < 4.0 + 1.0 <= 1.6 < 2.5 + + >>> x = np.array([1.2, 10.0, 12.4, 15.5, 20.]) + >>> bins = np.array([0, 5, 10, 15, 20]) + >>> np.digitize(x,bins,right=True) + array([1, 2, 3, 4, 4]) + >>> np.digitize(x,bins,right=False) + array([1, 3, 3, 4, 5]) + """ + x = _nx.asarray(x) + bins = _nx.asarray(bins) + + # here for compatibility, searchsorted below is happy to take this + if np.issubdtype(x.dtype, _nx.complexfloating): + raise TypeError("x may not be complex") + + mono = _monotonicity(bins) + if mono == 0: + raise ValueError("bins must be monotonically increasing or decreasing") + + # this is backwards because the arguments below are swapped + side = 'left' if right else 'right' + if mono == -1: + # reverse the bins, and invert the results + return len(bins) - _nx.searchsorted(bins[::-1], x, side=side) + else: + return _nx.searchsorted(bins, x, side=side) diff --git a/python/user_packages/Python313/site-packages/numpy/lib/_function_base_impl.pyi b/python/user_packages/Python313/site-packages/numpy/lib/_function_base_impl.pyi new file mode 100644 index 0000000000000000000000000000000000000000..0012dccf2ec0d3542d36f9ccf1f7686dcd549679 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/lib/_function_base_impl.pyi @@ -0,0 +1,2324 @@ +from _typeshed import ConvertibleToInt, Incomplete +from collections.abc import Callable, Iterable, Sequence +from typing import ( + Any, + Concatenate, + Literal as L, + Never, + ParamSpec, + Protocol, + SupportsIndex, + SupportsInt, + TypeAlias, + overload, + type_check_only, +) +from typing_extensions import TypeIs, TypeVar + +import numpy as np +from numpy import _OrderKACF +from numpy._core.multiarray import bincount +from numpy._globals import _NoValueType +from numpy._typing import ( + ArrayLike, + DTypeLike, + NDArray, + _ArrayLike, + _ArrayLikeBool_co, + _ArrayLikeComplex_co, + _ArrayLikeFloat_co, + _ArrayLikeInt_co, + _ArrayLikeNumber_co, + _ArrayLikeObject_co, + _ComplexLike_co, + _DTypeLike, + _FloatLike_co, + _NestedSequence as _SeqND, + _NumberLike_co, + _ScalarLike_co, + _ShapeLike, + _SupportsArray, +) + +__all__ = [ + "select", + "piecewise", + "trim_zeros", + "copy", + "iterable", + "percentile", + "diff", + "gradient", + "angle", + "unwrap", + "sort_complex", + "flip", + "rot90", + "extract", + "place", + "vectorize", + "asarray_chkfinite", + "average", + "bincount", + "digitize", + "cov", + "corrcoef", + "median", + "sinc", + "hamming", + "hanning", + "bartlett", + "blackman", + "kaiser", + "trapezoid", + "i0", + "meshgrid", + "delete", + "insert", + "append", + "interp", + "quantile", +] + +_T = TypeVar("_T") +_T_co = TypeVar("_T_co", covariant=True) +# The `{}ss` suffix refers to the PEP 695 (Python 3.12) `ParamSpec` syntax, `**P`. +_Tss = ParamSpec("_Tss") + +_ScalarT = TypeVar("_ScalarT", bound=np.generic) +_ScalarT1 = TypeVar("_ScalarT1", bound=np.generic) +_ScalarT2 = TypeVar("_ScalarT2", bound=np.generic) +_FloatingT = TypeVar("_FloatingT", bound=np.floating) +_InexactT = TypeVar("_InexactT", bound=np.inexact) +_InexactTimeT = TypeVar("_InexactTimeT", bound=np.inexact | np.timedelta64) +_InexactDateTimeT = TypeVar("_InexactDateTimeT", bound=np.inexact | np.timedelta64 | np.datetime64) +_ScalarNumericT = TypeVar("_ScalarNumericT", bound=np.inexact | np.timedelta64 | np.object_) +_AnyDoubleT = TypeVar("_AnyDoubleT", bound=np.float64 | np.longdouble | np.complex128 | np.clongdouble) + +_ArrayT = TypeVar("_ArrayT", bound=np.ndarray) +_ArrayFloatingT = TypeVar("_ArrayFloatingT", bound=NDArray[np.floating]) +_ArrayFloatObjT = TypeVar("_ArrayFloatObjT", bound=NDArray[np.floating | np.object_]) +_ArrayComplexT = TypeVar("_ArrayComplexT", bound=NDArray[np.complexfloating]) +_ArrayInexactT = TypeVar("_ArrayInexactT", bound=NDArray[np.inexact]) +_ArrayNumericT = TypeVar("_ArrayNumericT", bound=NDArray[np.inexact | np.timedelta64 | np.object_]) + +_ArrayLike1D: TypeAlias = _SupportsArray[np.dtype[_ScalarT]] | Sequence[_ScalarT] + +_ShapeT = TypeVar("_ShapeT", bound=tuple[int, ...]) + +_integer_co: TypeAlias = np.integer | np.bool +_float64_co: TypeAlias = np.float64 | _integer_co +_floating_co: TypeAlias = np.floating | _integer_co + +# non-trivial scalar-types that will become `complex128` in `sort_complex()`, +# i.e. all numeric scalar types except for `[u]int{8,16} | longdouble` +_SortsToComplex128: TypeAlias = ( + np.bool + | np.int32 + | np.uint32 + | np.int64 + | np.uint64 + | np.float16 + | np.float32 + | np.float64 + | np.timedelta64 + | np.object_ +) + +_Array: TypeAlias = np.ndarray[_ShapeT, np.dtype[_ScalarT]] +_Array0D: TypeAlias = np.ndarray[tuple[()], np.dtype[_ScalarT]] +_Array1D: TypeAlias = np.ndarray[tuple[int], np.dtype[_ScalarT]] +_Array2D: TypeAlias = np.ndarray[tuple[int, int], np.dtype[_ScalarT]] +_Array3D: TypeAlias = np.ndarray[tuple[int, int, int], np.dtype[_ScalarT]] +_ArrayMax2D: TypeAlias = np.ndarray[tuple[int] | tuple[int, int], np.dtype[_ScalarT]] +# workaround for mypy and pyright not following the typing spec for overloads +_ArrayNoD: TypeAlias = np.ndarray[tuple[Never, Never, Never, Never], np.dtype[_ScalarT]] + +_Seq1D: TypeAlias = Sequence[_T] +_Seq2D: TypeAlias = Sequence[Sequence[_T]] +_Seq3D: TypeAlias = Sequence[Sequence[Sequence[_T]]] +_ListSeqND: TypeAlias = list[_T] | _SeqND[list[_T]] + +_Tuple2: TypeAlias = tuple[_T, _T] +_Tuple3: TypeAlias = tuple[_T, _T, _T] +_Tuple4: TypeAlias = tuple[_T, _T, _T, _T] + +_Mesh1: TypeAlias = tuple[_Array1D[_ScalarT]] +_Mesh2: TypeAlias = tuple[_Array2D[_ScalarT], _Array2D[_ScalarT1]] +_Mesh3: TypeAlias = tuple[_Array3D[_ScalarT], _Array3D[_ScalarT1], _Array3D[_ScalarT2]] + +_IndexLike: TypeAlias = slice | _ArrayLikeInt_co + +_Indexing: TypeAlias = L["ij", "xy"] +_InterpolationMethod = L[ + "inverted_cdf", + "averaged_inverted_cdf", + "closest_observation", + "interpolated_inverted_cdf", + "hazen", + "weibull", + "linear", + "median_unbiased", + "normal_unbiased", + "lower", + "higher", + "midpoint", + "nearest", +] + +# The resulting value will be used as `y[cond] = func(vals, *args, **kw)`, so in can +# return any (usually 1d) array-like or scalar-like compatible with the input. +_PiecewiseFunction: TypeAlias = Callable[Concatenate[NDArray[_ScalarT], _Tss], ArrayLike] +_PiecewiseFunctions: TypeAlias = _SizedIterable[_PiecewiseFunction[_ScalarT, _Tss] | _ScalarLike_co] + +@type_check_only +class _TrimZerosSequence(Protocol[_T_co]): + def __len__(self, /) -> int: ... + @overload + def __getitem__(self, key: int, /) -> object: ... + @overload + def __getitem__(self, key: slice, /) -> _T_co: ... + +@type_check_only +class _SupportsRMulFloat(Protocol[_T_co]): + def __rmul__(self, other: float, /) -> _T_co: ... + +@type_check_only +class _SizedIterable(Protocol[_T_co]): + def __iter__(self) -> Iterable[_T_co]: ... + def __len__(self) -> int: ... + +### + +class vectorize: + __doc__: str | None + __module__: L["numpy"] = "numpy" + pyfunc: Callable[..., Incomplete] + cache: bool + signature: str | None + otypes: str | None + excluded: set[int | str] + + def __init__( + self, + /, + pyfunc: Callable[..., Incomplete] | _NoValueType = ..., # = _NoValue + otypes: str | Iterable[DTypeLike] | None = None, + doc: str | None = None, + excluded: Iterable[int | str] | None = None, + cache: bool = False, + signature: str | None = None, + ) -> None: ... + def __call__(self, /, *args: Incomplete, **kwargs: Incomplete) -> Incomplete: ... + +@overload +def rot90(m: _ArrayT, k: int = 1, axes: tuple[int, int] = (0, 1)) -> _ArrayT: ... +@overload +def rot90(m: _ArrayLike[_ScalarT], k: int = 1, axes: tuple[int, int] = (0, 1)) -> NDArray[_ScalarT]: ... +@overload +def rot90(m: ArrayLike, k: int = 1, axes: tuple[int, int] = (0, 1)) -> NDArray[Incomplete]: ... + +# NOTE: Technically `flip` also accept scalars, but that has no effect and complicates +# the overloads significantly, so we ignore that case here. +@overload +def flip(m: _ArrayT, axis: int | tuple[int, ...] | None = None) -> _ArrayT: ... +@overload +def flip(m: _ArrayLike[_ScalarT], axis: int | tuple[int, ...] | None = None) -> NDArray[_ScalarT]: ... +@overload +def flip(m: ArrayLike, axis: int | tuple[int, ...] | None = None) -> NDArray[Incomplete]: ... + +# +def iterable(y: object) -> TypeIs[Iterable[Any]]: ... + +# NOTE: This assumes that if `axis` is given the input is at least 2d, and will +# therefore always return an array. +# NOTE: This assumes that if `keepdims=True` the input is at least 1d, and will +# therefore always return an array. +@overload # inexact array, keepdims=True +def average( + a: _ArrayInexactT, + axis: int | tuple[int, ...] | None = None, + weights: _ArrayLikeNumber_co | None = None, + returned: L[False] = False, + *, + keepdims: L[True], +) -> _ArrayInexactT: ... +@overload # inexact array, returned=True keepdims=True +def average( + a: _ArrayInexactT, + axis: int | tuple[int, ...] | None = None, + weights: _ArrayLikeNumber_co | None = None, + *, + returned: L[True], + keepdims: L[True], +) -> _Tuple2[_ArrayInexactT]: ... +@overload # inexact array-like, axis=None +def average( + a: _ArrayLike[_InexactT], + axis: None = None, + weights: _ArrayLikeNumber_co | None = None, + returned: L[False] = False, + *, + keepdims: L[False] | _NoValueType = ..., +) -> _InexactT: ... +@overload # inexact array-like, axis= +def average( + a: _ArrayLike[_InexactT], + axis: int | tuple[int, ...], + weights: _ArrayLikeNumber_co | None = None, + returned: L[False] = False, + *, + keepdims: L[False] | _NoValueType = ..., +) -> NDArray[_InexactT]: ... +@overload # inexact array-like, keepdims=True +def average( + a: _ArrayLike[_InexactT], + axis: int | tuple[int, ...] | None = None, + weights: _ArrayLikeNumber_co | None = None, + returned: L[False] = False, + *, + keepdims: L[True], +) -> NDArray[_InexactT]: ... +@overload # inexact array-like, axis=None, returned=True +def average( + a: _ArrayLike[_InexactT], + axis: None = None, + weights: _ArrayLikeNumber_co | None = None, + *, + returned: L[True], + keepdims: L[False] | _NoValueType = ..., +) -> _Tuple2[_InexactT]: ... +@overload # inexact array-like, axis=, returned=True +def average( + a: _ArrayLike[_InexactT], + axis: int | tuple[int, ...], + weights: _ArrayLikeNumber_co | None = None, + *, + returned: L[True], + keepdims: L[False] | _NoValueType = ..., +) -> _Tuple2[NDArray[_InexactT]]: ... +@overload # inexact array-like, returned=True, keepdims=True +def average( + a: _ArrayLike[_InexactT], + axis: int | tuple[int, ...] | None = None, + weights: _ArrayLikeNumber_co | None = None, + *, + returned: L[True], + keepdims: L[True], +) -> _Tuple2[NDArray[_InexactT]]: ... +@overload # bool or integer array-like, axis=None +def average( + a: _SeqND[float] | _ArrayLikeInt_co, + axis: None = None, + weights: _ArrayLikeFloat_co | None = None, + returned: L[False] = False, + *, + keepdims: L[False] | _NoValueType = ..., +) -> np.float64: ... +@overload # bool or integer array-like, axis= +def average( + a: _SeqND[float] | _ArrayLikeInt_co, + axis: int | tuple[int, ...], + weights: _ArrayLikeFloat_co | None = None, + returned: L[False] = False, + *, + keepdims: L[False] | _NoValueType = ..., +) -> NDArray[np.float64]: ... +@overload # bool or integer array-like, keepdims=True +def average( + a: _SeqND[float] | _ArrayLikeInt_co, + axis: int | tuple[int, ...] | None = None, + weights: _ArrayLikeFloat_co | None = None, + returned: L[False] = False, + *, + keepdims: L[True], +) -> NDArray[np.float64]: ... +@overload # bool or integer array-like, axis=None, returned=True +def average( + a: _SeqND[float] | _ArrayLikeInt_co, + axis: None = None, + weights: _ArrayLikeFloat_co | None = None, + *, + returned: L[True], + keepdims: L[False] | _NoValueType = ..., +) -> _Tuple2[np.float64]: ... +@overload # bool or integer array-like, axis=, returned=True +def average( + a: _SeqND[float] | _ArrayLikeInt_co, + axis: int | tuple[int, ...], + weights: _ArrayLikeFloat_co | None = None, + *, + returned: L[True], + keepdims: L[False] | _NoValueType = ..., +) -> _Tuple2[NDArray[np.float64]]: ... +@overload # bool or integer array-like, returned=True, keepdims=True +def average( + a: _SeqND[float] | _ArrayLikeInt_co, + axis: int | tuple[int, ...] | None = None, + weights: _ArrayLikeFloat_co | None = None, + *, + returned: L[True], + keepdims: L[True], +) -> _Tuple2[NDArray[np.float64]]: ... +@overload # complex array-like, axis=None +def average( + a: _ListSeqND[complex], + axis: None = None, + weights: _ArrayLikeComplex_co | None = None, + returned: L[False] = False, + *, + keepdims: L[False] | _NoValueType = ..., +) -> np.complex128: ... +@overload # complex array-like, axis= +def average( + a: _ListSeqND[complex], + axis: int | tuple[int, ...], + weights: _ArrayLikeComplex_co | None = None, + returned: L[False] = False, + *, + keepdims: L[False] | _NoValueType = ..., +) -> NDArray[np.complex128]: ... +@overload # complex array-like, keepdims=True +def average( + a: _ListSeqND[complex], + axis: int | tuple[int, ...] | None = None, + weights: _ArrayLikeComplex_co | None = None, + returned: L[False] = False, + *, + keepdims: L[True], +) -> NDArray[np.complex128]: ... +@overload # complex array-like, axis=None, returned=True +def average( + a: _ListSeqND[complex], + axis: None = None, + weights: _ArrayLikeComplex_co | None = None, + *, + returned: L[True], + keepdims: L[False] | _NoValueType = ..., +) -> _Tuple2[np.complex128]: ... +@overload # complex array-like, axis=, returned=True +def average( + a: _ListSeqND[complex], + axis: int | tuple[int, ...], + weights: _ArrayLikeComplex_co | None = None, + *, + returned: L[True], + keepdims: L[False] | _NoValueType = ..., +) -> _Tuple2[NDArray[np.complex128]]: ... +@overload # complex array-like, keepdims=True, returned=True +def average( + a: _ListSeqND[complex], + axis: int | tuple[int, ...] | None = None, + weights: _ArrayLikeComplex_co | None = None, + *, + returned: L[True], + keepdims: L[True], +) -> _Tuple2[NDArray[np.complex128]]: ... +@overload # unknown, axis=None +def average( + a: _ArrayLikeNumber_co | _ArrayLikeObject_co, + axis: None = None, + weights: _ArrayLikeNumber_co | None = None, + returned: L[False] = False, + *, + keepdims: L[False] | _NoValueType = ..., +) -> Any: ... +@overload # unknown, axis= +def average( + a: _ArrayLikeNumber_co | _ArrayLikeObject_co, + axis: int | tuple[int, ...], + weights: _ArrayLikeNumber_co | None = None, + returned: L[False] = False, + *, + keepdims: L[False] | _NoValueType = ..., +) -> np.ndarray: ... +@overload # unknown, keepdims=True +def average( + a: _ArrayLikeNumber_co | _ArrayLikeObject_co, + axis: int | tuple[int, ...] | None = None, + weights: _ArrayLikeNumber_co | None = None, + returned: L[False] = False, + *, + keepdims: L[True], +) -> np.ndarray: ... +@overload # unknown, axis=None, returned=True +def average( + a: _ArrayLikeNumber_co | _ArrayLikeObject_co, + axis: None = None, + weights: _ArrayLikeNumber_co | None = None, + *, + returned: L[True], + keepdims: L[False] | _NoValueType = ..., +) -> _Tuple2[Any]: ... +@overload # unknown, axis=, returned=True +def average( + a: _ArrayLikeNumber_co | _ArrayLikeObject_co, + axis: int | tuple[int, ...], + weights: _ArrayLikeNumber_co | None = None, + *, + returned: L[True], + keepdims: L[False] | _NoValueType = ..., +) -> _Tuple2[np.ndarray]: ... +@overload # unknown, returned=True, keepdims=True +def average( + a: _ArrayLikeNumber_co | _ArrayLikeObject_co, + axis: int | tuple[int, ...] | None = None, + weights: _ArrayLikeNumber_co | None = None, + *, + returned: L[True], + keepdims: L[True], +) -> _Tuple2[np.ndarray]: ... + +# +@overload +def asarray_chkfinite(a: _ArrayT, dtype: None = None, order: _OrderKACF = None) -> _ArrayT: ... +@overload +def asarray_chkfinite( + a: np.ndarray[_ShapeT], dtype: _DTypeLike[_ScalarT], order: _OrderKACF = None +) -> _Array[_ShapeT, _ScalarT]: ... +@overload +def asarray_chkfinite(a: _ArrayLike[_ScalarT], dtype: None = None, order: _OrderKACF = None) -> NDArray[_ScalarT]: ... +@overload +def asarray_chkfinite(a: object, dtype: _DTypeLike[_ScalarT], order: _OrderKACF = None) -> NDArray[_ScalarT]: ... +@overload +def asarray_chkfinite(a: object, dtype: DTypeLike | None = None, order: _OrderKACF = None) -> NDArray[Incomplete]: ... + +# NOTE: Contrary to the documentation, scalars are also accepted and treated as +# `[condlist]`. And even though the documentation says these should be boolean, in +# practice anything that `np.array(condlist, dtype=bool)` accepts will work, i.e. any +# array-like. +@overload +def piecewise( + x: _Array[_ShapeT, _ScalarT], + condlist: ArrayLike, + funclist: _PiecewiseFunctions[Any, _Tss], + *args: _Tss.args, + **kw: _Tss.kwargs, +) -> _Array[_ShapeT, _ScalarT]: ... +@overload +def piecewise( + x: _ArrayLike[_ScalarT], + condlist: ArrayLike, + funclist: _PiecewiseFunctions[Any, _Tss], + *args: _Tss.args, + **kw: _Tss.kwargs, +) -> NDArray[_ScalarT]: ... +@overload +def piecewise( + x: ArrayLike, + condlist: ArrayLike, + funclist: _PiecewiseFunctions[_ScalarT, _Tss], + *args: _Tss.args, + **kw: _Tss.kwargs, +) -> NDArray[_ScalarT]: ... + +# NOTE: condition is usually boolean, but anything with zero/non-zero semantics works +@overload +def extract(condition: ArrayLike, arr: _ArrayLike[_ScalarT]) -> _Array1D[_ScalarT]: ... +@overload +def extract(condition: ArrayLike, arr: _SeqND[bool]) -> _Array1D[np.bool]: ... +@overload +def extract(condition: ArrayLike, arr: _ListSeqND[int]) -> _Array1D[np.int_]: ... +@overload +def extract(condition: ArrayLike, arr: _ListSeqND[float]) -> _Array1D[np.float64]: ... +@overload +def extract(condition: ArrayLike, arr: _ListSeqND[complex]) -> _Array1D[np.complex128]: ... +@overload +def extract(condition: ArrayLike, arr: _SeqND[bytes]) -> _Array1D[np.bytes_]: ... +@overload +def extract(condition: ArrayLike, arr: _SeqND[str]) -> _Array1D[np.str_]: ... +@overload +def extract(condition: ArrayLike, arr: ArrayLike) -> _Array1D[Incomplete]: ... + +# NOTE: unlike `extract`, passing non-boolean conditions for `condlist` will raise an +# error at runtime +@overload +def select( + condlist: _SizedIterable[_ArrayLikeBool_co], + choicelist: Sequence[_ArrayT], + default: ArrayLike = 0, +) -> _ArrayT: ... +@overload +def select( + condlist: _SizedIterable[_ArrayLikeBool_co], + choicelist: Sequence[_ArrayLike[_ScalarT]] | NDArray[_ScalarT], + default: ArrayLike = 0, +) -> NDArray[_ScalarT]: ... +@overload +def select( + condlist: _SizedIterable[_ArrayLikeBool_co], + choicelist: Sequence[ArrayLike], + default: ArrayLike = 0, +) -> np.ndarray: ... + +# keep roughly in sync with `ma.core.copy` +@overload +def copy(a: _ArrayT, order: _OrderKACF, subok: L[True]) -> _ArrayT: ... +@overload +def copy(a: _ArrayT, order: _OrderKACF = "K", *, subok: L[True]) -> _ArrayT: ... +@overload +def copy(a: _ArrayLike[_ScalarT], order: _OrderKACF = "K", subok: L[False] = False) -> NDArray[_ScalarT]: ... +@overload +def copy(a: ArrayLike, order: _OrderKACF = "K", subok: L[False] = False) -> NDArray[Incomplete]: ... + +# +@overload # ?d, known inexact scalar-type +def gradient( + f: _ArrayNoD[_InexactTimeT], + *varargs: _ArrayLikeNumber_co, + axis: _ShapeLike | None = None, + edge_order: L[1, 2] = 1, + # `| Any` instead of ` | tuple` is returned to avoid several mypy_primer errors +) -> _Array1D[_InexactTimeT] | Any: ... +@overload # 1d, known inexact scalar-type +def gradient( + f: _Array1D[_InexactTimeT], + *varargs: _ArrayLikeNumber_co, + axis: _ShapeLike | None = None, + edge_order: L[1, 2] = 1, +) -> _Array1D[_InexactTimeT]: ... +@overload # 2d, known inexact scalar-type +def gradient( + f: _Array2D[_InexactTimeT], + *varargs: _ArrayLikeNumber_co, + axis: _ShapeLike | None = None, + edge_order: L[1, 2] = 1, +) -> _Mesh2[_InexactTimeT, _InexactTimeT]: ... +@overload # 3d, known inexact scalar-type +def gradient( + f: _Array3D[_InexactTimeT], + *varargs: _ArrayLikeNumber_co, + axis: _ShapeLike | None = None, + edge_order: L[1, 2] = 1, +) -> _Mesh3[_InexactTimeT, _InexactTimeT, _InexactTimeT]: ... +@overload # ?d, datetime64 scalar-type +def gradient( + f: _ArrayNoD[np.datetime64], + *varargs: _ArrayLikeNumber_co, + axis: _ShapeLike | None = None, + edge_order: L[1, 2] = 1, +) -> _Array1D[np.timedelta64] | tuple[NDArray[np.timedelta64], ...]: ... +@overload # 1d, datetime64 scalar-type +def gradient( + f: _Array1D[np.datetime64], + *varargs: _ArrayLikeNumber_co, + axis: _ShapeLike | None = None, + edge_order: L[1, 2] = 1, +) -> _Array1D[np.timedelta64]: ... +@overload # 2d, datetime64 scalar-type +def gradient( + f: _Array2D[np.datetime64], + *varargs: _ArrayLikeNumber_co, + axis: _ShapeLike | None = None, + edge_order: L[1, 2] = 1, +) -> _Mesh2[np.timedelta64, np.timedelta64]: ... +@overload # 3d, datetime64 scalar-type +def gradient( + f: _Array3D[np.datetime64], + *varargs: _ArrayLikeNumber_co, + axis: _ShapeLike | None = None, + edge_order: L[1, 2] = 1, +) -> _Mesh3[np.timedelta64, np.timedelta64, np.timedelta64]: ... +@overload # 1d float-like +def gradient( + f: _Seq1D[float], + *varargs: _ArrayLikeNumber_co, + axis: _ShapeLike | None = None, + edge_order: L[1, 2] = 1, +) -> _Array1D[np.float64]: ... +@overload # 2d float-like +def gradient( + f: _Seq2D[float], + *varargs: _ArrayLikeNumber_co, + axis: _ShapeLike | None = None, + edge_order: L[1, 2] = 1, +) -> _Mesh2[np.float64, np.float64]: ... +@overload # 3d float-like +def gradient( + f: _Seq3D[float], + *varargs: _ArrayLikeNumber_co, + axis: _ShapeLike | None = None, + edge_order: L[1, 2] = 1, +) -> _Mesh3[np.float64, np.float64, np.float64]: ... +@overload # 1d complex-like (the `list` avoids overlap with the float-like overload) +def gradient( + f: list[complex], + *varargs: _ArrayLikeNumber_co, + axis: _ShapeLike | None = None, + edge_order: L[1, 2] = 1, +) -> _Array1D[np.complex128]: ... +@overload # 2d float-like +def gradient( + f: _Seq1D[list[complex]], + *varargs: _ArrayLikeNumber_co, + axis: _ShapeLike | None = None, + edge_order: L[1, 2] = 1, +) -> _Mesh2[np.complex128, np.complex128]: ... +@overload # 3d float-like +def gradient( + f: _Seq2D[list[complex]], + *varargs: _ArrayLikeNumber_co, + axis: _ShapeLike | None = None, + edge_order: L[1, 2] = 1, +) -> _Mesh3[np.complex128, np.complex128, np.complex128]: ... +@overload # fallback +def gradient( + f: ArrayLike, + *varargs: _ArrayLikeNumber_co, + axis: _ShapeLike | None = None, + edge_order: L[1, 2] = 1, +) -> Incomplete: ... + +# +@overload # n == 0; return input unchanged +def diff( + a: _T, + n: L[0], + axis: SupportsIndex = -1, + prepend: ArrayLike | _NoValueType = ..., # = _NoValue + append: ArrayLike | _NoValueType = ..., # = _NoValue +) -> _T: ... +@overload # known array-type +def diff( + a: _ArrayNumericT, + n: int = 1, + axis: SupportsIndex = -1, + prepend: ArrayLike | _NoValueType = ..., + append: ArrayLike | _NoValueType = ..., +) -> _ArrayNumericT: ... +@overload # known shape, datetime64 +def diff( + a: _Array[_ShapeT, np.datetime64], + n: int = 1, + axis: SupportsIndex = -1, + prepend: ArrayLike | _NoValueType = ..., + append: ArrayLike | _NoValueType = ..., +) -> _Array[_ShapeT, np.timedelta64]: ... +@overload # unknown shape, known scalar-type +def diff( + a: _ArrayLike[_ScalarNumericT], + n: int = 1, + axis: SupportsIndex = -1, + prepend: ArrayLike | _NoValueType = ..., + append: ArrayLike | _NoValueType = ..., +) -> NDArray[_ScalarNumericT]: ... +@overload # unknown shape, datetime64 +def diff( + a: _ArrayLike[np.datetime64], + n: int = 1, + axis: SupportsIndex = -1, + prepend: ArrayLike | _NoValueType = ..., + append: ArrayLike | _NoValueType = ..., +) -> NDArray[np.timedelta64]: ... +@overload # 1d int +def diff( + a: _Seq1D[int], + n: int = 1, + axis: SupportsIndex = -1, + prepend: ArrayLike | _NoValueType = ..., + append: ArrayLike | _NoValueType = ..., +) -> _Array1D[np.int_]: ... +@overload # 2d int +def diff( + a: _Seq2D[int], + n: int = 1, + axis: SupportsIndex = -1, + prepend: ArrayLike | _NoValueType = ..., + append: ArrayLike | _NoValueType = ..., +) -> _Array2D[np.int_]: ... +@overload # 1d float (the `list` avoids overlap with the `int` overloads) +def diff( + a: list[float], + n: int = 1, + axis: SupportsIndex = -1, + prepend: ArrayLike | _NoValueType = ..., + append: ArrayLike | _NoValueType = ..., +) -> _Array1D[np.float64]: ... +@overload # 2d float +def diff( + a: _Seq1D[list[float]], + n: int = 1, + axis: SupportsIndex = -1, + prepend: ArrayLike | _NoValueType = ..., + append: ArrayLike | _NoValueType = ..., +) -> _Array2D[np.float64]: ... +@overload # 1d complex (the `list` avoids overlap with the `int` overloads) +def diff( + a: list[complex], + n: int = 1, + axis: SupportsIndex = -1, + prepend: ArrayLike | _NoValueType = ..., + append: ArrayLike | _NoValueType = ..., +) -> _Array1D[np.complex128]: ... +@overload # 2d complex +def diff( + a: _Seq1D[list[complex]], + n: int = 1, + axis: SupportsIndex = -1, + prepend: ArrayLike | _NoValueType = ..., + append: ArrayLike | _NoValueType = ..., +) -> _Array2D[np.complex128]: ... +@overload # unknown shape, unknown scalar-type +def diff( + a: ArrayLike, + n: int = 1, + axis: SupportsIndex = -1, + prepend: ArrayLike | _NoValueType = ..., + append: ArrayLike | _NoValueType = ..., +) -> NDArray[Incomplete]: ... + +# +@overload # float scalar +def interp( + x: _FloatLike_co, + xp: _ArrayLikeFloat_co, + fp: _ArrayLikeFloat_co, + left: _FloatLike_co | None = None, + right: _FloatLike_co | None = None, + period: _FloatLike_co | None = None, +) -> np.float64: ... +@overload # complex scalar +def interp( + x: _FloatLike_co, + xp: _ArrayLikeFloat_co, + fp: _ArrayLike1D[np.complexfloating] | list[complex], + left: _NumberLike_co | None = None, + right: _NumberLike_co | None = None, + period: _FloatLike_co | None = None, +) -> np.complex128: ... +@overload # float array +def interp( + x: _Array[_ShapeT, _floating_co], + xp: _ArrayLikeFloat_co, + fp: _ArrayLikeFloat_co, + left: _FloatLike_co | None = None, + right: _FloatLike_co | None = None, + period: _FloatLike_co | None = None, +) -> _Array[_ShapeT, np.float64]: ... +@overload # complex array +def interp( + x: _Array[_ShapeT, _floating_co], + xp: _ArrayLikeFloat_co, + fp: _ArrayLike1D[np.complexfloating] | list[complex], + left: _NumberLike_co | None = None, + right: _NumberLike_co | None = None, + period: _FloatLike_co | None = None, +) -> _Array[_ShapeT, np.complex128]: ... +@overload # float sequence +def interp( + x: _Seq1D[_FloatLike_co], + xp: _ArrayLikeFloat_co, + fp: _ArrayLikeFloat_co, + left: _FloatLike_co | None = None, + right: _FloatLike_co | None = None, + period: _FloatLike_co | None = None, +) -> _Array1D[np.float64]: ... +@overload # complex sequence +def interp( + x: _Seq1D[_FloatLike_co], + xp: _ArrayLikeFloat_co, + fp: _ArrayLike1D[np.complexfloating] | list[complex], + left: _NumberLike_co | None = None, + right: _NumberLike_co | None = None, + period: _FloatLike_co | None = None, +) -> _Array1D[np.complex128]: ... +@overload # float array-like +def interp( + x: _SeqND[_FloatLike_co], + xp: _ArrayLikeFloat_co, + fp: _ArrayLikeFloat_co, + left: _FloatLike_co | None = None, + right: _FloatLike_co | None = None, + period: _FloatLike_co | None = None, +) -> NDArray[np.float64]: ... +@overload # complex array-like +def interp( + x: _SeqND[_FloatLike_co], + xp: _ArrayLikeFloat_co, + fp: _ArrayLike1D[np.complexfloating] | list[complex], + left: _NumberLike_co | None = None, + right: _NumberLike_co | None = None, + period: _FloatLike_co | None = None, +) -> NDArray[np.complex128]: ... +@overload # float scalar/array-like +def interp( + x: _ArrayLikeFloat_co, + xp: _ArrayLikeFloat_co, + fp: _ArrayLikeFloat_co, + left: _FloatLike_co | None = None, + right: _FloatLike_co | None = None, + period: _FloatLike_co | None = None, +) -> NDArray[np.float64] | np.float64: ... +@overload # complex scalar/array-like +def interp( + x: _ArrayLikeFloat_co, + xp: _ArrayLikeFloat_co, + fp: _ArrayLike1D[np.complexfloating], + left: _NumberLike_co | None = None, + right: _NumberLike_co | None = None, + period: _FloatLike_co | None = None, +) -> NDArray[np.complex128] | np.complex128: ... +@overload # float/complex scalar/array-like +def interp( + x: _ArrayLikeFloat_co, + xp: _ArrayLikeFloat_co, + fp: _ArrayLikeNumber_co, + left: _NumberLike_co | None = None, + right: _NumberLike_co | None = None, + period: _FloatLike_co | None = None, +) -> NDArray[np.complex128 | np.float64] | np.complex128 | np.float64: ... + +# +@overload # 0d T: floating -> 0d T +def angle(z: _FloatingT, deg: bool = False) -> _FloatingT: ... +@overload # 0d complex | float | ~integer -> 0d float64 +def angle(z: complex | _integer_co, deg: bool = False) -> np.float64: ... +@overload # 0d complex64 -> 0d float32 +def angle(z: np.complex64, deg: bool = False) -> np.float32: ... +@overload # 0d clongdouble -> 0d longdouble +def angle(z: np.clongdouble, deg: bool = False) -> np.longdouble: ... +@overload # T: nd floating -> T +def angle(z: _ArrayFloatingT, deg: bool = False) -> _ArrayFloatingT: ... +@overload # nd T: complex128 | ~integer -> nd float64 +def angle(z: _Array[_ShapeT, np.complex128 | _integer_co], deg: bool = False) -> _Array[_ShapeT, np.float64]: ... +@overload # nd T: complex64 -> nd float32 +def angle(z: _Array[_ShapeT, np.complex64], deg: bool = False) -> _Array[_ShapeT, np.float32]: ... +@overload # nd T: clongdouble -> nd longdouble +def angle(z: _Array[_ShapeT, np.clongdouble], deg: bool = False) -> _Array[_ShapeT, np.longdouble]: ... +@overload # 1d complex -> 1d float64 +def angle(z: _Seq1D[complex], deg: bool = False) -> _Array1D[np.float64]: ... +@overload # 2d complex -> 2d float64 +def angle(z: _Seq2D[complex], deg: bool = False) -> _Array2D[np.float64]: ... +@overload # 3d complex -> 3d float64 +def angle(z: _Seq3D[complex], deg: bool = False) -> _Array3D[np.float64]: ... +@overload # fallback +def angle(z: _ArrayLikeComplex_co, deg: bool = False) -> NDArray[np.floating] | Any: ... + +# +@overload # known array-type +def unwrap( + p: _ArrayFloatObjT, + discont: float | None = None, + axis: int = -1, + *, + period: float = ..., # = Ï„ +) -> _ArrayFloatObjT: ... +@overload # known shape, float64 +def unwrap( + p: _Array[_ShapeT, _float64_co], + discont: float | None = None, + axis: int = -1, + *, + period: float = ..., # = Ï„ +) -> _Array[_ShapeT, np.float64]: ... +@overload # 1d float64-like +def unwrap( + p: _Seq1D[float | _float64_co], + discont: float | None = None, + axis: int = -1, + *, + period: float = ..., # = Ï„ +) -> _Array1D[np.float64]: ... +@overload # 2d float64-like +def unwrap( + p: _Seq2D[float | _float64_co], + discont: float | None = None, + axis: int = -1, + *, + period: float = ..., # = Ï„ +) -> _Array2D[np.float64]: ... +@overload # 3d float64-like +def unwrap( + p: _Seq3D[float | _float64_co], + discont: float | None = None, + axis: int = -1, + *, + period: float = ..., # = Ï„ +) -> _Array3D[np.float64]: ... +@overload # ?d, float64 +def unwrap( + p: _SeqND[float] | _ArrayLike[_float64_co], + discont: float | None = None, + axis: int = -1, + *, + period: float = ..., # = Ï„ +) -> NDArray[np.float64]: ... +@overload # fallback +def unwrap( + p: _ArrayLikeFloat_co | _ArrayLikeObject_co, + discont: float | None = None, + axis: int = -1, + *, + period: float = ..., # = Ï„ +) -> np.ndarray: ... + +# +@overload +def sort_complex(a: _ArrayComplexT) -> _ArrayComplexT: ... +@overload # complex64, shape known +def sort_complex(a: _Array[_ShapeT, np.int8 | np.uint8 | np.int16 | np.uint16]) -> _Array[_ShapeT, np.complex64]: ... +@overload # complex64, shape unknown +def sort_complex(a: _ArrayLike[np.int8 | np.uint8 | np.int16 | np.uint16]) -> NDArray[np.complex64]: ... +@overload # complex128, shape known +def sort_complex(a: _Array[_ShapeT, _SortsToComplex128]) -> _Array[_ShapeT, np.complex128]: ... +@overload # complex128, shape unknown +def sort_complex(a: _ArrayLike[_SortsToComplex128]) -> NDArray[np.complex128]: ... +@overload # clongdouble, shape known +def sort_complex(a: _Array[_ShapeT, np.longdouble]) -> _Array[_ShapeT, np.clongdouble]: ... +@overload # clongdouble, shape unknown +def sort_complex(a: _ArrayLike[np.longdouble]) -> NDArray[np.clongdouble]: ... + +# +def trim_zeros(filt: _TrimZerosSequence[_T], trim: L["f", "b", "fb", "bf"] = "fb", axis: _ShapeLike | None = None) -> _T: ... + +# NOTE: keep in sync with `corrcoef` +@overload # ?d, known inexact scalar-type >=64 precision, y=. +def cov( + m: _ArrayLike[_AnyDoubleT], + y: _ArrayLike[_AnyDoubleT], + rowvar: bool = True, + bias: bool = False, + ddof: SupportsIndex | SupportsInt | None = None, + fweights: _ArrayLikeInt_co | None = None, + aweights: _ArrayLikeFloat_co | None = None, + *, + dtype: None = None, +) -> _Array2D[_AnyDoubleT]: ... +@overload # ?d, known inexact scalar-type >=64 precision, y=None -> 0d or 2d +def cov( + m: _ArrayNoD[_AnyDoubleT], + y: None = None, + rowvar: bool = True, + bias: bool = False, + ddof: SupportsIndex | SupportsInt | None = None, + fweights: _ArrayLikeInt_co | None = None, + aweights: _ArrayLikeFloat_co | None = None, + *, + dtype: _DTypeLike[_AnyDoubleT] | None = None, +) -> NDArray[_AnyDoubleT]: ... +@overload # 1d, known inexact scalar-type >=64 precision, y=None +def cov( + m: _Array1D[_AnyDoubleT], + y: None = None, + rowvar: bool = True, + bias: bool = False, + ddof: SupportsIndex | SupportsInt | None = None, + fweights: _ArrayLikeInt_co | None = None, + aweights: _ArrayLikeFloat_co | None = None, + *, + dtype: _DTypeLike[_AnyDoubleT] | None = None, +) -> _Array0D[_AnyDoubleT]: ... +@overload # nd, known inexact scalar-type >=64 precision, y=None -> 0d or 2d +def cov( + m: _ArrayLike[_AnyDoubleT], + y: None = None, + rowvar: bool = True, + bias: bool = False, + ddof: SupportsIndex | SupportsInt | None = None, + fweights: _ArrayLikeInt_co | None = None, + aweights: _ArrayLikeFloat_co | None = None, + *, + dtype: _DTypeLike[_AnyDoubleT] | None = None, +) -> NDArray[_AnyDoubleT]: ... +@overload # nd, casts to float64, y= +def cov( + m: NDArray[np.float32 | np.float16 | _integer_co] | _Seq1D[float] | _Seq2D[float], + y: NDArray[np.float32 | np.float16 | _integer_co] | _Seq1D[float] | _Seq2D[float], + rowvar: bool = True, + bias: bool = False, + ddof: SupportsIndex | SupportsInt | None = None, + fweights: _ArrayLikeInt_co | None = None, + aweights: _ArrayLikeFloat_co | None = None, + *, + dtype: _DTypeLike[np.float64] | None = None, +) -> _Array2D[np.float64]: ... +@overload # ?d or 2d, casts to float64, y=None -> 0d or 2d +def cov( + m: _ArrayNoD[np.float32 | np.float16 | _integer_co] | _Seq2D[float], + y: None = None, + rowvar: bool = True, + bias: bool = False, + ddof: SupportsIndex | SupportsInt | None = None, + fweights: _ArrayLikeInt_co | None = None, + aweights: _ArrayLikeFloat_co | None = None, + *, + dtype: _DTypeLike[np.float64] | None = None, +) -> NDArray[np.float64]: ... +@overload # 1d, casts to float64, y=None +def cov( + m: _Array1D[np.float32 | np.float16 | _integer_co] | _Seq1D[float], + y: None = None, + rowvar: bool = True, + bias: bool = False, + ddof: SupportsIndex | SupportsInt | None = None, + fweights: _ArrayLikeInt_co | None = None, + aweights: _ArrayLikeFloat_co | None = None, + *, + dtype: _DTypeLike[np.float64] | None = None, +) -> _Array0D[np.float64]: ... +@overload # nd, casts to float64, y=None -> 0d or 2d +def cov( + m: _ArrayLike[np.float32 | np.float16 | _integer_co], + y: None = None, + rowvar: bool = True, + bias: bool = False, + ddof: SupportsIndex | SupportsInt | None = None, + fweights: _ArrayLikeInt_co | None = None, + aweights: _ArrayLikeFloat_co | None = None, + *, + dtype: _DTypeLike[np.float64] | None = None, +) -> NDArray[np.float64]: ... +@overload # 1d complex, y= (`list` avoids overlap with float overloads) +def cov( + m: list[complex] | _Seq1D[list[complex]], + y: list[complex] | _Seq1D[list[complex]], + rowvar: bool = True, + bias: bool = False, + ddof: SupportsIndex | SupportsInt | None = None, + fweights: _ArrayLikeInt_co | None = None, + aweights: _ArrayLikeFloat_co | None = None, + *, + dtype: _DTypeLike[np.complex128] | None = None, +) -> _Array2D[np.complex128]: ... +@overload # 1d complex, y=None +def cov( + m: list[complex], + y: None = None, + rowvar: bool = True, + bias: bool = False, + ddof: SupportsIndex | SupportsInt | None = None, + fweights: _ArrayLikeInt_co | None = None, + aweights: _ArrayLikeFloat_co | None = None, + *, + dtype: _DTypeLike[np.complex128] | None = None, +) -> _Array0D[np.complex128]: ... +@overload # 2d complex, y=None -> 0d or 2d +def cov( + m: _Seq1D[list[complex]], + y: None = None, + rowvar: bool = True, + bias: bool = False, + ddof: SupportsIndex | SupportsInt | None = None, + fweights: _ArrayLikeInt_co | None = None, + aweights: _ArrayLikeFloat_co | None = None, + *, + dtype: _DTypeLike[np.complex128] | None = None, +) -> NDArray[np.complex128]: ... +@overload # 1d complex-like, y=None, dtype= +def cov( + m: _Seq1D[_ComplexLike_co], + y: None = None, + rowvar: bool = True, + bias: bool = False, + ddof: SupportsIndex | SupportsInt | None = None, + fweights: _ArrayLikeInt_co | None = None, + aweights: _ArrayLikeFloat_co | None = None, + *, + dtype: _DTypeLike[_ScalarT], +) -> _Array0D[_ScalarT]: ... +@overload # nd complex-like, y=, dtype= +def cov( + m: _ArrayLikeComplex_co, + y: _ArrayLikeComplex_co, + rowvar: bool = True, + bias: bool = False, + ddof: SupportsIndex | SupportsInt | None = None, + fweights: _ArrayLikeInt_co | None = None, + aweights: _ArrayLikeFloat_co | None = None, + *, + dtype: _DTypeLike[_ScalarT], +) -> _Array2D[_ScalarT]: ... +@overload # nd complex-like, y=None, dtype= -> 0d or 2d +def cov( + m: _ArrayLikeComplex_co, + y: None = None, + rowvar: bool = True, + bias: bool = False, + ddof: SupportsIndex | SupportsInt | None = None, + fweights: _ArrayLikeInt_co | None = None, + aweights: _ArrayLikeFloat_co | None = None, + *, + dtype: _DTypeLike[_ScalarT], +) -> NDArray[_ScalarT]: ... +@overload # nd complex-like, y=, dtype=? +def cov( + m: _ArrayLikeComplex_co, + y: _ArrayLikeComplex_co, + rowvar: bool = True, + bias: bool = False, + ddof: SupportsIndex | SupportsInt | None = None, + fweights: _ArrayLikeInt_co | None = None, + aweights: _ArrayLikeFloat_co | None = None, + *, + dtype: DTypeLike | None = None, +) -> _Array2D[Incomplete]: ... +@overload # 1d complex-like, y=None, dtype=? +def cov( + m: _Seq1D[_ComplexLike_co], + y: None = None, + rowvar: bool = True, + bias: bool = False, + ddof: SupportsIndex | SupportsInt | None = None, + fweights: _ArrayLikeInt_co | None = None, + aweights: _ArrayLikeFloat_co | None = None, + *, + dtype: DTypeLike | None = None, +) -> _Array0D[Incomplete]: ... +@overload # nd complex-like, dtype=? +def cov( + m: _ArrayLikeComplex_co, + y: _ArrayLikeComplex_co | None = None, + rowvar: bool = True, + bias: bool = False, + ddof: SupportsIndex | SupportsInt | None = None, + fweights: _ArrayLikeInt_co | None = None, + aweights: _ArrayLikeFloat_co | None = None, + *, + dtype: DTypeLike | None = None, +) -> NDArray[Incomplete]: ... + +# NOTE: If only `x` is given and the resulting array has shape (1,1), a bare scalar +# is returned instead of a 2D array. When y is given, a 2D array is always returned. +# This differs from `cov`, which returns 0-D arrays instead of scalars in such cases. +# NOTE: keep in sync with `cov` +@overload # ?d, known inexact scalar-type >=64 precision, y=. +def corrcoef( + x: _ArrayLike[_AnyDoubleT], + y: _ArrayLike[_AnyDoubleT], + rowvar: bool = True, + *, + dtype: _DTypeLike[_AnyDoubleT] | None = None, +) -> _Array2D[_AnyDoubleT]: ... +@overload # ?d, known inexact scalar-type >=64 precision, y=None +def corrcoef( + x: _ArrayNoD[_AnyDoubleT], + y: None = None, + rowvar: bool = True, + *, + dtype: _DTypeLike[_AnyDoubleT] | None = None, +) -> _Array2D[_AnyDoubleT] | _AnyDoubleT: ... +@overload # 1d, known inexact scalar-type >=64 precision, y=None +def corrcoef( + x: _Array1D[_AnyDoubleT], + y: None = None, + rowvar: bool = True, + *, + dtype: _DTypeLike[_AnyDoubleT] | None = None, +) -> _AnyDoubleT: ... +@overload # nd, known inexact scalar-type >=64 precision, y=None +def corrcoef( + x: _ArrayLike[_AnyDoubleT], + y: None = None, + rowvar: bool = True, + *, + dtype: _DTypeLike[_AnyDoubleT] | None = None, +) -> _Array2D[_AnyDoubleT] | _AnyDoubleT: ... +@overload # nd, casts to float64, y= +def corrcoef( + x: NDArray[np.float32 | np.float16 | _integer_co] | _Seq1D[float] | _Seq2D[float], + y: NDArray[np.float32 | np.float16 | _integer_co] | _Seq1D[float] | _Seq2D[float], + rowvar: bool = True, + *, + dtype: _DTypeLike[np.float64] | None = None, +) -> _Array2D[np.float64]: ... +@overload # ?d or 2d, casts to float64, y=None +def corrcoef( + x: _ArrayNoD[np.float32 | np.float16 | _integer_co] | _Seq2D[float], + y: None = None, + rowvar: bool = True, + *, + dtype: _DTypeLike[np.float64] | None = None, +) -> _Array2D[np.float64] | np.float64: ... +@overload # 1d, casts to float64, y=None +def corrcoef( + x: _Array1D[np.float32 | np.float16 | _integer_co] | _Seq1D[float], + y: None = None, + rowvar: bool = True, + *, + dtype: _DTypeLike[np.float64] | None = None, +) -> np.float64: ... +@overload # nd, casts to float64, y=None +def corrcoef( + x: _ArrayLike[np.float32 | np.float16 | _integer_co], + y: None = None, + rowvar: bool = True, + *, + dtype: _DTypeLike[np.float64] | None = None, +) -> _Array2D[np.float64] | np.float64: ... +@overload # 1d complex, y= (`list` avoids overlap with float overloads) +def corrcoef( + x: list[complex] | _Seq1D[list[complex]], + y: list[complex] | _Seq1D[list[complex]], + rowvar: bool = True, + *, + dtype: _DTypeLike[np.complex128] | None = None, +) -> _Array2D[np.complex128]: ... +@overload # 1d complex, y=None +def corrcoef( + x: list[complex], + y: None = None, + rowvar: bool = True, + *, + dtype: _DTypeLike[np.complex128] | None = None, +) -> np.complex128: ... +@overload # 2d complex, y=None +def corrcoef( + x: _Seq1D[list[complex]], + y: None = None, + rowvar: bool = True, + *, + dtype: _DTypeLike[np.complex128] | None = None, +) -> _Array2D[np.complex128] | np.complex128: ... +@overload # 1d complex-like, y=None, dtype= +def corrcoef( + x: _Seq1D[_ComplexLike_co], + y: None = None, + rowvar: bool = True, + *, + dtype: _DTypeLike[_ScalarT], +) -> _ScalarT: ... +@overload # nd complex-like, y=, dtype= +def corrcoef( + x: _ArrayLikeComplex_co, + y: _ArrayLikeComplex_co, + rowvar: bool = True, + *, + dtype: _DTypeLike[_ScalarT], +) -> _Array2D[_ScalarT]: ... +@overload # nd complex-like, y=None, dtype= +def corrcoef( + x: _ArrayLikeComplex_co, + y: None = None, + rowvar: bool = True, + *, + dtype: _DTypeLike[_ScalarT], +) -> _Array2D[_ScalarT] | _ScalarT: ... +@overload # nd complex-like, y=, dtype=? +def corrcoef( + x: _ArrayLikeComplex_co, + y: _ArrayLikeComplex_co, + rowvar: bool = True, + *, + dtype: DTypeLike | None = None, +) -> _Array2D[Incomplete]: ... +@overload # 1d complex-like, y=None, dtype=? +def corrcoef( + x: _Seq1D[_ComplexLike_co], + y: None = None, + rowvar: bool = True, + *, + dtype: DTypeLike | None = None, +) -> Incomplete: ... +@overload # nd complex-like, dtype=? +def corrcoef( + x: _ArrayLikeComplex_co, + y: _ArrayLikeComplex_co | None = None, + rowvar: bool = True, + *, + dtype: DTypeLike | None = None, +) -> _Array2D[Incomplete] | Incomplete: ... + +# note that floating `M` are accepted, but their fractional part is ignored +def blackman(M: _FloatLike_co) -> _Array1D[np.float64]: ... +def bartlett(M: _FloatLike_co) -> _Array1D[np.float64]: ... +def hanning(M: _FloatLike_co) -> _Array1D[np.float64]: ... +def hamming(M: _FloatLike_co) -> _Array1D[np.float64]: ... +def kaiser(M: _FloatLike_co, beta: _FloatLike_co) -> _Array1D[np.float64]: ... + +# +@overload +def i0(x: _Array[_ShapeT, np.floating | np.integer]) -> _Array[_ShapeT, np.float64]: ... +@overload +def i0(x: _FloatLike_co) -> _Array0D[np.float64]: ... +@overload +def i0(x: _Seq1D[_FloatLike_co]) -> _Array1D[np.float64]: ... +@overload +def i0(x: _Seq2D[_FloatLike_co]) -> _Array2D[np.float64]: ... +@overload +def i0(x: _Seq3D[_FloatLike_co]) -> _Array3D[np.float64]: ... +@overload +def i0(x: _ArrayLikeFloat_co) -> NDArray[np.float64]: ... + +# +@overload +def sinc(x: _InexactT) -> _InexactT: ... +@overload +def sinc(x: float | _float64_co) -> np.float64: ... +@overload +def sinc(x: complex) -> np.complex128 | Any: ... +@overload +def sinc(x: _ArrayInexactT) -> _ArrayInexactT: ... +@overload +def sinc(x: _Array[_ShapeT, _integer_co]) -> _Array[_ShapeT, np.float64]: ... +@overload +def sinc(x: _Seq1D[float]) -> _Array1D[np.float64]: ... +@overload +def sinc(x: _Seq2D[float]) -> _Array2D[np.float64]: ... +@overload +def sinc(x: _Seq3D[float]) -> _Array3D[np.float64]: ... +@overload +def sinc(x: _SeqND[float]) -> NDArray[np.float64]: ... +@overload +def sinc(x: list[complex]) -> _Array1D[np.complex128]: ... +@overload +def sinc(x: _Seq1D[list[complex]]) -> _Array2D[np.complex128]: ... +@overload +def sinc(x: _Seq2D[list[complex]]) -> _Array3D[np.complex128]: ... +@overload +def sinc(x: _ArrayLikeComplex_co) -> np.ndarray | Any: ... + +# NOTE: We assume that `axis` is only provided for >=1-D arrays because for <1-D arrays +# it has no effect, and would complicate the overloads significantly. +@overload # known scalar-type, keepdims=False (default) +def median( + a: _ArrayLike[_InexactTimeT], + axis: None = None, + out: None = None, + overwrite_input: bool = False, + keepdims: L[False] = False, +) -> _InexactTimeT: ... +@overload # float array-like, keepdims=False (default) +def median( + a: _ArrayLikeInt_co | _SeqND[float] | float, + axis: None = None, + out: None = None, + overwrite_input: bool = False, + keepdims: L[False] = False, +) -> np.float64: ... +@overload # complex array-like, keepdims=False (default) +def median( + a: _ListSeqND[complex], + axis: None = None, + out: None = None, + overwrite_input: bool = False, + keepdims: L[False] = False, +) -> np.complex128: ... +@overload # complex scalar, keepdims=False (default) +def median( + a: complex, + axis: None = None, + out: None = None, + overwrite_input: bool = False, + keepdims: L[False] = False, +) -> np.complex128 | Any: ... +@overload # known array-type, keepdims=True +def median( + a: _ArrayNumericT, + axis: _ShapeLike | None = None, + out: None = None, + overwrite_input: bool = False, + *, + keepdims: L[True], +) -> _ArrayNumericT: ... +@overload # known scalar-type, keepdims=True +def median( + a: _ArrayLike[_ScalarNumericT], + axis: _ShapeLike | None = None, + out: None = None, + overwrite_input: bool = False, + *, + keepdims: L[True], +) -> NDArray[_ScalarNumericT]: ... +@overload # known scalar-type, axis= +def median( + a: _ArrayLike[_ScalarNumericT], + axis: _ShapeLike, + out: None = None, + overwrite_input: bool = False, + keepdims: bool = False, +) -> NDArray[_ScalarNumericT]: ... +@overload # float array-like, keepdims=True +def median( + a: _SeqND[float], + axis: _ShapeLike | None = None, + out: None = None, + overwrite_input: bool = False, + *, + keepdims: L[True], +) -> NDArray[np.float64]: ... +@overload # float array-like, axis= +def median( + a: _SeqND[float], + axis: _ShapeLike, + out: None = None, + overwrite_input: bool = False, + keepdims: bool = False, +) -> NDArray[np.float64]: ... +@overload # complex array-like, keepdims=True +def median( + a: _ListSeqND[complex], + axis: _ShapeLike | None = None, + out: None = None, + overwrite_input: bool = False, + *, + keepdims: L[True], +) -> NDArray[np.complex128]: ... +@overload # complex array-like, axis= +def median( + a: _ListSeqND[complex], + axis: _ShapeLike, + out: None = None, + overwrite_input: bool = False, + keepdims: bool = False, +) -> NDArray[np.complex128]: ... +@overload # out= (keyword) +def median( + a: _ArrayLikeComplex_co | _ArrayLike[np.timedelta64 | np.object_], + axis: _ShapeLike | None = None, + *, + out: _ArrayT, + overwrite_input: bool = False, + keepdims: bool = False, +) -> _ArrayT: ... +@overload # out= (positional) +def median( + a: _ArrayLikeComplex_co | _ArrayLike[np.timedelta64 | np.object_], + axis: _ShapeLike | None, + out: _ArrayT, + overwrite_input: bool = False, + keepdims: bool = False, +) -> _ArrayT: ... +@overload # fallback +def median( + a: _ArrayLikeComplex_co | _ArrayLike[np.timedelta64 | np.object_], + axis: _ShapeLike | None = None, + out: None = None, + overwrite_input: bool = False, + keepdims: bool = False, +) -> Incomplete: ... + +# NOTE: keep in sync with `quantile` +@overload # inexact, scalar, axis=None +def percentile( + a: _ArrayLike[_InexactDateTimeT], + q: _FloatLike_co, + axis: None = None, + out: None = None, + overwrite_input: bool = False, + method: _InterpolationMethod = "linear", + keepdims: L[False] = False, + *, + weights: _ArrayLikeFloat_co | None = None, +) -> _InexactDateTimeT: ... +@overload # inexact, scalar, axis= +def percentile( + a: _ArrayLike[_InexactDateTimeT], + q: _FloatLike_co, + axis: _ShapeLike, + out: None = None, + overwrite_input: bool = False, + method: _InterpolationMethod = "linear", + keepdims: L[False] = False, + *, + weights: _ArrayLikeFloat_co | None = None, +) -> NDArray[_InexactDateTimeT]: ... +@overload # inexact, scalar, keepdims=True +def percentile( + a: _ArrayLike[_InexactDateTimeT], + q: _FloatLike_co, + axis: _ShapeLike | None = None, + out: None = None, + overwrite_input: bool = False, + method: _InterpolationMethod = "linear", + *, + keepdims: L[True], + weights: _ArrayLikeFloat_co | None = None, +) -> NDArray[_InexactDateTimeT]: ... +@overload # inexact, array, axis=None +def percentile( + a: _ArrayLike[_InexactDateTimeT], + q: _Array[_ShapeT, _floating_co], + axis: None = None, + out: None = None, + overwrite_input: bool = False, + method: _InterpolationMethod = "linear", + keepdims: L[False] = False, + *, + weights: _ArrayLikeFloat_co | None = None, +) -> _Array[_ShapeT, _InexactDateTimeT]: ... +@overload # inexact, array-like +def percentile( + a: _ArrayLike[_InexactDateTimeT], + q: NDArray[_floating_co] | _SeqND[_FloatLike_co], + axis: _ShapeLike | None = None, + out: None = None, + overwrite_input: bool = False, + method: _InterpolationMethod = "linear", + keepdims: bool = False, + *, + weights: _ArrayLikeFloat_co | None = None, +) -> NDArray[_InexactDateTimeT]: ... +@overload # float, scalar, axis=None +def percentile( + a: _SeqND[float] | _ArrayLikeInt_co, + q: _FloatLike_co, + axis: None = None, + out: None = None, + overwrite_input: bool = False, + method: _InterpolationMethod = "linear", + keepdims: L[False] = False, + *, + weights: _ArrayLikeFloat_co | None = None, +) -> np.float64: ... +@overload # float, scalar, axis= +def percentile( + a: _SeqND[float] | _ArrayLikeInt_co, + q: _FloatLike_co, + axis: _ShapeLike, + out: None = None, + overwrite_input: bool = False, + method: _InterpolationMethod = "linear", + keepdims: L[False] = False, + *, + weights: _ArrayLikeFloat_co | None = None, +) -> NDArray[np.float64]: ... +@overload # float, scalar, keepdims=True +def percentile( + a: _SeqND[float] | _ArrayLikeInt_co, + q: _FloatLike_co, + axis: _ShapeLike | None = None, + out: None = None, + overwrite_input: bool = False, + method: _InterpolationMethod = "linear", + *, + keepdims: L[True], + weights: _ArrayLikeFloat_co | None = None, +) -> NDArray[np.float64]: ... +@overload # float, array, axis=None +def percentile( + a: _SeqND[float] | _ArrayLikeInt_co, + q: _Array[_ShapeT, _floating_co], + axis: None = None, + out: None = None, + overwrite_input: bool = False, + method: _InterpolationMethod = "linear", + keepdims: L[False] = False, + *, + weights: _ArrayLikeFloat_co | None = None, +) -> _Array[_ShapeT, np.float64]: ... +@overload # float, array-like +def percentile( + a: _SeqND[float] | _ArrayLikeInt_co, + q: NDArray[_floating_co] | _SeqND[_FloatLike_co], + axis: _ShapeLike | None = None, + out: None = None, + overwrite_input: bool = False, + method: _InterpolationMethod = "linear", + keepdims: bool = False, + *, + weights: _ArrayLikeFloat_co | None = None, +) -> NDArray[np.float64]: ... +@overload # complex, scalar, axis=None +def percentile( + a: _ListSeqND[complex], + q: _FloatLike_co, + axis: None = None, + out: None = None, + overwrite_input: bool = False, + method: _InterpolationMethod = "linear", + keepdims: L[False] = False, + *, + weights: _ArrayLikeFloat_co | None = None, +) -> np.complex128: ... +@overload # complex, scalar, axis= +def percentile( + a: _ListSeqND[complex], + q: _FloatLike_co, + axis: _ShapeLike, + out: None = None, + overwrite_input: bool = False, + method: _InterpolationMethod = "linear", + keepdims: L[False] = False, + *, + weights: _ArrayLikeFloat_co | None = None, +) -> NDArray[np.complex128]: ... +@overload # complex, scalar, keepdims=True +def percentile( + a: _ListSeqND[complex], + q: _FloatLike_co, + axis: _ShapeLike | None = None, + out: None = None, + overwrite_input: bool = False, + method: _InterpolationMethod = "linear", + *, + keepdims: L[True], + weights: _ArrayLikeFloat_co | None = None, +) -> NDArray[np.complex128]: ... +@overload # complex, array, axis=None +def percentile( + a: _ListSeqND[complex], + q: _Array[_ShapeT, _floating_co], + axis: None = None, + out: None = None, + overwrite_input: bool = False, + method: _InterpolationMethod = "linear", + keepdims: L[False] = False, + *, + weights: _ArrayLikeFloat_co | None = None, +) -> _Array[_ShapeT, np.complex128]: ... +@overload # complex, array-like +def percentile( + a: _ListSeqND[complex], + q: NDArray[_floating_co] | _SeqND[_FloatLike_co], + axis: _ShapeLike | None = None, + out: None = None, + overwrite_input: bool = False, + method: _InterpolationMethod = "linear", + keepdims: bool = False, + *, + weights: _ArrayLikeFloat_co | None = None, +) -> NDArray[np.complex128]: ... +@overload # object_, scalar, axis=None +def percentile( + a: _ArrayLikeObject_co, + q: _FloatLike_co, + axis: None = None, + out: None = None, + overwrite_input: bool = False, + method: _InterpolationMethod = "linear", + keepdims: L[False] = False, + *, + weights: _ArrayLikeFloat_co | None = None, +) -> Any: ... +@overload # object_, scalar, axis= +def percentile( + a: _ArrayLikeObject_co, + q: _FloatLike_co, + axis: _ShapeLike, + out: None = None, + overwrite_input: bool = False, + method: _InterpolationMethod = "linear", + keepdims: L[False] = False, + *, + weights: _ArrayLikeFloat_co | None = None, +) -> NDArray[np.object_]: ... +@overload # object_, scalar, keepdims=True +def percentile( + a: _ArrayLikeObject_co, + q: _FloatLike_co, + axis: _ShapeLike | None = None, + out: None = None, + overwrite_input: bool = False, + method: _InterpolationMethod = "linear", + *, + keepdims: L[True], + weights: _ArrayLikeFloat_co | None = None, +) -> NDArray[np.object_]: ... +@overload # object_, array, axis=None +def percentile( + a: _ArrayLikeObject_co, + q: _Array[_ShapeT, _floating_co], + axis: None = None, + out: None = None, + overwrite_input: bool = False, + method: _InterpolationMethod = "linear", + keepdims: L[False] = False, + *, + weights: _ArrayLikeFloat_co | None = None, +) -> _Array[_ShapeT, np.object_]: ... +@overload # object_, array-like +def percentile( + a: _ArrayLikeObject_co, + q: NDArray[_floating_co] | _SeqND[_FloatLike_co], + axis: _ShapeLike | None = None, + out: None = None, + overwrite_input: bool = False, + method: _InterpolationMethod = "linear", + keepdims: bool = False, + *, + weights: _ArrayLikeFloat_co | None = None, +) -> NDArray[np.object_]: ... +@overload # out= (keyword) +def percentile( + a: ArrayLike, + q: _ArrayLikeFloat_co, + axis: _ShapeLike | None, + out: _ArrayT, + overwrite_input: bool = False, + method: _InterpolationMethod = "linear", + keepdims: bool = False, + *, + weights: _ArrayLikeFloat_co | None = None, +) -> _ArrayT: ... +@overload # out= (positional) +def percentile( + a: ArrayLike, + q: _ArrayLikeFloat_co, + axis: _ShapeLike | None = None, + *, + out: _ArrayT, + overwrite_input: bool = False, + method: _InterpolationMethod = "linear", + keepdims: bool = False, + weights: _ArrayLikeFloat_co | None = None, +) -> _ArrayT: ... +@overload # fallback +def percentile( + a: _ArrayLikeNumber_co | _ArrayLikeObject_co, + q: _ArrayLikeFloat_co, + axis: _ShapeLike | None = None, + out: None = None, + overwrite_input: bool = False, + method: _InterpolationMethod = "linear", + keepdims: bool = False, + *, + weights: _ArrayLikeFloat_co | None = None, +) -> Incomplete: ... + +# NOTE: keep in sync with `percentile` +@overload # inexact, scalar, axis=None +def quantile( + a: _ArrayLike[_InexactDateTimeT], + q: _FloatLike_co, + axis: None = None, + out: None = None, + overwrite_input: bool = False, + method: _InterpolationMethod = "linear", + keepdims: L[False] = False, + *, + weights: _ArrayLikeFloat_co | None = None, +) -> _InexactDateTimeT: ... +@overload # inexact, scalar, axis= +def quantile( + a: _ArrayLike[_InexactDateTimeT], + q: _FloatLike_co, + axis: _ShapeLike, + out: None = None, + overwrite_input: bool = False, + method: _InterpolationMethod = "linear", + keepdims: L[False] = False, + *, + weights: _ArrayLikeFloat_co | None = None, +) -> NDArray[_InexactDateTimeT]: ... +@overload # inexact, scalar, keepdims=True +def quantile( + a: _ArrayLike[_InexactDateTimeT], + q: _FloatLike_co, + axis: _ShapeLike | None = None, + out: None = None, + overwrite_input: bool = False, + method: _InterpolationMethod = "linear", + *, + keepdims: L[True], + weights: _ArrayLikeFloat_co | None = None, +) -> NDArray[_InexactDateTimeT]: ... +@overload # inexact, array, axis=None +def quantile( + a: _ArrayLike[_InexactDateTimeT], + q: _Array[_ShapeT, _floating_co], + axis: None = None, + out: None = None, + overwrite_input: bool = False, + method: _InterpolationMethod = "linear", + keepdims: L[False] = False, + *, + weights: _ArrayLikeFloat_co | None = None, +) -> _Array[_ShapeT, _InexactDateTimeT]: ... +@overload # inexact, array-like +def quantile( + a: _ArrayLike[_InexactDateTimeT], + q: NDArray[_floating_co] | _SeqND[_FloatLike_co], + axis: _ShapeLike | None = None, + out: None = None, + overwrite_input: bool = False, + method: _InterpolationMethod = "linear", + keepdims: bool = False, + *, + weights: _ArrayLikeFloat_co | None = None, +) -> NDArray[_InexactDateTimeT]: ... +@overload # float, scalar, axis=None +def quantile( + a: _SeqND[float] | _ArrayLikeInt_co, + q: _FloatLike_co, + axis: None = None, + out: None = None, + overwrite_input: bool = False, + method: _InterpolationMethod = "linear", + keepdims: L[False] = False, + *, + weights: _ArrayLikeFloat_co | None = None, +) -> np.float64: ... +@overload # float, scalar, axis= +def quantile( + a: _SeqND[float] | _ArrayLikeInt_co, + q: _FloatLike_co, + axis: _ShapeLike, + out: None = None, + overwrite_input: bool = False, + method: _InterpolationMethod = "linear", + keepdims: L[False] = False, + *, + weights: _ArrayLikeFloat_co | None = None, +) -> NDArray[np.float64]: ... +@overload # float, scalar, keepdims=True +def quantile( + a: _SeqND[float] | _ArrayLikeInt_co, + q: _FloatLike_co, + axis: _ShapeLike | None = None, + out: None = None, + overwrite_input: bool = False, + method: _InterpolationMethod = "linear", + *, + keepdims: L[True], + weights: _ArrayLikeFloat_co | None = None, +) -> NDArray[np.float64]: ... +@overload # float, array, axis=None +def quantile( + a: _SeqND[float] | _ArrayLikeInt_co, + q: _Array[_ShapeT, _floating_co], + axis: None = None, + out: None = None, + overwrite_input: bool = False, + method: _InterpolationMethod = "linear", + keepdims: L[False] = False, + *, + weights: _ArrayLikeFloat_co | None = None, +) -> _Array[_ShapeT, np.float64]: ... +@overload # float, array-like +def quantile( + a: _SeqND[float] | _ArrayLikeInt_co, + q: NDArray[_floating_co] | _SeqND[_FloatLike_co], + axis: _ShapeLike | None = None, + out: None = None, + overwrite_input: bool = False, + method: _InterpolationMethod = "linear", + keepdims: bool = False, + *, + weights: _ArrayLikeFloat_co | None = None, +) -> NDArray[np.float64]: ... +@overload # complex, scalar, axis=None +def quantile( + a: _ListSeqND[complex], + q: _FloatLike_co, + axis: None = None, + out: None = None, + overwrite_input: bool = False, + method: _InterpolationMethod = "linear", + keepdims: L[False] = False, + *, + weights: _ArrayLikeFloat_co | None = None, +) -> np.complex128: ... +@overload # complex, scalar, axis= +def quantile( + a: _ListSeqND[complex], + q: _FloatLike_co, + axis: _ShapeLike, + out: None = None, + overwrite_input: bool = False, + method: _InterpolationMethod = "linear", + keepdims: L[False] = False, + *, + weights: _ArrayLikeFloat_co | None = None, +) -> NDArray[np.complex128]: ... +@overload # complex, scalar, keepdims=True +def quantile( + a: _ListSeqND[complex], + q: _FloatLike_co, + axis: _ShapeLike | None = None, + out: None = None, + overwrite_input: bool = False, + method: _InterpolationMethod = "linear", + *, + keepdims: L[True], + weights: _ArrayLikeFloat_co | None = None, +) -> NDArray[np.complex128]: ... +@overload # complex, array, axis=None +def quantile( + a: _ListSeqND[complex], + q: _Array[_ShapeT, _floating_co], + axis: None = None, + out: None = None, + overwrite_input: bool = False, + method: _InterpolationMethod = "linear", + keepdims: L[False] = False, + *, + weights: _ArrayLikeFloat_co | None = None, +) -> _Array[_ShapeT, np.complex128]: ... +@overload # complex, array-like +def quantile( + a: _ListSeqND[complex], + q: NDArray[_floating_co] | _SeqND[_FloatLike_co], + axis: _ShapeLike | None = None, + out: None = None, + overwrite_input: bool = False, + method: _InterpolationMethod = "linear", + keepdims: bool = False, + *, + weights: _ArrayLikeFloat_co | None = None, +) -> NDArray[np.complex128]: ... +@overload # object_, scalar, axis=None +def quantile( + a: _ArrayLikeObject_co, + q: _FloatLike_co, + axis: None = None, + out: None = None, + overwrite_input: bool = False, + method: _InterpolationMethod = "linear", + keepdims: L[False] = False, + *, + weights: _ArrayLikeFloat_co | None = None, +) -> Any: ... +@overload # object_, scalar, axis= +def quantile( + a: _ArrayLikeObject_co, + q: _FloatLike_co, + axis: _ShapeLike, + out: None = None, + overwrite_input: bool = False, + method: _InterpolationMethod = "linear", + keepdims: L[False] = False, + *, + weights: _ArrayLikeFloat_co | None = None, +) -> NDArray[np.object_]: ... +@overload # object_, scalar, keepdims=True +def quantile( + a: _ArrayLikeObject_co, + q: _FloatLike_co, + axis: _ShapeLike | None = None, + out: None = None, + overwrite_input: bool = False, + method: _InterpolationMethod = "linear", + *, + keepdims: L[True], + weights: _ArrayLikeFloat_co | None = None, +) -> NDArray[np.object_]: ... +@overload # object_, array, axis=None +def quantile( + a: _ArrayLikeObject_co, + q: _Array[_ShapeT, _floating_co], + axis: None = None, + out: None = None, + overwrite_input: bool = False, + method: _InterpolationMethod = "linear", + keepdims: L[False] = False, + *, + weights: _ArrayLikeFloat_co | None = None, +) -> _Array[_ShapeT, np.object_]: ... +@overload # object_, array-like +def quantile( + a: _ArrayLikeObject_co, + q: NDArray[_floating_co] | _SeqND[_FloatLike_co], + axis: _ShapeLike | None = None, + out: None = None, + overwrite_input: bool = False, + method: _InterpolationMethod = "linear", + keepdims: bool = False, + *, + weights: _ArrayLikeFloat_co | None = None, +) -> NDArray[np.object_]: ... +@overload # out= (keyword) +def quantile( + a: ArrayLike, + q: _ArrayLikeFloat_co, + axis: _ShapeLike | None, + out: _ArrayT, + overwrite_input: bool = False, + method: _InterpolationMethod = "linear", + keepdims: bool = False, + *, + weights: _ArrayLikeFloat_co | None = None, +) -> _ArrayT: ... +@overload # out= (positional) +def quantile( + a: ArrayLike, + q: _ArrayLikeFloat_co, + axis: _ShapeLike | None = None, + *, + out: _ArrayT, + overwrite_input: bool = False, + method: _InterpolationMethod = "linear", + keepdims: bool = False, + weights: _ArrayLikeFloat_co | None = None, +) -> _ArrayT: ... +@overload # fallback +def quantile( + a: _ArrayLikeNumber_co | _ArrayLikeObject_co, + q: _ArrayLikeFloat_co, + axis: _ShapeLike | None = None, + out: None = None, + overwrite_input: bool = False, + method: _InterpolationMethod = "linear", + keepdims: bool = False, + *, + weights: _ArrayLikeFloat_co | None = None, +) -> Incomplete: ... + +# +@overload # ?d, known inexact/timedelta64 scalar-type +def trapezoid( + y: _ArrayNoD[_InexactTimeT], + x: _ArrayLike[_InexactTimeT] | _ArrayLikeFloat_co | None = None, + dx: float = 1.0, + axis: SupportsIndex = -1, +) -> NDArray[_InexactTimeT] | _InexactTimeT: ... +@overload # ?d, casts to float64 +def trapezoid( + y: _ArrayNoD[_integer_co], + x: _ArrayLikeFloat_co | None = None, + dx: float = 1.0, + axis: SupportsIndex = -1, +) -> NDArray[np.float64] | np.float64: ... +@overload # strict 1d, known inexact/timedelta64 scalar-type +def trapezoid( + y: _Array1D[_InexactTimeT], + x: _Array1D[_InexactTimeT] | _Seq1D[float] | None = None, + dx: float = 1.0, + axis: SupportsIndex = -1, +) -> _InexactTimeT: ... +@overload # strict 1d, casts to float64 +def trapezoid( + y: _Array1D[_float64_co] | _Seq1D[float], + x: _Array1D[_float64_co] | _Seq1D[float] | None = None, + dx: float = 1.0, + axis: SupportsIndex = -1, +) -> np.float64: ... +@overload # strict 1d, casts to complex128 (`list` prevents overlapping overloads) +def trapezoid( + y: list[complex], + x: _Seq1D[complex] | None = None, + dx: complex = 1.0, + axis: SupportsIndex = -1, +) -> np.complex128: ... +@overload # strict 1d, casts to complex128 +def trapezoid( + y: _Seq1D[complex], + x: list[complex], + dx: complex = 1.0, + axis: SupportsIndex = -1, +) -> np.complex128: ... +@overload # strict 2d, known inexact/timedelta64 scalar-type +def trapezoid( + y: _Array2D[_InexactTimeT], + x: _ArrayMax2D[_InexactTimeT] | _Seq2D[float] | _Seq1D[float] | None = None, + dx: float = 1.0, + axis: SupportsIndex = -1, +) -> _InexactTimeT: ... +@overload # strict 2d, casts to float64 +def trapezoid( + y: _Array2D[_float64_co] | _Seq2D[float], + x: _ArrayMax2D[_float64_co] | _Seq2D[float] | _Seq1D[float] | None = None, + dx: float = 1.0, + axis: SupportsIndex = -1, +) -> np.float64: ... +@overload # strict 2d, casts to complex128 (`list` prevents overlapping overloads) +def trapezoid( + y: _Seq1D[list[complex]], + x: _Seq2D[complex] | _Seq1D[complex] | None = None, + dx: complex = 1.0, + axis: SupportsIndex = -1, +) -> np.complex128: ... +@overload # strict 2d, casts to complex128 +def trapezoid( + y: _Seq2D[complex] | _Seq1D[complex], + x: _Seq1D[list[complex]], + dx: complex = 1.0, + axis: SupportsIndex = -1, +) -> np.complex128: ... +@overload +def trapezoid( + y: _ArrayLike[_InexactTimeT], + x: _ArrayLike[_InexactTimeT] | _ArrayLikeInt_co | None = None, + dx: complex = 1.0, + axis: SupportsIndex = -1, +) -> NDArray[_InexactTimeT] | _InexactTimeT: ... +@overload +def trapezoid( + y: _ArrayLike[_float64_co], + x: _ArrayLikeFloat_co | None = None, + dx: float = 1.0, + axis: SupportsIndex = -1, +) -> NDArray[np.float64] | np.float64: ... +@overload +def trapezoid( + y: _ArrayLike[np.complex128], + x: _ArrayLikeComplex_co | None = None, + dx: float = 1.0, + axis: SupportsIndex = -1, +) -> NDArray[np.complex128] | np.complex128: ... +@overload +def trapezoid( + y: _ArrayLikeComplex_co, + x: _ArrayLike[np.complex128], + dx: float = 1.0, + axis: SupportsIndex = -1, +) -> NDArray[np.complex128] | np.complex128: ... +@overload +def trapezoid( + y: _ArrayLikeObject_co, + x: _ArrayLikeObject_co | _ArrayLikeFloat_co | None = None, + dx: float = 1.0, + axis: SupportsIndex = -1, +) -> NDArray[np.object_] | Any: ... +@overload +def trapezoid( + y: _Seq1D[_SupportsRMulFloat[_T]], + x: _Seq1D[_SupportsRMulFloat[_T] | _T] | None = None, + dx: complex = 1.0, + axis: SupportsIndex = -1, +) -> _T: ... +@overload +def trapezoid( + y: _ArrayLikeComplex_co | _ArrayLike[np.timedelta64 | np.object_], + x: _ArrayLikeComplex_co | _ArrayLike[np.timedelta64 | np.object_] | None = None, + dx: complex = 1.0, + axis: SupportsIndex = -1, +) -> Incomplete: ... + +# +@overload # 0d +def meshgrid(*, copy: bool = True, sparse: bool = False, indexing: _Indexing = "xy") -> tuple[()]: ... +@overload # 1d, known scalar-type +def meshgrid( + x1: _ArrayLike[_ScalarT], + /, + *, + copy: bool = True, + sparse: bool = False, + indexing: _Indexing = "xy", +) -> _Mesh1[_ScalarT]: ... +@overload # 1d, unknown scalar-type +def meshgrid( + x1: ArrayLike, + /, + *, + copy: bool = True, + sparse: bool = False, + indexing: _Indexing = "xy", +) -> _Mesh1[Any]: ... +@overload # 2d, known scalar-types +def meshgrid( + x1: _ArrayLike[_ScalarT], + x2: _ArrayLike[_ScalarT1], + /, + *, + copy: bool = True, + sparse: bool = False, + indexing: _Indexing = "xy", +) -> _Mesh2[_ScalarT, _ScalarT1]: ... +@overload # 2d, known/unknown scalar-types +def meshgrid( + x1: _ArrayLike[_ScalarT], + x2: ArrayLike, + /, + *, + copy: bool = True, + sparse: bool = False, + indexing: _Indexing = "xy", +) -> _Mesh2[_ScalarT, Any]: ... +@overload # 2d, unknown/known scalar-types +def meshgrid( + x1: ArrayLike, + x2: _ArrayLike[_ScalarT], + /, + *, + copy: bool = True, + sparse: bool = False, + indexing: _Indexing = "xy", +) -> _Mesh2[Any, _ScalarT]: ... +@overload # 2d, unknown scalar-types +def meshgrid( + x1: ArrayLike, + x2: ArrayLike, + /, + *, + copy: bool = True, + sparse: bool = False, + indexing: _Indexing = "xy", +) -> _Mesh2[Any, Any]: ... +@overload # 3d, known scalar-types +def meshgrid( + x1: _ArrayLike[_ScalarT], + x2: _ArrayLike[_ScalarT1], + x3: _ArrayLike[_ScalarT2], + /, + *, + copy: bool = True, + sparse: bool = False, + indexing: _Indexing = "xy", +) -> _Mesh3[_ScalarT, _ScalarT1, _ScalarT2]: ... +@overload # 3d, unknown scalar-types +def meshgrid( + x1: ArrayLike, + x2: ArrayLike, + x3: ArrayLike, + /, + *, + copy: bool = True, + sparse: bool = False, + indexing: _Indexing = "xy", +) -> _Mesh3[Any, Any, Any]: ... +@overload # ?d, known scalar-types +def meshgrid( + *xi: _ArrayLike[_ScalarT], + copy: bool = True, + sparse: bool = False, + indexing: _Indexing = "xy", +) -> tuple[NDArray[_ScalarT], ...]: ... +@overload # ?d, unknown scalar-types +def meshgrid( + *xi: ArrayLike, + copy: bool = True, + sparse: bool = False, + indexing: _Indexing = "xy", +) -> tuple[NDArray[Any], ...]: ... + +# +def place(arr: np.ndarray, mask: ConvertibleToInt | Sequence[ConvertibleToInt], vals: ArrayLike) -> None: ... + +# keep in sync with `insert` +@overload # known scalar-type, axis=None (default) +def delete(arr: _ArrayLike[_ScalarT], obj: _IndexLike, axis: None = None) -> _Array1D[_ScalarT]: ... +@overload # known array-type, axis specified +def delete(arr: _ArrayT, obj: _IndexLike, axis: SupportsIndex) -> _ArrayT: ... +@overload # known scalar-type, axis specified +def delete(arr: _ArrayLike[_ScalarT], obj: _IndexLike, axis: SupportsIndex) -> NDArray[_ScalarT]: ... +@overload # known scalar-type, axis=None (default) +def delete(arr: ArrayLike, obj: _IndexLike, axis: None = None) -> _Array1D[Any]: ... +@overload # unknown scalar-type, axis specified +def delete(arr: ArrayLike, obj: _IndexLike, axis: SupportsIndex) -> NDArray[Any]: ... + +# keep in sync with `delete` +@overload # known scalar-type, axis=None (default) +def insert(arr: _ArrayLike[_ScalarT], obj: _IndexLike, values: ArrayLike, axis: None = None) -> _Array1D[_ScalarT]: ... +@overload # known array-type, axis specified +def insert(arr: _ArrayT, obj: _IndexLike, values: ArrayLike, axis: SupportsIndex) -> _ArrayT: ... +@overload # known scalar-type, axis specified +def insert(arr: _ArrayLike[_ScalarT], obj: _IndexLike, values: ArrayLike, axis: SupportsIndex) -> NDArray[_ScalarT]: ... +@overload # known scalar-type, axis=None (default) +def insert(arr: ArrayLike, obj: _IndexLike, values: ArrayLike, axis: None = None) -> _Array1D[Any]: ... +@overload # unknown scalar-type, axis specified +def insert(arr: ArrayLike, obj: _IndexLike, values: ArrayLike, axis: SupportsIndex) -> NDArray[Any]: ... + +# +@overload # known array type, axis specified +def append(arr: _ArrayT, values: _ArrayT, axis: SupportsIndex) -> _ArrayT: ... +@overload # 1d, known scalar type, axis specified +def append(arr: _Seq1D[_ScalarT], values: _Seq1D[_ScalarT], axis: SupportsIndex) -> _Array1D[_ScalarT]: ... +@overload # 2d, known scalar type, axis specified +def append(arr: _Seq2D[_ScalarT], values: _Seq2D[_ScalarT], axis: SupportsIndex) -> _Array2D[_ScalarT]: ... +@overload # 3d, known scalar type, axis specified +def append(arr: _Seq3D[_ScalarT], values: _Seq3D[_ScalarT], axis: SupportsIndex) -> _Array3D[_ScalarT]: ... +@overload # ?d, known scalar type, axis specified +def append(arr: _SeqND[_ScalarT], values: _SeqND[_ScalarT], axis: SupportsIndex) -> NDArray[_ScalarT]: ... +@overload # ?d, unknown scalar type, axis specified +def append(arr: np.ndarray | _SeqND[_ScalarLike_co], values: _SeqND[_ScalarLike_co], axis: SupportsIndex) -> np.ndarray: ... +@overload # known scalar type, axis=None +def append(arr: _ArrayLike[_ScalarT], values: _ArrayLike[_ScalarT], axis: None = None) -> _Array1D[_ScalarT]: ... +@overload # unknown scalar type, axis=None +def append(arr: ArrayLike, values: ArrayLike, axis: None = None) -> _Array1D[Any]: ... + +# +@overload +def digitize( + x: _Array[_ShapeT, np.floating | np.integer], bins: _ArrayLikeFloat_co, right: bool = False +) -> _Array[_ShapeT, np.int_]: ... +@overload +def digitize(x: _FloatLike_co, bins: _ArrayLikeFloat_co, right: bool = False) -> np.int_: ... +@overload +def digitize(x: _Seq1D[_FloatLike_co], bins: _ArrayLikeFloat_co, right: bool = False) -> _Array1D[np.int_]: ... +@overload +def digitize(x: _Seq2D[_FloatLike_co], bins: _ArrayLikeFloat_co, right: bool = False) -> _Array2D[np.int_]: ... +@overload +def digitize(x: _Seq3D[_FloatLike_co], bins: _ArrayLikeFloat_co, right: bool = False) -> _Array3D[np.int_]: ... +@overload +def digitize(x: _ArrayLikeFloat_co, bins: _ArrayLikeFloat_co, right: bool = False) -> NDArray[np.int_] | Any: ... diff --git a/python/user_packages/Python313/site-packages/numpy/lib/_histograms_impl.py b/python/user_packages/Python313/site-packages/numpy/lib/_histograms_impl.py new file mode 100644 index 0000000000000000000000000000000000000000..6aa0aa9e64cc3877dd360187c5a555d6a9a77a36 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/lib/_histograms_impl.py @@ -0,0 +1,1085 @@ +""" +Histogram-related functions +""" +import contextlib +import functools +import operator +import warnings + +import numpy as np +from numpy._core import overrides + +__all__ = ['histogram', 'histogramdd', 'histogram_bin_edges'] + +array_function_dispatch = functools.partial( + overrides.array_function_dispatch, module='numpy') + +# range is a keyword argument to many functions, so save the builtin so they can +# use it. +_range = range + + +def _ptp(x): + """Peak-to-peak value of x. + + This implementation avoids the problem of signed integer arrays having a + peak-to-peak value that cannot be represented with the array's data type. + This function returns an unsigned value for signed integer arrays. + """ + return _unsigned_subtract(x.max(), x.min()) + + +def _hist_bin_sqrt(x, range): + """ + Square root histogram bin estimator. + + Bin width is inversely proportional to the data size. Used by many + programs for its simplicity. + + Parameters + ---------- + x : array_like + Input data that is to be histogrammed, trimmed to range. May not + be empty. + + Returns + ------- + h : An estimate of the optimal bin width for the given data. + """ + del range # unused + return _ptp(x) / np.sqrt(x.size) + + +def _hist_bin_sturges(x, range): + """ + Sturges histogram bin estimator. + + A very simplistic estimator based on the assumption of normality of + the data. This estimator has poor performance for non-normal data, + which becomes especially obvious for large data sets. The estimate + depends only on size of the data. + + Parameters + ---------- + x : array_like + Input data that is to be histogrammed, trimmed to range. May not + be empty. + + Returns + ------- + h : An estimate of the optimal bin width for the given data. + """ + del range # unused + return _ptp(x) / (np.log2(x.size) + 1.0) + + +def _hist_bin_rice(x, range): + """ + Rice histogram bin estimator. + + Another simple estimator with no normality assumption. It has better + performance for large data than Sturges, but tends to overestimate + the number of bins. The number of bins is proportional to the cube + root of data size (asymptotically optimal). The estimate depends + only on size of the data. + + Parameters + ---------- + x : array_like + Input data that is to be histogrammed, trimmed to range. May not + be empty. + + Returns + ------- + h : An estimate of the optimal bin width for the given data. + """ + del range # unused + return _ptp(x) / (2.0 * x.size ** (1.0 / 3)) + + +def _hist_bin_scott(x, range): + """ + Scott histogram bin estimator. + + The binwidth is proportional to the standard deviation of the data + and inversely proportional to the cube root of data size + (asymptotically optimal). + + Parameters + ---------- + x : array_like + Input data that is to be histogrammed, trimmed to range. May not + be empty. + + Returns + ------- + h : An estimate of the optimal bin width for the given data. + """ + del range # unused + return (24.0 * np.pi**0.5 / x.size)**(1.0 / 3.0) * np.std(x) + + +def _hist_bin_stone(x, range): + """ + Histogram bin estimator based on minimizing the estimated integrated squared error (ISE). + + The number of bins is chosen by minimizing the estimated ISE against the unknown + true distribution. The ISE is estimated using cross-validation and can be regarded + as a generalization of Scott's rule. + https://en.wikipedia.org/wiki/Histogram#Scott.27s_normal_reference_rule + + This paper by Stone appears to be the origination of this rule. + https://digitalassets.lib.berkeley.edu/sdtr/ucb/text/34.pdf + + Parameters + ---------- + x : array_like + Input data that is to be histogrammed, trimmed to range. May not + be empty. + range : (float, float) + The lower and upper range of the bins. + + Returns + ------- + h : An estimate of the optimal bin width for the given data. + """ # noqa: E501 + + n = x.size + ptp_x = _ptp(x) + if n <= 1 or ptp_x == 0: + return 0 + + def jhat(nbins): + hh = ptp_x / nbins + p_k = np.histogram(x, bins=nbins, range=range)[0] / n + return (2 - (n + 1) * p_k.dot(p_k)) / hh + + nbins_upper_bound = max(100, int(np.sqrt(n))) + nbins = min(_range(1, nbins_upper_bound + 1), key=jhat) + if nbins == nbins_upper_bound: + warnings.warn("The number of bins estimated may be suboptimal.", + RuntimeWarning, stacklevel=3) + return ptp_x / nbins + + +def _hist_bin_doane(x, range): + """ + Doane's histogram bin estimator. + + Improved version of Sturges' formula which works better for + non-normal data. See + stats.stackexchange.com/questions/55134/doanes-formula-for-histogram-binning + + Parameters + ---------- + x : array_like + Input data that is to be histogrammed, trimmed to range. May not + be empty. + + Returns + ------- + h : An estimate of the optimal bin width for the given data. + """ + del range # unused + if x.size > 2: + sg1 = np.sqrt(6.0 * (x.size - 2) / ((x.size + 1.0) * (x.size + 3))) + sigma = np.std(x) + if sigma > 0.0: + # These three operations add up to + # g1 = np.mean(((x - np.mean(x)) / sigma)**3) + # but use only one temp array instead of three + temp = x - np.mean(x) + np.true_divide(temp, sigma, temp) + np.power(temp, 3, temp) + g1 = np.mean(temp) + return _ptp(x) / (1.0 + np.log2(x.size) + + np.log2(1.0 + np.absolute(g1) / sg1)) + return 0.0 + + +def _hist_bin_fd(x, range): + """ + The Freedman-Diaconis histogram bin estimator. + + The Freedman-Diaconis rule uses interquartile range (IQR) to + estimate binwidth. It is considered a variation of the Scott rule + with more robustness as the IQR is less affected by outliers than + the standard deviation. However, the IQR depends on fewer points + than the standard deviation, so it is less accurate, especially for + long tailed distributions. + + If the IQR is 0, this function returns 0 for the bin width. + Binwidth is inversely proportional to the cube root of data size + (asymptotically optimal). + + Parameters + ---------- + x : array_like + Input data that is to be histogrammed, trimmed to range. May not + be empty. + + Returns + ------- + h : An estimate of the optimal bin width for the given data. + """ + del range # unused + iqr = np.subtract(*np.percentile(x, [75, 25])) + return 2.0 * iqr * x.size ** (-1.0 / 3.0) + + +def _hist_bin_auto(x, range): + """ + Histogram bin estimator that uses the minimum width of a relaxed + Freedman-Diaconis and Sturges estimators if the FD bin width does + not result in a large number of bins. The relaxed Freedman-Diaconis estimator + limits the bin width to half the sqrt estimated to avoid small bins. + + The FD estimator is usually the most robust method, but its width + estimate tends to be too large for small `x` and bad for data with limited + variance. The Sturges estimator is quite good for small (<1000) datasets + and is the default in the R language. This method gives good off-the-shelf + behaviour. + + + Parameters + ---------- + x : array_like + Input data that is to be histogrammed, trimmed to range. May not + be empty. + range : Tuple with range for the histogram + + Returns + ------- + h : An estimate of the optimal bin width for the given data. + + See Also + -------- + _hist_bin_fd, _hist_bin_sturges + """ + fd_bw = _hist_bin_fd(x, range) + sturges_bw = _hist_bin_sturges(x, range) + sqrt_bw = _hist_bin_sqrt(x, range) + # heuristic to limit the maximal number of bins + fd_bw_corrected = max(fd_bw, sqrt_bw / 2) + return min(fd_bw_corrected, sturges_bw) + + +# Private dict initialized at module load time +_hist_bin_selectors = {'stone': _hist_bin_stone, + 'auto': _hist_bin_auto, + 'doane': _hist_bin_doane, + 'fd': _hist_bin_fd, + 'rice': _hist_bin_rice, + 'scott': _hist_bin_scott, + 'sqrt': _hist_bin_sqrt, + 'sturges': _hist_bin_sturges} + + +def _ravel_and_check_weights(a, weights): + """ Check a and weights have matching shapes, and ravel both """ + a = np.asarray(a) + + # Ensure that the array is a "subtractable" dtype + if a.dtype == np.bool: + msg = f"Converting input from {a.dtype} to {np.uint8} for compatibility." + warnings.warn(msg, RuntimeWarning, stacklevel=3) + a = a.astype(np.uint8) + + if weights is not None: + weights = np.asarray(weights) + if weights.shape != a.shape: + raise ValueError( + 'weights should have the same shape as a.') + weights = weights.ravel() + a = a.ravel() + return a, weights + + +def _get_outer_edges(a, range): + """ + Determine the outer bin edges to use, from either the data or the range + argument + """ + if range is not None: + first_edge, last_edge = range + if first_edge > last_edge: + raise ValueError( + 'max must be larger than min in range parameter.') + if not (np.isfinite(first_edge) and np.isfinite(last_edge)): + raise ValueError( + f"supplied range of [{first_edge}, {last_edge}] is not finite") + elif a.size == 0: + # handle empty arrays. Can't determine range, so use 0-1. + first_edge, last_edge = 0, 1 + else: + first_edge, last_edge = a.min(), a.max() + if not (np.isfinite(first_edge) and np.isfinite(last_edge)): + raise ValueError( + f"autodetected range of [{first_edge}, {last_edge}] is not finite") + + # expand empty range to avoid divide by zero + if first_edge == last_edge: + first_edge = first_edge - 0.5 + last_edge = last_edge + 0.5 + + return first_edge, last_edge + + +def _unsigned_subtract(a, b): + """ + Subtract two values where a >= b, and produce an unsigned result + + This is needed when finding the difference between the upper and lower + bound of an int16 histogram + """ + # coerce to a single type + signed_to_unsigned = { + np.byte: np.ubyte, + np.short: np.ushort, + np.intc: np.uintc, + np.int_: np.uint, + np.longlong: np.ulonglong + } + dt = np.result_type(a, b) + try: + unsigned_dt = signed_to_unsigned[dt.type] + except KeyError: + return np.subtract(a, b, dtype=dt) + else: + # we know the inputs are integers, and we are deliberately casting + # signed to unsigned. The input may be negative python integers so + # ensure we pass in arrays with the initial dtype (related to NEP 50). + return np.subtract(np.asarray(a, dtype=dt), np.asarray(b, dtype=dt), + casting='unsafe', dtype=unsigned_dt) + + +def _get_bin_edges(a, bins, range, weights): + """ + Computes the bins used internally by `histogram`. + + Parameters + ========== + a : ndarray + Ravelled data array + bins, range + Forwarded arguments from `histogram`. + weights : ndarray, optional + Ravelled weights array, or None + + Returns + ======= + bin_edges : ndarray + Array of bin edges + uniform_bins : (Number, Number, int): + The upper bound, lowerbound, and number of bins, used in the optimized + implementation of `histogram` that works on uniform bins. + """ + # parse the overloaded bins argument + n_equal_bins = None + bin_edges = None + + if isinstance(bins, str): + bin_name = bins + # if `bins` is a string for an automatic method, + # this will replace it with the number of bins calculated + if bin_name not in _hist_bin_selectors: + raise ValueError( + f"{bin_name!r} is not a valid estimator for `bins`") + if weights is not None: + raise TypeError("Automated estimation of the number of " + "bins is not supported for weighted data") + + first_edge, last_edge = _get_outer_edges(a, range) + + # truncate the range if needed + if range is not None: + keep = (a >= first_edge) + keep &= (a <= last_edge) + if not np.logical_and.reduce(keep): + a = a[keep] + + if a.size == 0: + n_equal_bins = 1 + else: + # Do not call selectors on empty arrays + width = _hist_bin_selectors[bin_name](a, (first_edge, last_edge)) + if width: + if np.issubdtype(a.dtype, np.integer) and width < 1: + width = 1 + delta = _unsigned_subtract(last_edge, first_edge) + n_equal_bins = int(np.ceil(delta / width)) + else: + # Width can be zero for some estimators, e.g. FD when + # the IQR of the data is zero. + n_equal_bins = 1 + + elif np.ndim(bins) == 0: + try: + n_equal_bins = operator.index(bins) + except TypeError as e: + raise TypeError( + '`bins` must be an integer, a string, or an array') from e + if n_equal_bins < 1: + raise ValueError('`bins` must be positive, when an integer') + + first_edge, last_edge = _get_outer_edges(a, range) + + elif np.ndim(bins) == 1: + bin_edges = np.asarray(bins) + if np.any(bin_edges[:-1] > bin_edges[1:]): + raise ValueError( + '`bins` must increase monotonically, when an array') + + else: + raise ValueError('`bins` must be 1d, when an array') + + if n_equal_bins is not None: + # gh-10322 means that type resolution rules are dependent on array + # shapes. To avoid this causing problems, we pick a type now and stick + # with it throughout. + bin_type = np.result_type(first_edge, last_edge, a) + if np.issubdtype(bin_type, np.integer): + bin_type = np.result_type(bin_type, float) + + # bin edges must be computed + bin_edges = np.linspace( + first_edge, last_edge, n_equal_bins + 1, + endpoint=True, dtype=bin_type) + if np.any(bin_edges[:-1] >= bin_edges[1:]): + raise ValueError( + f'Too many bins for data range. Cannot create {n_equal_bins} ' + f'finite-sized bins.') + return bin_edges, (first_edge, last_edge, n_equal_bins) + else: + return bin_edges, None + + +def _search_sorted_inclusive(a, v): + """ + Like `searchsorted`, but where the last item in `v` is placed on the right. + + In the context of a histogram, this makes the last bin edge inclusive + """ + return np.concatenate(( + a.searchsorted(v[:-1], 'left'), + a.searchsorted(v[-1:], 'right') + )) + + +def _histogram_bin_edges_dispatcher(a, bins=None, range=None, weights=None): + return (a, bins, weights) + + +@array_function_dispatch(_histogram_bin_edges_dispatcher) +def histogram_bin_edges(a, bins=10, range=None, weights=None): + r""" + Function to calculate only the edges of the bins used by the `histogram` + function. + + Parameters + ---------- + a : array_like + Input data. The histogram is computed over the flattened array. + bins : int or sequence of scalars or str, optional + If `bins` is an int, it defines the number of equal-width + bins in the given range (10, by default). If `bins` is a + sequence, it defines the bin edges, including the rightmost + edge, allowing for non-uniform bin widths. + + If `bins` is a string from the list below, `histogram_bin_edges` will + use the method chosen to calculate the optimal bin width and + consequently the number of bins (see the Notes section for more detail + on the estimators) from the data that falls within the requested range. + While the bin width will be optimal for the actual data + in the range, the number of bins will be computed to fill the + entire range, including the empty portions. For visualisation, + using the 'auto' option is suggested. Weighted data is not + supported for automated bin size selection. + + 'auto' + Minimum bin width between the 'sturges' and 'fd' estimators. + Provides good all-around performance. + + 'fd' (Freedman Diaconis Estimator) + Robust (resilient to outliers) estimator that takes into + account data variability and data size. + + 'doane' + An improved version of Sturges' estimator that works better + with non-normal datasets. + + 'scott' + Less robust estimator that takes into account data variability + and data size. + + 'stone' + Estimator based on leave-one-out cross-validation estimate of + the integrated squared error. Can be regarded as a generalization + of Scott's rule. + + 'rice' + Estimator does not take variability into account, only data + size. Commonly overestimates number of bins required. + + 'sturges' + R's default method, only accounts for data size. Only + optimal for gaussian data and underestimates number of bins + for large non-gaussian datasets. + + 'sqrt' + Square root (of data size) estimator, used by Excel and + other programs for its speed and simplicity. + + range : (float, float), optional + The lower and upper range of the bins. If not provided, range + is simply ``(a.min(), a.max())``. Values outside the range are + ignored. The first element of the range must be less than or + equal to the second. `range` affects the automatic bin + computation as well. While bin width is computed to be optimal + based on the actual data within `range`, the bin count will fill + the entire range including portions containing no data. + + weights : array_like, optional + An array of weights, of the same shape as `a`. Each value in + `a` only contributes its associated weight towards the bin count + (instead of 1). This is currently not used by any of the bin estimators, + but may be in the future. + + Returns + ------- + bin_edges : array of dtype float + The edges to pass into `histogram` + + See Also + -------- + histogram + + Notes + ----- + The methods to estimate the optimal number of bins are well founded + in literature, and are inspired by the choices R provides for + histogram visualisation. Note that having the number of bins + proportional to :math:`n^{1/3}` is asymptotically optimal, which is + why it appears in most estimators. These are simply plug-in methods + that give good starting points for number of bins. In the equations + below, :math:`h` is the binwidth and :math:`n_h` is the number of + bins. All estimators that compute bin counts are recast to bin width + using the `ptp` of the data. The final bin count is obtained from + ``np.round(np.ceil(range / h))``. The final bin width is often less + than what is returned by the estimators below. + + 'auto' (minimum bin width of the 'sturges' and 'fd' estimators) + A compromise to get a good value. For small datasets the Sturges + value will usually be chosen, while larger datasets will usually + default to FD. Avoids the overly conservative behaviour of FD + and Sturges for small and large datasets respectively. + Switchover point is usually :math:`a.size \approx 1000`. + + 'fd' (Freedman Diaconis Estimator) + .. math:: h = 2 \frac{IQR}{n^{1/3}} + + The binwidth is proportional to the interquartile range (IQR) + and inversely proportional to cube root of a.size. Can be too + conservative for small datasets, but is quite good for large + datasets. The IQR is very robust to outliers. + + 'scott' + .. math:: h = \sigma \sqrt[3]{\frac{24 \sqrt{\pi}}{n}} + + The binwidth is proportional to the standard deviation of the + data and inversely proportional to cube root of ``x.size``. Can + be too conservative for small datasets, but is quite good for + large datasets. The standard deviation is not very robust to + outliers. Values are very similar to the Freedman-Diaconis + estimator in the absence of outliers. + + 'rice' + .. math:: n_h = 2n^{1/3} + + The number of bins is only proportional to cube root of + ``a.size``. It tends to overestimate the number of bins and it + does not take into account data variability. + + 'sturges' + .. math:: n_h = \log _{2}(n) + 1 + + The number of bins is the base 2 log of ``a.size``. This + estimator assumes normality of data and is too conservative for + larger, non-normal datasets. This is the default method in R's + ``hist`` method. + + 'doane' + .. math:: n_h = 1 + \log_{2}(n) + + \log_{2}\left(1 + \frac{|g_1|}{\sigma_{g_1}}\right) + + g_1 = mean\left[\left(\frac{x - \mu}{\sigma}\right)^3\right] + + \sigma_{g_1} = \sqrt{\frac{6(n - 2)}{(n + 1)(n + 3)}} + + An improved version of Sturges' formula that produces better + estimates for non-normal datasets. This estimator attempts to + account for the skew of the data. + + 'sqrt' + .. math:: n_h = \sqrt n + + The simplest and fastest estimator. Only takes into account the + data size. + + Additionally, if the data is of integer dtype, then the binwidth will never + be less than 1. + + Examples + -------- + >>> import numpy as np + >>> arr = np.array([0, 0, 0, 1, 2, 3, 3, 4, 5]) + >>> np.histogram_bin_edges(arr, bins='auto', range=(0, 1)) + array([0. , 0.25, 0.5 , 0.75, 1. ]) + >>> np.histogram_bin_edges(arr, bins=2) + array([0. , 2.5, 5. ]) + + For consistency with histogram, an array of pre-computed bins is + passed through unmodified: + + >>> np.histogram_bin_edges(arr, [1, 2]) + array([1, 2]) + + This function allows one set of bins to be computed, and reused across + multiple histograms: + + >>> shared_bins = np.histogram_bin_edges(arr, bins='auto') + >>> shared_bins + array([0., 1., 2., 3., 4., 5.]) + + >>> group_id = np.array([0, 1, 1, 0, 1, 1, 0, 1, 1]) + >>> hist_0, _ = np.histogram(arr[group_id == 0], bins=shared_bins) + >>> hist_1, _ = np.histogram(arr[group_id == 1], bins=shared_bins) + + >>> hist_0; hist_1 + array([1, 1, 0, 1, 0]) + array([2, 0, 1, 1, 2]) + + Which gives more easily comparable results than using separate bins for + each histogram: + + >>> hist_0, bins_0 = np.histogram(arr[group_id == 0], bins='auto') + >>> hist_1, bins_1 = np.histogram(arr[group_id == 1], bins='auto') + >>> hist_0; hist_1 + array([1, 1, 1]) + array([2, 1, 1, 2]) + >>> bins_0; bins_1 + array([0., 1., 2., 3.]) + array([0. , 1.25, 2.5 , 3.75, 5. ]) + + """ + a, weights = _ravel_and_check_weights(a, weights) + bin_edges, _ = _get_bin_edges(a, bins, range, weights) + return bin_edges + + +def _histogram_dispatcher( + a, bins=None, range=None, density=None, weights=None): + return (a, bins, weights) + + +@array_function_dispatch(_histogram_dispatcher) +def histogram(a, bins=10, range=None, density=None, weights=None): + r""" + Compute the histogram of a dataset. + + Parameters + ---------- + a : array_like + Input data. The histogram is computed over the flattened array. + bins : int or sequence of scalars or str, optional + If `bins` is an int, it defines the number of equal-width + bins in the given range (10, by default). If `bins` is a + sequence, it defines a monotonically increasing array of bin edges, + including the rightmost edge, allowing for non-uniform bin widths. + + If `bins` is a string, it defines the method used to calculate the + optimal bin width, as defined by `histogram_bin_edges`. + + range : (float, float), optional + The lower and upper range of the bins. If not provided, range + is simply ``(a.min(), a.max())``. Values outside the range are + ignored. The first element of the range must be less than or + equal to the second. `range` affects the automatic bin + computation as well. While bin width is computed to be optimal + based on the actual data within `range`, the bin count will fill + the entire range including portions containing no data. + weights : array_like, optional + An array of weights, of the same shape as `a`. Each value in + `a` only contributes its associated weight towards the bin count + (instead of 1). If `density` is True, the weights are + normalized, so that the integral of the density over the range + remains 1. + Please note that the ``dtype`` of `weights` will also become the + ``dtype`` of the returned accumulator (`hist`), so it must be + large enough to hold accumulated values as well. + density : bool, optional + If ``False``, the result will contain the number of samples in + each bin. If ``True``, the result is the value of the + probability *density* function at the bin, normalized such that + the *integral* over the range is 1. Note that the sum of the + histogram values will not be equal to 1 unless bins of unity + width are chosen; it is not a probability *mass* function. + + Returns + ------- + hist : array + The values of the histogram. See `density` and `weights` for a + description of the possible semantics. If `weights` are given, + ``hist.dtype`` will be taken from `weights`. + bin_edges : array of dtype float + Return the bin edges ``(length(hist)+1)``. + + + See Also + -------- + histogramdd, bincount, searchsorted, digitize, histogram_bin_edges + + Notes + ----- + All but the last (righthand-most) bin is half-open. In other words, + if `bins` is:: + + [1, 2, 3, 4] + + then the first bin is ``[1, 2)`` (including 1, but excluding 2) and + the second ``[2, 3)``. The last bin, however, is ``[3, 4]``, which + *includes* 4. + + + Examples + -------- + >>> import numpy as np + >>> np.histogram([1, 2, 1], bins=[0, 1, 2, 3]) + (array([0, 2, 1]), array([0, 1, 2, 3])) + >>> np.histogram(np.arange(4), bins=np.arange(5), density=True) + (array([0.25, 0.25, 0.25, 0.25]), array([0, 1, 2, 3, 4])) + >>> np.histogram([[1, 2, 1], [1, 0, 1]], bins=[0,1,2,3]) + (array([1, 4, 1]), array([0, 1, 2, 3])) + + >>> a = np.arange(5) + >>> hist, bin_edges = np.histogram(a, density=True) + >>> hist + array([0.5, 0. , 0.5, 0. , 0. , 0.5, 0. , 0.5, 0. , 0.5]) + >>> hist.sum() + 2.4999999999999996 + >>> np.sum(hist * np.diff(bin_edges)) + 1.0 + + Automated Bin Selection Methods example, using 2 peak random data + with 2000 points. + + .. plot:: + :include-source: + + import matplotlib.pyplot as plt + import numpy as np + + rng = np.random.RandomState(10) # deterministic random data + a = np.hstack((rng.normal(size=1000), + rng.normal(loc=5, scale=2, size=1000))) + plt.hist(a, bins='auto') # arguments are passed to np.histogram + plt.title("Histogram with 'auto' bins") + plt.show() + + """ + a, weights = _ravel_and_check_weights(a, weights) + + bin_edges, uniform_bins = _get_bin_edges(a, bins, range, weights) + + # Histogram is an integer or a float array depending on the weights. + if weights is None: + ntype = np.dtype(np.intp) + else: + ntype = weights.dtype + + # We set a block size, as this allows us to iterate over chunks when + # computing histograms, to minimize memory usage. + BLOCK = 65536 + + # The fast path uses bincount, but that only works for certain types + # of weight + simple_weights = ( + weights is None or + np.can_cast(weights.dtype, np.double) or + np.can_cast(weights.dtype, complex) + ) + + if uniform_bins is not None and simple_weights: + # Fast algorithm for equal bins + # We now convert values of a to bin indices, under the assumption of + # equal bin widths (which is valid here). + first_edge, last_edge, n_equal_bins = uniform_bins + + # Initialize empty histogram + n = np.zeros(n_equal_bins, ntype) + + # Pre-compute histogram scaling factor + norm_numerator = n_equal_bins + norm_denom = _unsigned_subtract(last_edge, first_edge) + + # We iterate over blocks here for two reasons: the first is that for + # large arrays, it is actually faster (for example for a 10^8 array it + # is 2x as fast) and it results in a memory footprint 3x lower in the + # limit of large arrays. + for i in _range(0, len(a), BLOCK): + tmp_a = a[i:i + BLOCK] + if weights is None: + tmp_w = None + else: + tmp_w = weights[i:i + BLOCK] + + # Only include values in the right range + keep = (tmp_a >= first_edge) + keep &= (tmp_a <= last_edge) + if not np.logical_and.reduce(keep): + tmp_a = tmp_a[keep] + if tmp_w is not None: + tmp_w = tmp_w[keep] + + # This cast ensures no type promotions occur below, which gh-10322 + # make unpredictable. Getting it wrong leads to precision errors + # like gh-8123. + tmp_a = tmp_a.astype(bin_edges.dtype, copy=False) + + # Compute the bin indices, and for values that lie exactly on + # last_edge we need to subtract one + f_indices = ((_unsigned_subtract(tmp_a, first_edge) / norm_denom) + * norm_numerator) + indices = f_indices.astype(np.intp) + indices[indices == n_equal_bins] -= 1 + + # The index computation is not guaranteed to give exactly + # consistent results within ~1 ULP of the bin edges. + decrement = tmp_a < bin_edges[indices] + indices[decrement] -= 1 + # The last bin includes the right edge. The other bins do not. + increment = ((tmp_a >= bin_edges[indices + 1]) + & (indices != n_equal_bins - 1)) + indices[increment] += 1 + + # We now compute the histogram using bincount + if ntype.kind == 'c': + n.real += np.bincount(indices, weights=tmp_w.real, + minlength=n_equal_bins) + n.imag += np.bincount(indices, weights=tmp_w.imag, + minlength=n_equal_bins) + else: + n += np.bincount(indices, weights=tmp_w, + minlength=n_equal_bins).astype(ntype) + else: + # Compute via cumulative histogram + cum_n = np.zeros(bin_edges.shape, ntype) + if weights is None: + for i in _range(0, len(a), BLOCK): + sa = np.sort(a[i:i + BLOCK]) + cum_n += _search_sorted_inclusive(sa, bin_edges) + else: + zero = np.zeros(1, dtype=ntype) + for i in _range(0, len(a), BLOCK): + tmp_a = a[i:i + BLOCK] + tmp_w = weights[i:i + BLOCK] + sorting_index = np.argsort(tmp_a) + sa = tmp_a[sorting_index] + sw = tmp_w[sorting_index] + cw = np.concatenate((zero, sw.cumsum())) + bin_index = _search_sorted_inclusive(sa, bin_edges) + cum_n += cw[bin_index] + + n = np.diff(cum_n) + + if density: + db = np.array(np.diff(bin_edges), float) + return n / db / n.sum(), bin_edges + + return n, bin_edges + + +def _histogramdd_dispatcher(sample, bins=None, range=None, density=None, + weights=None): + if hasattr(sample, 'shape'): # same condition as used in histogramdd + yield sample + else: + yield from sample + with contextlib.suppress(TypeError): + yield from bins + yield weights + + +@array_function_dispatch(_histogramdd_dispatcher) +def histogramdd(sample, bins=10, range=None, density=None, weights=None): + """ + Compute the multidimensional histogram of some data. + + Parameters + ---------- + sample : (N, D) array, or (N, D) array_like + The data to be histogrammed. + + Note the unusual interpretation of sample when an array_like: + + * When an array, each row is a coordinate in a D-dimensional space - + such as ``histogramdd(np.array([p1, p2, p3]))``. + * When an array_like, each element is the list of values for single + coordinate - such as ``histogramdd((X, Y, Z))``. + + The first form should be preferred. + + bins : sequence or int, optional + The bin specification: + + * A sequence of arrays describing the monotonically increasing bin + edges along each dimension. + * The number of bins for each dimension (nx, ny, ... =bins) + * The number of bins for all dimensions (nx=ny=...=bins). + + range : sequence, optional + A sequence of length D, each an optional (lower, upper) tuple giving + the outer bin edges to be used if the edges are not given explicitly in + `bins`. + An entry of None in the sequence results in the minimum and maximum + values being used for the corresponding dimension. + The default, None, is equivalent to passing a tuple of D None values. + density : bool, optional + If False, the default, returns the number of samples in each bin. + If True, returns the probability *density* function at the bin, + ``bin_count / sample_count / bin_volume``. + weights : (N,) array_like, optional + An array of values `w_i` weighing each sample `(x_i, y_i, z_i, ...)`. + Weights are normalized to 1 if density is True. If density is False, + the values of the returned histogram are equal to the sum of the + weights belonging to the samples falling into each bin. + + Returns + ------- + H : ndarray + The multidimensional histogram of sample x. See density and weights + for the different possible semantics. + edges : tuple of ndarrays + A tuple of D arrays describing the bin edges for each dimension. + + See Also + -------- + histogram: 1-D histogram + histogram2d: 2-D histogram + + Examples + -------- + >>> import numpy as np + >>> rng = np.random.default_rng() + >>> r = rng.normal(size=(100,3)) + >>> H, edges = np.histogramdd(r, bins = (5, 8, 4)) + >>> H.shape, edges[0].size, edges[1].size, edges[2].size + ((5, 8, 4), 6, 9, 5) + + """ + + try: + # Sample is an ND-array. + N, D = sample.shape + except (AttributeError, ValueError): + # Sample is a sequence of 1D arrays. + sample = np.atleast_2d(sample).T + N, D = sample.shape + + nbin = np.empty(D, np.intp) + edges = D * [None] + dedges = D * [None] + if weights is not None: + weights = np.asarray(weights) + + try: + M = len(bins) + if M != D: + raise ValueError( + 'The dimension of bins must be equal to the dimension of the ' + 'sample x.') + except TypeError: + # bins is an integer + bins = D * [bins] + + # normalize the range argument + if range is None: + range = (None,) * D + elif len(range) != D: + raise ValueError('range argument must have one entry per dimension') + + # Create edge arrays + for i in _range(D): + if np.ndim(bins[i]) == 0: + if bins[i] < 1: + raise ValueError( + f'`bins[{i}]` must be positive, when an integer') + smin, smax = _get_outer_edges(sample[:, i], range[i]) + try: + n = operator.index(bins[i]) + + except TypeError as e: + raise TypeError( + f"`bins[{i}]` must be an integer, when a scalar" + ) from e + + edges[i] = np.linspace(smin, smax, n + 1) + elif np.ndim(bins[i]) == 1: + edges[i] = np.asarray(bins[i]) + if np.any(edges[i][:-1] > edges[i][1:]): + raise ValueError( + f'`bins[{i}]` must be monotonically increasing, when an array') + else: + raise ValueError( + f'`bins[{i}]` must be a scalar or 1d array') + + nbin[i] = len(edges[i]) + 1 # includes an outlier on each end + dedges[i] = np.diff(edges[i]) + + # Compute the bin number each sample falls into. + Ncount = tuple( + # avoid np.digitize to work around gh-11022 + np.searchsorted(edges[i], sample[:, i], side='right') + for i in _range(D) + ) + + # Using digitize, values that fall on an edge are put in the right bin. + # For the rightmost bin, we want values equal to the right edge to be + # counted in the last bin, and not as an outlier. + for i in _range(D): + # Find which points are on the rightmost edge. + on_edge = (sample[:, i] == edges[i][-1]) + # Shift these points one bin to the left. + Ncount[i][on_edge] -= 1 + + # Compute the sample indices in the flattened histogram matrix. + # This raises an error if the array is too large. + xy = np.ravel_multi_index(Ncount, nbin) + + # Compute the number of repetitions in xy and assign it to the + # flattened histmat. + hist = np.bincount(xy, weights, minlength=nbin.prod()) + + # Shape into a proper matrix + hist = hist.reshape(nbin) + + # This preserves the (bad) behavior observed in gh-7845, for now. + hist = hist.astype(float, casting='safe') + + # Remove outliers (indices 0 and -1 for each dimension). + core = D * (slice(1, -1),) + hist = hist[core] + + if density: + # calculate the probability density function + s = hist.sum() + for i in _range(D): + shape = np.ones(D, int) + shape[i] = nbin[i] - 2 + hist = hist / dedges[i].reshape(shape) + hist /= s + + if (hist.shape != nbin - 2).any(): + raise RuntimeError( + "Internal Shape Error") + return hist, edges diff --git a/python/user_packages/Python313/site-packages/numpy/lib/_histograms_impl.pyi b/python/user_packages/Python313/site-packages/numpy/lib/_histograms_impl.pyi new file mode 100644 index 0000000000000000000000000000000000000000..b9fa4914234d9a019812ec74e68d4de88853a060 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/lib/_histograms_impl.pyi @@ -0,0 +1,40 @@ +from collections.abc import Sequence +from typing import Any, Literal as L, SupportsIndex, TypeAlias + +from numpy._typing import ArrayLike, NDArray + +__all__ = ["histogram", "histogramdd", "histogram_bin_edges"] + +_BinKind: TypeAlias = L[ + "stone", + "auto", + "doane", + "fd", + "rice", + "scott", + "sqrt", + "sturges", +] + +def histogram_bin_edges( + a: ArrayLike, + bins: _BinKind | SupportsIndex | ArrayLike = 10, + range: tuple[float, float] | None = None, + weights: ArrayLike | None = None, +) -> NDArray[Any]: ... + +def histogram( + a: ArrayLike, + bins: _BinKind | SupportsIndex | ArrayLike = 10, + range: tuple[float, float] | None = None, + density: bool | None = None, + weights: ArrayLike | None = None, +) -> tuple[NDArray[Any], NDArray[Any]]: ... + +def histogramdd( + sample: ArrayLike, + bins: SupportsIndex | ArrayLike = 10, + range: Sequence[tuple[float, float]] | None = None, + density: bool | None = None, + weights: ArrayLike | None = None, +) -> tuple[NDArray[Any], tuple[NDArray[Any], ...]]: ... diff --git a/python/user_packages/Python313/site-packages/numpy/lib/_index_tricks_impl.py b/python/user_packages/Python313/site-packages/numpy/lib/_index_tricks_impl.py new file mode 100644 index 0000000000000000000000000000000000000000..bc86430c2604162ad9f9d83e5ee50ae72d0a90dc --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/lib/_index_tricks_impl.py @@ -0,0 +1,1048 @@ +import functools +import math +import sys +from itertools import product + +import numpy as np +import numpy._core.numeric as _nx +import numpy.matrixlib as matrixlib +from numpy._core import linspace, overrides +from numpy._core.multiarray import ravel_multi_index, unravel_index +from numpy._core.numeric import ScalarType, array +from numpy._core.numerictypes import issubdtype +from numpy._utils import set_module +from numpy.lib._function_base_impl import diff + +array_function_dispatch = functools.partial( + overrides.array_function_dispatch, module='numpy') + + +__all__ = [ + 'ravel_multi_index', 'unravel_index', 'mgrid', 'ogrid', 'r_', 'c_', + 's_', 'index_exp', 'ix_', 'ndenumerate', 'ndindex', 'fill_diagonal', + 'diag_indices', 'diag_indices_from' +] + + +def _ix__dispatcher(*args): + return args + + +@array_function_dispatch(_ix__dispatcher) +def ix_(*args): + """ + Construct an open mesh from multiple sequences. + + This function takes N 1-D sequences and returns N outputs with N + dimensions each, such that the shape is 1 in all but one dimension + and the dimension with the non-unit shape value cycles through all + N dimensions. + + Using `ix_` one can quickly construct index arrays that will index + the cross product. ``a[np.ix_([1,3],[2,5])]`` returns the array + ``[[a[1,2] a[1,5]], [a[3,2] a[3,5]]]``. + + Parameters + ---------- + args : 1-D sequences + Each sequence should be of integer or boolean type. + Boolean sequences will be interpreted as boolean masks for the + corresponding dimension (equivalent to passing in + ``np.nonzero(boolean_sequence)``). + + Returns + ------- + out : tuple of ndarrays + N arrays with N dimensions each, with N the number of input + sequences. Together these arrays form an open mesh. + + See Also + -------- + ogrid, mgrid, meshgrid + + Examples + -------- + >>> import numpy as np + >>> a = np.arange(10).reshape(2, 5) + >>> a + array([[0, 1, 2, 3, 4], + [5, 6, 7, 8, 9]]) + >>> ixgrid = np.ix_([0, 1], [2, 4]) + >>> ixgrid + (array([[0], + [1]]), array([[2, 4]])) + >>> ixgrid[0].shape, ixgrid[1].shape + ((2, 1), (1, 2)) + >>> a[ixgrid] + array([[2, 4], + [7, 9]]) + + >>> ixgrid = np.ix_([True, True], [2, 4]) + >>> a[ixgrid] + array([[2, 4], + [7, 9]]) + >>> ixgrid = np.ix_([True, True], [False, False, True, False, True]) + >>> a[ixgrid] + array([[2, 4], + [7, 9]]) + + """ + out = [] + nd = len(args) + for k, new in enumerate(args): + if not isinstance(new, _nx.ndarray): + new = np.asarray(new) + if new.size == 0: + # Explicitly type empty arrays to avoid float default + new = new.astype(_nx.intp) + if new.ndim != 1: + raise ValueError("Cross index must be 1 dimensional") + if issubdtype(new.dtype, _nx.bool): + new, = new.nonzero() + new = new.reshape((1,) * k + (new.size,) + (1,) * (nd - k - 1)) + out.append(new) + return tuple(out) + + +class nd_grid: + """ + Construct a multi-dimensional "meshgrid". + + ``grid = nd_grid()`` creates an instance which will return a mesh-grid + when indexed. The dimension and number of the output arrays are equal + to the number of indexing dimensions. If the step length is not a + complex number, then the stop is not inclusive. + + However, if the step length is a **complex number** (e.g. 5j), then the + integer part of its magnitude is interpreted as specifying the + number of points to create between the start and stop values, where + the stop value **is inclusive**. + + If instantiated with an argument of ``sparse=True``, the mesh-grid is + open (or not fleshed out) so that only one-dimension of each returned + argument is greater than 1. + + Parameters + ---------- + sparse : bool, optional + Whether the grid is sparse or not. Default is False. + + Notes + ----- + Two instances of `nd_grid` are made available in the NumPy namespace, + `mgrid` and `ogrid`, approximately defined as:: + + mgrid = nd_grid(sparse=False) + ogrid = nd_grid(sparse=True) + + Users should use these pre-defined instances instead of using `nd_grid` + directly. + """ + __slots__ = ('sparse',) + + def __init__(self, sparse=False): + self.sparse = sparse + + def __getitem__(self, key): + try: + size = [] + # Mimic the behavior of `np.arange` and use a data type + # which is at least as large as `np.int_` + num_list = [0] + for k in range(len(key)): + step = key[k].step + start = key[k].start + stop = key[k].stop + if start is None: + start = 0 + if step is None: + step = 1 + if isinstance(step, (_nx.complexfloating, complex)): + step = abs(step) + size.append(int(step)) + else: + size.append( + math.ceil((stop - start) / step)) + num_list += [start, stop, step] + typ = _nx.result_type(*num_list) + if self.sparse: + nn = [_nx.arange(_x, dtype=_t) + for _x, _t in zip(size, (typ,) * len(size))] + else: + nn = _nx.indices(size, typ) + for k, kk in enumerate(key): + step = kk.step + start = kk.start + if start is None: + start = 0 + if step is None: + step = 1 + if isinstance(step, (_nx.complexfloating, complex)): + step = int(abs(step)) + if step != 1: + step = (kk.stop - start) / float(step - 1) + nn[k] = (nn[k] * step + start) + if self.sparse: + slobj = [_nx.newaxis] * len(size) + for k in range(len(size)): + slobj[k] = slice(None, None) + nn[k] = nn[k][tuple(slobj)] + slobj[k] = _nx.newaxis + return tuple(nn) # ogrid -> tuple of arrays + return nn # mgrid -> ndarray + except (IndexError, TypeError): + step = key.step + stop = key.stop + start = key.start + if start is None: + start = 0 + if isinstance(step, (_nx.complexfloating, complex)): + # Prevent the (potential) creation of integer arrays + step_float = abs(step) + step = length = int(step_float) + if step != 1: + step = (key.stop - start) / float(step - 1) + typ = _nx.result_type(start, stop, step_float) + return _nx.arange(0, length, 1, dtype=typ) * step + start + else: + return _nx.arange(start, stop, step) + + +class MGridClass(nd_grid): + """ + An instance which returns a dense multi-dimensional "meshgrid". + + An instance which returns a dense (or fleshed out) mesh-grid + when indexed, so that each returned argument has the same shape. + The dimensions and number of the output arrays are equal to the + number of indexing dimensions. If the step length is not a complex + number, then the stop is not inclusive. + + However, if the step length is a **complex number** (e.g. 5j), then + the integer part of its magnitude is interpreted as specifying the + number of points to create between the start and stop values, where + the stop value **is inclusive**. + + Returns + ------- + mesh-grid : ndarray + A single array, containing a set of `ndarray`\\ s all of the same + dimensions. stacked along the first axis. + + See Also + -------- + ogrid : like `mgrid` but returns open (not fleshed out) mesh grids + meshgrid: return coordinate matrices from coordinate vectors + r_ : array concatenator + :ref:`how-to-partition` + + Examples + -------- + >>> import numpy as np + >>> np.mgrid[0:5, 0:5] + array([[[0, 0, 0, 0, 0], + [1, 1, 1, 1, 1], + [2, 2, 2, 2, 2], + [3, 3, 3, 3, 3], + [4, 4, 4, 4, 4]], + [[0, 1, 2, 3, 4], + [0, 1, 2, 3, 4], + [0, 1, 2, 3, 4], + [0, 1, 2, 3, 4], + [0, 1, 2, 3, 4]]]) + >>> np.mgrid[-1:1:5j] + array([-1. , -0.5, 0. , 0.5, 1. ]) + + >>> np.mgrid[0:4].shape + (4,) + >>> np.mgrid[0:4, 0:5].shape + (2, 4, 5) + >>> np.mgrid[0:4, 0:5, 0:6].shape + (3, 4, 5, 6) + + """ + __slots__ = () + + def __init__(self): + super().__init__(sparse=False) + + +mgrid = MGridClass() + + +class OGridClass(nd_grid): + """ + An instance which returns an open multi-dimensional "meshgrid". + + An instance which returns an open (i.e. not fleshed out) mesh-grid + when indexed, so that only one dimension of each returned array is + greater than 1. The dimension and number of the output arrays are + equal to the number of indexing dimensions. If the step length is + not a complex number, then the stop is not inclusive. + + However, if the step length is a **complex number** (e.g. 5j), then + the integer part of its magnitude is interpreted as specifying the + number of points to create between the start and stop values, where + the stop value **is inclusive**. + + Returns + ------- + mesh-grid : ndarray or tuple of ndarrays + If the input is a single slice, returns an array. + If the input is multiple slices, returns a tuple of arrays, with + only one dimension not equal to 1. + + See Also + -------- + mgrid : like `ogrid` but returns dense (or fleshed out) mesh grids + meshgrid: return coordinate matrices from coordinate vectors + r_ : array concatenator + :ref:`how-to-partition` + + Examples + -------- + >>> from numpy import ogrid + >>> ogrid[-1:1:5j] + array([-1. , -0.5, 0. , 0.5, 1. ]) + >>> ogrid[0:5, 0:5] + (array([[0], + [1], + [2], + [3], + [4]]), + array([[0, 1, 2, 3, 4]])) + + """ + __slots__ = () + + def __init__(self): + super().__init__(sparse=True) + + +ogrid = OGridClass() + + +class AxisConcatenator: + """ + Translates slice objects to concatenation along an axis. + + For detailed documentation on usage, see `r_`. + """ + __slots__ = ('axis', 'matrix', 'ndmin', 'trans1d') + + # allow ma.mr_ to override this + concatenate = staticmethod(_nx.concatenate) + makemat = staticmethod(matrixlib.matrix) + + def __init__(self, axis=0, matrix=False, ndmin=1, trans1d=-1): + self.axis = axis + self.matrix = matrix + self.trans1d = trans1d + self.ndmin = ndmin + + def __getitem__(self, key): + # handle matrix builder syntax + if isinstance(key, str): + frame = sys._getframe().f_back + mymat = matrixlib.bmat(key, frame.f_globals, frame.f_locals) + return mymat + + if not isinstance(key, tuple): + key = (key,) + + # copy attributes, since they can be overridden in the first argument + trans1d = self.trans1d + ndmin = self.ndmin + matrix = self.matrix + axis = self.axis + + objs = [] + # dtypes or scalars for weak scalar handling in result_type + result_type_objs = [] + + for k, item in enumerate(key): + scalar = False + if isinstance(item, slice): + step = item.step + start = item.start + stop = item.stop + if start is None: + start = 0 + if step is None: + step = 1 + if isinstance(step, (_nx.complexfloating, complex)): + size = int(abs(step)) + newobj = linspace(start, stop, num=size) + else: + newobj = _nx.arange(start, stop, step) + if ndmin > 1: + newobj = array(newobj, copy=None, ndmin=ndmin) + if trans1d != -1: + newobj = newobj.swapaxes(-1, trans1d) + elif isinstance(item, str): + if k != 0: + raise ValueError("special directives must be the " + "first entry.") + if item in ('r', 'c'): + matrix = True + col = (item == 'c') + continue + if ',' in item: + vec = item.split(',') + try: + axis, ndmin = [int(x) for x in vec[:2]] + if len(vec) == 3: + trans1d = int(vec[2]) + continue + except Exception as e: + raise ValueError( + f"unknown special directive {item!r}" + ) from e + try: + axis = int(item) + continue + except (ValueError, TypeError) as e: + raise ValueError("unknown special directive") from e + elif type(item) in ScalarType: + scalar = True + newobj = item + else: + item_ndim = np.ndim(item) + newobj = array(item, copy=None, subok=True, ndmin=ndmin) + if trans1d != -1 and item_ndim < ndmin: + k2 = ndmin - item_ndim + k1 = trans1d + if k1 < 0: + k1 += k2 + 1 + defaxes = list(range(ndmin)) + axes = defaxes[:k1] + defaxes[k2:] + defaxes[k1:k2] + newobj = newobj.transpose(axes) + + objs.append(newobj) + if scalar: + result_type_objs.append(item) + else: + result_type_objs.append(newobj.dtype) + + # Ensure that scalars won't up-cast unless warranted, for 0, drops + # through to error in concatenate. + if len(result_type_objs) != 0: + final_dtype = _nx.result_type(*result_type_objs) + # concatenate could do cast, but that can be overridden: + objs = [array(obj, copy=None, subok=True, + ndmin=ndmin, dtype=final_dtype) for obj in objs] + + res = self.concatenate(tuple(objs), axis=axis) + + if matrix: + oldndim = res.ndim + res = self.makemat(res) + if oldndim == 1 and col: + res = res.T + return res + + def __len__(self): + return 0 + +# separate classes are used here instead of just making r_ = concatenator(0), +# etc. because otherwise we couldn't get the doc string to come out right +# in help(r_) + + +class RClass(AxisConcatenator): + """ + Translates slice objects to concatenation along the first axis. + + This is a simple way to build up arrays quickly. There are two use cases. + + 1. If the index expression contains comma separated arrays, then stack + them along their first axis. + 2. If the index expression contains slice notation or scalars then create + a 1-D array with a range indicated by the slice notation. + + If slice notation is used, the syntax ``start:stop:step`` is equivalent + to ``np.arange(start, stop, step)`` inside of the brackets. However, if + ``step`` is an imaginary number (i.e. 100j) then its integer portion is + interpreted as a number-of-points desired and the start and stop are + inclusive. In other words ``start:stop:stepj`` is interpreted as + ``np.linspace(start, stop, step, endpoint=1)`` inside of the brackets. + After expansion of slice notation, all comma separated sequences are + concatenated together. + + Optional character strings placed as the first element of the index + expression can be used to change the output. The strings 'r' or 'c' result + in matrix output. If the result is 1-D and 'r' is specified a 1 x N (row) + matrix is produced. If the result is 1-D and 'c' is specified, then + an N x 1 (column) matrix is produced. + If the result is 2-D then both provide the same matrix result. + + A string integer specifies which axis to stack multiple comma separated + arrays along. A string of two comma-separated integers allows indication + of the minimum number of dimensions to force each entry into as the + second integer (the axis to concatenate along is still the first integer). + + A string with three comma-separated integers allows specification of the + axis to concatenate along, the minimum number of dimensions to force the + entries to, and which axis should contain the start of the arrays which + are less than the specified number of dimensions. In other words the third + integer allows you to specify where the 1's should be placed in the shape + of the arrays that have their shapes upgraded. By default, they are placed + in the front of the shape tuple. The third argument allows you to specify + where the start of the array should be instead. Thus, a third argument of + '0' would place the 1's at the end of the array shape. Negative integers + specify where in the new shape tuple the last dimension of upgraded arrays + should be placed, so the default is '-1'. + + Parameters + ---------- + Not a function, so takes no parameters + + + Returns + ------- + A concatenated ndarray or matrix. + + See Also + -------- + concatenate : Join a sequence of arrays along an existing axis. + c_ : Translates slice objects to concatenation along the second axis. + + Examples + -------- + >>> import numpy as np + >>> np.r_[np.array([1,2,3]), 0, 0, np.array([4,5,6])] + array([1, 2, 3, ..., 4, 5, 6]) + >>> np.r_[-1:1:6j, [0]*3, 5, 6] + array([-1. , -0.6, -0.2, 0.2, 0.6, 1. , 0. , 0. , 0. , 5. , 6. ]) + + String integers specify the axis to concatenate along or the minimum + number of dimensions to force entries into. + + >>> a = np.array([[0, 1, 2], [3, 4, 5]]) + >>> np.r_['-1', a, a] # concatenate along last axis + array([[0, 1, 2, 0, 1, 2], + [3, 4, 5, 3, 4, 5]]) + >>> np.r_['0,2', [1,2,3], [4,5,6]] # concatenate along first axis, dim>=2 + array([[1, 2, 3], + [4, 5, 6]]) + + >>> np.r_['0,2,0', [1,2,3], [4,5,6]] + array([[1], + [2], + [3], + [4], + [5], + [6]]) + >>> np.r_['1,2,0', [1,2,3], [4,5,6]] + array([[1, 4], + [2, 5], + [3, 6]]) + + Using 'r' or 'c' as a first string argument creates a matrix. + + >>> np.r_['r',[1,2,3], [4,5,6]] + matrix([[1, 2, 3, 4, 5, 6]]) + + """ + __slots__ = () + + def __init__(self): + AxisConcatenator.__init__(self, 0) + + +r_ = RClass() + + +class CClass(AxisConcatenator): + """ + Translates slice objects to concatenation along the second axis. + + This is short-hand for ``np.r_['-1,2,0', index expression]``, which is + useful because of its common occurrence. In particular, arrays will be + stacked along their last axis after being upgraded to at least 2-D with + 1's post-pended to the shape (column vectors made out of 1-D arrays). + + See Also + -------- + column_stack : Stack 1-D arrays as columns into a 2-D array. + r_ : For more detailed documentation. + + Examples + -------- + >>> import numpy as np + >>> np.c_[np.array([1,2,3]), np.array([4,5,6])] + array([[1, 4], + [2, 5], + [3, 6]]) + >>> np.c_[np.array([[1,2,3]]), 0, 0, np.array([[4,5,6]])] + array([[1, 2, 3, ..., 4, 5, 6]]) + + """ + __slots__ = () + + def __init__(self): + AxisConcatenator.__init__(self, -1, ndmin=2, trans1d=0) + + +c_ = CClass() + + +@set_module('numpy') +class ndenumerate: + """ + Multidimensional index iterator. + + Return an iterator yielding pairs of array coordinates and values. + + Parameters + ---------- + arr : ndarray + Input array. + + See Also + -------- + ndindex, flatiter + + Examples + -------- + >>> import numpy as np + >>> a = np.array([[1, 2], [3, 4]]) + >>> for index, x in np.ndenumerate(a): + ... print(index, x) + (0, 0) 1 + (0, 1) 2 + (1, 0) 3 + (1, 1) 4 + + """ + + def __init__(self, arr): + self.iter = np.asarray(arr).flat + + def __next__(self): + """ + Standard iterator method, returns the index tuple and array value. + + Returns + ------- + coords : tuple of ints + The indices of the current iteration. + val : scalar + The array element of the current iteration. + + """ + return self.iter.coords, next(self.iter) + + def __iter__(self): + return self + + +@set_module('numpy') +class ndindex: + """ + An N-dimensional iterator object to index arrays. + + Given the shape of an array, an `ndindex` instance iterates over + the N-dimensional index of the array. At each iteration a tuple + of indices is returned, the last dimension is iterated over first. + + Parameters + ---------- + shape : ints, or a single tuple of ints + The size of each dimension of the array can be passed as + individual parameters or as the elements of a tuple. + + See Also + -------- + ndenumerate, flatiter + + Examples + -------- + >>> import numpy as np + + Dimensions as individual arguments + + >>> for index in np.ndindex(3, 2, 1): + ... print(index) + (0, 0, 0) + (0, 1, 0) + (1, 0, 0) + (1, 1, 0) + (2, 0, 0) + (2, 1, 0) + + Same dimensions - but in a tuple ``(3, 2, 1)`` + + >>> for index in np.ndindex((3, 2, 1)): + ... print(index) + (0, 0, 0) + (0, 1, 0) + (1, 0, 0) + (1, 1, 0) + (2, 0, 0) + (2, 1, 0) + + """ + + def __init__(self, *shape): + if len(shape) == 1 and isinstance(shape[0], tuple): + shape = shape[0] + if min(shape, default=0) < 0: + raise ValueError("negative dimensions are not allowed") + self._iter = product(*map(range, shape)) + + def __iter__(self): + return self + + def __next__(self): + """ + Standard iterator method, updates the index and returns the index + tuple. + + Returns + ------- + val : tuple of ints + Returns a tuple containing the indices of the current + iteration. + + """ + return next(self._iter) + + +# You can do all this with slice() plus a few special objects, +# but there's a lot to remember. This version is simpler because +# it uses the standard array indexing syntax. +# +# Written by Konrad Hinsen +# last revision: 1999-7-23 +# +# Cosmetic changes by T. Oliphant 2001 +# +# + +class IndexExpression: + """ + A nicer way to build up index tuples for arrays. + + .. note:: + Use one of the two predefined instances ``index_exp`` or `s_` + rather than directly using `IndexExpression`. + + For any index combination, including slicing and axis insertion, + ``a[indices]`` is the same as ``a[np.index_exp[indices]]`` for any + array `a`. However, ``np.index_exp[indices]`` can be used anywhere + in Python code and returns a tuple of slice objects that can be + used in the construction of complex index expressions. + + Parameters + ---------- + maketuple : bool + If True, always returns a tuple. + + See Also + -------- + s_ : Predefined instance without tuple conversion: + `s_ = IndexExpression(maketuple=False)`. + The ``index_exp`` is another predefined instance that + always returns a tuple: + `index_exp = IndexExpression(maketuple=True)`. + + Notes + ----- + You can do all this with :class:`slice` plus a few special objects, + but there's a lot to remember and this version is simpler because + it uses the standard array indexing syntax. + + Examples + -------- + >>> import numpy as np + >>> np.s_[2::2] + slice(2, None, 2) + >>> np.index_exp[2::2] + (slice(2, None, 2),) + + >>> np.array([0, 1, 2, 3, 4])[np.s_[2::2]] + array([2, 4]) + + """ + __slots__ = ('maketuple',) + + def __init__(self, maketuple): + self.maketuple = maketuple + + def __getitem__(self, item): + if self.maketuple and not isinstance(item, tuple): + return (item,) + else: + return item + + +index_exp = IndexExpression(maketuple=True) +s_ = IndexExpression(maketuple=False) + +# End contribution from Konrad. + + +# The following functions complement those in twodim_base, but are +# applicable to N-dimensions. + + +def _fill_diagonal_dispatcher(a, val, wrap=None): + return (a,) + + +@array_function_dispatch(_fill_diagonal_dispatcher) +def fill_diagonal(a, val, wrap=False): + """Fill the main diagonal of the given array of any dimensionality. + + For an array `a` with ``a.ndim >= 2``, the diagonal is the list of + values ``a[i, ..., i]`` with indices ``i`` all identical. This function + modifies the input array in-place without returning a value. + + Parameters + ---------- + a : array, at least 2-D. + Array whose diagonal is to be filled in-place. + val : scalar or array_like + Value(s) to write on the diagonal. If `val` is scalar, the value is + written along the diagonal. If array-like, the flattened `val` is + written along the diagonal, repeating if necessary to fill all + diagonal entries. + + wrap : bool + For tall matrices in NumPy version up to 1.6.2, the + diagonal "wrapped" after N columns. You can have this behavior + with this option. This affects only tall matrices. + + See also + -------- + diag_indices, diag_indices_from + + Notes + ----- + This functionality can be obtained via `diag_indices`, but internally + this version uses a much faster implementation that never constructs the + indices and uses simple slicing. + + Examples + -------- + >>> import numpy as np + >>> a = np.zeros((3, 3), int) + >>> np.fill_diagonal(a, 5) + >>> a + array([[5, 0, 0], + [0, 5, 0], + [0, 0, 5]]) + + The same function can operate on a 4-D array: + + >>> a = np.zeros((3, 3, 3, 3), int) + >>> np.fill_diagonal(a, 4) + + We only show a few blocks for clarity: + + >>> a[0, 0] + array([[4, 0, 0], + [0, 0, 0], + [0, 0, 0]]) + >>> a[1, 1] + array([[0, 0, 0], + [0, 4, 0], + [0, 0, 0]]) + >>> a[2, 2] + array([[0, 0, 0], + [0, 0, 0], + [0, 0, 4]]) + + The wrap option affects only tall matrices: + + >>> # tall matrices no wrap + >>> a = np.zeros((5, 3), int) + >>> np.fill_diagonal(a, 4) + >>> a + array([[4, 0, 0], + [0, 4, 0], + [0, 0, 4], + [0, 0, 0], + [0, 0, 0]]) + + >>> # tall matrices wrap + >>> a = np.zeros((5, 3), int) + >>> np.fill_diagonal(a, 4, wrap=True) + >>> a + array([[4, 0, 0], + [0, 4, 0], + [0, 0, 4], + [0, 0, 0], + [4, 0, 0]]) + + >>> # wide matrices + >>> a = np.zeros((3, 5), int) + >>> np.fill_diagonal(a, 4, wrap=True) + >>> a + array([[4, 0, 0, 0, 0], + [0, 4, 0, 0, 0], + [0, 0, 4, 0, 0]]) + + The anti-diagonal can be filled by reversing the order of elements + using either `numpy.flipud` or `numpy.fliplr`. + + >>> a = np.zeros((3, 3), int); + >>> np.fill_diagonal(np.fliplr(a), [1,2,3]) # Horizontal flip + >>> a + array([[0, 0, 1], + [0, 2, 0], + [3, 0, 0]]) + >>> np.fill_diagonal(np.flipud(a), [1,2,3]) # Vertical flip + >>> a + array([[0, 0, 3], + [0, 2, 0], + [1, 0, 0]]) + + Note that the order in which the diagonal is filled varies depending + on the flip function. + """ + if a.ndim < 2: + raise ValueError("array must be at least 2-d") + end = None + if a.ndim == 2: + # Explicit, fast formula for the common case. For 2-d arrays, we + # accept rectangular ones. + step = a.shape[1] + 1 + # This is needed to don't have tall matrix have the diagonal wrap. + if not wrap: + end = a.shape[1] * a.shape[1] + else: + # For more than d=2, the strided formula is only valid for arrays with + # all dimensions equal, so we check first. + if not np.all(diff(a.shape) == 0): + raise ValueError("All dimensions of input must be of equal length") + step = 1 + (np.cumprod(a.shape[:-1])).sum() + + # Write the value out into the diagonal. + a.flat[:end:step] = val + + +@set_module('numpy') +def diag_indices(n, ndim=2): + """ + Return the indices to access the main diagonal of an array. + + This returns a tuple of indices that can be used to access the main + diagonal of an array `a` with ``a.ndim >= 2`` dimensions and shape + (n, n, ..., n). For ``a.ndim = 2`` this is the usual diagonal, for + ``a.ndim > 2`` this is the set of indices to access ``a[i, i, ..., i]`` + for ``i = [0..n-1]``. + + Parameters + ---------- + n : int + The size, along each dimension, of the arrays for which the returned + indices can be used. + + ndim : int, optional + The number of dimensions. + + See Also + -------- + diag_indices_from + + Examples + -------- + >>> import numpy as np + + Create a set of indices to access the diagonal of a (4, 4) array: + + >>> di = np.diag_indices(4) + >>> di + (array([0, 1, 2, 3]), array([0, 1, 2, 3])) + >>> a = np.arange(16).reshape(4, 4) + >>> a + array([[ 0, 1, 2, 3], + [ 4, 5, 6, 7], + [ 8, 9, 10, 11], + [12, 13, 14, 15]]) + >>> a[di] = 100 + >>> a + array([[100, 1, 2, 3], + [ 4, 100, 6, 7], + [ 8, 9, 100, 11], + [ 12, 13, 14, 100]]) + + Now, we create indices to manipulate a 3-D array: + + >>> d3 = np.diag_indices(2, 3) + >>> d3 + (array([0, 1]), array([0, 1]), array([0, 1])) + + And use it to set the diagonal of an array of zeros to 1: + + >>> a = np.zeros((2, 2, 2), dtype=int) + >>> a[d3] = 1 + >>> a + array([[[1, 0], + [0, 0]], + [[0, 0], + [0, 1]]]) + + """ + idx = np.arange(n) + return (idx,) * ndim + + +def _diag_indices_from(arr): + return (arr,) + + +@array_function_dispatch(_diag_indices_from) +def diag_indices_from(arr): + """ + Return the indices to access the main diagonal of an n-dimensional array. + + See `diag_indices` for full details. + + Parameters + ---------- + arr : array, at least 2-D + + See Also + -------- + diag_indices + + Examples + -------- + >>> import numpy as np + + Create a 4 by 4 array. + + >>> a = np.arange(16).reshape(4, 4) + >>> a + array([[ 0, 1, 2, 3], + [ 4, 5, 6, 7], + [ 8, 9, 10, 11], + [12, 13, 14, 15]]) + + Get the indices of the diagonal elements. + + >>> di = np.diag_indices_from(a) + >>> di + (array([0, 1, 2, 3]), array([0, 1, 2, 3])) + + >>> a[di] + array([ 0, 5, 10, 15]) + + This is simply syntactic sugar for diag_indices. + + >>> np.diag_indices(a.shape[0]) + (array([0, 1, 2, 3]), array([0, 1, 2, 3])) + + """ + + if not arr.ndim >= 2: + raise ValueError("input array must be at least 2-d") + # For more than d=2, the strided formula is only valid for arrays with + # all dimensions equal, so we check first. + if not np.all(diff(arr.shape) == 0): + raise ValueError("All dimensions of input must be of equal length") + + return diag_indices(arr.shape[0], arr.ndim) diff --git a/python/user_packages/Python313/site-packages/numpy/lib/_index_tricks_impl.pyi b/python/user_packages/Python313/site-packages/numpy/lib/_index_tricks_impl.pyi new file mode 100644 index 0000000000000000000000000000000000000000..34d92476870616b33e2710ca032e7304484fedf9 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/lib/_index_tricks_impl.pyi @@ -0,0 +1,267 @@ +from _typeshed import Incomplete, SupportsLenAndGetItem +from collections.abc import Sequence +from typing import ( + Any, + ClassVar, + Final, + Generic, + Literal as L, + Self, + SupportsIndex, + final, + overload, +) +from typing_extensions import TypeVar + +import numpy as np +from numpy import _CastingKind +from numpy._core.multiarray import ravel_multi_index, unravel_index +from numpy._typing import ( + ArrayLike, + DTypeLike, + NDArray, + _AnyShape, + _ArrayLike, + _DTypeLike, + _FiniteNestedSequence, + _HasDType, + _NestedSequence, + _SupportsArray, +) + +__all__ = [ # noqa: RUF022 + "ravel_multi_index", + "unravel_index", + "mgrid", + "ogrid", + "r_", + "c_", + "s_", + "index_exp", + "ix_", + "ndenumerate", + "ndindex", + "fill_diagonal", + "diag_indices", + "diag_indices_from", +] + +### + +_T = TypeVar("_T") +_TupleT = TypeVar("_TupleT", bound=tuple[Any, ...]) +_ArrayT = TypeVar("_ArrayT", bound=NDArray[Any]) +_DTypeT = TypeVar("_DTypeT", bound=np.dtype) +_ScalarT = TypeVar("_ScalarT", bound=np.generic) +_ScalarT_co = TypeVar("_ScalarT_co", bound=np.generic, default=Any, covariant=True) +_BoolT_co = TypeVar("_BoolT_co", bound=bool, default=bool, covariant=True) + +_AxisT_co = TypeVar("_AxisT_co", bound=int, default=L[0], covariant=True) +_MatrixT_co = TypeVar("_MatrixT_co", bound=bool, default=L[False], covariant=True) +_NDMinT_co = TypeVar("_NDMinT_co", bound=int, default=L[1], covariant=True) +_Trans1DT_co = TypeVar("_Trans1DT_co", bound=int, default=L[-1], covariant=True) + +### + +class ndenumerate(Generic[_ScalarT_co]): + @overload + def __init__(self: ndenumerate[_ScalarT], arr: _FiniteNestedSequence[_SupportsArray[np.dtype[_ScalarT]]]) -> None: ... + @overload + def __init__(self: ndenumerate[np.str_], arr: str | _NestedSequence[str]) -> None: ... + @overload + def __init__(self: ndenumerate[np.bytes_], arr: bytes | _NestedSequence[bytes]) -> None: ... + @overload + def __init__(self: ndenumerate[np.bool], arr: bool | _NestedSequence[bool]) -> None: ... + @overload + def __init__(self: ndenumerate[np.intp], arr: int | _NestedSequence[int]) -> None: ... + @overload + def __init__(self: ndenumerate[np.float64], arr: float | _NestedSequence[float]) -> None: ... + @overload + def __init__(self: ndenumerate[np.complex128], arr: complex | _NestedSequence[complex]) -> None: ... + @overload + def __init__(self: ndenumerate[Incomplete], arr: object) -> None: ... + + # The first overload is a (semi-)workaround for a mypy bug (tested with v1.10 and v1.11) + @overload + def __next__( + self: ndenumerate[np.bool | np.number | np.flexible | np.datetime64 | np.timedelta64], + /, + ) -> tuple[_AnyShape, _ScalarT_co]: ... + @overload + def __next__(self: ndenumerate[np.object_], /) -> tuple[_AnyShape, Incomplete]: ... + @overload + def __next__(self, /) -> tuple[_AnyShape, _ScalarT_co]: ... + + # + def __iter__(self) -> Self: ... + +class ndindex: + @overload + def __init__(self, shape: tuple[SupportsIndex, ...], /) -> None: ... + @overload + def __init__(self, /, *shape: SupportsIndex) -> None: ... + + # + def __iter__(self) -> Self: ... + def __next__(self) -> _AnyShape: ... + +class nd_grid(Generic[_BoolT_co]): + __slots__ = ("sparse",) + + sparse: _BoolT_co + def __init__(self, sparse: _BoolT_co = ...) -> None: ... # stubdefaulter: ignore[missing-default] + @overload + def __getitem__(self: nd_grid[L[False]], key: slice | Sequence[slice]) -> NDArray[Incomplete]: ... + @overload + def __getitem__(self: nd_grid[L[True]], key: slice | Sequence[slice]) -> tuple[NDArray[Incomplete], ...]: ... + +@final +class MGridClass(nd_grid[L[False]]): + __slots__ = () + + def __init__(self) -> None: ... + +@final +class OGridClass(nd_grid[L[True]]): + __slots__ = () + + def __init__(self) -> None: ... + +class AxisConcatenator(Generic[_AxisT_co, _MatrixT_co, _NDMinT_co, _Trans1DT_co]): + __slots__ = "axis", "matrix", "ndmin", "trans1d" + + makemat: ClassVar[type[np.matrix[tuple[int, int], np.dtype]]] + + axis: _AxisT_co + matrix: _MatrixT_co + ndmin: _NDMinT_co + trans1d: _Trans1DT_co + + # NOTE: mypy does not understand that these default values are the same as the + # TypeVar defaults. Since the workaround would require us to write 16 overloads, + # we ignore the assignment type errors here. + def __init__( + self, + /, + axis: _AxisT_co = 0, # type: ignore[assignment] + matrix: _MatrixT_co = False, # type: ignore[assignment] + ndmin: _NDMinT_co = 1, # type: ignore[assignment] + trans1d: _Trans1DT_co = -1, # type: ignore[assignment] + ) -> None: ... + + # TODO(jorenham): annotate this + def __getitem__(self, key: Incomplete, /) -> Incomplete: ... + def __len__(self, /) -> L[0]: ... + + # Keep in sync with _core.multiarray.concatenate + @staticmethod + @overload + def concatenate( + arrays: _ArrayLike[_ScalarT], + /, + axis: SupportsIndex | None = 0, + out: None = None, + *, + dtype: None = None, + casting: _CastingKind | None = "same_kind", + ) -> NDArray[_ScalarT]: ... + @staticmethod + @overload + def concatenate( + arrays: SupportsLenAndGetItem[ArrayLike], + /, + axis: SupportsIndex | None = 0, + out: None = None, + *, + dtype: _DTypeLike[_ScalarT], + casting: _CastingKind | None = "same_kind", + ) -> NDArray[_ScalarT]: ... + @staticmethod + @overload + def concatenate( + arrays: SupportsLenAndGetItem[ArrayLike], + /, + axis: SupportsIndex | None = 0, + out: None = None, + *, + dtype: DTypeLike | None = None, + casting: _CastingKind | None = "same_kind", + ) -> NDArray[Incomplete]: ... + @staticmethod + @overload + def concatenate( + arrays: SupportsLenAndGetItem[ArrayLike], + /, + axis: SupportsIndex | None = 0, + *, + out: _ArrayT, + dtype: DTypeLike | None = None, + casting: _CastingKind | None = "same_kind", + ) -> _ArrayT: ... + @staticmethod + @overload + def concatenate( + arrays: SupportsLenAndGetItem[ArrayLike], + /, + axis: SupportsIndex | None, + out: _ArrayT, + *, + dtype: DTypeLike | None = None, + casting: _CastingKind | None = "same_kind", + ) -> _ArrayT: ... + +@final +class RClass(AxisConcatenator[L[0], L[False], L[1], L[-1]]): + __slots__ = () + + def __init__(self, /) -> None: ... + +@final +class CClass(AxisConcatenator[L[-1], L[False], L[2], L[0]]): + __slots__ = () + + def __init__(self, /) -> None: ... + +class IndexExpression(Generic[_BoolT_co]): + __slots__ = ("maketuple",) + + maketuple: _BoolT_co + def __init__(self, maketuple: _BoolT_co) -> None: ... + @overload + def __getitem__(self, item: _TupleT) -> _TupleT: ... + @overload + def __getitem__(self: IndexExpression[L[True]], item: _T) -> tuple[_T]: ... + @overload + def __getitem__(self: IndexExpression[L[False]], item: _T) -> _T: ... + +@overload +def ix_(*args: _FiniteNestedSequence[_HasDType[_DTypeT]]) -> tuple[np.ndarray[_AnyShape, _DTypeT], ...]: ... +@overload +def ix_(*args: str | _NestedSequence[str]) -> tuple[NDArray[np.str_], ...]: ... +@overload +def ix_(*args: bytes | _NestedSequence[bytes]) -> tuple[NDArray[np.bytes_], ...]: ... +@overload +def ix_(*args: bool | _NestedSequence[bool]) -> tuple[NDArray[np.bool], ...]: ... +@overload +def ix_(*args: int | _NestedSequence[int]) -> tuple[NDArray[np.intp], ...]: ... +@overload +def ix_(*args: float | _NestedSequence[float]) -> tuple[NDArray[np.float64], ...]: ... +@overload +def ix_(*args: complex | _NestedSequence[complex]) -> tuple[NDArray[np.complex128], ...]: ... + +# +def fill_diagonal(a: NDArray[Any], val: object, wrap: bool = False) -> None: ... + +# +def diag_indices(n: int, ndim: int = 2) -> tuple[NDArray[np.intp], ...]: ... +def diag_indices_from(arr: ArrayLike) -> tuple[NDArray[np.intp], ...]: ... + +# +mgrid: Final[MGridClass] = ... +ogrid: Final[OGridClass] = ... + +r_: Final[RClass] = ... +c_: Final[CClass] = ... + +index_exp: Final[IndexExpression[L[True]]] = ... +s_: Final[IndexExpression[L[False]]] = ... diff --git a/python/user_packages/Python313/site-packages/numpy/lib/_iotools.py b/python/user_packages/Python313/site-packages/numpy/lib/_iotools.py new file mode 100644 index 0000000000000000000000000000000000000000..5f41996bb79b160d9221eeab23fa9666916b60e5 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/lib/_iotools.py @@ -0,0 +1,900 @@ +"""A collection of functions designed to help I/O with ascii files. + +""" +__docformat__ = "restructuredtext en" + +import itertools + +import numpy as np +import numpy._core.numeric as nx +from numpy._utils import asbytes, asunicode + + +def _decode_line(line, encoding=None): + """Decode bytes from binary input streams. + + Defaults to decoding from 'latin1'. + + Parameters + ---------- + line : str or bytes + Line to be decoded. + encoding : str + Encoding used to decode `line`. + + Returns + ------- + decoded_line : str + + """ + if type(line) is bytes: + if encoding is None: + encoding = "latin1" + line = line.decode(encoding) + + return line + + +def _is_string_like(obj): + """ + Check whether obj behaves like a string. + """ + try: + obj + '' + except (TypeError, ValueError): + return False + return True + + +def _is_bytes_like(obj): + """ + Check whether obj behaves like a bytes object. + """ + try: + obj + b'' + except (TypeError, ValueError): + return False + return True + + +def has_nested_fields(ndtype): + """ + Returns whether one or several fields of a dtype are nested. + + Parameters + ---------- + ndtype : dtype + Data-type of a structured array. + + Raises + ------ + AttributeError + If `ndtype` does not have a `names` attribute. + + Examples + -------- + >>> import numpy as np + >>> dt = np.dtype([('name', 'S4'), ('x', float), ('y', float)]) + >>> np.lib._iotools.has_nested_fields(dt) + False + + """ + return any(ndtype[name].names is not None for name in ndtype.names or ()) + + +def flatten_dtype(ndtype, flatten_base=False): + """ + Unpack a structured data-type by collapsing nested fields and/or fields + with a shape. + + Note that the field names are lost. + + Parameters + ---------- + ndtype : dtype + The datatype to collapse + flatten_base : bool, optional + If True, transform a field with a shape into several fields. Default is + False. + + Examples + -------- + >>> import numpy as np + >>> dt = np.dtype([('name', 'S4'), ('x', float), ('y', float), + ... ('block', int, (2, 3))]) + >>> np.lib._iotools.flatten_dtype(dt) + [dtype('S4'), dtype('float64'), dtype('float64'), dtype('int64')] + >>> np.lib._iotools.flatten_dtype(dt, flatten_base=True) + [dtype('S4'), + dtype('float64'), + dtype('float64'), + dtype('int64'), + dtype('int64'), + dtype('int64'), + dtype('int64'), + dtype('int64'), + dtype('int64')] + + """ + names = ndtype.names + if names is None: + if flatten_base: + return [ndtype.base] * int(np.prod(ndtype.shape)) + return [ndtype.base] + else: + types = [] + for field in names: + info = ndtype.fields[field] + flat_dt = flatten_dtype(info[0], flatten_base) + types.extend(flat_dt) + return types + + +class LineSplitter: + """ + Object to split a string at a given delimiter or at given places. + + Parameters + ---------- + delimiter : str, int, or sequence of ints, optional + If a string, character used to delimit consecutive fields. + If an integer or a sequence of integers, width(s) of each field. + comments : str, optional + Character used to mark the beginning of a comment. Default is '#'. + autostrip : bool, optional + Whether to strip each individual field. Default is True. + + """ + + def autostrip(self, method): + """ + Wrapper to strip each member of the output of `method`. + + Parameters + ---------- + method : function + Function that takes a single argument and returns a sequence of + strings. + + Returns + ------- + wrapped : function + The result of wrapping `method`. `wrapped` takes a single input + argument and returns a list of strings that are stripped of + white-space. + + """ + return lambda input: [_.strip() for _ in method(input)] + + def __init__(self, delimiter=None, comments='#', autostrip=True, + encoding=None): + delimiter = _decode_line(delimiter) + comments = _decode_line(comments) + + self.comments = comments + + # Delimiter is a character + if (delimiter is None) or isinstance(delimiter, str): + delimiter = delimiter or None + _handyman = self._delimited_splitter + # Delimiter is a list of field widths + elif hasattr(delimiter, '__iter__'): + _handyman = self._variablewidth_splitter + idx = np.cumsum([0] + list(delimiter)) + delimiter = [slice(i, j) for (i, j) in itertools.pairwise(idx)] + # Delimiter is a single integer + elif int(delimiter): + (_handyman, delimiter) = ( + self._fixedwidth_splitter, int(delimiter)) + else: + (_handyman, delimiter) = (self._delimited_splitter, None) + self.delimiter = delimiter + if autostrip: + self._handyman = self.autostrip(_handyman) + else: + self._handyman = _handyman + self.encoding = encoding + + def _delimited_splitter(self, line): + """Chop off comments, strip, and split at delimiter. """ + if self.comments is not None: + line = line.split(self.comments)[0] + line = line.strip(" \r\n") + if not line: + return [] + return line.split(self.delimiter) + + def _fixedwidth_splitter(self, line): + if self.comments is not None: + line = line.split(self.comments)[0] + line = line.strip("\r\n") + if not line: + return [] + fixed = self.delimiter + slices = [slice(i, i + fixed) for i in range(0, len(line), fixed)] + return [line[s] for s in slices] + + def _variablewidth_splitter(self, line): + if self.comments is not None: + line = line.split(self.comments)[0] + if not line: + return [] + slices = self.delimiter + return [line[s] for s in slices] + + def __call__(self, line): + return self._handyman(_decode_line(line, self.encoding)) + + +class NameValidator: + """ + Object to validate a list of strings to use as field names. + + The strings are stripped of any non alphanumeric character, and spaces + are replaced by '_'. During instantiation, the user can define a list + of names to exclude, as well as a list of invalid characters. Names in + the exclusion list are appended a '_' character. + + Once an instance has been created, it can be called with a list of + names, and a list of valid names will be created. The `__call__` + method accepts an optional keyword "default" that sets the default name + in case of ambiguity. By default this is 'f', so that names will + default to `f0`, `f1`, etc. + + Parameters + ---------- + excludelist : sequence, optional + A list of names to exclude. This list is appended to the default + list ['return', 'file', 'print']. Excluded names are appended an + underscore: for example, `file` becomes `file_` if supplied. + deletechars : str, optional + A string combining invalid characters that must be deleted from the + names. + case_sensitive : {True, False, 'upper', 'lower'}, optional + * If True, field names are case-sensitive. + * If False or 'upper', field names are converted to upper case. + * If 'lower', field names are converted to lower case. + + The default value is True. + replace_space : '_', optional + Character(s) used in replacement of white spaces. + + Notes + ----- + Calling an instance of `NameValidator` is the same as calling its + method `validate`. + + Examples + -------- + >>> import numpy as np + >>> validator = np.lib._iotools.NameValidator() + >>> validator(['file', 'field2', 'with space', 'CaSe']) + ('file_', 'field2', 'with_space', 'CaSe') + + >>> validator = np.lib._iotools.NameValidator(excludelist=['excl'], + ... deletechars='q', + ... case_sensitive=False) + >>> validator(['excl', 'field2', 'no_q', 'with space', 'CaSe']) + ('EXCL', 'FIELD2', 'NO_Q', 'WITH_SPACE', 'CASE') + + """ + + defaultexcludelist = 'return', 'file', 'print' + defaultdeletechars = frozenset(r"""~!@#$%^&*()-=+~\|]}[{';: /?.>,<""") + + def __init__(self, excludelist=None, deletechars=None, + case_sensitive=None, replace_space='_'): + # Process the exclusion list .. + if excludelist is None: + excludelist = [] + excludelist.extend(self.defaultexcludelist) + self.excludelist = excludelist + # Process the list of characters to delete + if deletechars is None: + delete = set(self.defaultdeletechars) + else: + delete = set(deletechars) + delete.add('"') + self.deletechars = delete + # Process the case option ..... + if (case_sensitive is None) or (case_sensitive is True): + self.case_converter = lambda x: x + elif (case_sensitive is False) or case_sensitive.startswith('u'): + self.case_converter = lambda x: x.upper() + elif case_sensitive.startswith('l'): + self.case_converter = lambda x: x.lower() + else: + msg = f'unrecognized case_sensitive value {case_sensitive}.' + raise ValueError(msg) + + self.replace_space = replace_space + + def validate(self, names, defaultfmt="f%i", nbfields=None): + """ + Validate a list of strings as field names for a structured array. + + Parameters + ---------- + names : sequence of str + Strings to be validated. + defaultfmt : str, optional + Default format string, used if validating a given string + reduces its length to zero. + nbfields : integer, optional + Final number of validated names, used to expand or shrink the + initial list of names. + + Returns + ------- + validatednames : list of str + The list of validated field names. + + Notes + ----- + A `NameValidator` instance can be called directly, which is the + same as calling `validate`. For examples, see `NameValidator`. + + """ + # Initial checks .............. + if (names is None): + if (nbfields is None): + return None + names = [] + if isinstance(names, str): + names = [names, ] + if nbfields is not None: + nbnames = len(names) + if (nbnames < nbfields): + names = list(names) + [''] * (nbfields - nbnames) + elif (nbnames > nbfields): + names = names[:nbfields] + # Set some shortcuts ........... + deletechars = self.deletechars + excludelist = self.excludelist + case_converter = self.case_converter + replace_space = self.replace_space + # Initializes some variables ... + validatednames = [] + seen = {} + nbempty = 0 + + for item in names: + item = case_converter(item).strip() + if replace_space: + item = item.replace(' ', replace_space) + item = ''.join([c for c in item if c not in deletechars]) + if item == '': + item = defaultfmt % nbempty + while item in names: + nbempty += 1 + item = defaultfmt % nbempty + nbempty += 1 + elif item in excludelist: + item += '_' + cnt = seen.get(item, 0) + if cnt > 0: + validatednames.append(item + '_%d' % cnt) + else: + validatednames.append(item) + seen[item] = cnt + 1 + return tuple(validatednames) + + def __call__(self, names, defaultfmt="f%i", nbfields=None): + return self.validate(names, defaultfmt=defaultfmt, nbfields=nbfields) + + +def str2bool(value): + """ + Tries to transform a string supposed to represent a boolean to a boolean. + + Parameters + ---------- + value : str + The string that is transformed to a boolean. + + Returns + ------- + boolval : bool + The boolean representation of `value`. + + Raises + ------ + ValueError + If the string is not 'True' or 'False' (case independent) + + Examples + -------- + >>> import numpy as np + >>> np.lib._iotools.str2bool('TRUE') + True + >>> np.lib._iotools.str2bool('false') + False + + """ + value = value.upper() + if value == 'TRUE': + return True + elif value == 'FALSE': + return False + else: + raise ValueError("Invalid boolean") + + +class ConverterError(Exception): + """ + Exception raised when an error occurs in a converter for string values. + + """ + pass + + +class ConverterLockError(ConverterError): + """ + Exception raised when an attempt is made to upgrade a locked converter. + + """ + pass + + +class ConversionWarning(UserWarning): + """ + Warning issued when a string converter has a problem. + + Notes + ----- + In `genfromtxt` a `ConversionWarning` is issued if raising exceptions + is explicitly suppressed with the "invalid_raise" keyword. + + """ + pass + + +class StringConverter: + """ + Factory class for function transforming a string into another object + (int, float). + + After initialization, an instance can be called to transform a string + into another object. If the string is recognized as representing a + missing value, a default value is returned. + + Attributes + ---------- + func : function + Function used for the conversion. + default : any + Default value to return when the input corresponds to a missing + value. + type : type + Type of the output. + _status : int + Integer representing the order of the conversion. + _mapper : sequence of tuples + Sequence of tuples (dtype, function, default value) to evaluate in + order. + _locked : bool + Holds `locked` parameter. + + Parameters + ---------- + dtype_or_func : {None, dtype, function}, optional + If a `dtype`, specifies the input data type, used to define a basic + function and a default value for missing data. For example, when + `dtype` is float, the `func` attribute is set to `float` and the + default value to `np.nan`. If a function, this function is used to + convert a string to another object. In this case, it is recommended + to give an associated default value as input. + default : any, optional + Value to return by default, that is, when the string to be + converted is flagged as missing. If not given, `StringConverter` + tries to supply a reasonable default value. + missing_values : {None, sequence of str}, optional + ``None`` or sequence of strings indicating a missing value. If ``None`` + then missing values are indicated by empty entries. The default is + ``None``. + locked : bool, optional + Whether the StringConverter should be locked to prevent automatic + upgrade or not. Default is False. + + """ + _mapper = [(nx.bool, str2bool, False), + (nx.int_, int, -1),] + + # On 32-bit systems, we need to make sure that we explicitly include + # nx.int64 since ns.int_ is nx.int32. + if nx.dtype(nx.int_).itemsize < nx.dtype(nx.int64).itemsize: + _mapper.append((nx.int64, int, -1)) + + _mapper.extend([(nx.float64, float, nx.nan), + (nx.complex128, complex, nx.nan + 0j), + (nx.longdouble, nx.longdouble, nx.nan), + # If a non-default dtype is passed, fall back to generic + # ones (should only be used for the converter) + (nx.integer, int, -1), + (nx.floating, float, nx.nan), + (nx.complexfloating, complex, nx.nan + 0j), + # Last, try with the string types (must be last, because + # `_mapper[-1]` is used as default in some cases) + (nx.str_, asunicode, '???'), + (nx.bytes_, asbytes, '???'), + ]) + + @classmethod + def _getdtype(cls, val): + """Returns the dtype of the input variable.""" + return np.array(val).dtype + + @classmethod + def _getsubdtype(cls, val): + """Returns the type of the dtype of the input variable.""" + return np.array(val).dtype.type + + @classmethod + def _dtypeortype(cls, dtype): + """Returns dtype for datetime64 and type of dtype otherwise.""" + + # This is a bit annoying. We want to return the "general" type in most + # cases (ie. "string" rather than "S10"), but we want to return the + # specific type for datetime64 (ie. "datetime64[us]" rather than + # "datetime64"). + if dtype.type == np.datetime64: + return dtype + return dtype.type + + @classmethod + def upgrade_mapper(cls, func, default=None): + """ + Upgrade the mapper of a StringConverter by adding a new function and + its corresponding default. + + The input function (or sequence of functions) and its associated + default value (if any) is inserted in penultimate position of the + mapper. The corresponding type is estimated from the dtype of the + default value. + + Parameters + ---------- + func : var + Function, or sequence of functions + + Examples + -------- + >>> import dateutil.parser + >>> import datetime + >>> dateparser = dateutil.parser.parse + >>> defaultdate = datetime.date(2000, 1, 1) + >>> StringConverter.upgrade_mapper(dateparser, default=defaultdate) + """ + # Func is a single functions + if callable(func): + cls._mapper.insert(-1, (cls._getsubdtype(default), func, default)) + return + elif hasattr(func, '__iter__'): + if isinstance(func[0], (tuple, list)): + for _ in func: + cls._mapper.insert(-1, _) + return + if default is None: + default = [None] * len(func) + else: + default = list(default) + default.append([None] * (len(func) - len(default))) + for fct, dft in zip(func, default): + cls._mapper.insert(-1, (cls._getsubdtype(dft), fct, dft)) + + @classmethod + def _find_map_entry(cls, dtype): + # if a converter for the specific dtype is available use that + for i, (deftype, func, default_def) in enumerate(cls._mapper): + if dtype.type == deftype: + return i, (deftype, func, default_def) + + # otherwise find an inexact match + for i, (deftype, func, default_def) in enumerate(cls._mapper): + if np.issubdtype(dtype.type, deftype): + return i, (deftype, func, default_def) + + raise LookupError + + def __init__(self, dtype_or_func=None, default=None, missing_values=None, + locked=False): + # Defines a lock for upgrade + self._locked = bool(locked) + # No input dtype: minimal initialization + if dtype_or_func is None: + self.func = str2bool + self._status = 0 + self.default = default or False + dtype = np.dtype('bool') + else: + # Is the input a np.dtype ? + try: + self.func = None + dtype = np.dtype(dtype_or_func) + except TypeError: + # dtype_or_func must be a function, then + if not callable(dtype_or_func): + errmsg = ("The input argument `dtype` is neither a" + " function nor a dtype (got '%s' instead)") + raise TypeError(errmsg % type(dtype_or_func)) + # Set the function + self.func = dtype_or_func + # If we don't have a default, try to guess it or set it to + # None + if default is None: + try: + default = self.func('0') + except ValueError: + default = None + dtype = self._getdtype(default) + + # find the best match in our mapper + try: + self._status, (_, func, default_def) = self._find_map_entry(dtype) + except LookupError: + # no match + self.default = default + _, func, _ = self._mapper[-1] + self._status = 0 + else: + # use the found default only if we did not already have one + if default is None: + self.default = default_def + else: + self.default = default + + # If the input was a dtype, set the function to the last we saw + if self.func is None: + self.func = func + + # If the status is 1 (int), change the function to + # something more robust. + if self.func == self._mapper[1][1]: + if issubclass(dtype.type, np.uint64): + self.func = np.uint64 + elif issubclass(dtype.type, np.int64): + self.func = np.int64 + else: + self.func = lambda x: int(float(x)) + # Store the list of strings corresponding to missing values. + if missing_values is None: + self.missing_values = {''} + else: + if isinstance(missing_values, str): + missing_values = missing_values.split(",") + self.missing_values = set(list(missing_values) + ['']) + + self._callingfunction = self._strict_call + self.type = self._dtypeortype(dtype) + self._checked = False + self._initial_default = default + + def _loose_call(self, value): + try: + return self.func(value) + except ValueError: + return self.default + + def _strict_call(self, value): + try: + + # We check if we can convert the value using the current function + new_value = self.func(value) + + # In addition to having to check whether func can convert the + # value, we also have to make sure that we don't get overflow + # errors for integers. + if self.func is int: + try: + np.array(value, dtype=self.type) + except OverflowError: + raise ValueError + + # We're still here so we can now return the new value + return new_value + + except ValueError: + if value.strip() in self.missing_values: + if not self._status: + self._checked = False + return self.default + raise ValueError(f"Cannot convert string '{value}'") + + def __call__(self, value): + return self._callingfunction(value) + + def _do_upgrade(self): + # Raise an exception if we locked the converter... + if self._locked: + errmsg = "Converter is locked and cannot be upgraded" + raise ConverterLockError(errmsg) + _statusmax = len(self._mapper) + # Complains if we try to upgrade by the maximum + _status = self._status + if _status == _statusmax: + errmsg = "Could not find a valid conversion function" + raise ConverterError(errmsg) + elif _status < _statusmax - 1: + _status += 1 + self.type, self.func, default = self._mapper[_status] + self._status = _status + if self._initial_default is not None: + self.default = self._initial_default + else: + self.default = default + + def upgrade(self, value): + """ + Find the best converter for a given string, and return the result. + + The supplied string `value` is converted by testing different + converters in order. First the `func` method of the + `StringConverter` instance is tried, if this fails other available + converters are tried. The order in which these other converters + are tried is determined by the `_status` attribute of the instance. + + Parameters + ---------- + value : str + The string to convert. + + Returns + ------- + out : any + The result of converting `value` with the appropriate converter. + + """ + self._checked = True + try: + return self._strict_call(value) + except ValueError: + self._do_upgrade() + return self.upgrade(value) + + def iterupgrade(self, value): + self._checked = True + if not hasattr(value, '__iter__'): + value = (value,) + _strict_call = self._strict_call + try: + for _m in value: + _strict_call(_m) + except ValueError: + self._do_upgrade() + self.iterupgrade(value) + + def update(self, func, default=None, testing_value=None, + missing_values='', locked=False): + """ + Set StringConverter attributes directly. + + Parameters + ---------- + func : function + Conversion function. + default : any, optional + Value to return by default, that is, when the string to be + converted is flagged as missing. If not given, + `StringConverter` tries to supply a reasonable default value. + testing_value : str, optional + A string representing a standard input value of the converter. + This string is used to help defining a reasonable default + value. + missing_values : {sequence of str, None}, optional + Sequence of strings indicating a missing value. If ``None``, then + the existing `missing_values` are cleared. The default is ``''``. + locked : bool, optional + Whether the StringConverter should be locked to prevent + automatic upgrade or not. Default is False. + + Notes + ----- + `update` takes the same parameters as the constructor of + `StringConverter`, except that `func` does not accept a `dtype` + whereas `dtype_or_func` in the constructor does. + + """ + self.func = func + self._locked = locked + + # Don't reset the default to None if we can avoid it + if default is not None: + self.default = default + self.type = self._dtypeortype(self._getdtype(default)) + else: + try: + tester = func(testing_value or '1') + except (TypeError, ValueError): + tester = None + self.type = self._dtypeortype(self._getdtype(tester)) + + # Add the missing values to the existing set or clear it. + if missing_values is None: + # Clear all missing values even though the ctor initializes it to + # set(['']) when the argument is None. + self.missing_values = set() + else: + if not np.iterable(missing_values): + missing_values = [missing_values] + if not all(isinstance(v, str) for v in missing_values): + raise TypeError("missing_values must be strings or unicode") + self.missing_values.update(missing_values) + + +def easy_dtype(ndtype, names=None, defaultfmt="f%i", **validationargs): + """ + Convenience function to create a `np.dtype` object. + + The function processes the input `dtype` and matches it with the given + names. + + Parameters + ---------- + ndtype : var + Definition of the dtype. Can be any string or dictionary recognized + by the `np.dtype` function, or a sequence of types. + names : str or sequence, optional + Sequence of strings to use as field names for a structured dtype. + For convenience, `names` can be a string of a comma-separated list + of names. + defaultfmt : str, optional + Format string used to define missing names, such as ``"f%i"`` + (default) or ``"fields_%02i"``. + validationargs : optional + A series of optional arguments used to initialize a + `NameValidator`. + + Examples + -------- + >>> import numpy as np + >>> np.lib._iotools.easy_dtype(float) + dtype('float64') + >>> np.lib._iotools.easy_dtype("i4, f8") + dtype([('f0', '>> np.lib._iotools.easy_dtype("i4, f8", defaultfmt="field_%03i") + dtype([('field_000', '>> np.lib._iotools.easy_dtype((int, float, float), names="a,b,c") + dtype([('a', '>> np.lib._iotools.easy_dtype(float, names="a,b,c") + dtype([('a', ' None: ... + def __call__(self, /, line: str | bytes) -> list[str]: ... + def autostrip(self, /, method: Callable[[_T], Iterable[str]]) -> Callable[[_T], list[str]]: ... + +class NameValidator: + defaultexcludelist: ClassVar[Sequence[str]] = ... + defaultdeletechars: ClassVar[frozenset[str]] = ... + excludelist: list[str] + deletechars: set[str] + case_converter: Callable[[str], str] + replace_space: str + + def __init__( + self, + /, + excludelist: Iterable[str] | None = None, + deletechars: Iterable[str] | None = None, + case_sensitive: Literal["upper", "lower"] | bool | None = None, + replace_space: str = "_", + ) -> None: ... + def __call__(self, /, names: Iterable[str], defaultfmt: str = "f%i", nbfields: int | None = None) -> tuple[str, ...]: ... + def validate(self, /, names: Iterable[str], defaultfmt: str = "f%i", nbfields: int | None = None) -> tuple[str, ...]: ... + +class StringConverter: + func: Callable[[str], Any] | None + default: Any + missing_values: set[str] + type: np.dtype[np.datetime64] | np.generic + + def __init__( + self, + /, + dtype_or_func: npt.DTypeLike | None = None, + default: None = None, + missing_values: Iterable[str] | None = None, + locked: bool = False, + ) -> None: ... + def update( + self, + /, + func: Callable[[str], Any], + default: object | None = None, + testing_value: str | None = None, + missing_values: str = "", + locked: bool = False, + ) -> None: ... + # + def __call__(self, /, value: str) -> Any: ... + def upgrade(self, /, value: str) -> Any: ... + def iterupgrade(self, /, value: Iterable[str] | str) -> None: ... + + # + @classmethod + def upgrade_mapper(cls, func: Callable[[str], Any], default: object | None = None) -> None: ... + +def _decode_line(line: str | bytes, encoding: str | None = None) -> str: ... +def _is_string_like(obj: object) -> bool: ... +def _is_bytes_like(obj: object) -> bool: ... +def has_nested_fields(ndtype: np.dtype[np.void]) -> bool: ... +def flatten_dtype(ndtype: np.dtype[np.void], flatten_base: bool = False) -> type[np.dtype]: ... +@overload +def str2bool(value: Literal["false", "False", "FALSE"]) -> Literal[False]: ... +@overload +def str2bool(value: Literal["true", "True", "TRUE"]) -> Literal[True]: ... +def easy_dtype( + ndtype: str | Sequence[_DTypeLikeNested], + names: str | Sequence[str] | None = None, + defaultfmt: str = "f%i", + **validationargs: Unpack[_NameValidatorKwargs], +) -> np.dtype[np.void]: ... diff --git a/python/user_packages/Python313/site-packages/numpy/lib/_nanfunctions_impl.py b/python/user_packages/Python313/site-packages/numpy/lib/_nanfunctions_impl.py new file mode 100644 index 0000000000000000000000000000000000000000..b65e260bf9010408ca8d76ce5137e65145e6a87c --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/lib/_nanfunctions_impl.py @@ -0,0 +1,2006 @@ +""" +Functions that ignore NaN. + +Functions +--------- + +- `nanmin` -- minimum non-NaN value +- `nanmax` -- maximum non-NaN value +- `nanargmin` -- index of minimum non-NaN value +- `nanargmax` -- index of maximum non-NaN value +- `nansum` -- sum of non-NaN values +- `nanprod` -- product of non-NaN values +- `nancumsum` -- cumulative sum of non-NaN values +- `nancumprod` -- cumulative product of non-NaN values +- `nanmean` -- mean of non-NaN values +- `nanvar` -- variance of non-NaN values +- `nanstd` -- standard deviation of non-NaN values +- `nanmedian` -- median of non-NaN values +- `nanquantile` -- qth quantile of non-NaN values +- `nanpercentile` -- qth percentile of non-NaN values + +""" +import functools +import warnings + +import numpy as np +import numpy._core.numeric as _nx +from numpy._core import overrides +from numpy.lib import _function_base_impl as fnb +from numpy.lib._function_base_impl import _weights_are_valid + +array_function_dispatch = functools.partial( + overrides.array_function_dispatch, module='numpy') + + +__all__ = [ + 'nansum', 'nanmax', 'nanmin', 'nanargmax', 'nanargmin', 'nanmean', + 'nanmedian', 'nanpercentile', 'nanvar', 'nanstd', 'nanprod', + 'nancumsum', 'nancumprod', 'nanquantile' + ] + + +def _nan_mask(a, out=None): + """ + Parameters + ---------- + a : array-like + Input array with at least 1 dimension. + out : ndarray, optional + Alternate output array in which to place the result. The default + is ``None``; if provided, it must have the same shape as the + expected output and will prevent the allocation of a new array. + + Returns + ------- + y : bool ndarray or True + A bool array where ``np.nan`` positions are marked with ``False`` + and other positions are marked with ``True``. If the type of ``a`` + is such that it can't possibly contain ``np.nan``, returns ``True``. + """ + # we assume that a is an array for this private function + + if a.dtype.kind not in 'fc': + return True + + y = np.isnan(a, out=out) + y = np.invert(y, out=y) + return y + +def _replace_nan(a, val): + """ + If `a` is of inexact type, make a copy of `a`, replace NaNs with + the `val` value, and return the copy together with a boolean mask + marking the locations where NaNs were present. If `a` is not of + inexact type, do nothing and return `a` together with a mask of None. + + Note that scalars will end up as array scalars, which is important + for using the result as the value of the out argument in some + operations. + + Parameters + ---------- + a : array-like + Input array. + val : float + NaN values are set to val before doing the operation. + + Returns + ------- + y : ndarray + If `a` is of inexact type, return a copy of `a` with the NaNs + replaced by the fill value, otherwise return `a`. + mask: {bool, None} + If `a` is of inexact type, return a boolean mask marking locations of + NaNs, otherwise return None. + + """ + a = np.asanyarray(a) + + if a.dtype == np.object_: + # object arrays do not support `isnan` (gh-9009), so make a guess + mask = np.not_equal(a, a, dtype=bool) + elif issubclass(a.dtype.type, np.inexact): + mask = np.isnan(a) + else: + mask = None + + if mask is not None: + a = np.array(a, subok=True, copy=True) + np.copyto(a, val, where=mask) + + return a, mask + + +def _copyto(a, val, mask): + """ + Replace values in `a` with NaN where `mask` is True. This differs from + copyto in that it will deal with the case where `a` is a numpy scalar. + + Parameters + ---------- + a : ndarray or numpy scalar + Array or numpy scalar some of whose values are to be replaced + by val. + val : numpy scalar + Value used a replacement. + mask : ndarray, scalar + Boolean array. Where True the corresponding element of `a` is + replaced by `val`. Broadcasts. + + Returns + ------- + res : ndarray, scalar + Array with elements replaced or scalar `val`. + + """ + if isinstance(a, np.ndarray): + np.copyto(a, val, where=mask, casting='unsafe') + else: + a = a.dtype.type(val) + return a + + +def _remove_nan_1d(arr1d, second_arr1d=None, overwrite_input=False): + """ + Equivalent to arr1d[~arr1d.isnan()], but in a different order + + Presumably faster as it incurs fewer copies + + Parameters + ---------- + arr1d : ndarray + Array to remove nans from + second_arr1d : ndarray or None + A second array which will have the same positions removed as arr1d. + overwrite_input : bool + True if `arr1d` can be modified in place + + Returns + ------- + res : ndarray + Array with nan elements removed + second_res : ndarray or None + Second array with nan element positions of first array removed. + overwrite_input : bool + True if `res` can be modified in place, given the constraint on the + input + """ + if arr1d.dtype == object: + # object arrays do not support `isnan` (gh-9009), so make a guess + c = np.not_equal(arr1d, arr1d, dtype=bool) + else: + c = np.isnan(arr1d) + + s = np.nonzero(c)[0] + if s.size == arr1d.size: + warnings.warn("All-NaN slice encountered", RuntimeWarning, + stacklevel=6) + if second_arr1d is None: + return arr1d[:0], None, True + else: + return arr1d[:0], second_arr1d[:0], True + elif s.size == 0: + return arr1d, second_arr1d, overwrite_input + else: + if not overwrite_input: + arr1d = arr1d.copy() + # select non-nans at end of array + enonan = arr1d[-s.size:][~c[-s.size:]] + # fill nans in beginning of array with non-nans of end + arr1d[s[:enonan.size]] = enonan + + if second_arr1d is None: + return arr1d[:-s.size], None, True + else: + if not overwrite_input: + second_arr1d = second_arr1d.copy() + enonan = second_arr1d[-s.size:][~c[-s.size:]] + second_arr1d[s[:enonan.size]] = enonan + + return arr1d[:-s.size], second_arr1d[:-s.size], True + + +def _divide_by_count(a, b, out=None): + """ + Compute a/b ignoring invalid results. If `a` is an array the division + is done in place. If `a` is a scalar, then its type is preserved in the + output. If out is None, then a is used instead so that the division + is in place. Note that this is only called with `a` an inexact type. + + Parameters + ---------- + a : {ndarray, numpy scalar} + Numerator. Expected to be of inexact type but not checked. + b : {ndarray, numpy scalar} + Denominator. + out : ndarray, optional + Alternate output array in which to place the result. The default + is ``None``; if provided, it must have the same shape as the + expected output, but the type will be cast if necessary. + + Returns + ------- + ret : {ndarray, numpy scalar} + The return value is a/b. If `a` was an ndarray the division is done + in place. If `a` is a numpy scalar, the division preserves its type. + + """ + with np.errstate(invalid='ignore', divide='ignore'): + if isinstance(a, np.ndarray): + if out is None: + return np.divide(a, b, out=a, casting='unsafe') + else: + return np.divide(a, b, out=out, casting='unsafe') + elif out is None: + # Precaution against reduced object arrays + try: + return a.dtype.type(a / b) + except AttributeError: + return a / b + else: + # This is questionable, but currently a numpy scalar can + # be output to a zero dimensional array. + return np.divide(a, b, out=out, casting='unsafe') + + +def _nanmin_dispatcher(a, axis=None, out=None, keepdims=None, + initial=None, where=None): + return (a, out) + + +@array_function_dispatch(_nanmin_dispatcher) +def nanmin(a, axis=None, out=None, keepdims=np._NoValue, initial=np._NoValue, + where=np._NoValue): + """ + Return minimum of an array or minimum along an axis, ignoring any NaNs. + When all-NaN slices are encountered a ``RuntimeWarning`` is raised and + Nan is returned for that slice. + + Parameters + ---------- + a : array_like + Array containing numbers whose minimum is desired. If `a` is not an + array, a conversion is attempted. + axis : {int, tuple of int, None}, optional + Axis or axes along which the minimum is computed. The default is to compute + the minimum of the flattened array. + out : ndarray, optional + Alternate output array in which to place the result. The default + is ``None``; if provided, it must have the same shape as the + expected output, but the type will be cast if necessary. See + :ref:`ufuncs-output-type` for more details. + keepdims : bool, optional + If this is set to True, the axes which are reduced are left + in the result as dimensions with size one. With this option, + the result will broadcast correctly against the original `a`. + + If the value is anything but the default, then + `keepdims` will be passed through to the `min` method + of sub-classes of `ndarray`. If the sub-classes methods + does not implement `keepdims` any exceptions will be raised. + initial : scalar, optional + The maximum value of an output element. Must be present to allow + computation on empty slice. See `~numpy.ufunc.reduce` for details. + + .. versionadded:: 1.22.0 + where : array_like of bool, optional + Elements to compare for the minimum. See `~numpy.ufunc.reduce` + for details. + + .. versionadded:: 1.22.0 + + Returns + ------- + nanmin : ndarray + An array with the same shape as `a`, with the specified axis + removed. If `a` is a 0-d array, or if axis is None, an ndarray + scalar is returned. The same dtype as `a` is returned. + + See Also + -------- + nanmax : + The maximum value of an array along a given axis, ignoring any NaNs. + amin : + The minimum value of an array along a given axis, propagating any NaNs. + fmin : + Element-wise minimum of two arrays, ignoring any NaNs. + minimum : + Element-wise minimum of two arrays, propagating any NaNs. + isnan : + Shows which elements are Not a Number (NaN). + isfinite: + Shows which elements are neither NaN nor infinity. + + amax, fmax, maximum + + Notes + ----- + NumPy uses the IEEE Standard for Binary Floating-Point for Arithmetic + (IEEE 754). This means that Not a Number is not equivalent to infinity. + Positive infinity is treated as a very large number and negative + infinity is treated as a very small (i.e. negative) number. + + If the input has a integer type the function is equivalent to np.min. + + Examples + -------- + >>> import numpy as np + >>> a = np.array([[1, 2], [3, np.nan]]) + >>> np.nanmin(a) + 1.0 + >>> np.nanmin(a, axis=0) + array([1., 2.]) + >>> np.nanmin(a, axis=1) + array([1., 3.]) + + When positive infinity and negative infinity are present: + + >>> np.nanmin([1, 2, np.nan, np.inf]) + 1.0 + >>> np.nanmin([1, 2, np.nan, -np.inf]) + -inf + + """ + kwargs = {} + if keepdims is not np._NoValue: + kwargs['keepdims'] = keepdims + if initial is not np._NoValue: + kwargs['initial'] = initial + if where is not np._NoValue: + kwargs['where'] = where + + if (type(a) is np.ndarray or type(a) is np.memmap) and a.dtype != np.object_: + # Fast, but not safe for subclasses of ndarray, or object arrays, + # which do not implement isnan (gh-9009), or fmin correctly (gh-8975) + res = np.fmin.reduce(a, axis=axis, out=out, **kwargs) + if np.isnan(res).any(): + warnings.warn("All-NaN slice encountered", RuntimeWarning, + stacklevel=2) + else: + # Slow, but safe for subclasses of ndarray + a, mask = _replace_nan(a, +np.inf) + res = np.amin(a, axis=axis, out=out, **kwargs) + if mask is None: + return res + + # Check for all-NaN axis + kwargs.pop("initial", None) + mask = np.all(mask, axis=axis, **kwargs) + if np.any(mask): + res = _copyto(res, np.nan, mask) + warnings.warn("All-NaN axis encountered", RuntimeWarning, + stacklevel=2) + return res + + +def _nanmax_dispatcher(a, axis=None, out=None, keepdims=None, + initial=None, where=None): + return (a, out) + + +@array_function_dispatch(_nanmax_dispatcher) +def nanmax(a, axis=None, out=None, keepdims=np._NoValue, initial=np._NoValue, + where=np._NoValue): + """ + Return the maximum of an array or maximum along an axis, ignoring any + NaNs. When all-NaN slices are encountered a ``RuntimeWarning`` is + raised and NaN is returned for that slice. + + Parameters + ---------- + a : array_like + Array containing numbers whose maximum is desired. If `a` is not an + array, a conversion is attempted. + axis : {int, tuple of int, None}, optional + Axis or axes along which the maximum is computed. The default is to compute + the maximum of the flattened array. + out : ndarray, optional + Alternate output array in which to place the result. The default + is ``None``; if provided, it must have the same shape as the + expected output, but the type will be cast if necessary. See + :ref:`ufuncs-output-type` for more details. + keepdims : bool, optional + If this is set to True, the axes which are reduced are left + in the result as dimensions with size one. With this option, + the result will broadcast correctly against the original `a`. + If the value is anything but the default, then + `keepdims` will be passed through to the `max` method + of sub-classes of `ndarray`. If the sub-classes methods + does not implement `keepdims` any exceptions will be raised. + initial : scalar, optional + The minimum value of an output element. Must be present to allow + computation on empty slice. See `~numpy.ufunc.reduce` for details. + + .. versionadded:: 1.22.0 + where : array_like of bool, optional + Elements to compare for the maximum. See `~numpy.ufunc.reduce` + for details. + + .. versionadded:: 1.22.0 + + Returns + ------- + nanmax : ndarray + An array with the same shape as `a`, with the specified axis removed. + If `a` is a 0-d array, or if axis is None, an ndarray scalar is + returned. The same dtype as `a` is returned. + + See Also + -------- + nanmin : + The minimum value of an array along a given axis, ignoring any NaNs. + amax : + The maximum value of an array along a given axis, propagating any NaNs. + fmax : + Element-wise maximum of two arrays, ignoring any NaNs. + maximum : + Element-wise maximum of two arrays, propagating any NaNs. + isnan : + Shows which elements are Not a Number (NaN). + isfinite: + Shows which elements are neither NaN nor infinity. + + amin, fmin, minimum + + Notes + ----- + NumPy uses the IEEE Standard for Binary Floating-Point for Arithmetic + (IEEE 754). This means that Not a Number is not equivalent to infinity. + Positive infinity is treated as a very large number and negative + infinity is treated as a very small (i.e. negative) number. + + If the input has a integer type the function is equivalent to np.max. + + Examples + -------- + >>> import numpy as np + >>> a = np.array([[1, 2], [3, np.nan]]) + >>> np.nanmax(a) + 3.0 + >>> np.nanmax(a, axis=0) + array([3., 2.]) + >>> np.nanmax(a, axis=1) + array([2., 3.]) + + When positive infinity and negative infinity are present: + + >>> np.nanmax([1, 2, np.nan, -np.inf]) + 2.0 + >>> np.nanmax([1, 2, np.nan, np.inf]) + inf + + """ + kwargs = {} + if keepdims is not np._NoValue: + kwargs['keepdims'] = keepdims + if initial is not np._NoValue: + kwargs['initial'] = initial + if where is not np._NoValue: + kwargs['where'] = where + + if (type(a) is np.ndarray or type(a) is np.memmap) and a.dtype != np.object_: + # Fast, but not safe for subclasses of ndarray, or object arrays, + # which do not implement isnan (gh-9009), or fmax correctly (gh-8975) + res = np.fmax.reduce(a, axis=axis, out=out, **kwargs) + if np.isnan(res).any(): + warnings.warn("All-NaN slice encountered", RuntimeWarning, + stacklevel=2) + else: + # Slow, but safe for subclasses of ndarray + a, mask = _replace_nan(a, -np.inf) + res = np.amax(a, axis=axis, out=out, **kwargs) + if mask is None: + return res + + # Check for all-NaN axis + kwargs.pop("initial", None) + mask = np.all(mask, axis=axis, **kwargs) + if np.any(mask): + res = _copyto(res, np.nan, mask) + warnings.warn("All-NaN axis encountered", RuntimeWarning, + stacklevel=2) + return res + + +def _nanargmin_dispatcher(a, axis=None, out=None, *, keepdims=None): + return (a,) + + +@array_function_dispatch(_nanargmin_dispatcher) +def nanargmin(a, axis=None, out=None, *, keepdims=np._NoValue): + """ + Return the indices of the minimum values in the specified axis ignoring + NaNs. For all-NaN slices ``ValueError`` is raised. Warning: the results + cannot be trusted if a slice contains only NaNs and Infs. + + Parameters + ---------- + a : array_like + Input data. + axis : int, optional + Axis along which to operate. By default flattened input is used. + out : array, optional + If provided, the result will be inserted into this array. It should + be of the appropriate shape and dtype. + + .. versionadded:: 1.22.0 + keepdims : bool, optional + If this is set to True, the axes which are reduced are left + in the result as dimensions with size one. With this option, + the result will broadcast correctly against the array. + + .. versionadded:: 1.22.0 + + Returns + ------- + index_array : ndarray + An array of indices or a single index value. + + See Also + -------- + argmin, nanargmax + + Examples + -------- + >>> import numpy as np + >>> a = np.array([[np.nan, 4], [2, 3]]) + >>> np.argmin(a) + 0 + >>> np.nanargmin(a) + 2 + >>> np.nanargmin(a, axis=0) + array([1, 1]) + >>> np.nanargmin(a, axis=1) + array([1, 0]) + + """ + a, mask = _replace_nan(a, np.inf) + if mask is not None and mask.size: + mask = np.all(mask, axis=axis) + if np.any(mask): + raise ValueError("All-NaN slice encountered") + res = np.argmin(a, axis=axis, out=out, keepdims=keepdims) + return res + + +def _nanargmax_dispatcher(a, axis=None, out=None, *, keepdims=None): + return (a,) + + +@array_function_dispatch(_nanargmax_dispatcher) +def nanargmax(a, axis=None, out=None, *, keepdims=np._NoValue): + """ + Return the indices of the maximum values in the specified axis ignoring + NaNs. For all-NaN slices ``ValueError`` is raised. Warning: the + results cannot be trusted if a slice contains only NaNs and -Infs. + + + Parameters + ---------- + a : array_like + Input data. + axis : int, optional + Axis along which to operate. By default flattened input is used. + out : array, optional + If provided, the result will be inserted into this array. It should + be of the appropriate shape and dtype. + + .. versionadded:: 1.22.0 + keepdims : bool, optional + If this is set to True, the axes which are reduced are left + in the result as dimensions with size one. With this option, + the result will broadcast correctly against the array. + + .. versionadded:: 1.22.0 + + Returns + ------- + index_array : ndarray + An array of indices or a single index value. + + See Also + -------- + argmax, nanargmin + + Examples + -------- + >>> import numpy as np + >>> a = np.array([[np.nan, 4], [2, 3]]) + >>> np.argmax(a) + 0 + >>> np.nanargmax(a) + 1 + >>> np.nanargmax(a, axis=0) + array([1, 0]) + >>> np.nanargmax(a, axis=1) + array([1, 1]) + + """ + a, mask = _replace_nan(a, -np.inf) + if mask is not None and mask.size: + mask = np.all(mask, axis=axis) + if np.any(mask): + raise ValueError("All-NaN slice encountered") + res = np.argmax(a, axis=axis, out=out, keepdims=keepdims) + return res + + +def _nansum_dispatcher(a, axis=None, dtype=None, out=None, keepdims=None, + initial=None, where=None): + return (a, out) + + +@array_function_dispatch(_nansum_dispatcher) +def nansum(a, axis=None, dtype=None, out=None, keepdims=np._NoValue, + initial=np._NoValue, where=np._NoValue): + """ + Return the sum of array elements over a given axis treating Not a + Numbers (NaNs) as zero. + + In NumPy versions <= 1.9.0 Nan is returned for slices that are all-NaN or + empty. In later versions zero is returned. + + Parameters + ---------- + a : array_like + Array containing numbers whose sum is desired. If `a` is not an + array, a conversion is attempted. + axis : {int, tuple of int, None}, optional + Axis or axes along which the sum is computed. The default is to compute the + sum of the flattened array. + dtype : data-type, optional + The type of the returned array and of the accumulator in which the + elements are summed. By default, the dtype of `a` is used. An + exception is when `a` has an integer type with less precision than + the platform (u)intp. In that case, the default will be either + (u)int32 or (u)int64 depending on whether the platform is 32 or 64 + bits. For inexact inputs, dtype must be inexact. + out : ndarray, optional + Alternate output array in which to place the result. The default + is ``None``. If provided, it must have the same shape as the + expected output, but the type will be cast if necessary. See + :ref:`ufuncs-output-type` for more details. The casting of NaN to integer + can yield unexpected results. + keepdims : bool, optional + If this is set to True, the axes which are reduced are left + in the result as dimensions with size one. With this option, + the result will broadcast correctly against the original `a`. + + If the value is anything but the default, then + `keepdims` will be passed through to the `mean` or `sum` methods + of sub-classes of `ndarray`. If the sub-classes methods + does not implement `keepdims` any exceptions will be raised. + initial : scalar, optional + Starting value for the sum. See `~numpy.ufunc.reduce` for details. + + .. versionadded:: 1.22.0 + where : array_like of bool, optional + Elements to include in the sum. See `~numpy.ufunc.reduce` for details. + + .. versionadded:: 1.22.0 + + Returns + ------- + nansum : ndarray. + A new array holding the result is returned unless `out` is + specified, in which it is returned. The result has the same + size as `a`, and the same shape as `a` if `axis` is not None + or `a` is a 1-d array. + + See Also + -------- + numpy.sum : Sum across array propagating NaNs. + isnan : Show which elements are NaN. + isfinite : Show which elements are not NaN or +/-inf. + + Notes + ----- + If both positive and negative infinity are present, the sum will be Not + A Number (NaN). + + Examples + -------- + >>> import numpy as np + >>> np.nansum(1) + 1 + >>> np.nansum([1]) + 1 + >>> np.nansum([1, np.nan]) + 1.0 + >>> a = np.array([[1, 1], [1, np.nan]]) + >>> np.nansum(a) + 3.0 + >>> np.nansum(a, axis=0) + array([2., 1.]) + >>> np.nansum([1, np.nan, np.inf]) + inf + >>> np.nansum([1, np.nan, -np.inf]) + -inf + >>> with np.errstate(invalid="ignore"): + ... np.nansum([1, np.nan, np.inf, -np.inf]) # both +/- infinity present + np.float64(nan) + + """ + a, mask = _replace_nan(a, 0) + return np.sum(a, axis=axis, dtype=dtype, out=out, keepdims=keepdims, + initial=initial, where=where) + + +def _nanprod_dispatcher(a, axis=None, dtype=None, out=None, keepdims=None, + initial=None, where=None): + return (a, out) + + +@array_function_dispatch(_nanprod_dispatcher) +def nanprod(a, axis=None, dtype=None, out=None, keepdims=np._NoValue, + initial=np._NoValue, where=np._NoValue): + """ + Return the product of array elements over a given axis treating Not a + Numbers (NaNs) as ones. + + One is returned for slices that are all-NaN or empty. + + Parameters + ---------- + a : array_like + Array containing numbers whose product is desired. If `a` is not an + array, a conversion is attempted. + axis : {int, tuple of int, None}, optional + Axis or axes along which the product is computed. The default is to compute + the product of the flattened array. + dtype : data-type, optional + The type of the returned array and of the accumulator in which the + elements are summed. By default, the dtype of `a` is used. An + exception is when `a` has an integer type with less precision than + the platform (u)intp. In that case, the default will be either + (u)int32 or (u)int64 depending on whether the platform is 32 or 64 + bits. For inexact inputs, dtype must be inexact. + out : ndarray, optional + Alternate output array in which to place the result. The default + is ``None``. If provided, it must have the same shape as the + expected output, but the type will be cast if necessary. See + :ref:`ufuncs-output-type` for more details. The casting of NaN to integer + can yield unexpected results. + keepdims : bool, optional + If True, the axes which are reduced are left in the result as + dimensions with size one. With this option, the result will + broadcast correctly against the original `arr`. + initial : scalar, optional + The starting value for this product. See `~numpy.ufunc.reduce` + for details. + + .. versionadded:: 1.22.0 + where : array_like of bool, optional + Elements to include in the product. See `~numpy.ufunc.reduce` + for details. + + .. versionadded:: 1.22.0 + + Returns + ------- + nanprod : ndarray + A new array holding the result is returned unless `out` is + specified, in which case it is returned. + + See Also + -------- + numpy.prod : Product across array propagating NaNs. + isnan : Show which elements are NaN. + + Examples + -------- + >>> import numpy as np + >>> np.nanprod(1) + 1 + >>> np.nanprod([1]) + 1 + >>> np.nanprod([1, np.nan]) + 1.0 + >>> a = np.array([[1, 2], [3, np.nan]]) + >>> np.nanprod(a) + 6.0 + >>> np.nanprod(a, axis=0) + array([3., 2.]) + + """ + a, mask = _replace_nan(a, 1) + return np.prod(a, axis=axis, dtype=dtype, out=out, keepdims=keepdims, + initial=initial, where=where) + + +def _nancumsum_dispatcher(a, axis=None, dtype=None, out=None): + return (a, out) + + +@array_function_dispatch(_nancumsum_dispatcher) +def nancumsum(a, axis=None, dtype=None, out=None): + """ + Return the cumulative sum of array elements over a given axis treating Not a + Numbers (NaNs) as zero. The cumulative sum does not change when NaNs are + encountered and leading NaNs are replaced by zeros. + + Zeros are returned for slices that are all-NaN or empty. + + Parameters + ---------- + a : array_like + Input array. + axis : int, optional + Axis along which the cumulative sum is computed. The default + (None) is to compute the cumsum over the flattened array. + dtype : dtype, optional + Type of the returned array and of the accumulator in which the + elements are summed. If `dtype` is not specified, it defaults + to the dtype of `a`, unless `a` has an integer dtype with a + precision less than that of the default platform integer. In + that case, the default platform integer is used. + out : ndarray, optional + Alternative output array in which to place the result. It must + have the same shape and buffer length as the expected output + but the type will be cast if necessary. See :ref:`ufuncs-output-type` for + more details. + + Returns + ------- + nancumsum : ndarray. + A new array holding the result is returned unless `out` is + specified, in which it is returned. The result has the same + size as `a`, and the same shape as `a` if `axis` is not None + or `a` is a 1-d array. + + See Also + -------- + numpy.cumsum : Cumulative sum across array propagating NaNs. + isnan : Show which elements are NaN. + + Examples + -------- + >>> import numpy as np + >>> np.nancumsum(1) + array([1]) + >>> np.nancumsum([1]) + array([1]) + >>> np.nancumsum([1, np.nan]) + array([1., 1.]) + >>> a = np.array([[1, 2], [3, np.nan]]) + >>> np.nancumsum(a) + array([1., 3., 6., 6.]) + >>> np.nancumsum(a, axis=0) + array([[1., 2.], + [4., 2.]]) + >>> np.nancumsum(a, axis=1) + array([[1., 3.], + [3., 3.]]) + + """ + a, mask = _replace_nan(a, 0) + return np.cumsum(a, axis=axis, dtype=dtype, out=out) + + +def _nancumprod_dispatcher(a, axis=None, dtype=None, out=None): + return (a, out) + + +@array_function_dispatch(_nancumprod_dispatcher) +def nancumprod(a, axis=None, dtype=None, out=None): + """ + Return the cumulative product of array elements over a given axis treating Not a + Numbers (NaNs) as one. The cumulative product does not change when NaNs are + encountered and leading NaNs are replaced by ones. + + Ones are returned for slices that are all-NaN or empty. + + Parameters + ---------- + a : array_like + Input array. + axis : int, optional + Axis along which the cumulative product is computed. By default + the input is flattened. + dtype : dtype, optional + Type of the returned array, as well as of the accumulator in which + the elements are multiplied. If *dtype* is not specified, it + defaults to the dtype of `a`, unless `a` has an integer dtype with + a precision less than that of the default platform integer. In + that case, the default platform integer is used instead. + out : ndarray, optional + Alternative output array in which to place the result. It must + have the same shape and buffer length as the expected output + but the type of the resulting values will be cast if necessary. + + Returns + ------- + nancumprod : ndarray + A new array holding the result is returned unless `out` is + specified, in which case it is returned. + + See Also + -------- + numpy.cumprod : Cumulative product across array propagating NaNs. + isnan : Show which elements are NaN. + + Examples + -------- + >>> import numpy as np + >>> np.nancumprod(1) + array([1]) + >>> np.nancumprod([1]) + array([1]) + >>> np.nancumprod([1, np.nan]) + array([1., 1.]) + >>> a = np.array([[1, 2], [3, np.nan]]) + >>> np.nancumprod(a) + array([1., 2., 6., 6.]) + >>> np.nancumprod(a, axis=0) + array([[1., 2.], + [3., 2.]]) + >>> np.nancumprod(a, axis=1) + array([[1., 2.], + [3., 3.]]) + + """ + a, mask = _replace_nan(a, 1) + return np.cumprod(a, axis=axis, dtype=dtype, out=out) + + +def _nanmean_dispatcher(a, axis=None, dtype=None, out=None, keepdims=None, + *, where=None): + return (a, out) + + +@array_function_dispatch(_nanmean_dispatcher) +def nanmean(a, axis=None, dtype=None, out=None, keepdims=np._NoValue, + *, where=np._NoValue): + """ + Compute the arithmetic mean along the specified axis, ignoring NaNs. + + Returns the average of the array elements. The average is taken over + the flattened array by default, otherwise over the specified axis. + `float64` intermediate and return values are used for integer inputs. + + For all-NaN slices, NaN is returned and a `RuntimeWarning` is raised. + + Parameters + ---------- + a : array_like + Array containing numbers whose mean is desired. If `a` is not an + array, a conversion is attempted. + axis : {int, tuple of int, None}, optional + Axis or axes along which the means are computed. The default is to compute + the mean of the flattened array. + dtype : data-type, optional + Type to use in computing the mean. For integer inputs, the default + is `float64`; for inexact inputs, it is the same as the input + dtype. + out : ndarray, optional + Alternate output array in which to place the result. The default + is ``None``; if provided, it must have the same shape as the + expected output, but the type will be cast if necessary. + See :ref:`ufuncs-output-type` for more details. + keepdims : bool, optional + If this is set to True, the axes which are reduced are left + in the result as dimensions with size one. With this option, + the result will broadcast correctly against the original `a`. + + If the value is anything but the default, then + `keepdims` will be passed through to the `mean` or `sum` methods + of sub-classes of `ndarray`. If the sub-classes methods + does not implement `keepdims` any exceptions will be raised. + where : array_like of bool, optional + Elements to include in the mean. See `~numpy.ufunc.reduce` for details. + + .. versionadded:: 1.22.0 + + Returns + ------- + m : ndarray, see dtype parameter above + If `out=None`, returns a new array containing the mean values, + otherwise a reference to the output array is returned. Nan is + returned for slices that contain only NaNs. + + See Also + -------- + average : Weighted average + mean : Arithmetic mean taken while not ignoring NaNs + var, nanvar + + Notes + ----- + The arithmetic mean is the sum of the non-NaN elements along the axis + divided by the number of non-NaN elements. + + Note that for floating-point input, the mean is computed using the same + precision the input has. Depending on the input data, this can cause + the results to be inaccurate, especially for `float32`. Specifying a + higher-precision accumulator using the `dtype` keyword can alleviate + this issue. + + Examples + -------- + >>> import numpy as np + >>> a = np.array([[1, np.nan], [3, 4]]) + >>> np.nanmean(a) + 2.6666666666666665 + >>> np.nanmean(a, axis=0) + array([2., 4.]) + >>> np.nanmean(a, axis=1) + array([1., 3.5]) # may vary + + """ + arr, mask = _replace_nan(a, 0) + if mask is None: + return np.mean(arr, axis=axis, dtype=dtype, out=out, keepdims=keepdims, + where=where) + + if dtype is not None: + dtype = np.dtype(dtype) + if dtype is not None and not issubclass(dtype.type, np.inexact): + raise TypeError("If a is inexact, then dtype must be inexact") + if out is not None and not issubclass(out.dtype.type, np.inexact): + raise TypeError("If a is inexact, then out must be inexact") + + cnt = np.sum(~mask, axis=axis, dtype=np.intp, keepdims=keepdims, + where=where) + tot = np.sum(arr, axis=axis, dtype=dtype, out=out, keepdims=keepdims, + where=where) + avg = _divide_by_count(tot, cnt, out=out) + + isbad = (cnt == 0) + if isbad.any(): + warnings.warn("Mean of empty slice", RuntimeWarning, stacklevel=2) + # NaN is the only possible bad value, so no further + # action is needed to handle bad results. + return avg + + +def _nanmedian1d(arr1d, overwrite_input=False): + """ + Private function for rank 1 arrays. Compute the median ignoring NaNs. + See nanmedian for parameter usage + """ + arr1d_parsed, _, overwrite_input = _remove_nan_1d( + arr1d, overwrite_input=overwrite_input, + ) + + if arr1d_parsed.size == 0: + # Ensure that a nan-esque scalar of the appropriate type (and unit) + # is returned for `timedelta64` and `complexfloating` + return arr1d[-1] + + return np.median(arr1d_parsed, overwrite_input=overwrite_input) + + +def _nanmedian(a, axis=None, out=None, overwrite_input=False): + """ + Private function that doesn't support extended axis or keepdims. + These methods are extended to this function using _ureduce + See nanmedian for parameter usage + + """ + if axis is None or a.ndim == 1: + part = a.ravel() + if out is None: + return _nanmedian1d(part, overwrite_input) + else: + out[...] = _nanmedian1d(part, overwrite_input) + return out + else: + # for small medians use sort + indexing which is still faster than + # apply_along_axis + # benchmarked with shuffled (50, 50, x) containing a few NaN + if a.shape[axis] < 600: + return _nanmedian_small(a, axis, out, overwrite_input) + result = np.apply_along_axis(_nanmedian1d, axis, a, overwrite_input) + if out is not None: + out[...] = result + return result + + +def _nanmedian_small(a, axis=None, out=None, overwrite_input=False): + """ + sort + indexing median, faster for small medians along multiple + dimensions due to the high overhead of apply_along_axis + + see nanmedian for parameter usage + """ + a = np.ma.masked_array(a, np.isnan(a)) + m = np.ma.median(a, axis=axis, overwrite_input=overwrite_input) + for i in range(np.count_nonzero(m.mask.ravel())): + warnings.warn("All-NaN slice encountered", RuntimeWarning, + stacklevel=5) + + fill_value = np.timedelta64("NaT") if m.dtype.kind == "m" else np.nan + if out is not None: + out[...] = m.filled(fill_value) + return out + return m.filled(fill_value) + + +def _nanmedian_dispatcher( + a, axis=None, out=None, overwrite_input=None, keepdims=None): + return (a, out) + + +@array_function_dispatch(_nanmedian_dispatcher) +def nanmedian(a, axis=None, out=None, overwrite_input=False, keepdims=np._NoValue): + """ + Compute the median along the specified axis, while ignoring NaNs. + + Returns the median of the array elements. + + Parameters + ---------- + a : array_like + Input array or object that can be converted to an array. + axis : {int, sequence of int, None}, optional + Axis or axes along which the medians are computed. The default + is to compute the median along a flattened version of the array. + A sequence of axes is supported since version 1.9.0. + out : ndarray, optional + Alternative output array in which to place the result. It must + have the same shape and buffer length as the expected output, + but the type (of the output) will be cast if necessary. + overwrite_input : bool, optional + If True, then allow use of memory of input array `a` for + calculations. The input array will be modified by the call to + `median`. This will save memory when you do not need to preserve + the contents of the input array. Treat the input as undefined, + but it will probably be fully or partially sorted. Default is + False. If `overwrite_input` is ``True`` and `a` is not already an + `ndarray`, an error will be raised. + keepdims : bool, optional + If this is set to True, the axes which are reduced are left + in the result as dimensions with size one. With this option, + the result will broadcast correctly against the original `a`. + + If this is anything but the default value it will be passed + through (in the special case of an empty array) to the + `mean` function of the underlying array. If the array is + a sub-class and `mean` does not have the kwarg `keepdims` this + will raise a RuntimeError. + + Returns + ------- + median : ndarray + A new array holding the result. If the input contains integers + or floats smaller than ``float64``, then the output data-type is + ``np.float64``. Otherwise, the data-type of the output is the + same as that of the input. If `out` is specified, that array is + returned instead. + + See Also + -------- + mean, median, percentile + + Notes + ----- + Given a vector ``V`` of length ``N``, the median of ``V`` is the + middle value of a sorted copy of ``V``, ``V_sorted`` - i.e., + ``V_sorted[(N-1)/2]``, when ``N`` is odd and the average of the two + middle values of ``V_sorted`` when ``N`` is even. + + Examples + -------- + >>> import numpy as np + >>> a = np.array([[10.0, 7, 4], [3, 2, 1]]) + >>> a[0, 1] = np.nan + >>> a + array([[10., nan, 4.], + [ 3., 2., 1.]]) + >>> np.median(a) + np.float64(nan) + >>> np.nanmedian(a) + 3.0 + >>> np.nanmedian(a, axis=0) + array([6.5, 2. , 2.5]) + >>> np.median(a, axis=1) + array([nan, 2.]) + >>> b = a.copy() + >>> np.nanmedian(b, axis=1, overwrite_input=True) + array([7., 2.]) + >>> assert not np.all(a==b) + >>> b = a.copy() + >>> np.nanmedian(b, axis=None, overwrite_input=True) + 3.0 + >>> assert not np.all(a==b) + + """ + a = np.asanyarray(a) + # apply_along_axis in _nanmedian doesn't handle empty arrays well, + # so deal them upfront + if a.size == 0: + return np.nanmean(a, axis, out=out, keepdims=keepdims) + + return fnb._ureduce(a, func=_nanmedian, keepdims=keepdims, + axis=axis, out=out, + overwrite_input=overwrite_input) + + +def _nanpercentile_dispatcher( + a, q, axis=None, out=None, overwrite_input=None, + method=None, keepdims=None, *, weights=None): + return (a, q, out, weights) + + +@array_function_dispatch(_nanpercentile_dispatcher) +def nanpercentile( + a, + q, + axis=None, + out=None, + overwrite_input=False, + method="linear", + keepdims=np._NoValue, + *, + weights=None, +): + """ + Compute the qth percentile of the data along the specified axis, + while ignoring nan values. + + Returns the qth percentile(s) of the array elements. + + Parameters + ---------- + a : array_like + Input array or object that can be converted to an array, containing + nan values to be ignored. + q : array_like of float + Percentile or sequence of percentiles to compute, which must be + between 0 and 100 inclusive. + axis : {int, tuple of int, None}, optional + Axis or axes along which the percentiles are computed. The default + is to compute the percentile(s) along a flattened version of the + array. + out : ndarray, optional + Alternative output array in which to place the result. It must have + the same shape and buffer length as the expected output, but the + type (of the output) will be cast if necessary. + overwrite_input : bool, optional + If True, then allow the input array `a` to be modified by + intermediate calculations, to save memory. In this case, the + contents of the input `a` after this function completes is + undefined. + method : str, optional + This parameter specifies the method to use for estimating the + percentile. There are many different methods, some unique to NumPy. + See the notes for explanation. The options sorted by their R type + as summarized in the H&F paper [1]_ are: + + 1. 'inverted_cdf' + 2. 'averaged_inverted_cdf' + 3. 'closest_observation' + 4. 'interpolated_inverted_cdf' + 5. 'hazen' + 6. 'weibull' + 7. 'linear' (default) + 8. 'median_unbiased' + 9. 'normal_unbiased' + + The first three methods are discontinuous. NumPy further defines the + following discontinuous variations of the default 'linear' (7.) option: + + * 'lower' + * 'higher', + * 'midpoint' + * 'nearest' + + .. versionchanged:: 1.22.0 + This argument was previously called "interpolation" and only + offered the "linear" default and last four options. + + keepdims : bool, optional + If this is set to True, the axes which are reduced are left in + the result as dimensions with size one. With this option, the + result will broadcast correctly against the original array `a`. + + If this is anything but the default value it will be passed + through (in the special case of an empty array) to the + `mean` function of the underlying array. If the array is + a sub-class and `mean` does not have the kwarg `keepdims` this + will raise a RuntimeError. + + weights : array_like, optional + An array of weights associated with the values in `a`. Each value in + `a` contributes to the percentile according to its associated weight. + The weights array can either be 1-D (in which case its length must be + the size of `a` along the given axis) or of the same shape as `a`. + If `weights=None`, then all data in `a` are assumed to have a + weight equal to one. + Only `method="inverted_cdf"` supports weights. + + .. versionadded:: 2.0.0 + + Returns + ------- + percentile : scalar or ndarray + If `q` is a single percentile and `axis=None`, then the result + is a scalar. If multiple percentiles are given, first axis of + the result corresponds to the percentiles. The other axes are + the axes that remain after the reduction of `a`. If the input + contains integers or floats smaller than ``float64``, the output + data-type is ``float64``. Otherwise, the output data-type is the + same as that of the input. If `out` is specified, that array is + returned instead. + + See Also + -------- + nanmean + nanmedian : equivalent to ``nanpercentile(..., 50)`` + percentile, median, mean + nanquantile : equivalent to nanpercentile, except q in range [0, 1]. + + Notes + ----- + The behavior of `numpy.nanpercentile` with percentage `q` is that of + `numpy.quantile` with argument ``q/100`` (ignoring nan values). + For more information, please see `numpy.quantile`. + + Examples + -------- + >>> import numpy as np + >>> a = np.array([[10., 7., 4.], [3., 2., 1.]]) + >>> a[0][1] = np.nan + >>> a + array([[10., nan, 4.], + [ 3., 2., 1.]]) + >>> np.percentile(a, 50) + np.float64(nan) + >>> np.nanpercentile(a, 50) + 3.0 + >>> np.nanpercentile(a, 50, axis=0) + array([6.5, 2. , 2.5]) + >>> np.nanpercentile(a, 50, axis=1, keepdims=True) + array([[7.], + [2.]]) + >>> m = np.nanpercentile(a, 50, axis=0) + >>> out = np.zeros_like(m) + >>> np.nanpercentile(a, 50, axis=0, out=out) + array([6.5, 2. , 2.5]) + >>> m + array([6.5, 2. , 2.5]) + + >>> b = a.copy() + >>> np.nanpercentile(b, 50, axis=1, overwrite_input=True) + array([7., 2.]) + >>> assert not np.all(a==b) + + References + ---------- + .. [1] R. J. Hyndman and Y. Fan, + "Sample quantiles in statistical packages," + The American Statistician, 50(4), pp. 361-365, 1996 + + """ + a = np.asanyarray(a) + if a.dtype.kind == "c": + raise TypeError("a must be an array of real numbers") + + weak_q = type(q) in (int, float) # use weak promotion for final result type + q = np.true_divide(q, 100, out=...) + if not fnb._quantile_is_valid(q): + raise ValueError("Percentiles must be in the range [0, 100]") + + if weights is not None: + if method != "inverted_cdf": + msg = ("Only method 'inverted_cdf' supports weights. " + f"Got: {method}.") + raise ValueError(msg) + if axis is not None: + axis = _nx.normalize_axis_tuple(axis, a.ndim, argname="axis") + weights = _weights_are_valid(weights=weights, a=a, axis=axis) + if np.any(weights < 0): + raise ValueError("Weights must be non-negative.") + + return _nanquantile_unchecked( + a, q, axis, out, overwrite_input, method, keepdims, weights, weak_q) + + +def _nanquantile_dispatcher(a, q, axis=None, out=None, overwrite_input=None, + method=None, keepdims=None, *, weights=None): + return (a, q, out, weights) + + +@array_function_dispatch(_nanquantile_dispatcher) +def nanquantile( + a, + q, + axis=None, + out=None, + overwrite_input=False, + method="linear", + keepdims=np._NoValue, + *, + weights=None, +): + """ + Compute the qth quantile of the data along the specified axis, + while ignoring nan values. + Returns the qth quantile(s) of the array elements. + + Parameters + ---------- + a : array_like + Input array or object that can be converted to an array, containing + nan values to be ignored + q : array_like of float + Probability or sequence of probabilities for the quantiles to compute. + Values must be between 0 and 1 inclusive. + axis : {int, tuple of int, None}, optional + Axis or axes along which the quantiles are computed. The + default is to compute the quantile(s) along a flattened + version of the array. + out : ndarray, optional + Alternative output array in which to place the result. It must + have the same shape and buffer length as the expected output, + but the type (of the output) will be cast if necessary. + overwrite_input : bool, optional + If True, then allow the input array `a` to be modified by intermediate + calculations, to save memory. In this case, the contents of the input + `a` after this function completes is undefined. + method : str, optional + This parameter specifies the method to use for estimating the + quantile. There are many different methods, some unique to NumPy. + See the notes for explanation. The options sorted by their R type + as summarized in the H&F paper [1]_ are: + + 1. 'inverted_cdf' + 2. 'averaged_inverted_cdf' + 3. 'closest_observation' + 4. 'interpolated_inverted_cdf' + 5. 'hazen' + 6. 'weibull' + 7. 'linear' (default) + 8. 'median_unbiased' + 9. 'normal_unbiased' + + The first three methods are discontinuous. NumPy further defines the + following discontinuous variations of the default 'linear' (7.) option: + + * 'lower' + * 'higher', + * 'midpoint' + * 'nearest' + + .. versionchanged:: 1.22.0 + This argument was previously called "interpolation" and only + offered the "linear" default and last four options. + + keepdims : bool, optional + If this is set to True, the axes which are reduced are left in + the result as dimensions with size one. With this option, the + result will broadcast correctly against the original array `a`. + + If this is anything but the default value it will be passed + through (in the special case of an empty array) to the + `mean` function of the underlying array. If the array is + a sub-class and `mean` does not have the kwarg `keepdims` this + will raise a RuntimeError. + + weights : array_like, optional + An array of weights associated with the values in `a`. Each value in + `a` contributes to the quantile according to its associated weight. + The weights array can either be 1-D (in which case its length must be + the size of `a` along the given axis) or of the same shape as `a`. + If `weights=None`, then all data in `a` are assumed to have a + weight equal to one. + Only `method="inverted_cdf"` supports weights. + + .. versionadded:: 2.0.0 + + Returns + ------- + quantile : scalar or ndarray + If `q` is a single probability and `axis=None`, then the result + is a scalar. If multiple probability levels are given, first axis of + the result corresponds to the quantiles. The other axes are + the axes that remain after the reduction of `a`. If the input + contains integers or floats smaller than ``float64``, the output + data-type is ``float64``. Otherwise, the output data-type is the + same as that of the input. If `out` is specified, that array is + returned instead. + + See Also + -------- + quantile + nanmean, nanmedian + nanmedian : equivalent to ``nanquantile(..., 0.5)`` + nanpercentile : same as nanquantile, but with q in the range [0, 100]. + + Notes + ----- + The behavior of `numpy.nanquantile` is the same as that of + `numpy.quantile` (ignoring nan values). + For more information, please see `numpy.quantile`. + + Examples + -------- + >>> import numpy as np + >>> a = np.array([[10., 7., 4.], [3., 2., 1.]]) + >>> a[0][1] = np.nan + >>> a + array([[10., nan, 4.], + [ 3., 2., 1.]]) + >>> np.quantile(a, 0.5) + np.float64(nan) + >>> np.nanquantile(a, 0.5) + 3.0 + >>> np.nanquantile(a, 0.5, axis=0) + array([6.5, 2. , 2.5]) + >>> np.nanquantile(a, 0.5, axis=1, keepdims=True) + array([[7.], + [2.]]) + >>> m = np.nanquantile(a, 0.5, axis=0) + >>> out = np.zeros_like(m) + >>> np.nanquantile(a, 0.5, axis=0, out=out) + array([6.5, 2. , 2.5]) + >>> m + array([6.5, 2. , 2.5]) + >>> b = a.copy() + >>> np.nanquantile(b, 0.5, axis=1, overwrite_input=True) + array([7., 2.]) + >>> assert not np.all(a==b) + + References + ---------- + .. [1] R. J. Hyndman and Y. Fan, + "Sample quantiles in statistical packages," + The American Statistician, 50(4), pp. 361-365, 1996 + + """ + a = np.asanyarray(a) + if a.dtype.kind == "c": + raise TypeError("a must be an array of real numbers") + + weak_q = type(q) in (int, float) # use weak promotion for final result type + q = np.asanyarray(q) + + if not fnb._quantile_is_valid(q): + raise ValueError("Quantiles must be in the range [0, 1]") + + if weights is not None: + if method != "inverted_cdf": + msg = ("Only method 'inverted_cdf' supports weights. " + f"Got: {method}.") + raise ValueError(msg) + if axis is not None: + axis = _nx.normalize_axis_tuple(axis, a.ndim, argname="axis") + weights = _weights_are_valid(weights=weights, a=a, axis=axis) + if np.any(weights < 0): + raise ValueError("Weights must be non-negative.") + + return _nanquantile_unchecked( + a, q, axis, out, overwrite_input, method, keepdims, weights, weak_q) + + +def _nanquantile_unchecked( + a, + q, + axis=None, + out=None, + overwrite_input=False, + method="linear", + keepdims=np._NoValue, + weights=None, + weak_q=False, +): + """Assumes that q is in [0, 1], and is an ndarray""" + # apply_along_axis in _nanpercentile doesn't handle empty arrays well, + # so deal them upfront + if a.size == 0: + return np.nanmean(a, axis, out=out, keepdims=keepdims) + return fnb._ureduce(a, + func=_nanquantile_ureduce_func, + q=q, + weights=weights, + keepdims=keepdims, + axis=axis, + out=out, + overwrite_input=overwrite_input, + method=method, + weak_q=weak_q) + + +def _nanquantile_ureduce_func( + a: np.array, + q: np.array, + weights: np.array, + axis: int | None = None, + out=None, + overwrite_input: bool = False, + method="linear", + weak_q=False, +): + """ + Private function that doesn't support extended axis or keepdims. + These methods are extended to this function using _ureduce + See nanpercentile for parameter usage + """ + if axis is None or a.ndim == 1: + part = a.ravel() + wgt = None if weights is None else weights.ravel() + result = _nanquantile_1d(part, q, overwrite_input, method, + weights=wgt, weak_q=weak_q) + # Note that this code could try to fill in `out` right away + elif weights is None: + result = np.apply_along_axis(_nanquantile_1d, axis, a, q, + overwrite_input, method, weights, weak_q) + # apply_along_axis fills in collapsed axis with results. + # Move those axes to the beginning to match percentile's + # convention. + if q.ndim != 0: + from_ax = [axis + i for i in range(q.ndim)] + result = np.moveaxis(result, from_ax, list(range(q.ndim))) + else: + # We need to apply along axis over 2 arrays, a and weights. + # move operation axes to end for simplicity: + a = np.moveaxis(a, axis, -1) + if weights is not None: + weights = np.moveaxis(weights, axis, -1) + if out is not None: + result = out + else: + # weights are limited to `inverted_cdf` so the result dtype + # is known to be identical to that of `a` here: + result = np.empty_like(a, shape=q.shape + a.shape[:-1]) + + for ii in np.ndindex(a.shape[:-1]): + result[(...,) + ii] = _nanquantile_1d( + a[ii], q, weights=weights[ii], + overwrite_input=overwrite_input, method=method, + weak_q=weak_q, + ) + # This path dealt with `out` already... + return result + + if out is not None: + out[...] = result + return result + + +def _nanquantile_1d( + arr1d, q, overwrite_input=False, method="linear", weights=None, + weak_q=False, +): + """ + Private function for rank 1 arrays. Compute quantile ignoring NaNs. + See nanpercentile for parameter usage + """ + # TODO: What to do when arr1d = [1, np.nan] and weights = [0, 1]? + arr1d, weights, overwrite_input = _remove_nan_1d(arr1d, + second_arr1d=weights, overwrite_input=overwrite_input) + if arr1d.size == 0: + # convert to scalar + return np.full(q.shape, np.nan, dtype=arr1d.dtype)[()] + + return fnb._quantile_unchecked( + arr1d, + q, + overwrite_input=overwrite_input, + method=method, + weights=weights, + weak_q=weak_q, + ) + + +def _nanvar_dispatcher(a, axis=None, dtype=None, out=None, ddof=None, + keepdims=None, *, where=None, mean=None, + correction=None): + return (a, out) + + +@array_function_dispatch(_nanvar_dispatcher) +def nanvar(a, axis=None, dtype=None, out=None, ddof=0, keepdims=np._NoValue, + *, where=np._NoValue, mean=np._NoValue, correction=np._NoValue): + """ + Compute the variance along the specified axis, while ignoring NaNs. + + Returns the variance of the array elements, a measure of the spread of + a distribution. The variance is computed for the flattened array by + default, otherwise over the specified axis. + + For all-NaN slices or slices with zero degrees of freedom, NaN is + returned and a `RuntimeWarning` is raised. + + Parameters + ---------- + a : array_like + Array containing numbers whose variance is desired. If `a` is not an + array, a conversion is attempted. + axis : {int, tuple of int, None}, optional + Axis or axes along which the variance is computed. The default is to compute + the variance of the flattened array. + dtype : data-type, optional + Type to use in computing the variance. For arrays of integer type + the default is `float64`; for arrays of float types it is the same as + the array type. + out : ndarray, optional + Alternate output array in which to place the result. It must have + the same shape as the expected output, but the type is cast if + necessary. + ddof : {int, float}, optional + "Delta Degrees of Freedom": the divisor used in the calculation is + ``N - ddof``, where ``N`` represents the number of non-NaN + elements. By default `ddof` is zero. + keepdims : bool, optional + If this is set to True, the axes which are reduced are left + in the result as dimensions with size one. With this option, + the result will broadcast correctly against the original `a`. + where : array_like of bool, optional + Elements to include in the variance. See `~numpy.ufunc.reduce` for + details. + + .. versionadded:: 1.22.0 + + mean : array_like, optional + Provide the mean to prevent its recalculation. The mean should have + a shape as if it was calculated with ``keepdims=True``. + The axis for the calculation of the mean should be the same as used in + the call to this var function. + + .. versionadded:: 2.0.0 + + correction : {int, float}, optional + Array API compatible name for the ``ddof`` parameter. Only one of them + can be provided at the same time. + + .. versionadded:: 2.0.0 + + Returns + ------- + variance : ndarray, see dtype parameter above + If `out` is None, return a new array containing the variance, + otherwise return a reference to the output array. If ddof is >= the + number of non-NaN elements in a slice or the slice contains only + NaNs, then the result for that slice is NaN. + + See Also + -------- + std : Standard deviation + mean : Average + var : Variance while not ignoring NaNs + nanstd, nanmean + :ref:`ufuncs-output-type` + + Notes + ----- + The variance is the average of the squared deviations from the mean, + i.e., ``var = mean(abs(x - x.mean())**2)``. + + The mean is normally calculated as ``x.sum() / N``, where ``N = len(x)``. + If, however, `ddof` is specified, the divisor ``N - ddof`` is used + instead. In standard statistical practice, ``ddof=1`` provides an + unbiased estimator of the variance of a hypothetical infinite + population. ``ddof=0`` provides a maximum likelihood estimate of the + variance for normally distributed variables. + + Note that for complex numbers, the absolute value is taken before + squaring, so that the result is always real and nonnegative. + + For floating-point input, the variance is computed using the same + precision the input has. Depending on the input data, this can cause + the results to be inaccurate, especially for `float32` (see example + below). Specifying a higher-accuracy accumulator using the ``dtype`` + keyword can alleviate this issue. + + For this function to work on sub-classes of ndarray, they must define + `sum` with the kwarg `keepdims` + + Examples + -------- + >>> import numpy as np + >>> a = np.array([[1, np.nan], [3, 4]]) + >>> np.nanvar(a) + 1.5555555555555554 + >>> np.nanvar(a, axis=0) + array([1., 0.]) + >>> np.nanvar(a, axis=1) + array([0., 0.25]) # may vary + + """ + arr, mask = _replace_nan(a, 0) + if mask is None: + return np.var(arr, axis=axis, dtype=dtype, out=out, ddof=ddof, + keepdims=keepdims, where=where, mean=mean, + correction=correction) + + if dtype is not None: + dtype = np.dtype(dtype) + if dtype is not None and not issubclass(dtype.type, np.inexact): + raise TypeError("If a is inexact, then dtype must be inexact") + if out is not None and not issubclass(out.dtype.type, np.inexact): + raise TypeError("If a is inexact, then out must be inexact") + + if correction != np._NoValue: + if ddof != 0: + raise ValueError( + "ddof and correction can't be provided simultaneously." + ) + else: + ddof = correction + + # Compute mean + if type(arr) is np.matrix: + _keepdims = np._NoValue + else: + _keepdims = True + + cnt = np.sum(~mask, axis=axis, dtype=np.intp, keepdims=_keepdims, + where=where) + + if mean is not np._NoValue: + avg = mean + else: + # we need to special case matrix for reverse compatibility + # in order for this to work, these sums need to be called with + # keepdims=True, however matrix now raises an error in this case, but + # the reason that it drops the keepdims kwarg is to force keepdims=True + # so this used to work by serendipity. + avg = np.sum(arr, axis=axis, dtype=dtype, + keepdims=_keepdims, where=where) + avg = _divide_by_count(avg, cnt) + + # Compute squared deviation from mean. + np.subtract(arr, avg, out=arr, casting='unsafe', where=where) + arr = _copyto(arr, 0, mask) + if issubclass(arr.dtype.type, np.complexfloating): + sqr = np.multiply(arr, arr.conj(), out=arr, where=where).real + else: + sqr = np.multiply(arr, arr, out=arr, where=where) + + # Compute variance. + var = np.sum(sqr, axis=axis, dtype=dtype, out=out, keepdims=keepdims, + where=where) + + # Precaution against reduced object arrays + try: + var_ndim = var.ndim + except AttributeError: + var_ndim = np.ndim(var) + if var_ndim < cnt.ndim: + # Subclasses of ndarray may ignore keepdims, so check here. + cnt = cnt.squeeze(axis) + dof = cnt - ddof + var = _divide_by_count(var, dof) + + isbad = (dof <= 0) + if np.any(isbad): + warnings.warn("Degrees of freedom <= 0 for slice.", RuntimeWarning, + stacklevel=2) + # NaN, inf, or negative numbers are all possible bad + # values, so explicitly replace them with NaN. + var = _copyto(var, np.nan, isbad) + return var + + +def _nanstd_dispatcher(a, axis=None, dtype=None, out=None, ddof=None, + keepdims=None, *, where=None, mean=None, + correction=None): + return (a, out) + + +@array_function_dispatch(_nanstd_dispatcher) +def nanstd(a, axis=None, dtype=None, out=None, ddof=0, keepdims=np._NoValue, + *, where=np._NoValue, mean=np._NoValue, correction=np._NoValue): + """ + Compute the standard deviation along the specified axis, while + ignoring NaNs. + + Returns the standard deviation, a measure of the spread of a + distribution, of the non-NaN array elements. The standard deviation is + computed for the flattened array by default, otherwise over the + specified axis. + + For all-NaN slices or slices with zero degrees of freedom, NaN is + returned and a `RuntimeWarning` is raised. + + Parameters + ---------- + a : array_like + Calculate the standard deviation of the non-NaN values. + axis : {int, tuple of int, None}, optional + Axis or axes along which the standard deviation is computed. The default is + to compute the standard deviation of the flattened array. + dtype : dtype, optional + Type to use in computing the standard deviation. For arrays of + integer type the default is float64, for arrays of float types it + is the same as the array type. + out : ndarray, optional + Alternative output array in which to place the result. It must have + the same shape as the expected output but the type (of the + calculated values) will be cast if necessary. + ddof : {int, float}, optional + Means Delta Degrees of Freedom. The divisor used in calculations + is ``N - ddof``, where ``N`` represents the number of non-NaN + elements. By default `ddof` is zero. + + keepdims : bool, optional + If this is set to True, the axes which are reduced are left + in the result as dimensions with size one. With this option, + the result will broadcast correctly against the original `a`. + + If this value is anything but the default it is passed through + as-is to the relevant functions of the sub-classes. If these + functions do not have a `keepdims` kwarg, a RuntimeError will + be raised. + where : array_like of bool, optional + Elements to include in the standard deviation. + See `~numpy.ufunc.reduce` for details. + + .. versionadded:: 1.22.0 + + mean : array_like, optional + Provide the mean to prevent its recalculation. The mean should have + a shape as if it was calculated with ``keepdims=True``. + The axis for the calculation of the mean should be the same as used in + the call to this std function. + + .. versionadded:: 2.0.0 + + correction : {int, float}, optional + Array API compatible name for the ``ddof`` parameter. Only one of them + can be provided at the same time. + + .. versionadded:: 2.0.0 + + Returns + ------- + standard_deviation : ndarray, see dtype parameter above. + If `out` is None, return a new array containing the standard + deviation, otherwise return a reference to the output array. If + ddof is >= the number of non-NaN elements in a slice or the slice + contains only NaNs, then the result for that slice is NaN. + + See Also + -------- + var, mean, std + nanvar, nanmean + :ref:`ufuncs-output-type` + + Notes + ----- + The standard deviation is the square root of the average of the squared + deviations from the mean: ``std = sqrt(mean(abs(x - x.mean())**2))``. + + The average squared deviation is normally calculated as + ``x.sum() / N``, where ``N = len(x)``. If, however, `ddof` is + specified, the divisor ``N - ddof`` is used instead. In standard + statistical practice, ``ddof=1`` provides an unbiased estimator of the + variance of the infinite population. ``ddof=0`` provides a maximum + likelihood estimate of the variance for normally distributed variables. + The standard deviation computed in this function is the square root of + the estimated variance, so even with ``ddof=1``, it will not be an + unbiased estimate of the standard deviation per se. + + Note that, for complex numbers, `std` takes the absolute value before + squaring, so that the result is always real and nonnegative. + + For floating-point input, the *std* is computed using the same + precision the input has. Depending on the input data, this can cause + the results to be inaccurate, especially for float32 (see example + below). Specifying a higher-accuracy accumulator using the `dtype` + keyword can alleviate this issue. + + Examples + -------- + >>> import numpy as np + >>> a = np.array([[1, np.nan], [3, 4]]) + >>> np.nanstd(a) + 1.247219128924647 + >>> np.nanstd(a, axis=0) + array([1., 0.]) + >>> np.nanstd(a, axis=1) + array([0., 0.5]) # may vary + + """ + var = nanvar(a, axis=axis, dtype=dtype, out=out, ddof=ddof, + keepdims=keepdims, where=where, mean=mean, + correction=correction) + if isinstance(var, np.ndarray): + std = np.sqrt(var, out=var) + elif hasattr(var, 'dtype'): + std = var.dtype.type(np.sqrt(var)) + else: + std = np.sqrt(var) + return std diff --git a/python/user_packages/Python313/site-packages/numpy/lib/_nanfunctions_impl.pyi b/python/user_packages/Python313/site-packages/numpy/lib/_nanfunctions_impl.pyi new file mode 100644 index 0000000000000000000000000000000000000000..6a8831c33fa269ec7c50bd49b3d5c63215d6b981 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/lib/_nanfunctions_impl.pyi @@ -0,0 +1,48 @@ +from numpy._core.fromnumeric import ( + amax, + amin, + argmax, + argmin, + cumprod, + cumsum, + mean, + prod, + std, + sum, + var, +) +from numpy.lib._function_base_impl import median, percentile, quantile + +__all__ = [ + "nansum", + "nanmax", + "nanmin", + "nanargmax", + "nanargmin", + "nanmean", + "nanmedian", + "nanpercentile", + "nanvar", + "nanstd", + "nanprod", + "nancumsum", + "nancumprod", + "nanquantile", +] + +# NOTE: In reality these functions are not aliases but distinct functions +# with identical signatures. +nanmin = amin +nanmax = amax +nanargmin = argmin +nanargmax = argmax +nansum = sum +nanprod = prod +nancumsum = cumsum +nancumprod = cumprod +nanmean = mean +nanvar = var +nanstd = std +nanmedian = median +nanpercentile = percentile +nanquantile = quantile diff --git a/python/user_packages/Python313/site-packages/numpy/lib/_npyio_impl.py b/python/user_packages/Python313/site-packages/numpy/lib/_npyio_impl.py new file mode 100644 index 0000000000000000000000000000000000000000..ce000967caa70b965cc300a5e728979502bf7ef0 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/lib/_npyio_impl.py @@ -0,0 +1,2583 @@ +""" +IO related functions. +""" +import contextlib +import functools +import itertools +import operator +import os +import pickle +import re +import warnings +import weakref +from collections.abc import Mapping +from operator import itemgetter + +import numpy as np +from numpy._core import overrides +from numpy._core._multiarray_umath import _load_from_filelike +from numpy._core.multiarray import packbits, unpackbits +from numpy._core.overrides import finalize_array_function_like, set_module +from numpy._utils import asbytes, asunicode + +from . import format +from ._datasource import DataSource # noqa: F401 +from ._format_impl import _MAX_HEADER_SIZE +from ._iotools import ( + ConversionWarning, + ConverterError, + ConverterLockError, + LineSplitter, + NameValidator, + StringConverter, + _decode_line, + _is_string_like, + easy_dtype, + flatten_dtype, + has_nested_fields, +) + +__all__ = [ + 'savetxt', 'loadtxt', 'genfromtxt', 'load', 'save', 'savez', + 'savez_compressed', 'packbits', 'unpackbits', 'fromregex' + ] + + +array_function_dispatch = functools.partial( + overrides.array_function_dispatch, module='numpy') + + +class BagObj: + """ + BagObj(obj) + + Convert attribute look-ups to getitems on the object passed in. + + Parameters + ---------- + obj : class instance + Object on which attribute look-up is performed. + + Examples + -------- + >>> import numpy as np + >>> from numpy.lib._npyio_impl import BagObj as BO + >>> class BagDemo: + ... def __getitem__(self, key): # An instance of BagObj(BagDemo) + ... # will call this method when any + ... # attribute look-up is required + ... result = "Doesn't matter what you want, " + ... return result + "you're gonna get this" + ... + >>> demo_obj = BagDemo() + >>> bagobj = BO(demo_obj) + >>> bagobj.hello_there + "Doesn't matter what you want, you're gonna get this" + >>> bagobj.I_can_be_anything + "Doesn't matter what you want, you're gonna get this" + + """ + + def __init__(self, obj): + # Use weakref to make NpzFile objects collectable by refcount + self._obj = weakref.proxy(obj) + + def __getattribute__(self, key): + try: + return object.__getattribute__(self, '_obj')[key] + except KeyError: + raise AttributeError(key) from None + + def __dir__(self): + """ + Enables dir(bagobj) to list the files in an NpzFile. + + This also enables tab-completion in an interpreter or IPython. + """ + return list(object.__getattribute__(self, '_obj').keys()) + + +def zipfile_factory(file, *args, **kwargs): + """ + Create a ZipFile. + + Allows for Zip64, and the `file` argument can accept file, str, or + pathlib.Path objects. `args` and `kwargs` are passed to the zipfile.ZipFile + constructor. + """ + if not hasattr(file, 'read'): + file = os.fspath(file) + import zipfile + kwargs['allowZip64'] = True + return zipfile.ZipFile(file, *args, **kwargs) + + +@set_module('numpy.lib.npyio') +class NpzFile(Mapping): + """ + NpzFile(fid) + + A dictionary-like object with lazy-loading of files in the zipped + archive provided on construction. + + `NpzFile` is used to load files in the NumPy ``.npz`` data archive + format. It assumes that files in the archive have a ``.npy`` extension, + other files are ignored. + + The arrays and file strings are lazily loaded on either + getitem access using ``obj['key']`` or attribute lookup using + ``obj.f.key``. A list of all files (without ``.npy`` extensions) can + be obtained with ``obj.files`` and the ZipFile object itself using + ``obj.zip``. + + Attributes + ---------- + files : list of str + List of all files in the archive with a ``.npy`` extension. + zip : ZipFile instance + The ZipFile object initialized with the zipped archive. + f : BagObj instance + An object on which attribute can be performed as an alternative + to getitem access on the `NpzFile` instance itself. + allow_pickle : bool, optional + Allow loading pickled data. Default: False + pickle_kwargs : dict, optional + Additional keyword arguments to pass on to pickle.load. + These are only useful when loading object arrays saved on + Python 2. + max_header_size : int, optional + Maximum allowed size of the header. Large headers may not be safe + to load securely and thus require explicitly passing a larger value. + See :py:func:`ast.literal_eval()` for details. + This option is ignored when `allow_pickle` is passed. In that case + the file is by definition trusted and the limit is unnecessary. + + Parameters + ---------- + fid : file, str, or pathlib.Path + The zipped archive to open. This is either a file-like object + or a string containing the path to the archive. + own_fid : bool, optional + Whether NpzFile should close the file handle. + Requires that `fid` is a file-like object. + + Examples + -------- + >>> import numpy as np + >>> from tempfile import TemporaryFile + >>> outfile = TemporaryFile() + >>> x = np.arange(10) + >>> y = np.sin(x) + >>> np.savez(outfile, x=x, y=y) + >>> _ = outfile.seek(0) + + >>> npz = np.load(outfile) + >>> isinstance(npz, np.lib.npyio.NpzFile) + True + >>> npz + NpzFile 'object' with keys: x, y + >>> sorted(npz.files) + ['x', 'y'] + >>> npz['x'] # getitem access + array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) + >>> npz.f.x # attribute lookup + array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) + + """ + # Make __exit__ safe if zipfile_factory raises an exception + zip = None + fid = None + _MAX_REPR_ARRAY_COUNT = 5 + + def __init__(self, fid, own_fid=False, allow_pickle=False, + pickle_kwargs=None, *, + max_header_size=_MAX_HEADER_SIZE): + # Import is postponed to here since zipfile depends on gzip, an + # optional component of the so-called standard library. + _zip = zipfile_factory(fid) + _files = _zip.namelist() + self.files = [name.removesuffix(".npy") for name in _files] + self._files = dict(zip(self.files, _files)) + self._files.update(zip(_files, _files)) + self.allow_pickle = allow_pickle + self.max_header_size = max_header_size + self.pickle_kwargs = pickle_kwargs + self.zip = _zip + self.f = BagObj(self) + if own_fid: + self.fid = fid + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_value, traceback): + self.close() + + def close(self): + """ + Close the file. + + """ + if self.zip is not None: + self.zip.close() + self.zip = None + if self.fid is not None: + self.fid.close() + self.fid = None + self.f = None # break reference cycle + + def __del__(self): + self.close() + + # Implement the Mapping ABC + def __iter__(self): + return iter(self.files) + + def __len__(self): + return len(self.files) + + def __getitem__(self, key): + try: + key = self._files[key] + except KeyError: + raise KeyError(f"{key} is not a file in the archive") from None + else: + with self.zip.open(key) as bytes: + magic = bytes.read(len(format.MAGIC_PREFIX)) + bytes.seek(0) + if magic == format.MAGIC_PREFIX: + # FIXME: This seems like it will copy strings around + # more than is strictly necessary. The zipfile + # will read the string and then + # the format.read_array will copy the string + # to another place in memory. + # It would be better if the zipfile could read + # (or at least uncompress) the data + # directly into the array memory. + return format.read_array( + bytes, + allow_pickle=self.allow_pickle, + pickle_kwargs=self.pickle_kwargs, + max_header_size=self.max_header_size + ) + else: + return bytes.read() + + def __contains__(self, key): + return (key in self._files) + + def __repr__(self): + # Get filename or default to `object` + if isinstance(self.fid, str): + filename = self.fid + else: + filename = getattr(self.fid, "name", "object") + + # Get the name of arrays + array_names = ', '.join(self.files[:self._MAX_REPR_ARRAY_COUNT]) + if len(self.files) > self._MAX_REPR_ARRAY_COUNT: + array_names += "..." + return f"NpzFile {filename!r} with keys: {array_names}" + + # Work around problems with the docstrings in the Mapping methods + # They contain a `->`, which confuses the type annotation interpretations + # of sphinx-docs. See gh-25964 + + def get(self, key, default=None, /): + """ + D.get(k,[,d]) returns D[k] if k in D, else d. d defaults to None. + """ + return Mapping.get(self, key, default) + + def items(self): + """ + D.items() returns a set-like object providing a view on the items + """ + return Mapping.items(self) + + def keys(self): + """ + D.keys() returns a set-like object providing a view on the keys + """ + return Mapping.keys(self) + + def values(self): + """ + D.values() returns a set-like object providing a view on the values + """ + return Mapping.values(self) + + +@set_module('numpy') +def load(file, mmap_mode=None, allow_pickle=False, fix_imports=True, + encoding='ASCII', *, max_header_size=_MAX_HEADER_SIZE): + """ + Load arrays or pickled objects from ``.npy``, ``.npz`` or pickled files. + + .. warning:: Loading files that contain object arrays uses the ``pickle`` + module, which is not secure against erroneous or maliciously + constructed data. Consider passing ``allow_pickle=False`` to + load data that is known not to contain object arrays for the + safer handling of untrusted sources. + + Parameters + ---------- + file : file-like object, string, or pathlib.Path + The file to read. File-like objects must support the + ``seek()`` and ``read()`` methods and must always + be opened in binary mode. Pickled files require that the + file-like object support the ``readline()`` method as well. + mmap_mode : {None, 'r+', 'r', 'w+', 'c'}, optional + If not None, then memory-map the file, using the given mode (see + `numpy.memmap` for a detailed description of the modes). A + memory-mapped array is kept on disk. However, it can be accessed + and sliced like any ndarray. Memory mapping is especially useful + for accessing small fragments of large files without reading the + entire file into memory. + allow_pickle : bool, optional + Allow loading pickled object arrays stored in npy files. Reasons for + disallowing pickles include security, as loading pickled data can + execute arbitrary code. If pickles are disallowed, loading object + arrays will fail. Default: False + fix_imports : bool, optional + Only useful when loading Python 2 generated pickled files, + which includes npy/npz files containing object arrays. If `fix_imports` + is True, pickle will try to map the old Python 2 names to the new names + used in Python 3. + encoding : str, optional + What encoding to use when reading Python 2 strings. Only useful when + loading Python 2 generated pickled files, which includes + npy/npz files containing object arrays. Values other than 'latin1', + 'ASCII', and 'bytes' are not allowed, as they can corrupt numerical + data. Default: 'ASCII' + max_header_size : int, optional + Maximum allowed size of the header. Large headers may not be safe + to load securely and thus require explicitly passing a larger value. + See :py:func:`ast.literal_eval()` for details. + This option is ignored when `allow_pickle` is passed. In that case + the file is by definition trusted and the limit is unnecessary. + + Returns + ------- + result : array, tuple, dict, etc. + Data stored in the file. For ``.npz`` files, the returned instance + of NpzFile class must be closed to avoid leaking file descriptors. + + Raises + ------ + OSError + If the input file does not exist or cannot be read. + UnpicklingError + If ``allow_pickle=True``, but the file cannot be loaded as a pickle. + ValueError + The file contains an object array, but ``allow_pickle=False`` given. + EOFError + When calling ``np.load`` multiple times on the same file handle, + if all data has already been read + + See Also + -------- + save, savez, savez_compressed, loadtxt + memmap : Create a memory-map to an array stored in a file on disk. + lib.format.open_memmap : Create or load a memory-mapped ``.npy`` file. + + Notes + ----- + - If the file contains pickle data, then whatever object is stored + in the pickle is returned. + - If the file is a ``.npy`` file, then a single array is returned. + - If the file is a ``.npz`` file, then a dictionary-like object is + returned, containing ``{filename: array}`` key-value pairs, one for + each file in the archive. + - If the file is a ``.npz`` file, the returned value supports the + context manager protocol in a similar fashion to the open function:: + + with load('foo.npz') as data: + a = data['a'] + + The underlying file descriptor is closed when exiting the 'with' + block. + + Examples + -------- + >>> import numpy as np + + Store data to disk, and load it again: + + >>> np.save('/tmp/123', np.array([[1, 2, 3], [4, 5, 6]])) + >>> np.load('/tmp/123.npy') + array([[1, 2, 3], + [4, 5, 6]]) + + Store compressed data to disk, and load it again: + + >>> a=np.array([[1, 2, 3], [4, 5, 6]]) + >>> b=np.array([1, 2]) + >>> np.savez('/tmp/123.npz', a=a, b=b) + >>> data = np.load('/tmp/123.npz') + >>> data['a'] + array([[1, 2, 3], + [4, 5, 6]]) + >>> data['b'] + array([1, 2]) + >>> data.close() + + Mem-map the stored array, and then access the second row + directly from disk: + + >>> X = np.load('/tmp/123.npy', mmap_mode='r') + >>> X[1, :] + memmap([4, 5, 6]) + + """ + if encoding not in ('ASCII', 'latin1', 'bytes'): + # The 'encoding' value for pickle also affects what encoding + # the serialized binary data of NumPy arrays is loaded + # in. Pickle does not pass on the encoding information to + # NumPy. The unpickling code in numpy._core.multiarray is + # written to assume that unicode data appearing where binary + # should be is in 'latin1'. 'bytes' is also safe, as is 'ASCII'. + # + # Other encoding values can corrupt binary data, and we + # purposefully disallow them. For the same reason, the errors= + # argument is not exposed, as values other than 'strict' + # result can similarly silently corrupt numerical data. + raise ValueError("encoding must be 'ASCII', 'latin1', or 'bytes'") + + pickle_kwargs = {'encoding': encoding, 'fix_imports': fix_imports} + + with contextlib.ExitStack() as stack: + if hasattr(file, 'read'): + fid = file + own_fid = False + else: + fid = stack.enter_context(open(os.fspath(file), "rb")) + own_fid = True + + # Code to distinguish from NumPy binary files and pickles. + _ZIP_PREFIX = b'PK\x03\x04' + _ZIP_SUFFIX = b'PK\x05\x06' # empty zip files start with this + N = len(format.MAGIC_PREFIX) + magic = fid.read(N) + if not magic: + raise EOFError("No data left in file") + # If the file size is less than N, we need to make sure not + # to seek past the beginning of the file + fid.seek(-min(N, len(magic)), 1) # back-up + if magic.startswith((_ZIP_PREFIX, _ZIP_SUFFIX)): + # zip-file (assume .npz) + # Potentially transfer file ownership to NpzFile + stack.pop_all() + ret = NpzFile(fid, own_fid=own_fid, allow_pickle=allow_pickle, + pickle_kwargs=pickle_kwargs, + max_header_size=max_header_size) + return ret + elif magic == format.MAGIC_PREFIX: + # .npy file + if mmap_mode: + if allow_pickle: + max_header_size = 2**64 + return format.open_memmap(file, mode=mmap_mode, + max_header_size=max_header_size) + else: + return format.read_array(fid, allow_pickle=allow_pickle, + pickle_kwargs=pickle_kwargs, + max_header_size=max_header_size) + else: + # Try a pickle + if not allow_pickle: + raise ValueError( + "This file contains pickled (object) data. If you trust " + "the file you can load it unsafely using the " + "`allow_pickle=` keyword argument or `pickle.load()`.") + try: + return pickle.load(fid, **pickle_kwargs) + except Exception as e: + raise pickle.UnpicklingError( + f"Failed to interpret file {file!r} as a pickle") from e + + +def _save_dispatcher(file, arr, allow_pickle=None): + return (arr,) + + +@array_function_dispatch(_save_dispatcher) +def save(file, arr, allow_pickle=True): + """ + Save an array to a binary file in NumPy ``.npy`` format. + + Parameters + ---------- + file : file, str, or pathlib.Path + File or filename to which the data is saved. If file is a file-object, + then the filename is unchanged. If file is a string or Path, + a ``.npy`` extension will be appended to the filename if it does not + already have one. + arr : array_like + Array data to be saved. + allow_pickle : bool, optional + Allow saving object arrays using Python pickles. Reasons for + disallowing pickles include security (loading pickled data can execute + arbitrary code) and portability (pickled objects may not be loadable + on different Python installations, for example if the stored objects + require libraries that are not available, and not all pickled data is + compatible between different versions of Python). + Default: True + + See Also + -------- + savez : Save several arrays into a ``.npz`` archive + savetxt, load + + Notes + ----- + For a description of the ``.npy`` format, see :py:mod:`numpy.lib.format`. + + Any data saved to the file is appended to the end of the file. + + Examples + -------- + >>> import numpy as np + + >>> from tempfile import TemporaryFile + >>> outfile = TemporaryFile() + + >>> x = np.arange(10) + >>> np.save(outfile, x) + + >>> _ = outfile.seek(0) # Only needed to simulate closing & reopening file + >>> np.load(outfile) + array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) + + + >>> with open('test.npy', 'wb') as f: + ... np.save(f, np.array([1, 2])) + ... np.save(f, np.array([1, 3])) + >>> with open('test.npy', 'rb') as f: + ... a = np.load(f) + ... b = np.load(f) + >>> print(a, b) + # [1 2] [1 3] + """ + if hasattr(file, 'write'): + file_ctx = contextlib.nullcontext(file) + else: + file = os.fspath(file) + if not file.endswith('.npy'): + file = file + '.npy' + file_ctx = open(file, "wb") + + with file_ctx as fid: + arr = np.asanyarray(arr) + format.write_array(fid, arr, allow_pickle=allow_pickle) + + +def _savez_dispatcher(file, *args, allow_pickle=True, **kwds): + yield from args + yield from kwds.values() + + +@array_function_dispatch(_savez_dispatcher) +def savez(file, *args, allow_pickle=True, **kwds): + """Save several arrays into a single file in uncompressed ``.npz`` format. + + Provide arrays as keyword arguments to store them under the + corresponding name in the output file: ``savez(fn, x=x, y=y)``. + + If arrays are specified as positional arguments, i.e., ``savez(fn, + x, y)``, their names will be `arr_0`, `arr_1`, etc. + + Parameters + ---------- + file : file, str, or pathlib.Path + Either the filename (string) or an open file (file-like object) + where the data will be saved. If file is a string or a Path, the + ``.npz`` extension will be appended to the filename if it is not + already there. + args : Arguments, optional + Arrays to save to the file. Please use keyword arguments (see + `kwds` below) to assign names to arrays. Arrays specified as + args will be named "arr_0", "arr_1", and so on. + allow_pickle : bool, optional + Allow saving object arrays using Python pickles. Reasons for + disallowing pickles include security (loading pickled data can execute + arbitrary code) and portability (pickled objects may not be loadable + on different Python installations, for example if the stored objects + require libraries that are not available, and not all pickled data is + compatible between different versions of Python). + Default: True + kwds : Keyword arguments, optional + Arrays to save to the file. Each array will be saved to the + output file with its corresponding keyword name. + + Returns + ------- + None + + See Also + -------- + save : Save a single array to a binary file in NumPy format. + savetxt : Save an array to a file as plain text. + savez_compressed : Save several arrays into a compressed ``.npz`` archive + + Notes + ----- + The ``.npz`` file format is a zipped archive of files named after the + variables they contain. The archive is not compressed and each file + in the archive contains one variable in ``.npy`` format. For a + description of the ``.npy`` format, see :py:mod:`numpy.lib.format`. + + When opening the saved ``.npz`` file with `load` a `~lib.npyio.NpzFile` + object is returned. This is a dictionary-like object which can be queried + for its list of arrays (with the ``.files`` attribute), and for the arrays + themselves. + + Keys passed in `kwds` are used as filenames inside the ZIP archive. + Therefore, keys should be valid filenames; e.g., avoid keys that begin with + ``/`` or contain ``.``. + + When naming variables with keyword arguments, it is not possible to name a + variable ``file``, as this would cause the ``file`` argument to be defined + twice in the call to ``savez``. + + Examples + -------- + >>> import numpy as np + >>> from tempfile import TemporaryFile + >>> outfile = TemporaryFile() + >>> x = np.arange(10) + >>> y = np.sin(x) + + Using `savez` with \\*args, the arrays are saved with default names. + + >>> np.savez(outfile, x, y) + >>> _ = outfile.seek(0) # Only needed to simulate closing & reopening file + >>> npzfile = np.load(outfile) + >>> npzfile.files + ['arr_0', 'arr_1'] + >>> npzfile['arr_0'] + array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) + + Using `savez` with \\**kwds, the arrays are saved with the keyword names. + + >>> outfile = TemporaryFile() + >>> np.savez(outfile, x=x, y=y) + >>> _ = outfile.seek(0) + >>> npzfile = np.load(outfile) + >>> sorted(npzfile.files) + ['x', 'y'] + >>> npzfile['x'] + array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) + + """ + _savez(file, args, kwds, False, allow_pickle=allow_pickle) + + +def _savez_compressed_dispatcher(file, *args, allow_pickle=True, **kwds): + yield from args + yield from kwds.values() + + +@array_function_dispatch(_savez_compressed_dispatcher) +def savez_compressed(file, *args, allow_pickle=True, **kwds): + """ + Save several arrays into a single file in compressed ``.npz`` format. + + Provide arrays as keyword arguments to store them under the + corresponding name in the output file: ``savez_compressed(fn, x=x, y=y)``. + + If arrays are specified as positional arguments, i.e., + ``savez_compressed(fn, x, y)``, their names will be `arr_0`, `arr_1`, etc. + + Parameters + ---------- + file : file, str, or pathlib.Path + Either the filename (string) or an open file (file-like object) + where the data will be saved. If file is a string or a Path, the + ``.npz`` extension will be appended to the filename if it is not + already there. + args : Arguments, optional + Arrays to save to the file. Please use keyword arguments (see + `kwds` below) to assign names to arrays. Arrays specified as + args will be named "arr_0", "arr_1", and so on. + allow_pickle : bool, optional + Allow saving object arrays using Python pickles. Reasons for + disallowing pickles include security (loading pickled data can execute + arbitrary code) and portability (pickled objects may not be loadable + on different Python installations, for example if the stored objects + require libraries that are not available, and not all pickled data is + compatible between different versions of Python). + Default: True + kwds : Keyword arguments, optional + Arrays to save to the file. Each array will be saved to the + output file with its corresponding keyword name. + + Returns + ------- + None + + See Also + -------- + numpy.save : Save a single array to a binary file in NumPy format. + numpy.savetxt : Save an array to a file as plain text. + numpy.savez : Save several arrays into an uncompressed ``.npz`` file format + numpy.load : Load the files created by savez_compressed. + + Notes + ----- + The ``.npz`` file format is a zipped archive of files named after the + variables they contain. The archive is compressed with + ``zipfile.ZIP_DEFLATED`` and each file in the archive contains one variable + in ``.npy`` format. For a description of the ``.npy`` format, see + :py:mod:`numpy.lib.format`. + + + When opening the saved ``.npz`` file with `load` a `~lib.npyio.NpzFile` + object is returned. This is a dictionary-like object which can be queried + for its list of arrays (with the ``.files`` attribute), and for the arrays + themselves. + + Examples + -------- + >>> import numpy as np + >>> test_array = np.random.rand(3, 2) + >>> test_vector = np.random.rand(4) + >>> np.savez_compressed('/tmp/123', a=test_array, b=test_vector) + >>> loaded = np.load('/tmp/123.npz') + >>> print(np.array_equal(test_array, loaded['a'])) + True + >>> print(np.array_equal(test_vector, loaded['b'])) + True + + """ + _savez(file, args, kwds, True, allow_pickle=allow_pickle) + + +def _savez(file, args, kwds, compress, allow_pickle=True, pickle_kwargs=None): + # Import is postponed to here since zipfile depends on gzip, an optional + # component of the so-called standard library. + import zipfile + + if not hasattr(file, 'write'): + file = os.fspath(file) + if not file.endswith('.npz'): + file = file + '.npz' + + namedict = kwds + for i, val in enumerate(args): + key = 'arr_%d' % i + if key in namedict.keys(): + raise ValueError( + f"Cannot use un-named variables and keyword {key}") + namedict[key] = val + + if compress: + compression = zipfile.ZIP_DEFLATED + else: + compression = zipfile.ZIP_STORED + + zipf = zipfile_factory(file, mode="w", compression=compression) + try: + for key, val in namedict.items(): + fname = key + '.npy' + val = np.asanyarray(val) + # always force zip64, gh-10776 + with zipf.open(fname, 'w', force_zip64=True) as fid: + format.write_array(fid, val, + allow_pickle=allow_pickle, + pickle_kwargs=pickle_kwargs) + finally: + zipf.close() + + +def _ensure_ndmin_ndarray_check_param(ndmin): + """Just checks if the param ndmin is supported on + _ensure_ndmin_ndarray. It is intended to be used as + verification before running anything expensive. + e.g. loadtxt, genfromtxt + """ + # Check correctness of the values of `ndmin` + if ndmin not in [0, 1, 2]: + raise ValueError(f"Illegal value of ndmin keyword: {ndmin}") + +def _ensure_ndmin_ndarray(a, *, ndmin: int): + """This is a helper function of loadtxt and genfromtxt to ensure + proper minimum dimension as requested + + ndim : int. Supported values 1, 2, 3 + ^^ whenever this changes, keep in sync with + _ensure_ndmin_ndarray_check_param + """ + # Verify that the array has at least dimensions `ndmin`. + # Tweak the size and shape of the arrays - remove extraneous dimensions + if a.ndim > ndmin: + a = np.squeeze(a) + # and ensure we have the minimum number of dimensions asked for + # - has to be in this order for the odd case ndmin=1, a.squeeze().ndim=0 + if a.ndim < ndmin: + if ndmin == 1: + a = np.atleast_1d(a) + elif ndmin == 2: + a = np.atleast_2d(a).T + + return a + + +# amount of lines loadtxt reads in one chunk, can be overridden for testing +_loadtxt_chunksize = 50000 + + +def _check_nonneg_int(value, name="argument"): + try: + operator.index(value) + except TypeError: + raise TypeError(f"{name} must be an integer") from None + if value < 0: + raise ValueError(f"{name} must be nonnegative") + + +def _preprocess_comments(iterable, comments, encoding): + """ + Generator that consumes a line iterated iterable and strips out the + multiple (or multi-character) comments from lines. + This is a pre-processing step to achieve feature parity with loadtxt + (we assume that this feature is a nieche feature). + """ + for line in iterable: + if isinstance(line, bytes): + # Need to handle conversion here, or the splitting would fail + line = line.decode(encoding) + + for c in comments: + line = line.split(c, 1)[0] + + yield line + + +# The number of rows we read in one go if confronted with a parametric dtype +_loadtxt_chunksize = 50000 + + +def _read(fname, *, delimiter=',', comment='#', quote='"', + imaginary_unit='j', usecols=None, skiplines=0, + max_rows=None, converters=None, ndmin=None, unpack=False, + dtype=np.float64, encoding=None): + r""" + Read a NumPy array from a text file. + This is a helper function for loadtxt. + + Parameters + ---------- + fname : file, str, or pathlib.Path + The filename or the file to be read. + delimiter : str, optional + Field delimiter of the fields in line of the file. + Default is a comma, ','. If None any sequence of whitespace is + considered a delimiter. + comment : str or sequence of str or None, optional + Character that begins a comment. All text from the comment + character to the end of the line is ignored. + Multiple comments or multiple-character comment strings are supported, + but may be slower and `quote` must be empty if used. + Use None to disable all use of comments. + quote : str or None, optional + Character that is used to quote string fields. Default is '"' + (a double quote). Use None to disable quote support. + imaginary_unit : str, optional + Character that represent the imaginary unit `sqrt(-1)`. + Default is 'j'. + usecols : array_like, optional + A one-dimensional array of integer column numbers. These are the + columns from the file to be included in the array. If this value + is not given, all the columns are used. + skiplines : int, optional + Number of lines to skip before interpreting the data in the file. + max_rows : int, optional + Maximum number of rows of data to read. Default is to read the + entire file. + converters : dict or callable, optional + A function to parse all columns strings into the desired value, or + a dictionary mapping column number to a parser function. + E.g. if column 0 is a date string: ``converters = {0: datestr2num}``. + Converters can also be used to provide a default value for missing + data, e.g. ``converters = lambda s: float(s.strip() or 0)`` will + convert empty fields to 0. + Default: None + ndmin : int, optional + Minimum dimension of the array returned. + Allowed values are 0, 1 or 2. Default is 0. + unpack : bool, optional + If True, the returned array is transposed, so that arguments may be + unpacked using ``x, y, z = read(...)``. When used with a structured + data-type, arrays are returned for each field. Default is False. + dtype : numpy data type + A NumPy dtype instance, can be a structured dtype to map to the + columns of the file. + encoding : str, optional + Encoding used to decode the inputfile. The special value 'bytes' + (the default) enables backwards-compatible behavior for `converters`, + ensuring that inputs to the converter functions are encoded + bytes objects. The special value 'bytes' has no additional effect if + ``converters=None``. If encoding is ``'bytes'`` or ``None``, the + default system encoding is used. + + Returns + ------- + ndarray + NumPy array. + """ + # Handle special 'bytes' keyword for encoding + byte_converters = False + if encoding == 'bytes': + encoding = None + byte_converters = True + + if dtype is None: + raise TypeError("a dtype must be provided.") + dtype = np.dtype(dtype) + + read_dtype_via_object_chunks = None + if dtype.kind in 'SUM' and dtype in { + np.dtype("S0"), np.dtype("U0"), np.dtype("M8"), np.dtype("m8")}: + # This is a legacy "flexible" dtype. We do not truly support + # parametric dtypes currently (no dtype discovery step in the core), + # but have to support these for backward compatibility. + read_dtype_via_object_chunks = dtype + dtype = np.dtype(object) + + if usecols is not None: + # Allow usecols to be a single int or a sequence of ints, the C-code + # handles the rest + try: + usecols = list(usecols) + except TypeError: + usecols = [usecols] + + _ensure_ndmin_ndarray_check_param(ndmin) + + if comment is None: + comments = None + else: + # assume comments are a sequence of strings + if "" in comment: + raise ValueError( + "comments cannot be an empty string. Use comments=None to " + "disable comments." + ) + comments = tuple(comment) + comment = None + if len(comments) == 0: + comments = None # No comments at all + elif len(comments) == 1: + # If there is only one comment, and that comment has one character, + # the normal parsing can deal with it just fine. + if isinstance(comments[0], str) and len(comments[0]) == 1: + comment = comments[0] + comments = None + # Input validation if there are multiple comment characters + elif delimiter in comments: + raise TypeError( + f"Comment characters '{comments}' cannot include the " + f"delimiter '{delimiter}'" + ) + + # comment is now either a 1 or 0 character string or a tuple: + if comments is not None: + # Note: An earlier version support two character comments (and could + # have been extended to multiple characters, we assume this is + # rare enough to not optimize for. + if quote is not None: + raise ValueError( + "when multiple comments or a multi-character comment is " + "given, quotes are not supported. In this case quotechar " + "must be set to None.") + + if len(imaginary_unit) != 1: + raise ValueError('len(imaginary_unit) must be 1.') + + _check_nonneg_int(skiplines) + if max_rows is not None: + _check_nonneg_int(max_rows) + else: + # Passing -1 to the C code means "read the entire file". + max_rows = -1 + + fh_closing_ctx = contextlib.nullcontext() + filelike = False + try: + if isinstance(fname, os.PathLike): + fname = os.fspath(fname) + if isinstance(fname, str): + fh = np.lib._datasource.open(fname, 'rt', encoding=encoding) + if encoding is None: + encoding = getattr(fh, 'encoding', 'latin1') + + fh_closing_ctx = contextlib.closing(fh) + data = fh + filelike = True + else: + if encoding is None: + encoding = getattr(fname, 'encoding', 'latin1') + data = iter(fname) + except TypeError as e: + raise ValueError( + f"fname must be a string, filehandle, list of strings,\n" + f"or generator. Got {type(fname)} instead.") from e + + with fh_closing_ctx: + if comments is not None: + if filelike: + data = iter(data) + filelike = False + data = _preprocess_comments(data, comments, encoding) + + if read_dtype_via_object_chunks is None: + arr = _load_from_filelike( + data, delimiter=delimiter, comment=comment, quote=quote, + imaginary_unit=imaginary_unit, + usecols=usecols, skiplines=skiplines, max_rows=max_rows, + converters=converters, dtype=dtype, + encoding=encoding, filelike=filelike, + byte_converters=byte_converters) + + else: + # This branch reads the file into chunks of object arrays and then + # casts them to the desired actual dtype. This ensures correct + # string-length and datetime-unit discovery (like `arr.astype()`). + # Due to chunking, certain error reports are less clear, currently. + if filelike: + data = iter(data) # cannot chunk when reading from file + filelike = False + + c_byte_converters = False + if read_dtype_via_object_chunks == "S": + c_byte_converters = True # Use latin1 rather than ascii + + chunks = [] + while max_rows != 0: + if max_rows < 0: + chunk_size = _loadtxt_chunksize + else: + chunk_size = min(_loadtxt_chunksize, max_rows) + + next_arr = _load_from_filelike( + data, delimiter=delimiter, comment=comment, quote=quote, + imaginary_unit=imaginary_unit, + usecols=usecols, skiplines=skiplines, max_rows=chunk_size, + converters=converters, dtype=dtype, + encoding=encoding, filelike=filelike, + byte_converters=byte_converters, + c_byte_converters=c_byte_converters) + # Cast here already. We hope that this is better even for + # large files because the storage is more compact. It could + # be adapted (in principle the concatenate could cast). + chunks.append(next_arr.astype(read_dtype_via_object_chunks)) + + skiplines = 0 # Only have to skip for first chunk + if max_rows >= 0: + max_rows -= chunk_size + if len(next_arr) < chunk_size: + # There was less data than requested, so we are done. + break + + # Need at least one chunk, but if empty, the last one may have + # the wrong shape. + if len(chunks) > 1 and len(chunks[-1]) == 0: + del chunks[-1] + if len(chunks) == 1: + arr = chunks[0] + else: + arr = np.concatenate(chunks, axis=0) + + # NOTE: ndmin works as advertised for structured dtypes, but normally + # these would return a 1D result plus the structured dimension, + # so ndmin=2 adds a third dimension even when no squeezing occurs. + # A `squeeze=False` could be a better solution (pandas uses squeeze). + arr = _ensure_ndmin_ndarray(arr, ndmin=ndmin) + + if arr.shape: + if arr.shape[0] == 0: + warnings.warn( + f'loadtxt: input contained no data: "{fname}"', + category=UserWarning, + stacklevel=3 + ) + + if unpack: + # Unpack structured dtypes if requested: + dt = arr.dtype + if dt.names is not None: + # For structured arrays, return an array for each field. + return [arr[field] for field in dt.names] + else: + return arr.T + else: + return arr + + +@finalize_array_function_like +@set_module('numpy') +def loadtxt(fname, dtype=float, comments='#', delimiter=None, + converters=None, skiprows=0, usecols=None, unpack=False, + ndmin=0, encoding=None, max_rows=None, *, quotechar=None, + like=None): + r""" + Load data from a text file. + + Parameters + ---------- + fname : file, str, pathlib.Path, list of str, generator + File, filename, list, or generator to read. If the filename + extension is ``.gz`` or ``.bz2``, the file is first decompressed. Note + that generators must return bytes or strings. The strings + in a list or produced by a generator are treated as lines. + dtype : data-type, optional + Data-type of the resulting array; default: float. If this is a + structured data-type, the resulting array will be 1-dimensional, and + each row will be interpreted as an element of the array. In this + case, the number of columns used must match the number of fields in + the data-type. + comments : str or sequence of str or None, optional + The characters or list of characters used to indicate the start of a + comment. None implies no comments. For backwards compatibility, byte + strings will be decoded as 'latin1'. The default is '#'. + delimiter : str, optional + The character used to separate the values. For backwards compatibility, + byte strings will be decoded as 'latin1'. The default is whitespace. + + .. versionchanged:: 1.23.0 + Only single character delimiters are supported. Newline characters + cannot be used as the delimiter. + + converters : dict or callable, optional + Converter functions to customize value parsing. If `converters` is + callable, the function is applied to all columns, else it must be a + dict that maps column number to a parser function. + See examples for further details. + Default: None. + + .. versionchanged:: 1.23.0 + The ability to pass a single callable to be applied to all columns + was added. + + skiprows : int, optional + Skip the first `skiprows` lines, including comments; default: 0. + usecols : int or sequence, optional + Which columns to read, with 0 being the first. For example, + ``usecols = (1,4,5)`` will extract the 2nd, 5th and 6th columns. + The default, None, results in all columns being read. + unpack : bool, optional + If True, the returned array is transposed, so that arguments may be + unpacked using ``x, y, z = loadtxt(...)``. When used with a + structured data-type, arrays are returned for each field. + Default is False. + ndmin : int, optional + The returned array will have at least `ndmin` dimensions. + Otherwise mono-dimensional axes will be squeezed. + Legal values: 0 (default), 1 or 2. + encoding : str, optional + Encoding used to decode the inputfile. Does not apply to input streams. + The special value 'bytes' enables backward compatibility workarounds + that ensures you receive byte arrays as results if possible and passes + 'latin1' encoded strings to converters. Override this value to receive + unicode arrays and pass strings as input to converters. If set to None + the system default is used. The default value is None. + + .. versionchanged:: 2.0 + Before NumPy 2, the default was ``'bytes'`` for Python 2 + compatibility. The default is now ``None``. + + max_rows : int, optional + Read `max_rows` rows of content after `skiprows` lines. The default is + to read all the rows. Note that empty rows containing no data such as + empty lines and comment lines are not counted towards `max_rows`, + while such lines are counted in `skiprows`. + + .. versionchanged:: 1.23.0 + Lines containing no data, including comment lines (e.g., lines + starting with '#' or as specified via `comments`) are not counted + towards `max_rows`. + quotechar : unicode character or None, optional + The character used to denote the start and end of a quoted item. + Occurrences of the delimiter or comment characters are ignored within + a quoted item. The default value is ``quotechar=None``, which means + quoting support is disabled. + + If two consecutive instances of `quotechar` are found within a quoted + field, the first is treated as an escape character. See examples. + + .. versionadded:: 1.23.0 + ${ARRAY_FUNCTION_LIKE} + + .. versionadded:: 1.20.0 + + Returns + ------- + out : ndarray + Data read from the text file. + + See Also + -------- + load, fromstring, fromregex + genfromtxt : Load data with missing values handled as specified. + scipy.io.loadmat : reads MATLAB data files + + Notes + ----- + This function aims to be a fast reader for simply formatted files. The + `genfromtxt` function provides more sophisticated handling of, e.g., + lines with missing values. + + Each row in the input text file must have the same number of values to be + able to read all values. If all rows do not have same number of values, a + subset of up to n columns (where n is the least number of values present + in all rows) can be read by specifying the columns via `usecols`. + + The strings produced by the Python float.hex method can be used as + input for floats. + + Examples + -------- + >>> import numpy as np + >>> from io import StringIO # StringIO behaves like a file object + >>> c = StringIO("0 1\n2 3") + >>> np.loadtxt(c) + array([[0., 1.], + [2., 3.]]) + + >>> d = StringIO("M 21 72\nF 35 58") + >>> np.loadtxt(d, dtype={'names': ('gender', 'age', 'weight'), + ... 'formats': ('S1', 'i4', 'f4')}) + array([(b'M', 21, 72.), (b'F', 35, 58.)], + dtype=[('gender', 'S1'), ('age', '>> c = StringIO("1,0,2\n3,0,4") + >>> x, y = np.loadtxt(c, delimiter=',', usecols=(0, 2), unpack=True) + >>> x + array([1., 3.]) + >>> y + array([2., 4.]) + + The `converters` argument is used to specify functions to preprocess the + text prior to parsing. `converters` can be a dictionary that maps + preprocessing functions to each column: + + >>> s = StringIO("1.618, 2.296\n3.141, 4.669\n") + >>> conv = { + ... 0: lambda x: np.floor(float(x)), # conversion fn for column 0 + ... 1: lambda x: np.ceil(float(x)), # conversion fn for column 1 + ... } + >>> np.loadtxt(s, delimiter=",", converters=conv) + array([[1., 3.], + [3., 5.]]) + + `converters` can be a callable instead of a dictionary, in which case it + is applied to all columns: + + >>> s = StringIO("0xDE 0xAD\n0xC0 0xDE") + >>> import functools + >>> conv = functools.partial(int, base=16) + >>> np.loadtxt(s, converters=conv) + array([[222., 173.], + [192., 222.]]) + + This example shows how `converters` can be used to convert a field + with a trailing minus sign into a negative number. + + >>> s = StringIO("10.01 31.25-\n19.22 64.31\n17.57- 63.94") + >>> def conv(fld): + ... return -float(fld[:-1]) if fld.endswith("-") else float(fld) + ... + >>> np.loadtxt(s, converters=conv) + array([[ 10.01, -31.25], + [ 19.22, 64.31], + [-17.57, 63.94]]) + + Using a callable as the converter can be particularly useful for handling + values with different formatting, e.g. floats with underscores: + + >>> s = StringIO("1 2.7 100_000") + >>> np.loadtxt(s, converters=float) + array([1.e+00, 2.7e+00, 1.e+05]) + + This idea can be extended to automatically handle values specified in + many different formats, such as hex values: + + >>> def conv(val): + ... try: + ... return float(val) + ... except ValueError: + ... return float.fromhex(val) + >>> s = StringIO("1, 2.5, 3_000, 0b4, 0x1.4000000000000p+2") + >>> np.loadtxt(s, delimiter=",", converters=conv) + array([1.0e+00, 2.5e+00, 3.0e+03, 1.8e+02, 5.0e+00]) + + Or a format where the ``-`` sign comes after the number: + + >>> s = StringIO("10.01 31.25-\n19.22 64.31\n17.57- 63.94") + >>> conv = lambda x: -float(x[:-1]) if x.endswith("-") else float(x) + >>> np.loadtxt(s, converters=conv) + array([[ 10.01, -31.25], + [ 19.22, 64.31], + [-17.57, 63.94]]) + + Support for quoted fields is enabled with the `quotechar` parameter. + Comment and delimiter characters are ignored when they appear within a + quoted item delineated by `quotechar`: + + >>> s = StringIO('"alpha, #42", 10.0\n"beta, #64", 2.0\n') + >>> dtype = np.dtype([("label", "U12"), ("value", float)]) + >>> np.loadtxt(s, dtype=dtype, delimiter=",", quotechar='"') + array([('alpha, #42', 10.), ('beta, #64', 2.)], + dtype=[('label', '>> s = StringIO('"alpha, #42" 10.0\n"beta, #64" 2.0\n') + >>> dtype = np.dtype([("label", "U12"), ("value", float)]) + >>> np.loadtxt(s, dtype=dtype, delimiter=None, quotechar='"') + array([('alpha, #42', 10.), ('beta, #64', 2.)], + dtype=[('label', '>> s = StringIO('"Hello, my name is ""Monty""!"') + >>> np.loadtxt(s, dtype="U", delimiter=",", quotechar='"') + array('Hello, my name is "Monty"!', dtype='>> d = StringIO("1 2\n2 4\n3 9 12\n4 16 20") + >>> np.loadtxt(d, usecols=(0, 1)) + array([[ 1., 2.], + [ 2., 4.], + [ 3., 9.], + [ 4., 16.]]) + + """ + + if like is not None: + return _loadtxt_with_like( + like, fname, dtype=dtype, comments=comments, delimiter=delimiter, + converters=converters, skiprows=skiprows, usecols=usecols, + unpack=unpack, ndmin=ndmin, encoding=encoding, + max_rows=max_rows + ) + + if isinstance(delimiter, bytes): + delimiter.decode("latin1") + + if dtype is None: + dtype = np.float64 + + comment = comments + # Control character type conversions for Py3 convenience + if comment is not None: + if isinstance(comment, (str, bytes)): + comment = [comment] + comment = [ + x.decode('latin1') if isinstance(x, bytes) else x for x in comment] + if isinstance(delimiter, bytes): + delimiter = delimiter.decode('latin1') + + arr = _read(fname, dtype=dtype, comment=comment, delimiter=delimiter, + converters=converters, skiplines=skiprows, usecols=usecols, + unpack=unpack, ndmin=ndmin, encoding=encoding, + max_rows=max_rows, quote=quotechar) + + return arr + + +_loadtxt_with_like = array_function_dispatch()(loadtxt) + + +def _savetxt_dispatcher(fname, X, fmt=None, delimiter=None, newline=None, + header=None, footer=None, comments=None, + encoding=None): + return (X,) + + +@array_function_dispatch(_savetxt_dispatcher) +def savetxt(fname, X, fmt='%.18e', delimiter=' ', newline='\n', header='', + footer='', comments='# ', encoding=None): + """ + Save an array to a text file. + + Parameters + ---------- + fname : filename, file handle or pathlib.Path + If the filename ends in ``.gz``, the file is automatically saved in + compressed gzip format. `loadtxt` understands gzipped files + transparently. + X : 1D or 2D array_like + Data to be saved to a text file. + fmt : str or sequence of strs, optional + A single format (%10.5f), a sequence of formats, or a + multi-format string, e.g. 'Iteration %d -- %10.5f', in which + case `delimiter` is ignored. For complex `X`, the legal options + for `fmt` are: + + * a single specifier, ``fmt='%.4e'``, resulting in numbers formatted + like ``' (%s+%sj)' % (fmt, fmt)`` + * a full string specifying every real and imaginary part, e.g. + ``' %.4e %+.4ej %.4e %+.4ej %.4e %+.4ej'`` for 3 columns + * a list of specifiers, one per column - in this case, the real + and imaginary part must have separate specifiers, + e.g. ``['%.3e + %.3ej', '(%.15e%+.15ej)']`` for 2 columns + delimiter : str, optional + String or character separating columns. + newline : str, optional + String or character separating lines. + header : str, optional + String that will be written at the beginning of the file. + footer : str, optional + String that will be written at the end of the file. + comments : str, optional + String that will be prepended to the ``header`` and ``footer`` strings, + to mark them as comments. Default: '# ', as expected by e.g. + ``numpy.loadtxt``. + encoding : {None, str}, optional + Encoding used to encode the outputfile. Does not apply to output + streams. If the encoding is something other than 'bytes' or 'latin1' + you will not be able to load the file in NumPy versions < 1.14. Default + is 'latin1'. + + See Also + -------- + save : Save an array to a binary file in NumPy ``.npy`` format + savez : Save several arrays into an uncompressed ``.npz`` archive + savez_compressed : Save several arrays into a compressed ``.npz`` archive + + Notes + ----- + Further explanation of the `fmt` parameter + (``%[flag]width[.precision]specifier``): + + flags: + ``-`` : left justify + + ``+`` : Forces to precede result with + or -. + + ``0`` : Left pad the number with zeros instead of space (see width). + + width: + Minimum number of characters to be printed. The value is not truncated + if it has more characters. + + precision: + - For integer specifiers (eg. ``d,i,o,x``), the minimum number of + digits. + - For ``e, E`` and ``f`` specifiers, the number of digits to print + after the decimal point. + - For ``g`` and ``G``, the maximum number of significant digits. + - For ``s``, the maximum number of characters. + + specifiers: + ``c`` : character + + ``d`` or ``i`` : signed decimal integer + + ``e`` or ``E`` : scientific notation with ``e`` or ``E``. + + ``f`` : decimal floating point + + ``g,G`` : use the shorter of ``e,E`` or ``f`` + + ``o`` : signed octal + + ``s`` : string of characters + + ``u`` : unsigned decimal integer + + ``x,X`` : unsigned hexadecimal integer + + This explanation of ``fmt`` is not complete, for an exhaustive + specification see [1]_. + + References + ---------- + .. [1] `Format Specification Mini-Language + `_, + Python Documentation. + + Examples + -------- + >>> import numpy as np + >>> x = y = z = np.arange(0.0,5.0,1.0) + >>> np.savetxt('test.out', x, delimiter=',') # X is an array + >>> np.savetxt('test.out', (x,y,z)) # x,y,z equal sized 1D arrays + >>> np.savetxt('test.out', x, fmt='%1.4e') # use exponential notation + + """ + + class WriteWrap: + """Convert to bytes on bytestream inputs. + + """ + def __init__(self, fh, encoding): + self.fh = fh + self.encoding = encoding + self.do_write = self.first_write + + def close(self): + self.fh.close() + + def write(self, v): + self.do_write(v) + + def write_bytes(self, v): + if isinstance(v, bytes): + self.fh.write(v) + else: + self.fh.write(v.encode(self.encoding)) + + def write_normal(self, v): + self.fh.write(asunicode(v)) + + def first_write(self, v): + try: + self.write_normal(v) + self.write = self.write_normal + except TypeError: + # input is probably a bytestream + self.write_bytes(v) + self.write = self.write_bytes + + own_fh = False + if isinstance(fname, os.PathLike): + fname = os.fspath(fname) + if _is_string_like(fname): + # datasource doesn't support creating a new file ... + open(fname, 'wt').close() + fh = np.lib._datasource.open(fname, 'wt', encoding=encoding) + own_fh = True + elif hasattr(fname, 'write'): + # wrap to handle byte output streams + fh = WriteWrap(fname, encoding or 'latin1') + else: + raise ValueError('fname must be a string or file handle') + + try: + X = np.asarray(X) + + # Handle 1-dimensional arrays + if X.ndim == 0 or X.ndim > 2: + raise ValueError( + "Expected 1D or 2D array, got %dD array instead" % X.ndim) + elif X.ndim == 1: + # Common case -- 1d array of numbers + if X.dtype.names is None: + X = np.atleast_2d(X).T + ncol = 1 + + # Complex dtype -- each field indicates a separate column + else: + ncol = len(X.dtype.names) + else: + ncol = X.shape[1] + + iscomplex_X = np.iscomplexobj(X) + # `fmt` can be a string with multiple insertion points or a + # list of formats. E.g. '%10.5f\t%10d' or ('%10.5f', '$10d') + if type(fmt) in (list, tuple): + if len(fmt) != ncol: + raise AttributeError(f'fmt has wrong shape. {str(fmt)}') + format = delimiter.join(fmt) + elif isinstance(fmt, str): + n_fmt_chars = fmt.count('%') + error = ValueError(f'fmt has wrong number of % formats: {fmt}') + if n_fmt_chars == 1: + if iscomplex_X: + fmt = [f' ({fmt}+{fmt}j)', ] * ncol + else: + fmt = [fmt, ] * ncol + format = delimiter.join(fmt) + elif iscomplex_X and n_fmt_chars != (2 * ncol): + raise error + elif ((not iscomplex_X) and n_fmt_chars != ncol): + raise error + else: + format = fmt + else: + raise ValueError(f'invalid fmt: {fmt!r}') + + if len(header) > 0: + header = header.replace('\n', '\n' + comments) + fh.write(comments + header + newline) + if iscomplex_X: + for row in X: + row2 = [] + for number in row: + row2.extend((number.real, number.imag)) + s = format % tuple(row2) + newline + fh.write(s.replace('+-', '-')) + else: + for row in X: + try: + v = format % tuple(row) + newline + except TypeError as e: + raise TypeError("Mismatch between array dtype ('%s') and " + "format specifier ('%s')" + % (str(X.dtype), format)) from e + fh.write(v) + + if len(footer) > 0: + footer = footer.replace('\n', '\n' + comments) + fh.write(comments + footer + newline) + finally: + if own_fh: + fh.close() + + +@set_module('numpy') +def fromregex(file, regexp, dtype, encoding=None): + r""" + Construct an array from a text file, using regular expression parsing. + + The returned array is always a structured array, and is constructed from + all matches of the regular expression in the file. Groups in the regular + expression are converted to fields of the structured array. + + Parameters + ---------- + file : file, str, or pathlib.Path + Filename or file object to read. + + .. versionchanged:: 1.22.0 + Now accepts `os.PathLike` implementations. + + regexp : str or regexp + Regular expression used to parse the file. + Groups in the regular expression correspond to fields in the dtype. + dtype : dtype or list of dtypes + Dtype for the structured array; must be a structured datatype. + encoding : str, optional + Encoding used to decode the inputfile. Does not apply to input streams. + + Returns + ------- + output : ndarray + The output array, containing the part of the content of `file` that + was matched by `regexp`. `output` is always a structured array. + + Raises + ------ + TypeError + When `dtype` is not a valid dtype for a structured array. + + See Also + -------- + fromstring, loadtxt + + Notes + ----- + Dtypes for structured arrays can be specified in several forms, but all + forms specify at least the data type and field name. For details see + `basics.rec`. + + Examples + -------- + >>> import numpy as np + >>> from io import StringIO + >>> text = StringIO("1312 foo\n1534 bar\n444 qux") + + >>> regexp = r"(\d+)\s+(...)" # match [digits, whitespace, anything] + >>> output = np.fromregex(text, regexp, + ... [('num', np.int64), ('key', 'S3')]) + >>> output + array([(1312, b'foo'), (1534, b'bar'), ( 444, b'qux')], + dtype=[('num', '>> output['num'] + array([1312, 1534, 444]) + + """ + own_fh = False + if not hasattr(file, "read"): + file = os.fspath(file) + file = np.lib._datasource.open(file, 'rt', encoding=encoding) + own_fh = True + + try: + if not isinstance(dtype, np.dtype): + dtype = np.dtype(dtype) + if dtype.names is None: + raise TypeError('dtype must be a structured datatype.') + + content = file.read() + if isinstance(content, bytes) and isinstance(regexp, str): + regexp = asbytes(regexp) + + if not hasattr(regexp, 'match'): + regexp = re.compile(regexp) + seq = regexp.findall(content) + if seq and not isinstance(seq[0], tuple): + # Only one group is in the regexp. + # Create the new array as a single data-type and then + # re-interpret as a single-field structured array. + newdtype = np.dtype(dtype[dtype.names[0]]) + output = np.array(seq, dtype=newdtype) + output = output.view(dtype) + else: + output = np.array(seq, dtype=dtype) + + return output + finally: + if own_fh: + file.close() + + +#####-------------------------------------------------------------------------- +#---- --- ASCII functions --- +#####-------------------------------------------------------------------------- + + +@finalize_array_function_like +@set_module('numpy') +def genfromtxt(fname, dtype=float, comments='#', delimiter=None, + skip_header=0, skip_footer=0, converters=None, + missing_values=None, filling_values=None, usecols=None, + names=None, excludelist=None, + deletechars=''.join(sorted(NameValidator.defaultdeletechars)), # noqa: B008 + replace_space='_', autostrip=False, case_sensitive=True, + defaultfmt="f%i", unpack=None, usemask=False, loose=True, + invalid_raise=True, max_rows=None, encoding=None, + *, ndmin=0, like=None): + """ + Load data from a text file, with missing values handled as specified. + + Each line past the first `skip_header` lines is split at the `delimiter` + character, and characters following the `comments` character are discarded. + + Parameters + ---------- + fname : file, str, pathlib.Path, list of str, generator + File, filename, list, or generator to read. If the filename + extension is ``.gz`` or ``.bz2``, the file is first decompressed. Note + that generators must return bytes or strings. The strings + in a list or produced by a generator are treated as lines. + dtype : dtype, optional + Data type of the resulting array. + If None, the dtypes will be determined by the contents of each + column, individually. + comments : str, optional + The character used to indicate the start of a comment. + All the characters occurring on a line after a comment are discarded. + delimiter : str, int, or sequence, optional + The string used to separate values. By default, any consecutive + whitespaces act as delimiter. An integer or sequence of integers + can also be provided as width(s) of each field. + skiprows : int, optional + `skiprows` was removed in numpy 1.10. Please use `skip_header` instead. + skip_header : int, optional + The number of lines to skip at the beginning of the file. + skip_footer : int, optional + The number of lines to skip at the end of the file. + converters : variable, optional + The set of functions that convert the data of a column to a value. + The converters can also be used to provide a default value + for missing data: ``converters = {3: lambda s: float(s or 0)}``. + missing : variable, optional + `missing` was removed in numpy 1.10. Please use `missing_values` + instead. + missing_values : variable, optional + The set of strings corresponding to missing data. + filling_values : variable, optional + The set of values to be used as default when the data are missing. + usecols : sequence, optional + Which columns to read, with 0 being the first. For example, + ``usecols = (1, 4, 5)`` will extract the 2nd, 5th and 6th columns. + names : {None, True, str, sequence}, optional + If `names` is True, the field names are read from the first line after + the first `skip_header` lines. This line can optionally be preceded + by a comment delimiter. Any content before the comment delimiter is + discarded. If `names` is a sequence or a single-string of + comma-separated names, the names will be used to define the field + names in a structured dtype. If `names` is None, the names of the + dtype fields will be used, if any. + excludelist : sequence, optional + A list of names to exclude. This list is appended to the default list + ['return','file','print']. Excluded names are appended with an + underscore: for example, `file` would become `file_`. + deletechars : str, optional + A string combining invalid characters that must be deleted from the + names. + defaultfmt : str, optional + A format used to define default field names, such as "f%i" or "f_%02i". + autostrip : bool, optional + Whether to automatically strip white spaces from the variables. + replace_space : char, optional + Character(s) used in replacement of white spaces in the variable + names. By default, use a '_'. + case_sensitive : {True, False, 'upper', 'lower'}, optional + If True, field names are case sensitive. + If False or 'upper', field names are converted to upper case. + If 'lower', field names are converted to lower case. + unpack : bool, optional + If True, the returned array is transposed, so that arguments may be + unpacked using ``x, y, z = genfromtxt(...)``. When used with a + structured data-type, arrays are returned for each field. + Default is False. + usemask : bool, optional + If True, return a masked array. + If False, return a regular array. + loose : bool, optional + If True, do not raise errors for invalid values. + invalid_raise : bool, optional + If True, an exception is raised if an inconsistency is detected in the + number of columns. + If False, a warning is emitted and the offending lines are skipped. + max_rows : int, optional + The maximum number of rows to read. Must not be used with skip_footer + at the same time. If given, the value must be at least 1. Default is + to read the entire file. + encoding : str, optional + Encoding used to decode the inputfile. Does not apply when `fname` + is a file object. The special value 'bytes' enables backward + compatibility workarounds that ensure that you receive byte arrays + when possible and passes latin1 encoded strings to converters. + Override this value to receive unicode arrays and pass strings + as input to converters. If set to None the system default is used. + The default value is 'bytes'. + + .. versionchanged:: 2.0 + Before NumPy 2, the default was ``'bytes'`` for Python 2 + compatibility. The default is now ``None``. + + ndmin : int, optional + Same parameter as `loadtxt` + + .. versionadded:: 1.23.0 + ${ARRAY_FUNCTION_LIKE} + + .. versionadded:: 1.20.0 + + Returns + ------- + out : ndarray + Data read from the text file. If `usemask` is True, this is a + masked array. + + See Also + -------- + numpy.loadtxt : equivalent function when no data is missing. + + Notes + ----- + * When spaces are used as delimiters, or when no delimiter has been given + as input, there should not be any missing data between two fields. + * When variables are named (either by a flexible dtype or with a `names` + sequence), there must not be any header in the file (else a ValueError + exception is raised). + * Individual values are not stripped of spaces by default. + When using a custom converter, make sure the function does remove spaces. + * Custom converters may receive unexpected values due to dtype + discovery. + + References + ---------- + .. [1] NumPy User Guide, section `I/O with NumPy + `_. + + Examples + -------- + >>> from io import StringIO + >>> import numpy as np + + Comma delimited file with mixed dtype + + >>> s = StringIO("1,1.3,abcde") + >>> data = np.genfromtxt(s, dtype=[('myint','i8'),('myfloat','f8'), + ... ('mystring','S5')], delimiter=",") + >>> data + array((1, 1.3, b'abcde'), + dtype=[('myint', '>> _ = s.seek(0) # needed for StringIO example only + >>> data = np.genfromtxt(s, dtype=None, + ... names = ['myint','myfloat','mystring'], delimiter=",") + >>> data + array((1, 1.3, 'abcde'), + dtype=[('myint', '>> _ = s.seek(0) + >>> data = np.genfromtxt(s, dtype="i8,f8,S5", + ... names=['myint','myfloat','mystring'], delimiter=",") + >>> data + array((1, 1.3, b'abcde'), + dtype=[('myint', '>> s = StringIO("11.3abcde") + >>> data = np.genfromtxt(s, dtype=None, names=['intvar','fltvar','strvar'], + ... delimiter=[1,3,5]) + >>> data + array((1, 1.3, 'abcde'), + dtype=[('intvar', '>> f = StringIO(''' + ... text,# of chars + ... hello world,11 + ... numpy,5''') + >>> np.genfromtxt(f, dtype='S12,S12', delimiter=',') + array([(b'text', b''), (b'hello world', b'11'), (b'numpy', b'5')], + dtype=[('f0', 'S12'), ('f1', 'S12')]) + + """ + + if like is not None: + return _genfromtxt_with_like( + like, fname, dtype=dtype, comments=comments, delimiter=delimiter, + skip_header=skip_header, skip_footer=skip_footer, + converters=converters, missing_values=missing_values, + filling_values=filling_values, usecols=usecols, names=names, + excludelist=excludelist, deletechars=deletechars, + replace_space=replace_space, autostrip=autostrip, + case_sensitive=case_sensitive, defaultfmt=defaultfmt, + unpack=unpack, usemask=usemask, loose=loose, + invalid_raise=invalid_raise, max_rows=max_rows, encoding=encoding, + ndmin=ndmin, + ) + + _ensure_ndmin_ndarray_check_param(ndmin) + + if max_rows is not None: + if skip_footer: + raise ValueError( + "The keywords 'skip_footer' and 'max_rows' can not be " + "specified at the same time.") + if max_rows < 1: + raise ValueError("'max_rows' must be at least 1.") + + if usemask: + from numpy.ma import MaskedArray, make_mask_descr + # Check the input dictionary of converters + user_converters = converters or {} + if not isinstance(user_converters, dict): + raise TypeError( + "The input argument 'converter' should be a valid dictionary " + "(got '%s' instead)" % type(user_converters)) + + if encoding == 'bytes': + encoding = None + byte_converters = True + else: + byte_converters = False + + # Initialize the filehandle, the LineSplitter and the NameValidator + if isinstance(fname, os.PathLike): + fname = os.fspath(fname) + if isinstance(fname, str): + fid = np.lib._datasource.open(fname, 'rt', encoding=encoding) + fid_ctx = contextlib.closing(fid) + else: + fid = fname + fid_ctx = contextlib.nullcontext(fid) + try: + fhd = iter(fid) + except TypeError as e: + raise TypeError( + "fname must be a string, a filehandle, a sequence of strings,\n" + f"or an iterator of strings. Got {type(fname)} instead." + ) from e + with fid_ctx: + split_line = LineSplitter(delimiter=delimiter, comments=comments, + autostrip=autostrip, encoding=encoding) + validate_names = NameValidator(excludelist=excludelist, + deletechars=deletechars, + case_sensitive=case_sensitive, + replace_space=replace_space) + + # Skip the first `skip_header` rows + try: + for i in range(skip_header): + next(fhd) + + # Keep on until we find the first valid values + first_values = None + + while not first_values: + first_line = _decode_line(next(fhd), encoding) + if (names is True) and (comments is not None): + if comments in first_line: + first_line = ( + ''.join(first_line.split(comments)[1:])) + first_values = split_line(first_line) + except StopIteration: + # return an empty array if the datafile is empty + first_line = '' + first_values = [] + warnings.warn( + f'genfromtxt: Empty input file: "{fname}"', stacklevel=2 + ) + + # Should we take the first values as names ? + if names is True: + fval = first_values[0].strip() + if comments is not None: + if fval in comments: + del first_values[0] + + # Check the columns to use: make sure `usecols` is a list + if usecols is not None: + try: + usecols = [_.strip() for _ in usecols.split(",")] + except AttributeError: + try: + usecols = list(usecols) + except TypeError: + usecols = [usecols, ] + nbcols = len(usecols or first_values) + + # Check the names and overwrite the dtype.names if needed + if names is True: + names = validate_names([str(_.strip()) for _ in first_values]) + first_line = '' + elif _is_string_like(names): + names = validate_names([_.strip() for _ in names.split(',')]) + elif names: + names = validate_names(names) + # Get the dtype + if dtype is not None: + dtype = easy_dtype(dtype, defaultfmt=defaultfmt, names=names, + excludelist=excludelist, + deletechars=deletechars, + case_sensitive=case_sensitive, + replace_space=replace_space) + # Make sure the names is a list (for 2.5) + if names is not None: + names = list(names) + + if usecols: + for (i, current) in enumerate(usecols): + # if usecols is a list of names, convert to a list of indices + if _is_string_like(current): + usecols[i] = names.index(current) + elif current < 0: + usecols[i] = current + len(first_values) + # If the dtype is not None, make sure we update it + if (dtype is not None) and (len(dtype) > nbcols): + descr = dtype.descr + dtype = np.dtype([descr[_] for _ in usecols]) + names = list(dtype.names) + # If `names` is not None, update the names + elif (names is not None) and (len(names) > nbcols): + names = [names[_] for _ in usecols] + elif (names is not None) and (dtype is not None): + names = list(dtype.names) + + # Process the missing values ............................... + # Rename missing_values for convenience + user_missing_values = missing_values or () + if isinstance(user_missing_values, bytes): + user_missing_values = user_missing_values.decode('latin1') + + # Define the list of missing_values (one column: one list) + missing_values = [[''] for _ in range(nbcols)] + + # We have a dictionary: process it field by field + if isinstance(user_missing_values, dict): + # Loop on the items + for (key, val) in user_missing_values.items(): + # Is the key a string ? + if _is_string_like(key): + try: + # Transform it into an integer + key = names.index(key) + except ValueError: + # We couldn't find it: the name must have been dropped + continue + # Redefine the key as needed if it's a column number + if usecols: + try: + key = usecols.index(key) + except ValueError: + pass + # Transform the value as a list of string + if isinstance(val, (list, tuple)): + val = [str(_) for _ in val] + else: + val = [str(val), ] + # Add the value(s) to the current list of missing + if key is None: + # None acts as default + for miss in missing_values: + miss.extend(val) + else: + missing_values[key].extend(val) + # We have a sequence : each item matches a column + elif isinstance(user_missing_values, (list, tuple)): + for (value, entry) in zip(user_missing_values, missing_values): + value = str(value) + if value not in entry: + entry.append(value) + # We have a string : apply it to all entries + elif isinstance(user_missing_values, str): + user_value = user_missing_values.split(",") + for entry in missing_values: + entry.extend(user_value) + # We have something else: apply it to all entries + else: + for entry in missing_values: + entry.extend([str(user_missing_values)]) + + # Process the filling_values ............................... + # Rename the input for convenience + user_filling_values = filling_values + if user_filling_values is None: + user_filling_values = [] + # Define the default + filling_values = [None] * nbcols + # We have a dictionary : update each entry individually + if isinstance(user_filling_values, dict): + for (key, val) in user_filling_values.items(): + if _is_string_like(key): + try: + # Transform it into an integer + key = names.index(key) + except ValueError: + # We couldn't find it: the name must have been dropped + continue + # Redefine the key if it's a column number + # and usecols is defined + if usecols: + try: + key = usecols.index(key) + except ValueError: + pass + # Add the value to the list + filling_values[key] = val + # We have a sequence : update on a one-to-one basis + elif isinstance(user_filling_values, (list, tuple)): + n = len(user_filling_values) + if (n <= nbcols): + filling_values[:n] = user_filling_values + else: + filling_values = user_filling_values[:nbcols] + # We have something else : use it for all entries + else: + filling_values = [user_filling_values] * nbcols + + # Initialize the converters ................................ + if dtype is None: + # Note: we can't use a [...]*nbcols, as we would have 3 times + # the same converter, instead of 3 different converters. + converters = [ + StringConverter(None, missing_values=miss, default=fill) + for (miss, fill) in zip(missing_values, filling_values) + ] + else: + dtype_flat = flatten_dtype(dtype, flatten_base=True) + # Initialize the converters + if len(dtype_flat) > 1: + # Flexible type : get a converter from each dtype + zipit = zip(dtype_flat, missing_values, filling_values) + converters = [StringConverter(dt, + locked=True, + missing_values=miss, + default=fill) + for (dt, miss, fill) in zipit] + else: + # Set to a default converter (but w/ different missing values) + zipit = zip(missing_values, filling_values) + converters = [StringConverter(dtype, + locked=True, + missing_values=miss, + default=fill) + for (miss, fill) in zipit] + # Update the converters to use the user-defined ones + uc_update = [] + for (j, conv) in user_converters.items(): + # If the converter is specified by column names, + # use the index instead + if _is_string_like(j): + try: + j = names.index(j) + i = j + except ValueError: + continue + elif usecols: + try: + i = usecols.index(j) + except ValueError: + # Unused converter specified + continue + else: + i = j + # Find the value to test - first_line is not filtered by usecols: + if len(first_line): + testing_value = first_values[j] + else: + testing_value = None + if conv is bytes: + user_conv = asbytes + elif byte_converters: + # Converters may use decode to workaround numpy's old + # behavior, so encode the string again before passing + # to the user converter. + def tobytes_first(x, conv): + if type(x) is bytes: + return conv(x) + return conv(x.encode("latin1")) + user_conv = functools.partial(tobytes_first, conv=conv) + else: + user_conv = conv + converters[i].update(user_conv, locked=True, + testing_value=testing_value, + default=filling_values[i], + missing_values=missing_values[i],) + uc_update.append((i, user_conv)) + # Make sure we have the corrected keys in user_converters... + user_converters.update(uc_update) + + # Fixme: possible error as following variable never used. + # miss_chars = [_.missing_values for _ in converters] + + # Initialize the output lists ... + # ... rows + rows = [] + append_to_rows = rows.append + # ... masks + if usemask: + masks = [] + append_to_masks = masks.append + # ... invalid + invalid = [] + append_to_invalid = invalid.append + + # Parse each line + for (i, line) in enumerate(itertools.chain([first_line, ], fhd)): + values = split_line(line) + nbvalues = len(values) + # Skip an empty line + if nbvalues == 0: + continue + if usecols: + # Select only the columns we need + try: + values = [values[_] for _ in usecols] + except IndexError: + append_to_invalid((i + skip_header + 1, nbvalues)) + continue + elif nbvalues != nbcols: + append_to_invalid((i + skip_header + 1, nbvalues)) + continue + # Store the values + append_to_rows(tuple(values)) + if usemask: + append_to_masks(tuple(v.strip() in m + for (v, m) in zip(values, + missing_values))) + if len(rows) == max_rows: + break + + # Upgrade the converters (if needed) + if dtype is None: + for (i, converter) in enumerate(converters): + current_column = [itemgetter(i)(_m) for _m in rows] + try: + converter.iterupgrade(current_column) + except ConverterLockError: + errmsg = f"Converter #{i} is locked and cannot be upgraded: " + current_column = map(itemgetter(i), rows) + for (j, value) in enumerate(current_column): + try: + converter.upgrade(value) + except (ConverterError, ValueError): + line_number = j + 1 + skip_header + errmsg += f"(occurred line #{line_number} for value '{value}')" + raise ConverterError(errmsg) + + # Check that we don't have invalid values + nbinvalid = len(invalid) + if nbinvalid > 0: + nbrows = len(rows) + nbinvalid - skip_footer + # Construct the error message + template = f" Line #%i (got %i columns instead of {nbcols})" + if skip_footer > 0: + nbinvalid_skipped = len([_ for _ in invalid + if _[0] > nbrows + skip_header]) + invalid = invalid[:nbinvalid - nbinvalid_skipped] + skip_footer -= nbinvalid_skipped +# +# nbrows -= skip_footer +# errmsg = [template % (i, nb) +# for (i, nb) in invalid if i < nbrows] +# else: + errmsg = [template % (i, nb) + for (i, nb) in invalid] + if len(errmsg): + errmsg.insert(0, "Some errors were detected !") + errmsg = "\n".join(errmsg) + # Raise an exception ? + if invalid_raise: + raise ValueError(errmsg) + # Issue a warning ? + else: + warnings.warn(errmsg, ConversionWarning, stacklevel=2) + + # Strip the last skip_footer data + if skip_footer > 0: + rows = rows[:-skip_footer] + if usemask: + masks = masks[:-skip_footer] + + # Convert each value according to the converter: + # We want to modify the list in place to avoid creating a new one... + if loose: + rows = list( + zip(*[[conv._loose_call(_r) for _r in map(itemgetter(i), rows)] + for (i, conv) in enumerate(converters)])) + else: + rows = list( + zip(*[[conv._strict_call(_r) for _r in map(itemgetter(i), rows)] + for (i, conv) in enumerate(converters)])) + + # Reset the dtype + data = rows + if dtype is None: + # Get the dtypes from the types of the converters + column_types = [conv.type for conv in converters] + # Find the columns with strings... + strcolidx = [i for (i, v) in enumerate(column_types) + if v == np.str_] + + if byte_converters and strcolidx: + # convert strings back to bytes for backward compatibility + warnings.warn( + "Reading unicode strings without specifying the encoding " + "argument is deprecated. Set the encoding, use None for the " + "system default.", + np.exceptions.VisibleDeprecationWarning, stacklevel=2) + + def encode_unicode_cols(row_tup): + row = list(row_tup) + for i in strcolidx: + row[i] = row[i].encode('latin1') + return tuple(row) + + try: + data = [encode_unicode_cols(r) for r in data] + except UnicodeEncodeError: + pass + else: + for i in strcolidx: + column_types[i] = np.bytes_ + + # Update string types to be the right length + sized_column_types = column_types.copy() + for i, col_type in enumerate(column_types): + if np.issubdtype(col_type, np.character): + n_chars = max(len(row[i]) for row in data) + sized_column_types[i] = (col_type, n_chars) + + if names is None: + # If the dtype is uniform (before sizing strings) + base = { + c_type + for c, c_type in zip(converters, column_types) + if c._checked} + if len(base) == 1: + uniform_type, = base + (ddtype, mdtype) = (uniform_type, bool) + else: + ddtype = [(defaultfmt % i, dt) + for (i, dt) in enumerate(sized_column_types)] + if usemask: + mdtype = [(defaultfmt % i, bool) + for (i, dt) in enumerate(sized_column_types)] + else: + ddtype = list(zip(names, sized_column_types)) + mdtype = list(zip(names, [bool] * len(sized_column_types))) + output = np.array(data, dtype=ddtype) + if usemask: + outputmask = np.array(masks, dtype=mdtype) + else: + # Overwrite the initial dtype names if needed + if names and dtype.names is not None: + dtype.names = names + # Case 1. We have a structured type + if len(dtype_flat) > 1: + # Nested dtype, eg [('a', int), ('b', [('b0', int), ('b1', 'f4')])] + # First, create the array using a flattened dtype: + # [('a', int), ('b1', int), ('b2', float)] + # Then, view the array using the specified dtype. + if 'O' in (_.char for _ in dtype_flat): + if has_nested_fields(dtype): + raise NotImplementedError( + "Nested fields involving objects are not supported...") + else: + output = np.array(data, dtype=dtype) + else: + rows = np.array(data, dtype=[('', _) for _ in dtype_flat]) + output = rows.view(dtype) + # Now, process the rowmasks the same way + if usemask: + rowmasks = np.array( + masks, dtype=np.dtype([('', bool) for t in dtype_flat])) + # Construct the new dtype + mdtype = make_mask_descr(dtype) + outputmask = rowmasks.view(mdtype) + # Case #2. We have a basic dtype + else: + # We used some user-defined converters + if user_converters: + ishomogeneous = True + descr = [] + for i, ttype in enumerate([conv.type for conv in converters]): + # Keep the dtype of the current converter + if i in user_converters: + ishomogeneous &= (ttype == dtype.type) + if np.issubdtype(ttype, np.character): + ttype = (ttype, max(len(row[i]) for row in data)) + descr.append(('', ttype)) + else: + descr.append(('', dtype)) + # So we changed the dtype ? + if not ishomogeneous: + # We have more than one field + if len(descr) > 1: + dtype = np.dtype(descr) + # We have only one field: drop the name if not needed. + else: + dtype = np.dtype(ttype) + # + output = np.array(data, dtype) + if usemask: + if dtype.names is not None: + mdtype = [(_, bool) for _ in dtype.names] + else: + mdtype = bool + outputmask = np.array(masks, dtype=mdtype) + # Try to take care of the missing data we missed + names = output.dtype.names + if usemask and names: + for (name, conv) in zip(names, converters): + missing_values = [conv(_) for _ in conv.missing_values + if _ != ''] + for mval in missing_values: + outputmask[name] |= (output[name] == mval) + # Construct the final array + if usemask: + output = output.view(MaskedArray) + output._mask = outputmask + + output = _ensure_ndmin_ndarray(output, ndmin=ndmin) + + if unpack: + if names is None: + return output.T + elif len(names) == 1: + # squeeze single-name dtypes too + return output[names[0]] + else: + # For structured arrays with multiple fields, + # return an array for each field. + return [output[field] for field in names] + return output + + +_genfromtxt_with_like = array_function_dispatch()(genfromtxt) + + +def recfromtxt(fname, **kwargs): + """ + Load ASCII data from a file and return it in a record array. + + If ``usemask=False`` a standard `recarray` is returned, + if ``usemask=True`` a MaskedRecords array is returned. + + .. deprecated:: 2.0 + Use `numpy.genfromtxt` instead. + + Parameters + ---------- + fname, kwargs : For a description of input parameters, see `genfromtxt`. + + See Also + -------- + numpy.genfromtxt : generic function + + Notes + ----- + By default, `dtype` is None, which means that the data-type of the output + array will be determined from the data. + + """ + + # Deprecated in NumPy 2.0, 2023-07-11 + warnings.warn( + "`recfromtxt` is deprecated, " + "use `numpy.genfromtxt` instead." + "(deprecated in NumPy 2.0)", + DeprecationWarning, + stacklevel=2 + ) + + kwargs.setdefault("dtype", None) + usemask = kwargs.get('usemask', False) + output = genfromtxt(fname, **kwargs) + if usemask: + from numpy.ma.mrecords import MaskedRecords + output = output.view(MaskedRecords) + else: + output = output.view(np.recarray) + return output + + +def recfromcsv(fname, **kwargs): + """ + Load ASCII data stored in a comma-separated file. + + The returned array is a record array (if ``usemask=False``, see + `recarray`) or a masked record array (if ``usemask=True``, + see `ma.mrecords.MaskedRecords`). + + .. deprecated:: 2.0 + Use `numpy.genfromtxt` with comma as `delimiter` instead. + + Parameters + ---------- + fname, kwargs : For a description of input parameters, see `genfromtxt`. + + See Also + -------- + numpy.genfromtxt : generic function to load ASCII data. + + Notes + ----- + By default, `dtype` is None, which means that the data-type of the output + array will be determined from the data. + + """ + + # Deprecated in NumPy 2.0, 2023-07-11 + warnings.warn( + "`recfromcsv` is deprecated, " + "use `numpy.genfromtxt` with comma as `delimiter` instead. " + "(deprecated in NumPy 2.0)", + DeprecationWarning, + stacklevel=2 + ) + + # Set default kwargs for genfromtxt as relevant to csv import. + kwargs.setdefault("case_sensitive", "lower") + kwargs.setdefault("names", True) + kwargs.setdefault("delimiter", ",") + kwargs.setdefault("dtype", None) + output = genfromtxt(fname, **kwargs) + + usemask = kwargs.get("usemask", False) + if usemask: + from numpy.ma.mrecords import MaskedRecords + output = output.view(MaskedRecords) + else: + output = output.view(np.recarray) + return output diff --git a/python/user_packages/Python313/site-packages/numpy/lib/_npyio_impl.pyi b/python/user_packages/Python313/site-packages/numpy/lib/_npyio_impl.pyi new file mode 100644 index 0000000000000000000000000000000000000000..d48691d6f36f0d5806b61f670db4c6afc743a622 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/lib/_npyio_impl.pyi @@ -0,0 +1,299 @@ +import types +import zipfile +from _typeshed import ( + StrOrBytesPath, + StrPath, + SupportsKeysAndGetItem, + SupportsRead, + SupportsWrite, +) +from collections.abc import Callable, Collection, Iterable, Iterator, Mapping, Sequence +from re import Pattern +from typing import ( + IO, + Any, + ClassVar, + Generic, + Literal as L, + Protocol, + Self, + TypeAlias, + overload, + type_check_only, +) +from typing_extensions import TypeVar, override + +import numpy as np +from numpy._core.multiarray import packbits, unpackbits +from numpy._typing import ArrayLike, DTypeLike, NDArray, _DTypeLike, _SupportsArrayFunc +from numpy.ma.mrecords import MaskedRecords + +from ._datasource import DataSource as DataSource + +__all__ = [ + "fromregex", + "genfromtxt", + "load", + "loadtxt", + "packbits", + "save", + "savetxt", + "savez", + "savez_compressed", + "unpackbits", +] + +_T = TypeVar("_T") +_T_co = TypeVar("_T_co", covariant=True) +_ScalarT = TypeVar("_ScalarT", bound=np.generic) +_ScalarT_co = TypeVar("_ScalarT_co", bound=np.generic, default=Any, covariant=True) + +_FName: TypeAlias = StrPath | Iterable[str] | Iterable[bytes] +_FNameRead: TypeAlias = StrPath | SupportsRead[str] | SupportsRead[bytes] +_FNameWriteBytes: TypeAlias = StrPath | SupportsWrite[bytes] +_FNameWrite: TypeAlias = _FNameWriteBytes | SupportsWrite[str] + +@type_check_only +class _SupportsReadSeek(SupportsRead[_T_co], Protocol[_T_co]): + def seek(self, offset: int, whence: int, /) -> object: ... + +class BagObj(Generic[_T_co]): + def __init__(self, /, obj: SupportsKeysAndGetItem[str, _T_co]) -> None: ... + def __getattribute__(self, key: str, /) -> _T_co: ... + def __dir__(self) -> list[str]: ... + +class NpzFile(Mapping[str, NDArray[_ScalarT_co]]): + _MAX_REPR_ARRAY_COUNT: ClassVar[int] = 5 + + zip: zipfile.ZipFile | None = None + fid: IO[str] | None = None + files: list[str] + allow_pickle: bool + pickle_kwargs: Mapping[str, Any] | None + f: BagObj[NpzFile[_ScalarT_co]] + + # + def __init__( + self, + /, + fid: IO[Any], + own_fid: bool = False, + allow_pickle: bool = False, + pickle_kwargs: Mapping[str, object] | None = None, + *, + max_header_size: int = 10_000, + ) -> None: ... + def __del__(self) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, cls: type[BaseException] | None, e: BaseException | None, tb: types.TracebackType | None, /) -> None: ... + @override + def __len__(self) -> int: ... + @override + def __iter__(self) -> Iterator[str]: ... + @override + def __getitem__(self, key: str, /) -> NDArray[_ScalarT_co]: ... + + # + @override + @overload + def get(self, key: str, default: None = None, /) -> NDArray[_ScalarT_co] | None: ... + @overload + def get(self, key: str, default: NDArray[_ScalarT_co] | _T, /) -> NDArray[_ScalarT_co] | _T: ... # pyright: ignore[reportIncompatibleMethodOverride] + + # + def close(self) -> None: ... + +# NOTE: Returns a `NpzFile` if file is a zip file; +# returns an `ndarray`/`memmap` otherwise +def load( + file: StrOrBytesPath | _SupportsReadSeek[bytes], + mmap_mode: L["r+", "r", "w+", "c"] | None = None, + allow_pickle: bool = False, + fix_imports: bool = True, + encoding: L["ASCII", "latin1", "bytes"] = "ASCII", + *, + max_header_size: int = 10_000, +) -> Any: ... + +def save(file: _FNameWriteBytes, arr: ArrayLike, allow_pickle: bool = True) -> None: ... +def savez(file: _FNameWriteBytes, *args: ArrayLike, allow_pickle: bool = True, **kwds: ArrayLike) -> None: ... +def savez_compressed(file: _FNameWriteBytes, *args: ArrayLike, allow_pickle: bool = True, **kwds: ArrayLike) -> None: ... + +# File-like objects only have to implement `__iter__` and, +# optionally, `encoding` +@overload +def loadtxt( + fname: _FName, + dtype: None = None, + comments: str | Sequence[str] | None = "#", + delimiter: str | None = None, + converters: Mapping[int | str, Callable[[str], Any]] | Callable[[str], Any] | None = None, + skiprows: int = 0, + usecols: int | Sequence[int] | None = None, + unpack: bool = False, + ndmin: L[0, 1, 2] = 0, + encoding: str | None = None, + max_rows: int | None = None, + *, + quotechar: str | None = None, + like: _SupportsArrayFunc | None = None, +) -> NDArray[np.float64]: ... +@overload +def loadtxt( + fname: _FName, + dtype: _DTypeLike[_ScalarT], + comments: str | Sequence[str] | None = "#", + delimiter: str | None = None, + converters: Mapping[int | str, Callable[[str], Any]] | Callable[[str], Any] | None = None, + skiprows: int = 0, + usecols: int | Sequence[int] | None = None, + unpack: bool = False, + ndmin: L[0, 1, 2] = 0, + encoding: str | None = None, + max_rows: int | None = None, + *, + quotechar: str | None = None, + like: _SupportsArrayFunc | None = None, +) -> NDArray[_ScalarT]: ... +@overload +def loadtxt( + fname: _FName, + dtype: DTypeLike | None, + comments: str | Sequence[str] | None = "#", + delimiter: str | None = None, + converters: Mapping[int | str, Callable[[str], Any]] | Callable[[str], Any] | None = None, + skiprows: int = 0, + usecols: int | Sequence[int] | None = None, + unpack: bool = False, + ndmin: L[0, 1, 2] = 0, + encoding: str | None = None, + max_rows: int | None = None, + *, + quotechar: str | None = None, + like: _SupportsArrayFunc | None = None, +) -> NDArray[Any]: ... + +def savetxt( + fname: _FNameWrite, + X: ArrayLike, + fmt: str | Sequence[str] = "%.18e", + delimiter: str = " ", + newline: str = "\n", + header: str = "", + footer: str = "", + comments: str = "# ", + encoding: str | None = None, +) -> None: ... + +@overload +def fromregex( + file: _FNameRead, + regexp: str | bytes | Pattern[Any], + dtype: _DTypeLike[_ScalarT], + encoding: str | None = None, +) -> NDArray[_ScalarT]: ... +@overload +def fromregex( + file: _FNameRead, + regexp: str | bytes | Pattern[Any], + dtype: DTypeLike | None, + encoding: str | None = None, +) -> NDArray[Any]: ... + +@overload +def genfromtxt( + fname: _FName, + dtype: None = None, + comments: str = "#", + delimiter: str | int | Iterable[int] | None = None, + skip_header: int = 0, + skip_footer: int = 0, + converters: Mapping[int | str, Callable[[str], Any]] | None = None, + missing_values: Any = None, + filling_values: Any = None, + usecols: Sequence[int] | None = None, + names: L[True] | str | Collection[str] | None = None, + excludelist: Sequence[str] | None = None, + deletechars: str = " !#$%&'()*+,-./:;<=>?@[\\]^{|}~", + replace_space: str = "_", + autostrip: bool = False, + case_sensitive: bool | L["upper", "lower"] = True, + defaultfmt: str = "f%i", + unpack: bool | None = None, + usemask: bool = False, + loose: bool = True, + invalid_raise: bool = True, + max_rows: int | None = None, + encoding: str | None = None, + *, + ndmin: L[0, 1, 2] = 0, + like: _SupportsArrayFunc | None = None, +) -> NDArray[Any]: ... +@overload +def genfromtxt( + fname: _FName, + dtype: _DTypeLike[_ScalarT], + comments: str = "#", + delimiter: str | int | Iterable[int] | None = None, + skip_header: int = 0, + skip_footer: int = 0, + converters: Mapping[int | str, Callable[[str], Any]] | None = None, + missing_values: Any = None, + filling_values: Any = None, + usecols: Sequence[int] | None = None, + names: L[True] | str | Collection[str] | None = None, + excludelist: Sequence[str] | None = None, + deletechars: str = " !#$%&'()*+,-./:;<=>?@[\\]^{|}~", + replace_space: str = "_", + autostrip: bool = False, + case_sensitive: bool | L["upper", "lower"] = True, + defaultfmt: str = "f%i", + unpack: bool | None = None, + usemask: bool = False, + loose: bool = True, + invalid_raise: bool = True, + max_rows: int | None = None, + encoding: str | None = None, + *, + ndmin: L[0, 1, 2] = 0, + like: _SupportsArrayFunc | None = None, +) -> NDArray[_ScalarT]: ... +@overload +def genfromtxt( + fname: _FName, + dtype: DTypeLike | None, + comments: str = "#", + delimiter: str | int | Iterable[int] | None = None, + skip_header: int = 0, + skip_footer: int = 0, + converters: Mapping[int | str, Callable[[str], Any]] | None = None, + missing_values: Any = None, + filling_values: Any = None, + usecols: Sequence[int] | None = None, + names: L[True] | str | Collection[str] | None = None, + excludelist: Sequence[str] | None = None, + deletechars: str = " !#$%&'()*+,-./:;<=>?@[\\]^{|}~", + replace_space: str = "_", + autostrip: bool = False, + case_sensitive: bool | L["upper", "lower"] = True, + defaultfmt: str = "f%i", + unpack: bool | None = None, + usemask: bool = False, + loose: bool = True, + invalid_raise: bool = True, + max_rows: int | None = None, + encoding: str | None = None, + *, + ndmin: L[0, 1, 2] = 0, + like: _SupportsArrayFunc | None = None, +) -> NDArray[Any]: ... + +@overload +def recfromtxt(fname: _FName, *, usemask: L[False] = False, **kwargs: object) -> np.recarray[Any, np.dtype[np.record]]: ... +@overload +def recfromtxt(fname: _FName, *, usemask: L[True], **kwargs: object) -> MaskedRecords[Any, np.dtype[np.void]]: ... + +@overload +def recfromcsv(fname: _FName, *, usemask: L[False] = False, **kwargs: object) -> np.recarray[Any, np.dtype[np.record]]: ... +@overload +def recfromcsv(fname: _FName, *, usemask: L[True], **kwargs: object) -> MaskedRecords[Any, np.dtype[np.void]]: ... diff --git a/python/user_packages/Python313/site-packages/numpy/lib/_polynomial_impl.py b/python/user_packages/Python313/site-packages/numpy/lib/_polynomial_impl.py new file mode 100644 index 0000000000000000000000000000000000000000..1e42244ac5fc495d47b7d197b2f3b9f6c0c5646a --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/lib/_polynomial_impl.py @@ -0,0 +1,1465 @@ +""" +Functions to operate on polynomials. + +""" +__all__ = ['poly', 'roots', 'polyint', 'polyder', 'polyadd', + 'polysub', 'polymul', 'polydiv', 'polyval', 'poly1d', + 'polyfit'] + +import functools +import re +import warnings + +import numpy._core.numeric as NX +from numpy._core import ( + abs, + array, + atleast_1d, + dot, + finfo, + hstack, + isscalar, + ones, + overrides, +) +from numpy._utils import set_module +from numpy.exceptions import RankWarning +from numpy.lib._function_base_impl import trim_zeros +from numpy.lib._twodim_base_impl import diag, vander +from numpy.lib._type_check_impl import imag, iscomplex, mintypecode, real +from numpy.linalg import eigvals, inv, lstsq + +array_function_dispatch = functools.partial( + overrides.array_function_dispatch, module='numpy') + + +def _poly_dispatcher(seq_of_zeros): + return seq_of_zeros + + +@array_function_dispatch(_poly_dispatcher) +def poly(seq_of_zeros): + """ + Find the coefficients of a polynomial with the given sequence of roots. + + .. note:: + This forms part of the old polynomial API. Since version 1.4, the + new polynomial API defined in `numpy.polynomial` is preferred. + A summary of the differences can be found in the + :doc:`transition guide `. + + Returns the coefficients of the polynomial whose leading coefficient + is one for the given sequence of zeros (multiple roots must be included + in the sequence as many times as their multiplicity; see Examples). + A square matrix (or array, which will be treated as a matrix) can also + be given, in which case the coefficients of the characteristic polynomial + of the matrix are returned. + + Parameters + ---------- + seq_of_zeros : array_like, shape (N,) or (N, N) + A sequence of polynomial roots, or a square array or matrix object. + + Returns + ------- + c : ndarray + 1D array of polynomial coefficients from highest to lowest degree: + + ``c[0] * x**(N) + c[1] * x**(N-1) + ... + c[N-1] * x + c[N]`` + where c[0] always equals 1. + + Raises + ------ + ValueError + If input is the wrong shape (the input must be a 1-D or square + 2-D array). + + See Also + -------- + polyval : Compute polynomial values. + roots : Return the roots of a polynomial. + polyfit : Least squares polynomial fit. + poly1d : A one-dimensional polynomial class. + + Notes + ----- + Specifying the roots of a polynomial still leaves one degree of + freedom, typically represented by an undetermined leading + coefficient. [1]_ In the case of this function, that coefficient - + the first one in the returned array - is always taken as one. (If + for some reason you have one other point, the only automatic way + presently to leverage that information is to use ``polyfit``.) + + The characteristic polynomial, :math:`p_a(t)`, of an `n`-by-`n` + matrix **A** is given by + + :math:`p_a(t) = \\mathrm{det}(t\\, \\mathbf{I} - \\mathbf{A})`, + + where **I** is the `n`-by-`n` identity matrix. [2]_ + + References + ---------- + .. [1] M. Sullivan and M. Sullivan, III, "Algebra and Trigonometry, + Enhanced With Graphing Utilities," Prentice-Hall, pg. 318, 1996. + + .. [2] G. Strang, "Linear Algebra and Its Applications, 2nd Edition," + Academic Press, pg. 182, 1980. + + Examples + -------- + + Given a sequence of a polynomial's zeros: + + >>> import numpy as np + + >>> np.poly((0, 0, 0)) # Multiple root example + array([1., 0., 0., 0.]) + + The line above represents z**3 + 0*z**2 + 0*z + 0. + + >>> np.poly((-1./2, 0, 1./2)) + array([ 1. , 0. , -0.25, 0. ]) + + The line above represents z**3 - z/4 + + >>> np.poly((np.random.random(1)[0], 0, np.random.random(1)[0])) + array([ 1. , -0.77086955, 0.08618131, 0. ]) # random + + Given a square array object: + + >>> P = np.array([[0, 1./3], [-1./2, 0]]) + >>> np.poly(P) + array([1. , 0. , 0.16666667]) + + Note how in all cases the leading coefficient is always 1. + + """ + seq_of_zeros = atleast_1d(seq_of_zeros) + sh = seq_of_zeros.shape + + if len(sh) == 2 and sh[0] == sh[1] and sh[0] != 0: + seq_of_zeros = eigvals(seq_of_zeros) + elif len(sh) == 1: + dt = seq_of_zeros.dtype + # Let object arrays slip through, e.g. for arbitrary precision + if dt != object: + seq_of_zeros = seq_of_zeros.astype(mintypecode(dt.char)) + else: + raise ValueError("input must be 1d or non-empty square 2d array.") + + if len(seq_of_zeros) == 0: + return 1.0 + dt = seq_of_zeros.dtype + a = ones((1,), dtype=dt) + for zero in seq_of_zeros: + a = NX.convolve(a, array([1, -zero], dtype=dt), mode='full') + + if issubclass(a.dtype.type, NX.complexfloating): + # if complex roots are all complex conjugates, the roots are real. + roots = NX.asarray(seq_of_zeros, complex) + if NX.all(NX.sort(roots) == NX.sort(roots.conjugate())): + a = a.real.copy() + + return a + + +def _roots_dispatcher(p): + return p + + +@array_function_dispatch(_roots_dispatcher) +def roots(p): + """ + Return the roots of a polynomial with coefficients given in p. + + .. note:: + This forms part of the old polynomial API. Since version 1.4, the + new polynomial API defined in `numpy.polynomial` is preferred. + A summary of the differences can be found in the + :doc:`transition guide `. + + The values in the rank-1 array `p` are coefficients of a polynomial. + If the length of `p` is n+1 then the polynomial is described by:: + + p[0] * x**n + p[1] * x**(n-1) + ... + p[n-1]*x + p[n] + + Parameters + ---------- + p : array_like + Rank-1 array of polynomial coefficients. + + Returns + ------- + out : ndarray + An array containing the roots of the polynomial. + + Raises + ------ + ValueError + When `p` cannot be converted to a rank-1 array. + + See also + -------- + poly : Find the coefficients of a polynomial with a given sequence + of roots. + polyval : Compute polynomial values. + polyfit : Least squares polynomial fit. + poly1d : A one-dimensional polynomial class. + + Notes + ----- + The algorithm relies on computing the eigenvalues of the + companion matrix [1]_. + + References + ---------- + .. [1] R. A. Horn & C. R. Johnson, *Matrix Analysis*. Cambridge, UK: + Cambridge University Press, 1999, pp. 146-7. + + Examples + -------- + >>> import numpy as np + >>> coeff = [3.2, 2, 1] + >>> np.roots(coeff) + array([-0.3125+0.46351241j, -0.3125-0.46351241j]) + + """ + # If input is scalar, this makes it an array + p = atleast_1d(p) + if p.ndim != 1: + raise ValueError("Input must be a rank-1 array.") + + # find non-zero array entries + non_zero = NX.nonzero(NX.ravel(p))[0] + + # Return an empty array if polynomial is all zeros + if len(non_zero) == 0: + return NX.array([]) + + # find the number of trailing zeros -- this is the number of roots at 0. + trailing_zeros = len(p) - non_zero[-1] - 1 + + # strip leading and trailing zeros + p = p[int(non_zero[0]):int(non_zero[-1]) + 1] + + # casting: if incoming array isn't floating point, make it floating point. + if not issubclass(p.dtype.type, (NX.floating, NX.complexfloating)): + p = p.astype(float) + + N = len(p) + if N > 1: + # build companion matrix and find its eigenvalues (the roots) + A = diag(NX.ones((N - 2,), p.dtype), -1) + A[0, :] = -p[1:] / p[0] + roots = eigvals(A) + else: + roots = NX.array([]) + + # tack any zeros onto the back of the array + roots = hstack((roots, NX.zeros(trailing_zeros, roots.dtype))) + return roots + + +def _polyint_dispatcher(p, m=None, k=None): + return (p,) + + +@array_function_dispatch(_polyint_dispatcher) +def polyint(p, m=1, k=None): + """ + Return an antiderivative (indefinite integral) of a polynomial. + + .. note:: + This forms part of the old polynomial API. Since version 1.4, the + new polynomial API defined in `numpy.polynomial` is preferred. + A summary of the differences can be found in the + :doc:`transition guide `. + + The returned order `m` antiderivative `P` of polynomial `p` satisfies + :math:`\\frac{d^m}{dx^m}P(x) = p(x)` and is defined up to `m - 1` + integration constants `k`. The constants determine the low-order + polynomial part + + .. math:: \\frac{k_{m-1}}{0!} x^0 + \\ldots + \\frac{k_0}{(m-1)!}x^{m-1} + + of `P` so that :math:`P^{(j)}(0) = k_{m-j-1}`. + + Parameters + ---------- + p : array_like or poly1d + Polynomial to integrate. + A sequence is interpreted as polynomial coefficients, see `poly1d`. + m : int, optional + Order of the antiderivative. (Default: 1) + k : list of `m` scalars or scalar, optional + Integration constants. They are given in the order of integration: + those corresponding to highest-order terms come first. + + If ``None`` (default), all constants are assumed to be zero. + If `m = 1`, a single scalar can be given instead of a list. + + See Also + -------- + polyder : derivative of a polynomial + poly1d.integ : equivalent method + + Examples + -------- + + The defining property of the antiderivative: + + >>> import numpy as np + + >>> p = np.poly1d([1,1,1]) + >>> P = np.polyint(p) + >>> P + poly1d([ 0.33333333, 0.5 , 1. , 0. ]) # may vary + >>> np.polyder(P) == p + True + + The integration constants default to zero, but can be specified: + + >>> P = np.polyint(p, 3) + >>> P(0) + 0.0 + >>> np.polyder(P)(0) + 0.0 + >>> np.polyder(P, 2)(0) + 0.0 + >>> P = np.polyint(p, 3, k=[6,5,3]) + >>> P + poly1d([ 0.01666667, 0.04166667, 0.16666667, 3. , 5. , 3. ]) # may vary + + Note that 3 = 6 / 2!, and that the constants are given in the order of + integrations. Constant of the highest-order polynomial term comes first: + + >>> np.polyder(P, 2)(0) + 6.0 + >>> np.polyder(P, 1)(0) + 5.0 + >>> P(0) + 3.0 + + """ + m = int(m) + if m < 0: + raise ValueError("Order of integral must be positive (see polyder)") + if k is None: + k = NX.zeros(m, float) + k = atleast_1d(k) + if len(k) == 1 and m > 1: + k = k[0] * NX.ones(m, float) + if len(k) < m: + raise ValueError( + "k must be a scalar or a rank-1 array of length 1 or >m.") + + truepoly = isinstance(p, poly1d) + p = NX.asarray(p) + if m == 0: + if truepoly: + return poly1d(p) + return p + else: + # Note: this must work also with object and integer arrays + y = NX.concatenate((p.__truediv__(NX.arange(len(p), 0, -1)), [k[0]])) + val = polyint(y, m - 1, k=k[1:]) + if truepoly: + return poly1d(val) + return val + + +def _polyder_dispatcher(p, m=None): + return (p,) + + +@array_function_dispatch(_polyder_dispatcher) +def polyder(p, m=1): + """ + Return the derivative of the specified order of a polynomial. + + .. note:: + This forms part of the old polynomial API. Since version 1.4, the + new polynomial API defined in `numpy.polynomial` is preferred. + A summary of the differences can be found in the + :doc:`transition guide `. + + Parameters + ---------- + p : poly1d or sequence + Polynomial to differentiate. + A sequence is interpreted as polynomial coefficients, see `poly1d`. + m : int, optional + Order of differentiation (default: 1) + + Returns + ------- + der : poly1d + A new polynomial representing the derivative. + + See Also + -------- + polyint : Anti-derivative of a polynomial. + poly1d : Class for one-dimensional polynomials. + + Examples + -------- + + The derivative of the polynomial :math:`x^3 + x^2 + x^1 + 1` is: + + >>> import numpy as np + + >>> p = np.poly1d([1,1,1,1]) + >>> p2 = np.polyder(p) + >>> p2 + poly1d([3, 2, 1]) + + which evaluates to: + + >>> p2(2.) + 17.0 + + We can verify this, approximating the derivative with + ``(f(x + h) - f(x))/h``: + + >>> (p(2. + 0.001) - p(2.)) / 0.001 + 17.007000999997857 + + The fourth-order derivative of a 3rd-order polynomial is zero: + + >>> np.polyder(p, 2) + poly1d([6, 2]) + >>> np.polyder(p, 3) + poly1d([6]) + >>> np.polyder(p, 4) + poly1d([0]) + + """ + m = int(m) + if m < 0: + raise ValueError("Order of derivative must be positive (see polyint)") + + truepoly = isinstance(p, poly1d) + p = NX.asarray(p) + n = len(p) - 1 + y = p[:-1] * NX.arange(n, 0, -1) + if m == 0: + val = p + else: + val = polyder(y, m - 1) + if truepoly: + val = poly1d(val) + return val + + +def _polyfit_dispatcher(x, y, deg, rcond=None, full=None, w=None, cov=None): + return (x, y, w) + + +@array_function_dispatch(_polyfit_dispatcher) +def polyfit(x, y, deg, rcond=None, full=False, w=None, cov=False): + """ + Least squares polynomial fit. + + .. note:: + This forms part of the old polynomial API. Since version 1.4, the + new polynomial API defined in `numpy.polynomial` is preferred. + A summary of the differences can be found in the + :doc:`transition guide `. + + Fit a polynomial ``p[0] * x**deg + ... + p[deg]`` of degree `deg` + to points `(x, y)`. Returns a vector of coefficients `p` that minimises + the squared error in the order `deg`, `deg-1`, ... `0`. + + The `Polynomial.fit ` class + method is recommended for new code as it is more stable numerically. See + the documentation of the method for more information. + + Parameters + ---------- + x : array_like, shape (M,) + x-coordinates of the M sample points ``(x[i], y[i])``. + y : array_like, shape (M,) or (M, K) + y-coordinates of the sample points. Several data sets of sample + points sharing the same x-coordinates can be fitted at once by + passing in a 2D-array that contains one dataset per column. + deg : int + Degree of the fitting polynomial + rcond : float, optional + Relative condition number of the fit. Singular values smaller than + this relative to the largest singular value will be ignored. The + default value is len(x)*eps, where eps is the relative precision of + the float type, about 2e-16 in most cases. + full : bool, optional + Switch determining nature of return value. When it is False (the + default) just the coefficients are returned, when True diagnostic + information from the singular value decomposition is also returned. + w : array_like, shape (M,), optional + Weights. If not None, the weight ``w[i]`` applies to the unsquared + residual ``y[i] - y_hat[i]`` at ``x[i]``. Ideally the weights are + chosen so that the errors of the products ``w[i]*y[i]`` all have the + same variance. When using inverse-variance weighting, use + ``w[i] = 1/sigma(y[i])``. The default value is None. + cov : bool or str, optional + If given and not `False`, return not just the estimate but also its + covariance matrix. By default, the covariance are scaled by + chi2/dof, where dof = M - (deg + 1), i.e., the weights are presumed + to be unreliable except in a relative sense and everything is scaled + such that the reduced chi2 is unity. This scaling is omitted if + ``cov='unscaled'``, as is relevant for the case that the weights are + w = 1/sigma, with sigma known to be a reliable estimate of the + uncertainty. + + Returns + ------- + p : ndarray, shape (deg + 1,) or (deg + 1, K) + Polynomial coefficients, highest power first. If `y` was 2-D, the + coefficients for `k`-th data set are in ``p[:,k]``. + + residuals, rank, singular_values, rcond + These values are only returned if ``full == True`` + + - residuals -- sum of squared residuals of the least squares fit + - rank -- the effective rank of the scaled Vandermonde + coefficient matrix + - singular_values -- singular values of the scaled Vandermonde + coefficient matrix + - rcond -- value of `rcond`. + + For more details, see `numpy.linalg.lstsq`. + + V : ndarray, shape (deg + 1, deg + 1) or (deg + 1, deg + 1, K) + Present only if ``full == False`` and ``cov == True``. The covariance + matrix of the polynomial coefficient estimates. The diagonal of + this matrix are the variance estimates for each coefficient. If y + is a 2-D array, then the covariance matrix for the `k`-th data set + are in ``V[:,:,k]`` + + + Warns + ----- + RankWarning + The rank of the coefficient matrix in the least-squares fit is + deficient. The warning is only raised if ``full == False``. + + The warnings can be turned off by + + >>> import warnings + >>> warnings.simplefilter('ignore', np.exceptions.RankWarning) + + See Also + -------- + polyval : Compute polynomial values. + linalg.lstsq : Computes a least-squares fit. + scipy.interpolate.UnivariateSpline : Computes spline fits. + + Notes + ----- + The solution minimizes the squared error + + .. math:: + E = \\sum_{j=0}^k |p(x_j) - y_j|^2 + + in the equations:: + + x[0]**n * p[0] + ... + x[0] * p[n-1] + p[n] = y[0] + x[1]**n * p[0] + ... + x[1] * p[n-1] + p[n] = y[1] + ... + x[k]**n * p[0] + ... + x[k] * p[n-1] + p[n] = y[k] + + The coefficient matrix of the coefficients `p` is a Vandermonde matrix. + + `polyfit` issues a `~exceptions.RankWarning` when the least-squares fit is + badly conditioned. This implies that the best fit is not well-defined due + to numerical error. The results may be improved by lowering the polynomial + degree or by replacing `x` by `x` - `x`.mean(). The `rcond` parameter + can also be set to a value smaller than its default, but the resulting + fit may be spurious: including contributions from the small singular + values can add numerical noise to the result. + + Note that fitting polynomial coefficients is inherently badly conditioned + when the degree of the polynomial is large or the interval of sample points + is badly centered. The quality of the fit should always be checked in these + cases. When polynomial fits are not satisfactory, splines may be a good + alternative. + + References + ---------- + .. [1] Wikipedia, "Curve fitting", + https://en.wikipedia.org/wiki/Curve_fitting + .. [2] Wikipedia, "Polynomial interpolation", + https://en.wikipedia.org/wiki/Polynomial_interpolation + + Examples + -------- + >>> import numpy as np + >>> import warnings + >>> x = np.array([0.0, 1.0, 2.0, 3.0, 4.0, 5.0]) + >>> y = np.array([0.0, 0.8, 0.9, 0.1, -0.8, -1.0]) + >>> z = np.polyfit(x, y, 3) + >>> z + array([ 0.08703704, -0.81349206, 1.69312169, -0.03968254]) # may vary + + It is convenient to use `poly1d` objects for dealing with polynomials: + + >>> p = np.poly1d(z) + >>> p(0.5) + 0.6143849206349179 # may vary + >>> p(3.5) + -0.34732142857143039 # may vary + >>> p(10) + 22.579365079365115 # may vary + + High-order polynomials may oscillate wildly: + + >>> with warnings.catch_warnings(): + ... warnings.simplefilter('ignore', np.exceptions.RankWarning) + ... p30 = np.poly1d(np.polyfit(x, y, 30)) + ... + >>> p30(4) + -0.80000000000000204 # may vary + >>> p30(5) + -0.99999999999999445 # may vary + >>> p30(4.5) + -0.10547061179440398 # may vary + + Illustration: + + >>> import matplotlib.pyplot as plt + >>> xp = np.linspace(-2, 6, 100) + >>> _ = plt.plot(x, y, '.', xp, p(xp), '-', xp, p30(xp), '--') + >>> plt.ylim(-2,2) + (-2, 2) + >>> plt.show() + + """ + order = int(deg) + 1 + x = NX.asarray(x) + 0.0 + y = NX.asarray(y) + 0.0 + + # check arguments. + if deg < 0: + raise ValueError("expected deg >= 0") + if x.ndim != 1: + raise TypeError("expected 1D vector for x") + if x.size == 0: + raise TypeError("expected non-empty vector for x") + if y.ndim < 1 or y.ndim > 2: + raise TypeError("expected 1D or 2D array for y") + if x.shape[0] != y.shape[0]: + raise TypeError("expected x and y to have same length") + + # set rcond + if rcond is None: + rcond = len(x) * finfo(x.dtype).eps + + # set up least squares equation for powers of x + lhs = vander(x, order) + rhs = y + + # apply weighting + if w is not None: + w = NX.asarray(w) + 0.0 + if w.ndim != 1: + raise TypeError("expected a 1-d array for weights") + if w.shape[0] != y.shape[0]: + raise TypeError("expected w and y to have the same length") + lhs *= w[:, NX.newaxis] + if rhs.ndim == 2: + rhs *= w[:, NX.newaxis] + else: + rhs *= w + + # scale lhs to improve condition number and solve + scale = NX.sqrt((lhs * lhs).sum(axis=0)) + lhs /= scale + c, resids, rank, s = lstsq(lhs, rhs, rcond) + c = (c.T / scale).T # broadcast scale coefficients + + # warn on rank reduction, which indicates an ill conditioned matrix + if rank != order and not full: + msg = "Polyfit may be poorly conditioned" + warnings.warn(msg, RankWarning, stacklevel=2) + + if full: + return c, resids, rank, s, rcond + elif cov: + Vbase = inv(dot(lhs.T, lhs)) + Vbase /= NX.outer(scale, scale) + if cov == "unscaled": + fac = 1 + else: + if len(x) <= order: + raise ValueError("the number of data points must exceed order " + "to scale the covariance matrix") + # note, this used to be: fac = resids / (len(x) - order - 2.0) + # it was decided that the "- 2" (originally justified by "Bayesian + # uncertainty analysis") is not what the user expects + # (see gh-11196 and gh-11197) + fac = resids / (len(x) - order) + if y.ndim == 1: + return c, Vbase * fac + else: + return c, Vbase[:, :, NX.newaxis] * fac + else: + return c + + +def _polyval_dispatcher(p, x): + return (p, x) + + +@array_function_dispatch(_polyval_dispatcher) +def polyval(p, x): + """ + Evaluate a polynomial at specific values. + + .. note:: + This forms part of the old polynomial API. Since version 1.4, the + new polynomial API defined in `numpy.polynomial` is preferred. + A summary of the differences can be found in the + :doc:`transition guide `. + + If `p` is of length N, this function returns the value:: + + p[0]*x**(N-1) + p[1]*x**(N-2) + ... + p[N-2]*x + p[N-1] + + If `x` is a sequence, then ``p(x)`` is returned for each element of ``x``. + If `x` is another polynomial then the composite polynomial ``p(x(t))`` + is returned. + + Parameters + ---------- + p : array_like or poly1d object + 1D array of polynomial coefficients (including coefficients equal + to zero) from highest degree to the constant term, or an + instance of poly1d. + x : array_like or poly1d object + A number, an array of numbers, or an instance of poly1d, at + which to evaluate `p`. + + Returns + ------- + values : ndarray or poly1d + If `x` is a poly1d instance, the result is the composition of the two + polynomials, i.e., `x` is "substituted" in `p` and the simplified + result is returned. In addition, the type of `x` - array_like or + poly1d - governs the type of the output: `x` array_like => `values` + array_like, `x` a poly1d object => `values` is also. + + See Also + -------- + poly1d: A polynomial class. + + Notes + ----- + Horner's scheme [1]_ is used to evaluate the polynomial. Even so, + for polynomials of high degree the values may be inaccurate due to + rounding errors. Use carefully. + + If `x` is a subtype of `ndarray` the return value will be of the same type. + + References + ---------- + .. [1] I. N. Bronshtein, K. A. Semendyayev, and K. A. Hirsch (Eng. + trans. Ed.), *Handbook of Mathematics*, New York, Van Nostrand + Reinhold Co., 1985, pg. 720. + + Examples + -------- + >>> import numpy as np + >>> np.polyval([3,0,1], 5) # 3 * 5**2 + 0 * 5**1 + 1 + 76 + >>> np.polyval([3,0,1], np.poly1d(5)) + poly1d([76]) + >>> np.polyval(np.poly1d([3,0,1]), 5) + 76 + >>> np.polyval(np.poly1d([3,0,1]), np.poly1d(5)) + poly1d([76]) + + """ + p = NX.asarray(p) + if isinstance(x, poly1d): + y = 0 + else: + x = NX.asanyarray(x) + y = NX.zeros_like(x) + for pv in p: + y = y * x + pv + return y + + +def _binary_op_dispatcher(a1, a2): + return (a1, a2) + + +@array_function_dispatch(_binary_op_dispatcher) +def polyadd(a1, a2): + """ + Find the sum of two polynomials. + + .. note:: + This forms part of the old polynomial API. Since version 1.4, the + new polynomial API defined in `numpy.polynomial` is preferred. + A summary of the differences can be found in the + :doc:`transition guide `. + + Returns the polynomial resulting from the sum of two input polynomials. + Each input must be either a poly1d object or a 1D sequence of polynomial + coefficients, from highest to lowest degree. + + Parameters + ---------- + a1, a2 : array_like or poly1d object + Input polynomials. + + Returns + ------- + out : ndarray or poly1d object + The sum of the inputs. If either input is a poly1d object, then the + output is also a poly1d object. Otherwise, it is a 1D array of + polynomial coefficients from highest to lowest degree. + + See Also + -------- + poly1d : A one-dimensional polynomial class. + poly, polyadd, polyder, polydiv, polyfit, polyint, polysub, polyval + + Examples + -------- + >>> import numpy as np + >>> np.polyadd([1, 2], [9, 5, 4]) + array([9, 6, 6]) + + Using poly1d objects: + + >>> p1 = np.poly1d([1, 2]) + >>> p2 = np.poly1d([9, 5, 4]) + >>> print(p1) + 1 x + 2 + >>> print(p2) + 2 + 9 x + 5 x + 4 + >>> print(np.polyadd(p1, p2)) + 2 + 9 x + 6 x + 6 + + """ + truepoly = (isinstance(a1, poly1d) or isinstance(a2, poly1d)) + a1 = atleast_1d(a1) + a2 = atleast_1d(a2) + diff = len(a2) - len(a1) + if diff == 0: + val = a1 + a2 + elif diff > 0: + zr = NX.zeros(diff, a1.dtype) + val = NX.concatenate((zr, a1)) + a2 + else: + zr = NX.zeros(abs(diff), a2.dtype) + val = a1 + NX.concatenate((zr, a2)) + if truepoly: + val = poly1d(val) + return val + + +@array_function_dispatch(_binary_op_dispatcher) +def polysub(a1, a2): + """ + Difference (subtraction) of two polynomials. + + .. note:: + This forms part of the old polynomial API. Since version 1.4, the + new polynomial API defined in `numpy.polynomial` is preferred. + A summary of the differences can be found in the + :doc:`transition guide `. + + Given two polynomials `a1` and `a2`, returns ``a1 - a2``. + `a1` and `a2` can be either array_like sequences of the polynomials' + coefficients (including coefficients equal to zero), or `poly1d` objects. + + Parameters + ---------- + a1, a2 : array_like or poly1d + Minuend and subtrahend polynomials, respectively. + + Returns + ------- + out : ndarray or poly1d + Array or `poly1d` object of the difference polynomial's coefficients. + + See Also + -------- + polyval, polydiv, polymul, polyadd + + Examples + -------- + + .. math:: (2 x^2 + 10 x - 2) - (3 x^2 + 10 x -4) = (-x^2 + 2) + + >>> import numpy as np + + >>> np.polysub([2, 10, -2], [3, 10, -4]) + array([-1, 0, 2]) + + """ + truepoly = (isinstance(a1, poly1d) or isinstance(a2, poly1d)) + a1 = atleast_1d(a1) + a2 = atleast_1d(a2) + diff = len(a2) - len(a1) + if diff == 0: + val = a1 - a2 + elif diff > 0: + zr = NX.zeros(diff, a1.dtype) + val = NX.concatenate((zr, a1)) - a2 + else: + zr = NX.zeros(abs(diff), a2.dtype) + val = a1 - NX.concatenate((zr, a2)) + if truepoly: + val = poly1d(val) + return val + + +@array_function_dispatch(_binary_op_dispatcher) +def polymul(a1, a2): + """ + Find the product of two polynomials. + + .. note:: + This forms part of the old polynomial API. Since version 1.4, the + new polynomial API defined in `numpy.polynomial` is preferred. + A summary of the differences can be found in the + :doc:`transition guide `. + + Finds the polynomial resulting from the multiplication of the two input + polynomials. Each input must be either a poly1d object or a 1D sequence + of polynomial coefficients, from highest to lowest degree. + + Parameters + ---------- + a1, a2 : array_like or poly1d object + Input polynomials. + + Returns + ------- + out : ndarray or poly1d object + The polynomial resulting from the multiplication of the inputs. If + either inputs is a poly1d object, then the output is also a poly1d + object. Otherwise, it is a 1D array of polynomial coefficients from + highest to lowest degree. + + See Also + -------- + poly1d : A one-dimensional polynomial class. + poly, polyadd, polyder, polydiv, polyfit, polyint, polysub, polyval + convolve : Array convolution. Same output as polymul, but has parameter + for overlap mode. + + Examples + -------- + >>> import numpy as np + >>> np.polymul([1, 2, 3], [9, 5, 1]) + array([ 9, 23, 38, 17, 3]) + + Using poly1d objects: + + >>> p1 = np.poly1d([1, 2, 3]) + >>> p2 = np.poly1d([9, 5, 1]) + >>> print(p1) + 2 + 1 x + 2 x + 3 + >>> print(p2) + 2 + 9 x + 5 x + 1 + >>> print(np.polymul(p1, p2)) + 4 3 2 + 9 x + 23 x + 38 x + 17 x + 3 + + """ + truepoly = (isinstance(a1, poly1d) or isinstance(a2, poly1d)) + a1, a2 = poly1d(a1), poly1d(a2) + val = NX.convolve(a1, a2) + if truepoly: + val = poly1d(val) + return val + + +def _polydiv_dispatcher(u, v): + return (u, v) + + +@array_function_dispatch(_polydiv_dispatcher) +def polydiv(u, v): + """ + Returns the quotient and remainder of polynomial division. + + .. note:: + This forms part of the old polynomial API. Since version 1.4, the + new polynomial API defined in `numpy.polynomial` is preferred. + A summary of the differences can be found in the + :doc:`transition guide `. + + The input arrays are the coefficients (including any coefficients + equal to zero) of the "numerator" (dividend) and "denominator" + (divisor) polynomials, respectively. + + Parameters + ---------- + u : array_like or poly1d + Dividend polynomial's coefficients. + + v : array_like or poly1d + Divisor polynomial's coefficients. + + Returns + ------- + q : ndarray + Coefficients, including those equal to zero, of the quotient. + r : ndarray + Coefficients, including those equal to zero, of the remainder. + + See Also + -------- + poly, polyadd, polyder, polydiv, polyfit, polyint, polymul, polysub + polyval + + Notes + ----- + Both `u` and `v` must be 0-d or 1-d (ndim = 0 or 1), but `u.ndim` need + not equal `v.ndim`. In other words, all four possible combinations - + ``u.ndim = v.ndim = 0``, ``u.ndim = v.ndim = 1``, + ``u.ndim = 1, v.ndim = 0``, and ``u.ndim = 0, v.ndim = 1`` - work. + + Examples + -------- + + .. math:: \\frac{3x^2 + 5x + 2}{2x + 1} = 1.5x + 1.75, remainder 0.25 + + >>> import numpy as np + + >>> x = np.array([3.0, 5.0, 2.0]) + >>> y = np.array([2.0, 1.0]) + >>> np.polydiv(x, y) + (array([1.5 , 1.75]), array([0.25])) + + """ + truepoly = (isinstance(u, poly1d) or isinstance(v, poly1d)) + u = atleast_1d(u) + 0.0 + v = atleast_1d(v) + 0.0 + # w has the common type + w = u[0] + v[0] + m = len(u) - 1 + n = len(v) - 1 + scale = 1. / v[0] + q = NX.zeros((max(m - n + 1, 1),), w.dtype) + r = u.astype(w.dtype) + for k in range(m - n + 1): + d = scale * r[k] + q[k] = d + r[k:k + n + 1] -= d * v + while NX.allclose(r[0], 0, rtol=1e-14) and (r.shape[-1] > 1): + r = r[1:] + if truepoly: + return poly1d(q), poly1d(r) + return q, r + + +_poly_mat = re.compile(r"\*\*([0-9]*)") +def _raise_power(astr, wrap=70): + n = 0 + line1 = '' + line2 = '' + output = ' ' + while True: + mat = _poly_mat.search(astr, n) + if mat is None: + break + span = mat.span() + power = mat.groups()[0] + partstr = astr[n:span[0]] + n = span[1] + toadd2 = partstr + ' ' * (len(power) - 1) + toadd1 = ' ' * (len(partstr) - 1) + power + if ((len(line2) + len(toadd2) > wrap) or + (len(line1) + len(toadd1) > wrap)): + output += line1 + "\n" + line2 + "\n " + line1 = toadd1 + line2 = toadd2 + else: + line2 += partstr + ' ' * (len(power) - 1) + line1 += ' ' * (len(partstr) - 1) + power + output += line1 + "\n" + line2 + return output + astr[n:] + + +@set_module('numpy') +class poly1d: + """ + A one-dimensional polynomial class. + + .. note:: + This forms part of the old polynomial API. Since version 1.4, the + new polynomial API defined in `numpy.polynomial` is preferred. + A summary of the differences can be found in the + :doc:`transition guide `. + + A convenience class, used to encapsulate "natural" operations on + polynomials so that said operations may take on their customary + form in code (see Examples). + + Parameters + ---------- + c_or_r : array_like + The polynomial's coefficients, in decreasing powers, or if + the value of the second parameter is True, the polynomial's + roots (values where the polynomial evaluates to 0). For example, + ``poly1d([1, 2, 3])`` returns an object that represents + :math:`x^2 + 2x + 3`, whereas ``poly1d([1, 2, 3], True)`` returns + one that represents :math:`(x-1)(x-2)(x-3) = x^3 - 6x^2 + 11x -6`. + r : bool, optional + If True, `c_or_r` specifies the polynomial's roots; the default + is False. + variable : str, optional + Changes the variable used when printing `p` from `x` to `variable` + (see Examples). + + Examples + -------- + >>> import numpy as np + + Construct the polynomial :math:`x^2 + 2x + 3`: + + >>> import numpy as np + + >>> p = np.poly1d([1, 2, 3]) + >>> print(np.poly1d(p)) + 2 + 1 x + 2 x + 3 + + Evaluate the polynomial at :math:`x = 0.5`: + + >>> p(0.5) + 4.25 + + Find the roots: + + >>> p.r + array([-1.+1.41421356j, -1.-1.41421356j]) + >>> p(p.r) + array([ -4.44089210e-16+0.j, -4.44089210e-16+0.j]) # may vary + + These numbers in the previous line represent (0, 0) to machine precision + + Show the coefficients: + + >>> p.c + array([1, 2, 3]) + + Display the order (the leading zero-coefficients are removed): + + >>> p.order + 2 + + Show the coefficient of the k-th power in the polynomial + (which is equivalent to ``p.c[-(i+1)]``): + + >>> p[1] + 2 + + Polynomials can be added, subtracted, multiplied, and divided + (returns quotient and remainder): + + >>> p * p + poly1d([ 1, 4, 10, 12, 9]) + + >>> (p**3 + 4) / p + (poly1d([ 1., 4., 10., 12., 9.]), poly1d([4.])) + + ``asarray(p)`` gives the coefficient array, so polynomials can be + used in all functions that accept arrays: + + >>> p**2 # square of polynomial + poly1d([ 1, 4, 10, 12, 9]) + + >>> np.square(p) # square of individual coefficients + array([1, 4, 9]) + + The variable used in the string representation of `p` can be modified, + using the `variable` parameter: + + >>> p = np.poly1d([1,2,3], variable='z') + >>> print(p) + 2 + 1 z + 2 z + 3 + + Construct a polynomial from its roots: + + >>> np.poly1d([1, 2], True) + poly1d([ 1., -3., 2.]) + + This is the same polynomial as obtained by: + + >>> np.poly1d([1, -1]) * np.poly1d([1, -2]) + poly1d([ 1, -3, 2]) + + """ + __hash__ = None + + @property + def coeffs(self): + """ The polynomial coefficients """ + return self._coeffs + + @coeffs.setter + def coeffs(self, value): + # allowing this makes p.coeffs *= 2 legal + if value is not self._coeffs: + raise AttributeError("Cannot set attribute") + + @property + def variable(self): + """ The name of the polynomial variable """ + return self._variable + + # calculated attributes + @property + def order(self): + """ The order or degree of the polynomial """ + return len(self._coeffs) - 1 + + @property + def roots(self): + """ The roots of the polynomial, where self(x) == 0 """ + return roots(self._coeffs) + + # our internal _coeffs property need to be backed by __dict__['coeffs'] for + # scipy to work correctly. + @property + def _coeffs(self): + return self.__dict__['coeffs'] + + @_coeffs.setter + def _coeffs(self, coeffs): + self.__dict__['coeffs'] = coeffs + + # alias attributes + r = roots + c = coef = coefficients = coeffs + o = order + + def __init__(self, c_or_r, r=False, variable=None): + if isinstance(c_or_r, poly1d): + self._variable = c_or_r._variable + self._coeffs = c_or_r._coeffs + + if set(c_or_r.__dict__) - set(self.__dict__): + msg = ("In the future extra properties will not be copied " + "across when constructing one poly1d from another") + warnings.warn(msg, FutureWarning, stacklevel=2) + self.__dict__.update(c_or_r.__dict__) + + if variable is not None: + self._variable = variable + return + if r: + c_or_r = poly(c_or_r) + c_or_r = atleast_1d(c_or_r) + if c_or_r.ndim > 1: + raise ValueError("Polynomial must be 1d only.") + c_or_r = trim_zeros(c_or_r, trim='f') + if len(c_or_r) == 0: + c_or_r = NX.array([0], dtype=c_or_r.dtype) + self._coeffs = c_or_r + if variable is None: + variable = 'x' + self._variable = variable + + def __array__(self, t=None, copy=None): + if t: + return NX.asarray(self.coeffs, t, copy=copy) + else: + return NX.asarray(self.coeffs, copy=copy) + + def __repr__(self): + vals = repr(self.coeffs) + vals = vals[6:-1] + return f"poly1d({vals})" + + def __len__(self): + return self.order + + def __str__(self): + thestr = "0" + var = self.variable + + # Remove leading zeros + coeffs = self.coeffs[NX.logical_or.accumulate(self.coeffs != 0)] + N = len(coeffs) - 1 + + def fmt_float(q): + s = f'{q:.4g}' + s = s.removesuffix('.0000') + return s + + for k, coeff in enumerate(coeffs): + if not iscomplex(coeff): + coefstr = fmt_float(real(coeff)) + elif real(coeff) == 0: + coefstr = f'{fmt_float(imag(coeff))}j' + else: + coefstr = f'({fmt_float(real(coeff))} + {fmt_float(imag(coeff))}j)' + + power = (N - k) + if power == 0: + if coefstr != '0': + newstr = f'{coefstr}' + elif k == 0: + newstr = '0' + else: + newstr = '' + elif power == 1: + if coefstr == '0': + newstr = '' + elif coefstr == 'b': + newstr = var + else: + newstr = f'{coefstr} {var}' + elif coefstr == '0': + newstr = '' + elif coefstr == 'b': + newstr = '%s**%d' % (var, power,) + else: + newstr = '%s %s**%d' % (coefstr, var, power) + + if k > 0: + if newstr != '': + if newstr.startswith('-'): + thestr = f"{thestr} - {newstr[1:]}" + else: + thestr = f"{thestr} + {newstr}" + else: + thestr = newstr + return _raise_power(thestr) + + def __call__(self, val): + return polyval(self.coeffs, val) + + def __neg__(self): + return poly1d(-self.coeffs) + + def __pos__(self): + return self + + def __mul__(self, other): + if isscalar(other): + return poly1d(self.coeffs * other) + else: + other = poly1d(other) + return poly1d(polymul(self.coeffs, other.coeffs)) + + def __rmul__(self, other): + if isscalar(other): + return poly1d(other * self.coeffs) + else: + other = poly1d(other) + return poly1d(polymul(self.coeffs, other.coeffs)) + + def __add__(self, other): + other = poly1d(other) + return poly1d(polyadd(self.coeffs, other.coeffs)) + + def __radd__(self, other): + other = poly1d(other) + return poly1d(polyadd(self.coeffs, other.coeffs)) + + def __pow__(self, val): + if not isscalar(val) or int(val) != val or val < 0: + raise ValueError("Power to non-negative integers only.") + res = [1] + for _ in range(val): + res = polymul(self.coeffs, res) + return poly1d(res) + + def __sub__(self, other): + other = poly1d(other) + return poly1d(polysub(self.coeffs, other.coeffs)) + + def __rsub__(self, other): + other = poly1d(other) + return poly1d(polysub(other.coeffs, self.coeffs)) + + def __truediv__(self, other): + if isscalar(other): + return poly1d(self.coeffs / other) + else: + other = poly1d(other) + return polydiv(self, other) + + def __rtruediv__(self, other): + if isscalar(other): + return poly1d(other / self.coeffs) + else: + other = poly1d(other) + return polydiv(other, self) + + def __eq__(self, other): + if not isinstance(other, poly1d): + return NotImplemented + if self.coeffs.shape != other.coeffs.shape: + return False + return (self.coeffs == other.coeffs).all() + + def __ne__(self, other): + if not isinstance(other, poly1d): + return NotImplemented + return not self.__eq__(other) + + def __getitem__(self, val): + ind = self.order - val + if val > self.order: + return self.coeffs.dtype.type(0) + if val < 0: + return self.coeffs.dtype.type(0) + return self.coeffs[ind] + + def __setitem__(self, key, val): + ind = self.order - key + if key < 0: + raise ValueError("Does not support negative powers.") + if key > self.order: + zr = NX.zeros(key - self.order, self.coeffs.dtype) + self._coeffs = NX.concatenate((zr, self.coeffs)) + ind = 0 + self._coeffs[ind] = val + + def __iter__(self): + return iter(self.coeffs) + + def integ(self, m=1, k=0): + """ + Return an antiderivative (indefinite integral) of this polynomial. + + Refer to `polyint` for full documentation. + + See Also + -------- + polyint : equivalent function + + """ + return poly1d(polyint(self.coeffs, m=m, k=k)) + + def deriv(self, m=1): + """ + Return a derivative of this polynomial. + + Refer to `polyder` for full documentation. + + See Also + -------- + polyder : equivalent function + + """ + return poly1d(polyder(self.coeffs, m=m)) + +# Stuff to do on module import + + +warnings.simplefilter('always', RankWarning) diff --git a/python/user_packages/Python313/site-packages/numpy/lib/_polynomial_impl.pyi b/python/user_packages/Python313/site-packages/numpy/lib/_polynomial_impl.pyi new file mode 100644 index 0000000000000000000000000000000000000000..2d8f2647ea6be904bc3aebdb070fbbe893655a18 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/lib/_polynomial_impl.pyi @@ -0,0 +1,338 @@ +from typing import ( + Any, + Literal as L, + NoReturn, + SupportsIndex, + SupportsInt, + TypeAlias, + TypeVar, + overload, +) + +import numpy as np +from numpy import ( + complex128, + complexfloating, + float64, + floating, + int32, + int64, + object_, + poly1d, + signedinteger, + unsignedinteger, +) +from numpy._typing import ( + ArrayLike, + NDArray, + _ArrayLikeBool_co, + _ArrayLikeComplex_co, + _ArrayLikeFloat_co, + _ArrayLikeInt_co, + _ArrayLikeObject_co, + _ArrayLikeUInt_co, +) + +_T = TypeVar("_T") + +_2Tup: TypeAlias = tuple[_T, _T] +_5Tup: TypeAlias = tuple[ + _T, + NDArray[float64], + NDArray[int32], + NDArray[float64], + NDArray[float64], +] + +__all__ = [ + "poly", + "roots", + "polyint", + "polyder", + "polyadd", + "polysub", + "polymul", + "polydiv", + "polyval", + "poly1d", + "polyfit", +] + +def poly(seq_of_zeros: ArrayLike) -> NDArray[floating]: ... + +# Returns either a float or complex array depending on the input values. +# See `np.linalg.eigvals`. +def roots(p: ArrayLike) -> NDArray[complexfloating] | NDArray[floating]: ... + +@overload +def polyint( + p: poly1d, + m: SupportsInt | SupportsIndex = 1, + k: _ArrayLikeComplex_co | _ArrayLikeObject_co | None = None, +) -> poly1d: ... +@overload +def polyint( + p: _ArrayLikeFloat_co, + m: SupportsInt | SupportsIndex = 1, + k: _ArrayLikeFloat_co | None = None, +) -> NDArray[floating]: ... +@overload +def polyint( + p: _ArrayLikeComplex_co, + m: SupportsInt | SupportsIndex = 1, + k: _ArrayLikeComplex_co | None = None, +) -> NDArray[complexfloating]: ... +@overload +def polyint( + p: _ArrayLikeObject_co, + m: SupportsInt | SupportsIndex = 1, + k: _ArrayLikeObject_co | None = None, +) -> NDArray[object_]: ... + +@overload +def polyder( + p: poly1d, + m: SupportsInt | SupportsIndex = 1, +) -> poly1d: ... +@overload +def polyder( + p: _ArrayLikeFloat_co, + m: SupportsInt | SupportsIndex = 1, +) -> NDArray[floating]: ... +@overload +def polyder( + p: _ArrayLikeComplex_co, + m: SupportsInt | SupportsIndex = 1, +) -> NDArray[complexfloating]: ... +@overload +def polyder( + p: _ArrayLikeObject_co, + m: SupportsInt | SupportsIndex = 1, +) -> NDArray[object_]: ... + +@overload +def polyfit( + x: _ArrayLikeFloat_co, + y: _ArrayLikeFloat_co, + deg: SupportsIndex | SupportsInt, + rcond: float | None = None, + full: L[False] = False, + w: _ArrayLikeFloat_co | None = None, + cov: L[False] = False, +) -> NDArray[float64]: ... +@overload +def polyfit( + x: _ArrayLikeComplex_co, + y: _ArrayLikeComplex_co, + deg: SupportsIndex | SupportsInt, + rcond: float | None = None, + full: L[False] = False, + w: _ArrayLikeFloat_co | None = None, + cov: L[False] = False, +) -> NDArray[complex128]: ... +@overload +def polyfit( + x: _ArrayLikeFloat_co, + y: _ArrayLikeFloat_co, + deg: SupportsIndex | SupportsInt, + rcond: float | None = None, + full: L[False] = False, + w: _ArrayLikeFloat_co | None = None, + *, + cov: L[True, "unscaled"], +) -> _2Tup[NDArray[float64]]: ... +@overload +def polyfit( + x: _ArrayLikeComplex_co, + y: _ArrayLikeComplex_co, + deg: SupportsIndex | SupportsInt, + rcond: float | None = None, + full: L[False] = False, + w: _ArrayLikeFloat_co | None = None, + *, + cov: L[True, "unscaled"], +) -> _2Tup[NDArray[complex128]]: ... +@overload +def polyfit( + x: _ArrayLikeFloat_co, + y: _ArrayLikeFloat_co, + deg: SupportsIndex | SupportsInt, + rcond: float | None, + full: L[True], + w: _ArrayLikeFloat_co | None = None, + cov: bool | L["unscaled"] = False, +) -> _5Tup[NDArray[float64]]: ... +@overload +def polyfit( + x: _ArrayLikeFloat_co, + y: _ArrayLikeFloat_co, + deg: SupportsIndex | SupportsInt, + rcond: float | None = None, + *, + full: L[True], + w: _ArrayLikeFloat_co | None = None, + cov: bool | L["unscaled"] = False, +) -> _5Tup[NDArray[float64]]: ... +@overload +def polyfit( + x: _ArrayLikeComplex_co, + y: _ArrayLikeComplex_co, + deg: SupportsIndex | SupportsInt, + rcond: float | None, + full: L[True], + w: _ArrayLikeFloat_co | None = None, + cov: bool | L["unscaled"] = False, +) -> _5Tup[NDArray[complex128]]: ... +@overload +def polyfit( + x: _ArrayLikeComplex_co, + y: _ArrayLikeComplex_co, + deg: SupportsIndex | SupportsInt, + rcond: float | None = None, + *, + full: L[True], + w: _ArrayLikeFloat_co | None = None, + cov: bool | L["unscaled"] = False, +) -> _5Tup[NDArray[complex128]]: ... + +@overload +def polyval( + p: _ArrayLikeBool_co, + x: _ArrayLikeBool_co, +) -> NDArray[int64]: ... +@overload +def polyval( + p: _ArrayLikeUInt_co, + x: _ArrayLikeUInt_co, +) -> NDArray[unsignedinteger]: ... +@overload +def polyval( + p: _ArrayLikeInt_co, + x: _ArrayLikeInt_co, +) -> NDArray[signedinteger]: ... +@overload +def polyval( + p: _ArrayLikeFloat_co, + x: _ArrayLikeFloat_co, +) -> NDArray[floating]: ... +@overload +def polyval( + p: _ArrayLikeComplex_co, + x: _ArrayLikeComplex_co, +) -> NDArray[complexfloating]: ... +@overload +def polyval( + p: _ArrayLikeObject_co, + x: _ArrayLikeObject_co, +) -> NDArray[object_]: ... + +@overload +def polyadd( + a1: poly1d, + a2: _ArrayLikeComplex_co | _ArrayLikeObject_co, +) -> poly1d: ... +@overload +def polyadd( + a1: _ArrayLikeComplex_co | _ArrayLikeObject_co, + a2: poly1d, +) -> poly1d: ... +@overload +def polyadd( + a1: _ArrayLikeBool_co, + a2: _ArrayLikeBool_co, +) -> NDArray[np.bool]: ... +@overload +def polyadd( + a1: _ArrayLikeUInt_co, + a2: _ArrayLikeUInt_co, +) -> NDArray[unsignedinteger]: ... +@overload +def polyadd( + a1: _ArrayLikeInt_co, + a2: _ArrayLikeInt_co, +) -> NDArray[signedinteger]: ... +@overload +def polyadd( + a1: _ArrayLikeFloat_co, + a2: _ArrayLikeFloat_co, +) -> NDArray[floating]: ... +@overload +def polyadd( + a1: _ArrayLikeComplex_co, + a2: _ArrayLikeComplex_co, +) -> NDArray[complexfloating]: ... +@overload +def polyadd( + a1: _ArrayLikeObject_co, + a2: _ArrayLikeObject_co, +) -> NDArray[object_]: ... + +@overload +def polysub( + a1: poly1d, + a2: _ArrayLikeComplex_co | _ArrayLikeObject_co, +) -> poly1d: ... +@overload +def polysub( + a1: _ArrayLikeComplex_co | _ArrayLikeObject_co, + a2: poly1d, +) -> poly1d: ... +@overload +def polysub( + a1: _ArrayLikeBool_co, + a2: _ArrayLikeBool_co, +) -> NoReturn: ... +@overload +def polysub( + a1: _ArrayLikeUInt_co, + a2: _ArrayLikeUInt_co, +) -> NDArray[unsignedinteger]: ... +@overload +def polysub( + a1: _ArrayLikeInt_co, + a2: _ArrayLikeInt_co, +) -> NDArray[signedinteger]: ... +@overload +def polysub( + a1: _ArrayLikeFloat_co, + a2: _ArrayLikeFloat_co, +) -> NDArray[floating]: ... +@overload +def polysub( + a1: _ArrayLikeComplex_co, + a2: _ArrayLikeComplex_co, +) -> NDArray[complexfloating]: ... +@overload +def polysub( + a1: _ArrayLikeObject_co, + a2: _ArrayLikeObject_co, +) -> NDArray[object_]: ... + +# NOTE: Not an alias, but they do have the same signature (that we can reuse) +polymul = polyadd + +@overload +def polydiv( + u: poly1d, + v: _ArrayLikeComplex_co | _ArrayLikeObject_co, +) -> _2Tup[poly1d]: ... +@overload +def polydiv( + u: _ArrayLikeComplex_co | _ArrayLikeObject_co, + v: poly1d, +) -> _2Tup[poly1d]: ... +@overload +def polydiv( + u: _ArrayLikeFloat_co, + v: _ArrayLikeFloat_co, +) -> _2Tup[NDArray[floating]]: ... +@overload +def polydiv( + u: _ArrayLikeComplex_co, + v: _ArrayLikeComplex_co, +) -> _2Tup[NDArray[complexfloating]]: ... +@overload +def polydiv( + u: _ArrayLikeObject_co, + v: _ArrayLikeObject_co, +) -> _2Tup[NDArray[Any]]: ... diff --git a/python/user_packages/Python313/site-packages/numpy/lib/_scimath_impl.py b/python/user_packages/Python313/site-packages/numpy/lib/_scimath_impl.py new file mode 100644 index 0000000000000000000000000000000000000000..b90ce9a33dd8ec959c23c9c78aee480787a17412 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/lib/_scimath_impl.py @@ -0,0 +1,642 @@ +""" +Wrapper functions to more user-friendly calling of certain math functions +whose output data-type is different than the input data-type in certain +domains of the input. + +For example, for functions like `log` with branch cuts, the versions in this +module provide the mathematically valid answers in the complex plane:: + + >>> import math + >>> np.emath.log(-math.exp(1)) == (1+1j*math.pi) + True + +Similarly, `sqrt`, other base logarithms, `power` and trig functions are +correctly handled. See their respective docstrings for specific examples. + +""" +import numpy._core.numeric as nx +import numpy._core.numerictypes as nt +from numpy._core.numeric import any, asarray +from numpy._core.overrides import array_function_dispatch, set_module +from numpy.lib._type_check_impl import isreal + +__all__ = [ + 'sqrt', 'log', 'log2', 'logn', 'log10', 'power', 'arccos', 'arcsin', + 'arctanh' + ] + + +_ln2 = nx.log(2.0) + + +def _tocomplex(arr): + """Convert its input `arr` to a complex array. + + The input is returned as a complex array of the smallest type that will fit + the original data: types like single, byte, short, etc. become csingle, + while others become cdouble. + + A copy of the input is always made. + + Parameters + ---------- + arr : array + + Returns + ------- + array + An array with the same input data as the input but in complex form. + + Examples + -------- + >>> import numpy as np + + First, consider an input of type short: + + >>> a = np.array([1,2,3],np.short) + + >>> ac = np.lib.scimath._tocomplex(a); ac + array([1.+0.j, 2.+0.j, 3.+0.j], dtype=complex64) + + >>> ac.dtype + dtype('complex64') + + If the input is of type double, the output is correspondingly of the + complex double type as well: + + >>> b = np.array([1,2,3],np.double) + + >>> bc = np.lib.scimath._tocomplex(b); bc + array([1.+0.j, 2.+0.j, 3.+0.j]) + + >>> bc.dtype + dtype('complex128') + + Note that even if the input was complex to begin with, a copy is still + made, since the astype() method always copies: + + >>> c = np.array([1,2,3],np.csingle) + + >>> cc = np.lib.scimath._tocomplex(c); cc + array([1.+0.j, 2.+0.j, 3.+0.j], dtype=complex64) + + >>> c *= 2; c + array([2.+0.j, 4.+0.j, 6.+0.j], dtype=complex64) + + >>> cc + array([1.+0.j, 2.+0.j, 3.+0.j], dtype=complex64) + """ + if issubclass(arr.dtype.type, (nt.single, nt.byte, nt.short, nt.ubyte, + nt.ushort, nt.csingle)): + return arr.astype(nt.csingle) + else: + return arr.astype(nt.cdouble) + + +def _fix_real_lt_zero(x): + """Convert `x` to complex if it has real, negative components. + + Otherwise, output is just the array version of the input (via asarray). + + Parameters + ---------- + x : array_like + + Returns + ------- + array + + Examples + -------- + >>> import numpy as np + >>> np.lib.scimath._fix_real_lt_zero([1,2]) + array([1, 2]) + + >>> np.lib.scimath._fix_real_lt_zero([-1,2]) + array([-1.+0.j, 2.+0.j]) + + """ + x = asarray(x) + if any(isreal(x) & (x < 0)): + x = _tocomplex(x) + return x + + +def _fix_int_lt_zero(x): + """Convert `x` to double if it has real, negative components. + + Otherwise, output is just the array version of the input (via asarray). + + Parameters + ---------- + x : array_like + + Returns + ------- + array + + Examples + -------- + >>> import numpy as np + >>> np.lib.scimath._fix_int_lt_zero([1,2]) + array([1, 2]) + + >>> np.lib.scimath._fix_int_lt_zero([-1,2]) + array([-1., 2.]) + """ + x = asarray(x) + if any(isreal(x) & (x < 0)): + x = x * 1.0 + return x + + +def _fix_real_abs_gt_1(x): + """Convert `x` to complex if it has real components x_i with abs(x_i)>1. + + Otherwise, output is just the array version of the input (via asarray). + + Parameters + ---------- + x : array_like + + Returns + ------- + array + + Examples + -------- + >>> import numpy as np + >>> np.lib.scimath._fix_real_abs_gt_1([0,1]) + array([0, 1]) + + >>> np.lib.scimath._fix_real_abs_gt_1([0,2]) + array([0.+0.j, 2.+0.j]) + """ + x = asarray(x) + if any(isreal(x) & (abs(x) > 1)): + x = _tocomplex(x) + return x + + +def _unary_dispatcher(x): + return (x,) + + +@set_module('numpy.lib.scimath') +@array_function_dispatch(_unary_dispatcher) +def sqrt(x): + """ + Compute the square root of x. + + For negative input elements, a complex value is returned + (unlike `numpy.sqrt` which returns NaN). + + Parameters + ---------- + x : array_like + The input value(s). + + Returns + ------- + out : ndarray or scalar + The square root of `x`. If `x` was a scalar, so is `out`, + otherwise an array is returned. + + See Also + -------- + numpy.sqrt + + Examples + -------- + For real, non-negative inputs this works just like `numpy.sqrt`: + + >>> import numpy as np + + >>> np.emath.sqrt(1) + 1.0 + >>> np.emath.sqrt([1, 4]) + array([1., 2.]) + + But it automatically handles negative inputs: + + >>> np.emath.sqrt(-1) + 1j + >>> np.emath.sqrt([-1,4]) + array([0.+1.j, 2.+0.j]) + + Different results are expected because: + floating point 0.0 and -0.0 are distinct. + + For more control, explicitly use complex() as follows: + + >>> np.emath.sqrt(complex(-4.0, 0.0)) + 2j + >>> np.emath.sqrt(complex(-4.0, -0.0)) + -2j + """ + x = _fix_real_lt_zero(x) + return nx.sqrt(x) + + +@set_module('numpy.lib.scimath') +@array_function_dispatch(_unary_dispatcher) +def log(x): + """ + Compute the natural logarithm of `x`. + + Return the "principal value" (for a description of this, see `numpy.log`) + of :math:`log_e(x)`. For real `x > 0`, this is a real number (``log(0)`` + returns ``-inf`` and ``log(np.inf)`` returns ``inf``). Otherwise, the + complex principle value is returned. + + Parameters + ---------- + x : array_like + The value(s) whose log is (are) required. + + Returns + ------- + out : ndarray or scalar + The log of the `x` value(s). If `x` was a scalar, so is `out`, + otherwise an array is returned. + + See Also + -------- + numpy.log + + Notes + ----- + For a log() that returns ``NAN`` when real `x < 0`, use `numpy.log` + (note, however, that otherwise `numpy.log` and this `log` are identical, + i.e., both return ``-inf`` for `x = 0`, ``inf`` for `x = inf`, and, + notably, the complex principle value if ``x.imag != 0``). + + Examples + -------- + >>> import numpy as np + >>> np.emath.log(np.exp(1)) + 1.0 + + Negative arguments are handled "correctly" (recall that + ``exp(log(x)) == x`` does *not* hold for real ``x < 0``): + + >>> np.emath.log(-np.exp(1)) == (1 + np.pi * 1j) + True + + """ + x = _fix_real_lt_zero(x) + return nx.log(x) + + +@set_module('numpy.lib.scimath') +@array_function_dispatch(_unary_dispatcher) +def log10(x): + """ + Compute the logarithm base 10 of `x`. + + Return the "principal value" (for a description of this, see + `numpy.log10`) of :math:`log_{10}(x)`. For real `x > 0`, this + is a real number (``log10(0)`` returns ``-inf`` and ``log10(np.inf)`` + returns ``inf``). Otherwise, the complex principle value is returned. + + Parameters + ---------- + x : array_like or scalar + The value(s) whose log base 10 is (are) required. + + Returns + ------- + out : ndarray or scalar + The log base 10 of the `x` value(s). If `x` was a scalar, so is `out`, + otherwise an array object is returned. + + See Also + -------- + numpy.log10 + + Notes + ----- + For a log10() that returns ``NAN`` when real `x < 0`, use `numpy.log10` + (note, however, that otherwise `numpy.log10` and this `log10` are + identical, i.e., both return ``-inf`` for `x = 0`, ``inf`` for `x = inf`, + and, notably, the complex principle value if ``x.imag != 0``). + + Examples + -------- + >>> import numpy as np + + (We set the printing precision so the example can be auto-tested) + + >>> np.set_printoptions(precision=4) + + >>> np.emath.log10(10**1) + 1.0 + + >>> np.emath.log10([-10**1, -10**2, 10**2]) + array([1.+1.3644j, 2.+1.3644j, 2.+0.j ]) + + """ + x = _fix_real_lt_zero(x) + return nx.log10(x) + + +def _logn_dispatcher(n, x): + return (n, x,) + + +@set_module('numpy.lib.scimath') +@array_function_dispatch(_logn_dispatcher) +def logn(n, x): + """ + Take log base n of x. + + If `x` contains negative inputs, the answer is computed and returned in the + complex domain. + + Parameters + ---------- + n : array_like + The integer base(s) in which the log is taken. + x : array_like + The value(s) whose log base `n` is (are) required. + + Returns + ------- + out : ndarray or scalar + The log base `n` of the `x` value(s). If `x` was a scalar, so is + `out`, otherwise an array is returned. + + Examples + -------- + >>> import numpy as np + >>> np.set_printoptions(precision=4) + + >>> np.emath.logn(2, [4, 8]) + array([2., 3.]) + >>> np.emath.logn(2, [-4, -8, 8]) + array([2.+4.5324j, 3.+4.5324j, 3.+0.j ]) + + """ + x = _fix_real_lt_zero(x) + n = _fix_real_lt_zero(n) + return nx.log(x) / nx.log(n) + + +@set_module('numpy.lib.scimath') +@array_function_dispatch(_unary_dispatcher) +def log2(x): + """ + Compute the logarithm base 2 of `x`. + + Return the "principal value" (for a description of this, see + `numpy.log2`) of :math:`log_2(x)`. For real `x > 0`, this is + a real number (``log2(0)`` returns ``-inf`` and ``log2(np.inf)`` returns + ``inf``). Otherwise, the complex principle value is returned. + + Parameters + ---------- + x : array_like + The value(s) whose log base 2 is (are) required. + + Returns + ------- + out : ndarray or scalar + The log base 2 of the `x` value(s). If `x` was a scalar, so is `out`, + otherwise an array is returned. + + See Also + -------- + numpy.log2 + + Notes + ----- + For a log2() that returns ``NAN`` when real `x < 0`, use `numpy.log2` + (note, however, that otherwise `numpy.log2` and this `log2` are + identical, i.e., both return ``-inf`` for `x = 0`, ``inf`` for `x = inf`, + and, notably, the complex principle value if ``x.imag != 0``). + + Examples + -------- + + We set the printing precision so the example can be auto-tested: + + >>> np.set_printoptions(precision=4) + + >>> np.emath.log2(8) + 3.0 + >>> np.emath.log2([-4, -8, 8]) + array([2.+4.5324j, 3.+4.5324j, 3.+0.j ]) + + """ + x = _fix_real_lt_zero(x) + return nx.log2(x) + + +def _power_dispatcher(x, p): + return (x, p) + + +@set_module('numpy.lib.scimath') +@array_function_dispatch(_power_dispatcher) +def power(x, p): + """ + Return x to the power p, (x**p). + + If `x` contains negative values, the output is converted to the + complex domain. + + Parameters + ---------- + x : array_like + The input value(s). + p : array_like of ints + The power(s) to which `x` is raised. If `x` contains multiple values, + `p` has to either be a scalar, or contain the same number of values + as `x`. In the latter case, the result is + ``x[0]**p[0], x[1]**p[1], ...``. + + Returns + ------- + out : ndarray or scalar + The result of ``x**p``. If `x` and `p` are scalars, so is `out`, + otherwise an array is returned. + + See Also + -------- + numpy.power + + Examples + -------- + >>> import numpy as np + >>> np.set_printoptions(precision=4) + + >>> np.emath.power(2, 2) + 4 + + >>> np.emath.power([2, 4], 2) + array([ 4, 16]) + + >>> np.emath.power([2, 4], -2) + array([0.25 , 0.0625]) + + >>> np.emath.power([-2, 4], 2) + array([ 4.-0.j, 16.+0.j]) + + >>> np.emath.power([2, 4], [2, 4]) + array([ 4, 256]) + + """ + x = _fix_real_lt_zero(x) + p = _fix_int_lt_zero(p) + return nx.power(x, p) + + +@set_module('numpy.lib.scimath') +@array_function_dispatch(_unary_dispatcher) +def arccos(x): + """ + Compute the inverse cosine of x. + + Return the "principal value" (for a description of this, see + `numpy.arccos`) of the inverse cosine of `x`. For real `x` such that + `abs(x) <= 1`, this is a real number in the closed interval + :math:`[0, \\pi]`. Otherwise, the complex principle value is returned. + + Parameters + ---------- + x : array_like or scalar + The value(s) whose arccos is (are) required. + + Returns + ------- + out : ndarray or scalar + The inverse cosine(s) of the `x` value(s). If `x` was a scalar, so + is `out`, otherwise an array object is returned. + + See Also + -------- + numpy.arccos + + Notes + ----- + For an arccos() that returns ``NAN`` when real `x` is not in the + interval ``[-1,1]``, use `numpy.arccos`. + + Examples + -------- + >>> import numpy as np + >>> np.set_printoptions(precision=4) + + >>> np.emath.arccos(1) # a scalar is returned + 0.0 + + >>> np.emath.arccos([1,2]) + array([0.-0.j , 0.-1.317j]) + + """ + x = _fix_real_abs_gt_1(x) + return nx.arccos(x) + + +@set_module('numpy.lib.scimath') +@array_function_dispatch(_unary_dispatcher) +def arcsin(x): + """ + Compute the inverse sine of x. + + Return the "principal value" (for a description of this, see + `numpy.arcsin`) of the inverse sine of `x`. For real `x` such that + `abs(x) <= 1`, this is a real number in the closed interval + :math:`[-\\pi/2, \\pi/2]`. Otherwise, the complex principle value is + returned. + + Parameters + ---------- + x : array_like or scalar + The value(s) whose arcsin is (are) required. + + Returns + ------- + out : ndarray or scalar + The inverse sine(s) of the `x` value(s). If `x` was a scalar, so + is `out`, otherwise an array object is returned. + + See Also + -------- + numpy.arcsin + + Notes + ----- + For an arcsin() that returns ``NAN`` when real `x` is not in the + interval ``[-1,1]``, use `numpy.arcsin`. + + Examples + -------- + >>> import numpy as np + >>> np.set_printoptions(precision=4) + + >>> np.emath.arcsin(0) + 0.0 + + >>> np.emath.arcsin([0,1]) + array([0. , 1.5708]) + + """ + x = _fix_real_abs_gt_1(x) + return nx.arcsin(x) + + +@set_module('numpy.lib.scimath') +@array_function_dispatch(_unary_dispatcher) +def arctanh(x): + """ + Compute the inverse hyperbolic tangent of `x`. + + Return the "principal value" (for a description of this, see + `numpy.arctanh`) of ``arctanh(x)``. For real `x` such that + ``abs(x) < 1``, this is a real number. If `abs(x) > 1`, or if `x` is + complex, the result is complex. Finally, `x = 1` returns``inf`` and + ``x=-1`` returns ``-inf``. + + Parameters + ---------- + x : array_like + The value(s) whose arctanh is (are) required. + + Returns + ------- + out : ndarray or scalar + The inverse hyperbolic tangent(s) of the `x` value(s). If `x` was + a scalar so is `out`, otherwise an array is returned. + + + See Also + -------- + numpy.arctanh + + Notes + ----- + For an arctanh() that returns ``NAN`` when real `x` is not in the + interval ``(-1,1)``, use `numpy.arctanh` (this latter, however, does + return +/-inf for ``x = +/-1``). + + Examples + -------- + >>> import numpy as np + >>> np.set_printoptions(precision=4) + + >>> np.emath.arctanh(0.5) + 0.5493061443340549 + + >>> import warnings + >>> with warnings.catch_warnings(): + ... warnings.simplefilter('ignore', RuntimeWarning) + ... np.emath.arctanh(np.eye(2)) + array([[inf, 0.], + [ 0., inf]]) + >>> np.emath.arctanh([1j]) + array([0.+0.7854j]) + + """ + x = _fix_real_abs_gt_1(x) + return nx.arctanh(x) diff --git a/python/user_packages/Python313/site-packages/numpy/lib/_scimath_impl.pyi b/python/user_packages/Python313/site-packages/numpy/lib/_scimath_impl.pyi new file mode 100644 index 0000000000000000000000000000000000000000..80a1a4108ad5ed1141b19a78993ab8da3cee929b --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/lib/_scimath_impl.pyi @@ -0,0 +1,93 @@ +from typing import Any, overload + +from numpy import complexfloating +from numpy._typing import ( + NDArray, + _ArrayLikeComplex_co, + _ArrayLikeFloat_co, + _ComplexLike_co, + _FloatLike_co, +) + +__all__ = ["sqrt", "log", "log2", "logn", "log10", "power", "arccos", "arcsin", "arctanh"] + +@overload +def sqrt(x: _FloatLike_co) -> Any: ... +@overload +def sqrt(x: _ComplexLike_co) -> complexfloating: ... +@overload +def sqrt(x: _ArrayLikeFloat_co) -> NDArray[Any]: ... +@overload +def sqrt(x: _ArrayLikeComplex_co) -> NDArray[complexfloating]: ... + +@overload +def log(x: _FloatLike_co) -> Any: ... +@overload +def log(x: _ComplexLike_co) -> complexfloating: ... +@overload +def log(x: _ArrayLikeFloat_co) -> NDArray[Any]: ... +@overload +def log(x: _ArrayLikeComplex_co) -> NDArray[complexfloating]: ... + +@overload +def log10(x: _FloatLike_co) -> Any: ... +@overload +def log10(x: _ComplexLike_co) -> complexfloating: ... +@overload +def log10(x: _ArrayLikeFloat_co) -> NDArray[Any]: ... +@overload +def log10(x: _ArrayLikeComplex_co) -> NDArray[complexfloating]: ... + +@overload +def log2(x: _FloatLike_co) -> Any: ... +@overload +def log2(x: _ComplexLike_co) -> complexfloating: ... +@overload +def log2(x: _ArrayLikeFloat_co) -> NDArray[Any]: ... +@overload +def log2(x: _ArrayLikeComplex_co) -> NDArray[complexfloating]: ... + +@overload +def logn(n: _FloatLike_co, x: _FloatLike_co) -> Any: ... +@overload +def logn(n: _ComplexLike_co, x: _ComplexLike_co) -> complexfloating: ... +@overload +def logn(n: _ArrayLikeFloat_co, x: _ArrayLikeFloat_co) -> NDArray[Any]: ... +@overload +def logn(n: _ArrayLikeComplex_co, x: _ArrayLikeComplex_co) -> NDArray[complexfloating]: ... + +@overload +def power(x: _FloatLike_co, p: _FloatLike_co) -> Any: ... +@overload +def power(x: _ComplexLike_co, p: _ComplexLike_co) -> complexfloating: ... +@overload +def power(x: _ArrayLikeFloat_co, p: _ArrayLikeFloat_co) -> NDArray[Any]: ... +@overload +def power(x: _ArrayLikeComplex_co, p: _ArrayLikeComplex_co) -> NDArray[complexfloating]: ... + +@overload +def arccos(x: _FloatLike_co) -> Any: ... +@overload +def arccos(x: _ComplexLike_co) -> complexfloating: ... +@overload +def arccos(x: _ArrayLikeFloat_co) -> NDArray[Any]: ... +@overload +def arccos(x: _ArrayLikeComplex_co) -> NDArray[complexfloating]: ... + +@overload +def arcsin(x: _FloatLike_co) -> Any: ... +@overload +def arcsin(x: _ComplexLike_co) -> complexfloating: ... +@overload +def arcsin(x: _ArrayLikeFloat_co) -> NDArray[Any]: ... +@overload +def arcsin(x: _ArrayLikeComplex_co) -> NDArray[complexfloating]: ... + +@overload +def arctanh(x: _FloatLike_co) -> Any: ... +@overload +def arctanh(x: _ComplexLike_co) -> complexfloating: ... +@overload +def arctanh(x: _ArrayLikeFloat_co) -> NDArray[Any]: ... +@overload +def arctanh(x: _ArrayLikeComplex_co) -> NDArray[complexfloating]: ... diff --git a/python/user_packages/Python313/site-packages/numpy/lib/_shape_base_impl.py b/python/user_packages/Python313/site-packages/numpy/lib/_shape_base_impl.py new file mode 100644 index 0000000000000000000000000000000000000000..861a938326006818a5614509bb5e2e01b3eac749 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/lib/_shape_base_impl.py @@ -0,0 +1,1289 @@ +import functools +import warnings + +import numpy as np +import numpy._core.numeric as _nx +from numpy._core import atleast_3d, overrides, vstack +from numpy._core._multiarray_umath import _array_converter +from numpy._core.fromnumeric import reshape, transpose +from numpy._core.multiarray import normalize_axis_index +from numpy._core.numeric import ( + array, + asanyarray, + asarray, + normalize_axis_tuple, + zeros, + zeros_like, +) +from numpy._core.overrides import set_module +from numpy._core.shape_base import _arrays_for_stack_dispatcher +from numpy.lib._index_tricks_impl import ndindex +from numpy.matrixlib.defmatrix import matrix # this raises all the right alarm bells + +__all__ = [ + 'column_stack', 'row_stack', 'dstack', 'array_split', 'split', + 'hsplit', 'vsplit', 'dsplit', 'apply_over_axes', 'expand_dims', + 'apply_along_axis', 'kron', 'tile', 'take_along_axis', + 'put_along_axis' + ] + + +array_function_dispatch = functools.partial( + overrides.array_function_dispatch, module='numpy') + + +def _make_along_axis_idx(arr_shape, indices, axis): + # compute dimensions to iterate over + if not _nx.issubdtype(indices.dtype, _nx.integer): + raise IndexError('`indices` must be an integer array') + if len(arr_shape) != indices.ndim: + raise ValueError( + "`indices` and `arr` must have the same number of dimensions") + shape_ones = (1,) * indices.ndim + dest_dims = list(range(axis)) + [None] + list(range(axis + 1, indices.ndim)) + + # build a fancy index, consisting of orthogonal aranges, with the + # requested index inserted at the right location + fancy_index = [] + for dim, n in zip(dest_dims, arr_shape): + if dim is None: + fancy_index.append(indices) + else: + ind_shape = shape_ones[:dim] + (-1,) + shape_ones[dim + 1:] + fancy_index.append(_nx.arange(n).reshape(ind_shape)) + + return tuple(fancy_index) + + +def _take_along_axis_dispatcher(arr, indices, axis=None): + return (arr, indices) + + +@array_function_dispatch(_take_along_axis_dispatcher) +def take_along_axis(arr, indices, axis=-1): + """ + Take values from the input array by matching 1d index and data slices. + + This iterates over matching 1d slices oriented along the specified axis in + the index and data arrays, and uses the former to look up values in the + latter. These slices can be different lengths. + + Functions returning an index along an axis, like `argsort` and + `argpartition`, produce suitable indices for this function. + + Parameters + ---------- + arr : ndarray (Ni..., M, Nk...) + Source array + indices : ndarray (Ni..., J, Nk...) + Indices to take along each 1d slice of ``arr``. This must match the + dimension of ``arr``, but dimensions Ni and Nj only need to broadcast + against ``arr``. + axis : int or None, optional + The axis to take 1d slices along. If axis is None, the input array is + treated as if it had first been flattened to 1d, for consistency with + `sort` and `argsort`. + + .. versionchanged:: 2.3 + The default value is now ``-1``. + + Returns + ------- + out: ndarray (Ni..., J, Nk...) + The indexed result. + + Notes + ----- + This is equivalent to (but faster than) the following use of `ndindex` and + `s_`, which sets each of ``ii`` and ``kk`` to a tuple of indices:: + + Ni, M, Nk = a.shape[:axis], a.shape[axis], a.shape[axis+1:] + J = indices.shape[axis] # Need not equal M + out = np.empty(Ni + (J,) + Nk) + + for ii in ndindex(Ni): + for kk in ndindex(Nk): + a_1d = a [ii + s_[:,] + kk] + indices_1d = indices[ii + s_[:,] + kk] + out_1d = out [ii + s_[:,] + kk] + for j in range(J): + out_1d[j] = a_1d[indices_1d[j]] + + Equivalently, eliminating the inner loop, the last two lines would be:: + + out_1d[:] = a_1d[indices_1d] + + See Also + -------- + take : Take along an axis, using the same indices for every 1d slice + put_along_axis : + Put values into the destination array by matching 1d index and data slices + + Examples + -------- + >>> import numpy as np + + For this sample array + + >>> a = np.array([[10, 30, 20], [60, 40, 50]]) + + We can sort either by using sort directly, or argsort and this function + + >>> np.sort(a, axis=1) + array([[10, 20, 30], + [40, 50, 60]]) + >>> ai = np.argsort(a, axis=1) + >>> ai + array([[0, 2, 1], + [1, 2, 0]]) + >>> np.take_along_axis(a, ai, axis=1) + array([[10, 20, 30], + [40, 50, 60]]) + + The same works for max and min, if you maintain the trivial dimension + with ``keepdims``: + + >>> np.max(a, axis=1, keepdims=True) + array([[30], + [60]]) + >>> ai = np.argmax(a, axis=1, keepdims=True) + >>> ai + array([[1], + [0]]) + >>> np.take_along_axis(a, ai, axis=1) + array([[30], + [60]]) + + If we want to get the max and min at the same time, we can stack the + indices first + + >>> ai_min = np.argmin(a, axis=1, keepdims=True) + >>> ai_max = np.argmax(a, axis=1, keepdims=True) + >>> ai = np.concatenate([ai_min, ai_max], axis=1) + >>> ai + array([[0, 1], + [1, 0]]) + >>> np.take_along_axis(a, ai, axis=1) + array([[10, 30], + [40, 60]]) + """ + # normalize inputs + if axis is None: + if indices.ndim != 1: + raise ValueError( + 'when axis=None, `indices` must have a single dimension.') + arr = np.array(arr.flat) + axis = 0 + else: + axis = normalize_axis_index(axis, arr.ndim) + + # use the fancy index + return arr[_make_along_axis_idx(arr.shape, indices, axis)] + + +def _put_along_axis_dispatcher(arr, indices, values, axis): + return (arr, indices, values) + + +@array_function_dispatch(_put_along_axis_dispatcher) +def put_along_axis(arr, indices, values, axis): + """ + Put values into the destination array by matching 1d index and data slices. + + This iterates over matching 1d slices oriented along the specified axis in + the index and data arrays, and uses the former to place values into the + latter. These slices can be different lengths. + + Functions returning an index along an axis, like `argsort` and + `argpartition`, produce suitable indices for this function. + + Parameters + ---------- + arr : ndarray (Ni..., M, Nk...) + Destination array. + indices : ndarray (Ni..., J, Nk...) + Indices to change along each 1d slice of `arr`. This must match the + dimension of arr, but dimensions in Ni and Nj may be 1 to broadcast + against `arr`. + values : array_like (Ni..., J, Nk...) + values to insert at those indices. Its shape and dimension are + broadcast to match that of `indices`. + axis : int + The axis to take 1d slices along. If axis is None, the destination + array is treated as if a flattened 1d view had been created of it. + + Notes + ----- + This is equivalent to (but faster than) the following use of `ndindex` and + `s_`, which sets each of ``ii`` and ``kk`` to a tuple of indices:: + + Ni, M, Nk = a.shape[:axis], a.shape[axis], a.shape[axis+1:] + J = indices.shape[axis] # Need not equal M + + for ii in ndindex(Ni): + for kk in ndindex(Nk): + a_1d = a [ii + s_[:,] + kk] + indices_1d = indices[ii + s_[:,] + kk] + values_1d = values [ii + s_[:,] + kk] + for j in range(J): + a_1d[indices_1d[j]] = values_1d[j] + + Equivalently, eliminating the inner loop, the last two lines would be:: + + a_1d[indices_1d] = values_1d + + See Also + -------- + take_along_axis : + Take values from the input array by matching 1d index and data slices + + Examples + -------- + >>> import numpy as np + + For this sample array + + >>> a = np.array([[10, 30, 20], [60, 40, 50]]) + + We can replace the maximum values with: + + >>> ai = np.argmax(a, axis=1, keepdims=True) + >>> ai + array([[1], + [0]]) + >>> np.put_along_axis(a, ai, 99, axis=1) + >>> a + array([[10, 99, 20], + [99, 40, 50]]) + + """ + # normalize inputs + if axis is None: + if indices.ndim != 1: + raise ValueError( + 'when axis=None, `indices` must have a single dimension.') + arr = np.array(arr.flat) + axis = 0 + else: + axis = normalize_axis_index(axis, arr.ndim) + + # use the fancy index + arr[_make_along_axis_idx(arr.shape, indices, axis)] = values + + +def _apply_along_axis_dispatcher(func1d, axis, arr, *args, **kwargs): + return (arr,) + + +@array_function_dispatch(_apply_along_axis_dispatcher) +def apply_along_axis(func1d, axis, arr, *args, **kwargs): + """ + Apply a function to 1-D slices along the given axis. + + Execute `func1d(a, *args, **kwargs)` where `func1d` operates on 1-D arrays + and `a` is a 1-D slice of `arr` along `axis`. + + This is equivalent to (but faster than) the following use of `ndindex` and + `s_`, which sets each of ``ii``, ``jj``, and ``kk`` to a tuple of indices:: + + Ni, Nk = a.shape[:axis], a.shape[axis+1:] + for ii in ndindex(Ni): + for kk in ndindex(Nk): + f = func1d(arr[ii + s_[:,] + kk]) + Nj = f.shape + for jj in ndindex(Nj): + out[ii + jj + kk] = f[jj] + + Equivalently, eliminating the inner loop, this can be expressed as:: + + Ni, Nk = a.shape[:axis], a.shape[axis+1:] + for ii in ndindex(Ni): + for kk in ndindex(Nk): + out[ii + s_[...,] + kk] = func1d(arr[ii + s_[:,] + kk]) + + Parameters + ---------- + func1d : function (M,) -> (Nj...) + This function should accept 1-D arrays. It is applied to 1-D + slices of `arr` along the specified axis. + axis : integer + Axis along which `arr` is sliced. + arr : ndarray (Ni..., M, Nk...) + Input array. + args : any + Additional arguments to `func1d`. + kwargs : any + Additional named arguments to `func1d`. + + Returns + ------- + out : ndarray (Ni..., Nj..., Nk...) + The output array. The shape of `out` is identical to the shape of + `arr`, except along the `axis` dimension. This axis is removed, and + replaced with new dimensions equal to the shape of the return value + of `func1d`. So if `func1d` returns a scalar `out` will have one + fewer dimensions than `arr`. + + See Also + -------- + apply_over_axes : Apply a function repeatedly over multiple axes. + + Examples + -------- + >>> import numpy as np + >>> def my_func(a): + ... \"\"\"Average first and last element of a 1-D array\"\"\" + ... return (a[0] + a[-1]) * 0.5 + >>> b = np.array([[1,2,3], [4,5,6], [7,8,9]]) + >>> np.apply_along_axis(my_func, 0, b) + array([4., 5., 6.]) + >>> np.apply_along_axis(my_func, 1, b) + array([2., 5., 8.]) + + For a function that returns a 1D array, the number of dimensions in + `outarr` is the same as `arr`. + + >>> b = np.array([[8,1,7], [4,3,9], [5,2,6]]) + >>> np.apply_along_axis(sorted, 1, b) + array([[1, 7, 8], + [3, 4, 9], + [2, 5, 6]]) + + For a function that returns a higher dimensional array, those dimensions + are inserted in place of the `axis` dimension. + + >>> b = np.array([[1,2,3], [4,5,6], [7,8,9]]) + >>> np.apply_along_axis(np.diag, -1, b) + array([[[1, 0, 0], + [0, 2, 0], + [0, 0, 3]], + [[4, 0, 0], + [0, 5, 0], + [0, 0, 6]], + [[7, 0, 0], + [0, 8, 0], + [0, 0, 9]]]) + """ + # handle negative axes + conv = _array_converter(arr) + arr = conv[0] + + nd = arr.ndim + axis = normalize_axis_index(axis, nd) + + # arr, with the iteration axis at the end + in_dims = list(range(nd)) + inarr_view = transpose(arr, in_dims[:axis] + in_dims[axis + 1:] + [axis]) + + # compute indices for the iteration axes, and append a trailing ellipsis to + # prevent 0d arrays decaying to scalars, which fixes gh-8642 + inds = ndindex(inarr_view.shape[:-1]) + inds = (ind + (Ellipsis,) for ind in inds) + + # invoke the function on the first item + try: + ind0 = next(inds) + except StopIteration: + raise ValueError( + 'Cannot apply_along_axis when any iteration dimensions are 0' + ) from None + res = asanyarray(func1d(inarr_view[ind0], *args, **kwargs)) + + # build a buffer for storing evaluations of func1d. + # remove the requested axis, and add the new ones on the end. + # laid out so that each write is contiguous. + # for a tuple index inds, buff[inds] = func1d(inarr_view[inds]) + if not isinstance(res, matrix): + buff = zeros_like(res, shape=inarr_view.shape[:-1] + res.shape) + else: + # Matrices are nasty with reshaping, so do not preserve them here. + buff = zeros(inarr_view.shape[:-1] + res.shape, dtype=res.dtype) + + # permutation of axes such that out = buff.transpose(buff_permute) + buff_dims = list(range(buff.ndim)) + buff_permute = ( + buff_dims[0 : axis] + + buff_dims[buff.ndim - res.ndim : buff.ndim] + + buff_dims[axis : buff.ndim - res.ndim] + ) + + # save the first result, then compute and save all remaining results + buff[ind0] = res + for ind in inds: + buff[ind] = asanyarray(func1d(inarr_view[ind], *args, **kwargs)) + + res = transpose(buff, buff_permute) + return conv.wrap(res) + + +def _apply_over_axes_dispatcher(func, a, axes): + return (a,) + + +@array_function_dispatch(_apply_over_axes_dispatcher) +def apply_over_axes(func, a, axes): + """ + Apply a function repeatedly over multiple axes. + + `func` is called as `res = func(a, axis)`, where `axis` is the first + element of `axes`. The result `res` of the function call must have + either the same dimensions as `a` or one less dimension. If `res` + has one less dimension than `a`, a dimension is inserted before + `axis`. The call to `func` is then repeated for each axis in `axes`, + with `res` as the first argument. + + Parameters + ---------- + func : function + This function must take two arguments, `func(a, axis)`. + a : array_like + Input array. + axes : array_like + Axes over which `func` is applied; the elements must be integers. + + Returns + ------- + apply_over_axis : ndarray + The output array. The number of dimensions is the same as `a`, + but the shape can be different. This depends on whether `func` + changes the shape of its output with respect to its input. + + See Also + -------- + apply_along_axis : + Apply a function to 1-D slices of an array along the given axis. + + Notes + ----- + This function is equivalent to tuple axis arguments to reorderable ufuncs + with keepdims=True. Tuple axis arguments to ufuncs have been available since + version 1.7.0. + + Examples + -------- + >>> import numpy as np + >>> a = np.arange(24).reshape(2,3,4) + >>> a + array([[[ 0, 1, 2, 3], + [ 4, 5, 6, 7], + [ 8, 9, 10, 11]], + [[12, 13, 14, 15], + [16, 17, 18, 19], + [20, 21, 22, 23]]]) + + Sum over axes 0 and 2. The result has same number of dimensions + as the original array: + + >>> np.apply_over_axes(np.sum, a, [0,2]) + array([[[ 60], + [ 92], + [124]]]) + + Tuple axis arguments to ufuncs are equivalent: + + >>> np.sum(a, axis=(0,2), keepdims=True) + array([[[ 60], + [ 92], + [124]]]) + + """ + val = asarray(a) + N = a.ndim + if array(axes).ndim == 0: + axes = (axes,) + for axis in axes: + if axis < 0: + axis = N + axis + args = (val, axis) + res = func(*args) + if res.ndim == val.ndim: + val = res + else: + res = expand_dims(res, axis) + if res.ndim == val.ndim: + val = res + else: + raise ValueError("function is not returning " + "an array of the correct shape") + return val + + +def _expand_dims_dispatcher(a, axis): + return (a,) + + +@array_function_dispatch(_expand_dims_dispatcher) +def expand_dims(a, axis): + """ + Expand the shape of an array. + + Insert a new axis that will appear at the `axis` position in the expanded + array shape. + + Parameters + ---------- + a : array_like + Input array. + axis : int or tuple of ints + Position in the expanded axes where the new axis (or axes) is placed. + + .. deprecated:: 1.13.0 + Passing an axis where ``axis > a.ndim`` will be treated as + ``axis == a.ndim``, and passing ``axis < -a.ndim - 1`` will + be treated as ``axis == 0``. This behavior is deprecated. + + Returns + ------- + result : ndarray + View of `a` with the number of dimensions increased. + + See Also + -------- + squeeze : The inverse operation, removing singleton dimensions + reshape : Insert, remove, and combine dimensions, and resize existing ones + atleast_1d, atleast_2d, atleast_3d + + Examples + -------- + >>> import numpy as np + >>> x = np.array([1, 2]) + >>> x.shape + (2,) + + The following is equivalent to ``x[np.newaxis, :]`` or ``x[np.newaxis]``: + + >>> y = np.expand_dims(x, axis=0) + >>> y + array([[1, 2]]) + >>> y.shape + (1, 2) + + The following is equivalent to ``x[:, np.newaxis]``: + + >>> y = np.expand_dims(x, axis=1) + >>> y + array([[1], + [2]]) + >>> y.shape + (2, 1) + + ``axis`` may also be a tuple: + + >>> y = np.expand_dims(x, axis=(0, 1)) + >>> y + array([[[1, 2]]]) + + >>> y = np.expand_dims(x, axis=(2, 0)) + >>> y + array([[[1], + [2]]]) + + Note that some examples may use ``None`` instead of ``np.newaxis``. These + are the same objects: + + >>> np.newaxis is None + True + + """ + if isinstance(a, matrix): + a = asarray(a) + else: + a = asanyarray(a) + + if not isinstance(axis, (tuple, list)): + axis = (axis,) + + out_ndim = len(axis) + a.ndim + axis = normalize_axis_tuple(axis, out_ndim) + + shape_it = iter(a.shape) + shape = [1 if ax in axis else next(shape_it) for ax in range(out_ndim)] + + return a.reshape(shape) + + +# NOTE: Remove once deprecation period passes +@set_module("numpy") +def row_stack(tup, *, dtype=None, casting="same_kind"): + # Deprecated in NumPy 2.0, 2023-08-18 + warnings.warn( + "`row_stack` alias is deprecated. " + "Use `np.vstack` directly.", + DeprecationWarning, + stacklevel=2 + ) + return vstack(tup, dtype=dtype, casting=casting) + + +row_stack.__doc__ = vstack.__doc__ + + +def _column_stack_dispatcher(tup): + return _arrays_for_stack_dispatcher(tup) + + +@array_function_dispatch(_column_stack_dispatcher) +def column_stack(tup): + """ + Stack 1-D arrays as columns into a 2-D array. + + Take a sequence of 1-D arrays and stack them as columns + to make a single 2-D array. 2-D arrays are stacked as-is, + just like with `hstack`. 1-D arrays are turned into 2-D columns + first. + + Parameters + ---------- + tup : sequence of 1-D or 2-D arrays. + Arrays to stack. All of them must have the same first dimension. + + Returns + ------- + stacked : 2-D array + The array formed by stacking the given arrays. + + See Also + -------- + stack, hstack, vstack, concatenate + + Examples + -------- + >>> import numpy as np + >>> a = np.array((1,2,3)) + >>> b = np.array((4,5,6)) + >>> np.column_stack((a,b)) + array([[1, 4], + [2, 5], + [3, 6]]) + + """ + arrays = [] + for v in tup: + arr = asanyarray(v) + if arr.ndim < 2: + arr = array(arr, copy=None, subok=True, ndmin=2).T + arrays.append(arr) + return _nx.concatenate(arrays, 1) + + +def _dstack_dispatcher(tup): + return _arrays_for_stack_dispatcher(tup) + + +@array_function_dispatch(_dstack_dispatcher) +def dstack(tup): + """ + Stack arrays in sequence depth wise (along third axis). + + This is equivalent to concatenation along the third axis after 2-D arrays + of shape `(M,N)` have been reshaped to `(M,N,1)` and 1-D arrays of shape + `(N,)` have been reshaped to `(1,N,1)`. Rebuilds arrays divided by + `dsplit`. + + This function makes most sense for arrays with up to 3 dimensions. For + instance, for pixel-data with a height (first axis), width (second axis), + and r/g/b channels (third axis). The functions `concatenate`, `stack` and + `block` provide more general stacking and concatenation operations. + + Parameters + ---------- + tup : sequence of arrays + The arrays must have the same shape along all but the third axis. + 1-D or 2-D arrays must have the same shape. + + Returns + ------- + stacked : ndarray + The array formed by stacking the given arrays, will be at least 3-D. + + See Also + -------- + concatenate : Join a sequence of arrays along an existing axis. + stack : Join a sequence of arrays along a new axis. + block : Assemble an nd-array from nested lists of blocks. + vstack : Stack arrays in sequence vertically (row wise). + hstack : Stack arrays in sequence horizontally (column wise). + column_stack : Stack 1-D arrays as columns into a 2-D array. + dsplit : Split array along third axis. + + Examples + -------- + >>> import numpy as np + >>> a = np.array((1,2,3)) + >>> b = np.array((4,5,6)) + >>> np.dstack((a,b)) + array([[[1, 4], + [2, 5], + [3, 6]]]) + + >>> a = np.array([[1],[2],[3]]) + >>> b = np.array([[4],[5],[6]]) + >>> np.dstack((a,b)) + array([[[1, 4]], + [[2, 5]], + [[3, 6]]]) + + """ + arrs = atleast_3d(*tup) + if not isinstance(arrs, tuple): + arrs = (arrs,) + return _nx.concatenate(arrs, 2) + + +def _array_split_dispatcher(ary, indices_or_sections, axis=None): + return (ary, indices_or_sections) + + +@array_function_dispatch(_array_split_dispatcher) +def array_split(ary, indices_or_sections, axis=0): + """ + Split an array into multiple sub-arrays. + + Please refer to the ``split`` documentation. The only difference + between these functions is that ``array_split`` allows + `indices_or_sections` to be an integer that does *not* equally + divide the axis. For an array of length l that should be split + into n sections, it returns l % n sub-arrays of size l//n + 1 + and the rest of size l//n. + + See Also + -------- + split : Split array into multiple sub-arrays of equal size. + + Examples + -------- + >>> import numpy as np + >>> x = np.arange(8.0) + >>> np.array_split(x, 3) + [array([0., 1., 2.]), array([3., 4., 5.]), array([6., 7.])] + + >>> x = np.arange(9) + >>> np.array_split(x, 4) + [array([0, 1, 2]), array([3, 4]), array([5, 6]), array([7, 8])] + + """ + try: + Ntotal = ary.shape[axis] + except AttributeError: + Ntotal = len(ary) + try: + # handle array case. + Nsections = len(indices_or_sections) + 1 + div_points = [0] + list(indices_or_sections) + [Ntotal] + except TypeError: + # indices_or_sections is a scalar, not an array. + Nsections = int(indices_or_sections) + if Nsections <= 0: + raise ValueError('number sections must be larger than 0.') from None + Neach_section, extras = divmod(Ntotal, Nsections) + section_sizes = ([0] + + extras * [Neach_section + 1] + + (Nsections - extras) * [Neach_section]) + div_points = _nx.array(section_sizes, dtype=_nx.intp).cumsum() + + sub_arys = [] + sary = _nx.swapaxes(ary, axis, 0) + for i in range(Nsections): + st = div_points[i] + end = div_points[i + 1] + sub_arys.append(_nx.swapaxes(sary[st:end], axis, 0)) + + return sub_arys + + +def _split_dispatcher(ary, indices_or_sections, axis=None): + return (ary, indices_or_sections) + + +@array_function_dispatch(_split_dispatcher) +def split(ary, indices_or_sections, axis=0): + """ + Split an array into multiple sub-arrays as views into `ary`. + + Parameters + ---------- + ary : ndarray + Array to be divided into sub-arrays. + indices_or_sections : int or 1-D array + If `indices_or_sections` is an integer, N, the array will be divided + into N equal arrays along `axis`. If such a split is not possible, + an error is raised. + + If `indices_or_sections` is a 1-D array of sorted integers, the entries + indicate where along `axis` the array is split. For example, + ``[2, 3]`` would, for ``axis=0``, result in + + - ary[:2] + - ary[2:3] + - ary[3:] + + If an index exceeds the dimension of the array along `axis`, + an empty sub-array is returned correspondingly. + axis : int, optional + The axis along which to split, default is 0. + + Returns + ------- + sub-arrays : list of ndarrays + A list of sub-arrays as views into `ary`. + + Raises + ------ + ValueError + If `indices_or_sections` is given as an integer, but + a split does not result in equal division. + + See Also + -------- + array_split : Split an array into multiple sub-arrays of equal or + near-equal size. Does not raise an exception if + an equal division cannot be made. + hsplit : Split array into multiple sub-arrays horizontally (column-wise). + vsplit : Split array into multiple sub-arrays vertically (row wise). + dsplit : Split array into multiple sub-arrays along the 3rd axis (depth). + concatenate : Join a sequence of arrays along an existing axis. + stack : Join a sequence of arrays along a new axis. + hstack : Stack arrays in sequence horizontally (column wise). + vstack : Stack arrays in sequence vertically (row wise). + dstack : Stack arrays in sequence depth wise (along third dimension). + + Examples + -------- + >>> import numpy as np + >>> x = np.arange(9.0) + >>> np.split(x, 3) + [array([0., 1., 2.]), array([3., 4., 5.]), array([6., 7., 8.])] + + >>> x = np.arange(8.0) + >>> np.split(x, [3, 5, 6, 10]) + [array([0., 1., 2.]), + array([3., 4.]), + array([5.]), + array([6., 7.]), + array([], dtype=float64)] + + """ + try: + len(indices_or_sections) + except TypeError: + sections = indices_or_sections + N = ary.shape[axis] + if N % sections: + raise ValueError( + 'array split does not result in an equal division') from None + return array_split(ary, indices_or_sections, axis) + + +def _hvdsplit_dispatcher(ary, indices_or_sections): + return (ary, indices_or_sections) + + +@array_function_dispatch(_hvdsplit_dispatcher) +def hsplit(ary, indices_or_sections): + """ + Split an array into multiple sub-arrays horizontally (column-wise). + + Please refer to the `split` documentation. `hsplit` is equivalent + to `split` with ``axis=1``, the array is always split along the second + axis except for 1-D arrays, where it is split at ``axis=0``. + + See Also + -------- + split : Split an array into multiple sub-arrays of equal size. + + Examples + -------- + >>> import numpy as np + >>> x = np.arange(16.0).reshape(4, 4) + >>> x + array([[ 0., 1., 2., 3.], + [ 4., 5., 6., 7.], + [ 8., 9., 10., 11.], + [12., 13., 14., 15.]]) + >>> np.hsplit(x, 2) + [array([[ 0., 1.], + [ 4., 5.], + [ 8., 9.], + [12., 13.]]), + array([[ 2., 3.], + [ 6., 7.], + [10., 11.], + [14., 15.]])] + >>> np.hsplit(x, np.array([3, 6])) + [array([[ 0., 1., 2.], + [ 4., 5., 6.], + [ 8., 9., 10.], + [12., 13., 14.]]), + array([[ 3.], + [ 7.], + [11.], + [15.]]), + array([], shape=(4, 0), dtype=float64)] + + With a higher dimensional array the split is still along the second axis. + + >>> x = np.arange(8.0).reshape(2, 2, 2) + >>> x + array([[[0., 1.], + [2., 3.]], + [[4., 5.], + [6., 7.]]]) + >>> np.hsplit(x, 2) + [array([[[0., 1.]], + [[4., 5.]]]), + array([[[2., 3.]], + [[6., 7.]]])] + + With a 1-D array, the split is along axis 0. + + >>> x = np.array([0, 1, 2, 3, 4, 5]) + >>> np.hsplit(x, 2) + [array([0, 1, 2]), array([3, 4, 5])] + + """ + if _nx.ndim(ary) == 0: + raise ValueError('hsplit only works on arrays of 1 or more dimensions') + if ary.ndim > 1: + return split(ary, indices_or_sections, 1) + else: + return split(ary, indices_or_sections, 0) + + +@array_function_dispatch(_hvdsplit_dispatcher) +def vsplit(ary, indices_or_sections): + """ + Split an array into multiple sub-arrays vertically (row-wise). + + Please refer to the ``split`` documentation. ``vsplit`` is equivalent + to ``split`` with `axis=0` (default), the array is always split along the + first axis regardless of the array dimension. + + See Also + -------- + split : Split an array into multiple sub-arrays of equal size. + + Examples + -------- + >>> import numpy as np + >>> x = np.arange(16.0).reshape(4, 4) + >>> x + array([[ 0., 1., 2., 3.], + [ 4., 5., 6., 7.], + [ 8., 9., 10., 11.], + [12., 13., 14., 15.]]) + >>> np.vsplit(x, 2) + [array([[0., 1., 2., 3.], + [4., 5., 6., 7.]]), + array([[ 8., 9., 10., 11.], + [12., 13., 14., 15.]])] + >>> np.vsplit(x, np.array([3, 6])) + [array([[ 0., 1., 2., 3.], + [ 4., 5., 6., 7.], + [ 8., 9., 10., 11.]]), + array([[12., 13., 14., 15.]]), + array([], shape=(0, 4), dtype=float64)] + + With a higher dimensional array the split is still along the first axis. + + >>> x = np.arange(8.0).reshape(2, 2, 2) + >>> x + array([[[0., 1.], + [2., 3.]], + [[4., 5.], + [6., 7.]]]) + >>> np.vsplit(x, 2) + [array([[[0., 1.], + [2., 3.]]]), + array([[[4., 5.], + [6., 7.]]])] + + """ + if _nx.ndim(ary) < 2: + raise ValueError('vsplit only works on arrays of 2 or more dimensions') + return split(ary, indices_or_sections, 0) + + +@array_function_dispatch(_hvdsplit_dispatcher) +def dsplit(ary, indices_or_sections): + """ + Split array into multiple sub-arrays along the 3rd axis (depth). + + Please refer to the `split` documentation. `dsplit` is equivalent + to `split` with ``axis=2``, the array is always split along the third + axis provided the array dimension is greater than or equal to 3. + + See Also + -------- + split : Split an array into multiple sub-arrays of equal size. + + Examples + -------- + >>> import numpy as np + >>> x = np.arange(16.0).reshape(2, 2, 4) + >>> x + array([[[ 0., 1., 2., 3.], + [ 4., 5., 6., 7.]], + [[ 8., 9., 10., 11.], + [12., 13., 14., 15.]]]) + >>> np.dsplit(x, 2) + [array([[[ 0., 1.], + [ 4., 5.]], + [[ 8., 9.], + [12., 13.]]]), array([[[ 2., 3.], + [ 6., 7.]], + [[10., 11.], + [14., 15.]]])] + >>> np.dsplit(x, np.array([3, 6])) + [array([[[ 0., 1., 2.], + [ 4., 5., 6.]], + [[ 8., 9., 10.], + [12., 13., 14.]]]), + array([[[ 3.], + [ 7.]], + [[11.], + [15.]]]), + array([], shape=(2, 2, 0), dtype=float64)] + """ + if _nx.ndim(ary) < 3: + raise ValueError('dsplit only works on arrays of 3 or more dimensions') + return split(ary, indices_or_sections, 2) + + +def get_array_wrap(*args): + """Find the wrapper for the array with the highest priority. + + In case of ties, leftmost wins. If no wrapper is found, return None. + + .. deprecated:: 2.0 + """ + + # Deprecated in NumPy 2.0, 2023-07-11 + warnings.warn( + "`get_array_wrap` is deprecated. " + "(deprecated in NumPy 2.0)", + DeprecationWarning, + stacklevel=2 + ) + + wrappers = sorted((getattr(x, '__array_priority__', 0), -i, + x.__array_wrap__) for i, x in enumerate(args) + if hasattr(x, '__array_wrap__')) + if wrappers: + return wrappers[-1][-1] + return None + + +def _kron_dispatcher(a, b): + return (a, b) + + +@array_function_dispatch(_kron_dispatcher) +def kron(a, b): + """ + Kronecker product of two arrays. + + Computes the Kronecker product, a composite array made of blocks of the + second array scaled by the first. + + Parameters + ---------- + a, b : array_like + + Returns + ------- + out : ndarray + + See Also + -------- + outer : The outer product + + Notes + ----- + The function assumes that the number of dimensions of `a` and `b` + are the same, if necessary prepending the smallest with ones. + If ``a.shape = (r0,r1,...,rN)`` and ``b.shape = (s0,s1,...,sN)``, + the Kronecker product has shape ``(r0*s0, r1*s1, ..., rN*SN)``. + The elements are products of elements from `a` and `b`, organized + explicitly by:: + + kron(a,b)[k0,k1,...,kN] = a[i0,i1,...,iN] * b[j0,j1,...,jN] + + where:: + + kt = it * st + jt, t = 0,...,N + + In the common 2-D case (N=1), the block structure can be visualized:: + + [[ a[0,0]*b, a[0,1]*b, ... , a[0,-1]*b ], + [ ... ... ], + [ a[-1,0]*b, a[-1,1]*b, ... , a[-1,-1]*b ]] + + + Examples + -------- + >>> import numpy as np + >>> np.kron([1,10,100], [5,6,7]) + array([ 5, 6, 7, ..., 500, 600, 700]) + >>> np.kron([5,6,7], [1,10,100]) + array([ 5, 50, 500, ..., 7, 70, 700]) + + >>> np.kron(np.eye(2), np.ones((2,2))) + array([[1., 1., 0., 0.], + [1., 1., 0., 0.], + [0., 0., 1., 1.], + [0., 0., 1., 1.]]) + + >>> a = np.arange(100).reshape((2,5,2,5)) + >>> b = np.arange(24).reshape((2,3,4)) + >>> c = np.kron(a,b) + >>> c.shape + (2, 10, 6, 20) + >>> I = (1,3,0,2) + >>> J = (0,2,1) + >>> J1 = (0,) + J # extend to ndim=4 + >>> S1 = (1,) + b.shape + >>> K = tuple(np.array(I) * np.array(S1) + np.array(J1)) + >>> c[K] == a[I]*b[J] + True + + """ + # Working: + # 1. Equalise the shapes by prepending smaller array with 1s + # 2. Expand shapes of both the arrays by adding new axes at + # odd positions for 1st array and even positions for 2nd + # 3. Compute the product of the modified array + # 4. The inner most array elements now contain the rows of + # the Kronecker product + # 5. Reshape the result to kron's shape, which is same as + # product of shapes of the two arrays. + b = asanyarray(b) + a = array(a, copy=None, subok=True, ndmin=b.ndim) + is_any_mat = isinstance(a, matrix) or isinstance(b, matrix) + ndb, nda = b.ndim, a.ndim + nd = max(ndb, nda) + + if (nda == 0 or ndb == 0): + return _nx.multiply(a, b) + + as_ = a.shape + bs = b.shape + if not a.flags.contiguous: + a = reshape(a, as_) + if not b.flags.contiguous: + b = reshape(b, bs) + + # Equalise the shapes by prepending smaller one with 1s + as_ = (1,) * max(0, ndb - nda) + as_ + bs = (1,) * max(0, nda - ndb) + bs + + # Insert empty dimensions + a_arr = expand_dims(a, axis=tuple(range(ndb - nda))) + b_arr = expand_dims(b, axis=tuple(range(nda - ndb))) + + # Compute the product + a_arr = expand_dims(a_arr, axis=tuple(range(1, nd * 2, 2))) + b_arr = expand_dims(b_arr, axis=tuple(range(0, nd * 2, 2))) + # In case of `mat`, convert result to `array` + result = _nx.multiply(a_arr, b_arr, subok=(not is_any_mat)) + + # Reshape back + result = result.reshape(_nx.multiply(as_, bs)) + + return result if not is_any_mat else matrix(result, copy=False) + + +def _tile_dispatcher(A, reps): + return (A, reps) + + +@array_function_dispatch(_tile_dispatcher) +def tile(A, reps): + """ + Construct an array by repeating A the number of times given by reps. + + If `reps` has length ``d``, the result will have dimension of + ``max(d, A.ndim)``. + + If ``A.ndim < d``, `A` is promoted to be d-dimensional by prepending new + axes. So a shape (3,) array is promoted to (1, 3) for 2-D replication, + or shape (1, 1, 3) for 3-D replication. If this is not the desired + behavior, promote `A` to d-dimensions manually before calling this + function. + + If ``A.ndim > d``, `reps` is promoted to `A`.ndim by prepending 1's to it. + Thus for an `A` of shape (2, 3, 4, 5), a `reps` of (2, 2) is treated as + (1, 1, 2, 2). + + Note : Although tile may be used for broadcasting, it is strongly + recommended to use numpy's broadcasting operations and functions. + + Parameters + ---------- + A : array_like + The input array. + reps : array_like + The number of repetitions of `A` along each axis. + + Returns + ------- + c : ndarray + The tiled output array. + + See Also + -------- + repeat : Repeat elements of an array. + broadcast_to : Broadcast an array to a new shape + + Examples + -------- + >>> import numpy as np + >>> a = np.array([0, 1, 2]) + >>> np.tile(a, 2) + array([0, 1, 2, 0, 1, 2]) + >>> np.tile(a, (2, 2)) + array([[0, 1, 2, 0, 1, 2], + [0, 1, 2, 0, 1, 2]]) + >>> np.tile(a, (2, 1, 2)) + array([[[0, 1, 2, 0, 1, 2]], + [[0, 1, 2, 0, 1, 2]]]) + + >>> b = np.array([[1, 2], [3, 4]]) + >>> np.tile(b, 2) + array([[1, 2, 1, 2], + [3, 4, 3, 4]]) + >>> np.tile(b, (2, 1)) + array([[1, 2], + [3, 4], + [1, 2], + [3, 4]]) + + >>> c = np.array([1,2,3,4]) + >>> np.tile(c,(4,1)) + array([[1, 2, 3, 4], + [1, 2, 3, 4], + [1, 2, 3, 4], + [1, 2, 3, 4]]) + """ + try: + tup = tuple(reps) + except TypeError: + tup = (reps,) + d = len(tup) + if all(x == 1 for x in tup) and isinstance(A, _nx.ndarray): + # Fixes the problem that the function does not make a copy if A is a + # numpy array and the repetitions are 1 in all dimensions + return _nx.array(A, copy=True, subok=True, ndmin=d) + else: + # Note that no copy of zero-sized arrays is made. However since they + # have no data there is no risk of an inadvertent overwrite. + c = _nx.array(A, copy=None, subok=True, ndmin=d) + if (d < c.ndim): + tup = (1,) * (c.ndim - d) + tup + shape_out = tuple(s * t for s, t in zip(c.shape, tup)) + n = c.size + if n > 0: + for dim_in, nrep in zip(c.shape, tup): + if nrep != 1: + c = c.reshape(-1, n).repeat(nrep, 0) + n //= dim_in + return c.reshape(shape_out) diff --git a/python/user_packages/Python313/site-packages/numpy/lib/_shape_base_impl.pyi b/python/user_packages/Python313/site-packages/numpy/lib/_shape_base_impl.pyi new file mode 100644 index 0000000000000000000000000000000000000000..aab222346486be54e8c074943b70eb47322fb779 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/lib/_shape_base_impl.pyi @@ -0,0 +1,236 @@ +from collections.abc import Callable, Sequence +from typing import ( + Any, + Concatenate, + ParamSpec, + Protocol, + SupportsIndex, + TypeVar, + overload, + type_check_only, +) +from typing_extensions import deprecated + +import numpy as np +from numpy import ( + _CastingKind, + complexfloating, + floating, + generic, + integer, + object_, + signedinteger, + ufunc, + unsignedinteger, +) +from numpy._typing import ( + ArrayLike, + DTypeLike, + NDArray, + _ArrayLike, + _ArrayLikeBool_co, + _ArrayLikeComplex_co, + _ArrayLikeFloat_co, + _ArrayLikeInt_co, + _ArrayLikeObject_co, + _ArrayLikeUInt_co, + _ShapeLike, +) + +__all__ = [ + "column_stack", + "row_stack", + "dstack", + "array_split", + "split", + "hsplit", + "vsplit", + "dsplit", + "apply_over_axes", + "expand_dims", + "apply_along_axis", + "kron", + "tile", + "take_along_axis", + "put_along_axis", +] + +_P = ParamSpec("_P") +_ScalarT = TypeVar("_ScalarT", bound=generic) + +# Signature of `__array_wrap__` +@type_check_only +class _ArrayWrap(Protocol): + def __call__( + self, + array: NDArray[Any], + context: tuple[ufunc, tuple[Any, ...], int] | None = ..., + return_scalar: bool = ..., + /, + ) -> Any: ... + +@type_check_only +class _SupportsArrayWrap(Protocol): + @property + def __array_wrap__(self) -> _ArrayWrap: ... + +### + +def take_along_axis( + arr: _ScalarT | NDArray[_ScalarT], + indices: NDArray[integer], + axis: int | None = -1, +) -> NDArray[_ScalarT]: ... + +def put_along_axis( + arr: NDArray[_ScalarT], + indices: NDArray[integer], + values: ArrayLike, + axis: int | None, +) -> None: ... + +@overload +def apply_along_axis( + func1d: Callable[Concatenate[NDArray[Any], _P], _ArrayLike[_ScalarT]], + axis: SupportsIndex, + arr: ArrayLike, + *args: _P.args, + **kwargs: _P.kwargs, +) -> NDArray[_ScalarT]: ... +@overload +def apply_along_axis( + func1d: Callable[Concatenate[NDArray[Any], _P], Any], + axis: SupportsIndex, + arr: ArrayLike, + *args: _P.args, + **kwargs: _P.kwargs, +) -> NDArray[Any]: ... + +def apply_over_axes( + func: Callable[[NDArray[Any], int], NDArray[_ScalarT]], + a: ArrayLike, + axes: int | Sequence[int], +) -> NDArray[_ScalarT]: ... + +@overload +def expand_dims( + a: _ArrayLike[_ScalarT], + axis: _ShapeLike, +) -> NDArray[_ScalarT]: ... +@overload +def expand_dims( + a: ArrayLike, + axis: _ShapeLike, +) -> NDArray[Any]: ... + +# Deprecated in NumPy 2.0, 2023-08-18 +@deprecated("`row_stack` alias is deprecated. Use `np.vstack` directly.") +def row_stack( + tup: Sequence[ArrayLike], + *, + dtype: DTypeLike | None = None, + casting: _CastingKind = "same_kind", +) -> NDArray[Any]: ... + +# keep in sync with `numpy.ma.extras.column_stack` +@overload +def column_stack(tup: Sequence[_ArrayLike[_ScalarT]]) -> NDArray[_ScalarT]: ... +@overload +def column_stack(tup: Sequence[ArrayLike]) -> NDArray[Any]: ... + +# keep in sync with `numpy.ma.extras.dstack` +@overload +def dstack(tup: Sequence[_ArrayLike[_ScalarT]]) -> NDArray[_ScalarT]: ... +@overload +def dstack(tup: Sequence[ArrayLike]) -> NDArray[Any]: ... + +@overload +def array_split( + ary: _ArrayLike[_ScalarT], + indices_or_sections: _ShapeLike, + axis: SupportsIndex = 0, +) -> list[NDArray[_ScalarT]]: ... +@overload +def array_split( + ary: ArrayLike, + indices_or_sections: _ShapeLike, + axis: SupportsIndex = 0, +) -> list[NDArray[Any]]: ... + +@overload +def split( + ary: _ArrayLike[_ScalarT], + indices_or_sections: _ShapeLike, + axis: SupportsIndex = 0, +) -> list[NDArray[_ScalarT]]: ... +@overload +def split( + ary: ArrayLike, + indices_or_sections: _ShapeLike, + axis: SupportsIndex = 0, +) -> list[NDArray[Any]]: ... + +# keep in sync with `numpy.ma.extras.hsplit` +@overload +def hsplit( + ary: _ArrayLike[_ScalarT], + indices_or_sections: _ShapeLike, +) -> list[NDArray[_ScalarT]]: ... +@overload +def hsplit( + ary: ArrayLike, + indices_or_sections: _ShapeLike, +) -> list[NDArray[Any]]: ... + +@overload +def vsplit( + ary: _ArrayLike[_ScalarT], + indices_or_sections: _ShapeLike, +) -> list[NDArray[_ScalarT]]: ... +@overload +def vsplit( + ary: ArrayLike, + indices_or_sections: _ShapeLike, +) -> list[NDArray[Any]]: ... + +@overload +def dsplit( + ary: _ArrayLike[_ScalarT], + indices_or_sections: _ShapeLike, +) -> list[NDArray[_ScalarT]]: ... +@overload +def dsplit( + ary: ArrayLike, + indices_or_sections: _ShapeLike, +) -> list[NDArray[Any]]: ... + +@overload +def get_array_wrap(*args: _SupportsArrayWrap) -> _ArrayWrap: ... +@overload +def get_array_wrap(*args: object) -> _ArrayWrap | None: ... + +@overload +def kron(a: _ArrayLikeBool_co, b: _ArrayLikeBool_co) -> NDArray[np.bool]: ... # type: ignore[misc] +@overload +def kron(a: _ArrayLikeUInt_co, b: _ArrayLikeUInt_co) -> NDArray[unsignedinteger]: ... # type: ignore[misc] +@overload +def kron(a: _ArrayLikeInt_co, b: _ArrayLikeInt_co) -> NDArray[signedinteger]: ... # type: ignore[misc] +@overload +def kron(a: _ArrayLikeFloat_co, b: _ArrayLikeFloat_co) -> NDArray[floating]: ... # type: ignore[misc] +@overload +def kron(a: _ArrayLikeComplex_co, b: _ArrayLikeComplex_co) -> NDArray[complexfloating]: ... +@overload +def kron(a: _ArrayLikeObject_co, b: Any) -> NDArray[object_]: ... +@overload +def kron(a: Any, b: _ArrayLikeObject_co) -> NDArray[object_]: ... + +@overload +def tile( + A: _ArrayLike[_ScalarT], + reps: int | Sequence[int], +) -> NDArray[_ScalarT]: ... +@overload +def tile( + A: ArrayLike, + reps: int | Sequence[int], +) -> NDArray[Any]: ... diff --git a/python/user_packages/Python313/site-packages/numpy/lib/_stride_tricks_impl.py b/python/user_packages/Python313/site-packages/numpy/lib/_stride_tricks_impl.py new file mode 100644 index 0000000000000000000000000000000000000000..0545dfa9d1a9dad3b62afba0c542be428ac2141a --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/lib/_stride_tricks_impl.py @@ -0,0 +1,582 @@ +""" +Utilities that manipulate strides to achieve desirable effects. + +An explanation of strides can be found in the :ref:`arrays.ndarray`. + +""" +import numpy as np +from numpy._core.numeric import normalize_axis_tuple +from numpy._core.overrides import array_function_dispatch, set_module + +__all__ = ['broadcast_to', 'broadcast_arrays', 'broadcast_shapes'] + + +class DummyArray: + """Dummy object that just exists to hang __array_interface__ dictionaries + and possibly keep alive a reference to a base array. + """ + + def __init__(self, interface, base=None): + self.__array_interface__ = interface + self.base = base + + +def _maybe_view_as_subclass(original_array, new_array): + if type(original_array) is not type(new_array): + # if input was an ndarray subclass and subclasses were OK, + # then view the result as that subclass. + new_array = new_array.view(type=type(original_array)) + # Since we have done something akin to a view from original_array, we + # should let the subclass finalize (if it has it implemented, i.e., is + # not None). + if new_array.__array_finalize__: + new_array.__array_finalize__(original_array) + return new_array + + +@set_module("numpy.lib.stride_tricks") +def as_strided(x, shape=None, strides=None, subok=False, writeable=True): + """ + Create a view into the array with the given shape and strides. + + .. warning:: This function has to be used with extreme care, see notes. + + Parameters + ---------- + x : ndarray + Array to create a new. + shape : sequence of int, optional + The shape of the new array. Defaults to ``x.shape``. + strides : sequence of int, optional + The strides of the new array. Defaults to ``x.strides``. + subok : bool, optional + If True, subclasses are preserved. + writeable : bool, optional + If set to False, the returned array will always be readonly. + Otherwise it will be writable if the original array was. It + is advisable to set this to False if possible (see Notes). + + Returns + ------- + view : ndarray + + See also + -------- + broadcast_to : broadcast an array to a given shape. + reshape : reshape an array. + lib.stride_tricks.sliding_window_view : + userfriendly and safe function for a creation of sliding window views. + + Notes + ----- + ``as_strided`` creates a view into the array given the exact strides + and shape. This means it manipulates the internal data structure of + ndarray and, if done incorrectly, the array elements can point to + invalid memory and can corrupt results or crash your program. + It is advisable to always use the original ``x.strides`` when + calculating new strides to avoid reliance on a contiguous memory + layout. + + Furthermore, arrays created with this function often contain self + overlapping memory, so that two elements are identical. + Vectorized write operations on such arrays will typically be + unpredictable. They may even give different results for small, large, + or transposed arrays. + + Since writing to these arrays has to be tested and done with great + care, you may want to use ``writeable=False`` to avoid accidental write + operations. + + For these reasons it is advisable to avoid ``as_strided`` when + possible. + """ + # first convert input to array, possibly keeping subclass + x = np.array(x, copy=None, subok=subok) + interface = dict(x.__array_interface__) + if shape is not None: + interface['shape'] = tuple(shape) + if strides is not None: + interface['strides'] = tuple(strides) + + array = np.asarray(DummyArray(interface, base=x)) + # The route via `__interface__` does not preserve structured + # dtypes. Since dtype should remain unchanged, we set it explicitly. + array.dtype = x.dtype + + view = _maybe_view_as_subclass(x, array) + + if view.flags.writeable and not writeable: + view.flags.writeable = False + + return view + + +def _sliding_window_view_dispatcher(x, window_shape, axis=None, *, + subok=None, writeable=None): + return (x,) + + +@array_function_dispatch( + _sliding_window_view_dispatcher, module="numpy.lib.stride_tricks" +) +def sliding_window_view(x, window_shape, axis=None, *, + subok=False, writeable=False): + """ + Create a sliding window view into the array with the given window shape. + + Also known as rolling or moving window, the window slides across all + dimensions of the array and extracts subsets of the array at all window + positions. + + .. versionadded:: 1.20.0 + + Parameters + ---------- + x : array_like + Array to create the sliding window view from. + window_shape : int or tuple of int + Size of window over each axis that takes part in the sliding window. + If `axis` is not present, must have same length as the number of input + array dimensions. Single integers `i` are treated as if they were the + tuple `(i,)`. + axis : int or tuple of int, optional + Axis or axes along which the sliding window is applied. + By default, the sliding window is applied to all axes and + `window_shape[i]` will refer to axis `i` of `x`. + If `axis` is given as a `tuple of int`, `window_shape[i]` will refer to + the axis `axis[i]` of `x`. + Single integers `i` are treated as if they were the tuple `(i,)`. + subok : bool, optional + If True, sub-classes will be passed-through, otherwise the returned + array will be forced to be a base-class array (default). + writeable : bool, optional + When true, allow writing to the returned view. The default is false, + as this should be used with caution: the returned view contains the + same memory location multiple times, so writing to one location will + cause others to change. + + Returns + ------- + view : ndarray + Sliding window view of the array. The sliding window dimensions are + inserted at the end, and the original dimensions are trimmed as + required by the size of the sliding window. + That is, ``view.shape = x_shape_trimmed + window_shape``, where + ``x_shape_trimmed`` is ``x.shape`` with every entry reduced by one less + than the corresponding window size. + + See Also + -------- + lib.stride_tricks.as_strided: A lower-level and less safe routine for + creating arbitrary views from custom shape and strides. + broadcast_to: broadcast an array to a given shape. + + Notes + ----- + .. warning:: + + This function creates views with overlapping memory. When + ``writeable=True``, writing to the view will modify the original array + and may affect multiple view positions. See the examples below and + :doc:`this guide ` + about the difference between copies and views. + + For many applications using a sliding window view can be convenient, but + potentially very slow. Often specialized solutions exist, for example: + + - `scipy.signal.fftconvolve` + + - filtering functions in `scipy.ndimage` + + - moving window functions provided by + `bottleneck `_. + + As a rough estimate, a sliding window approach with an input size of `N` + and a window size of `W` will scale as `O(N*W)` where frequently a special + algorithm can achieve `O(N)`. That means that the sliding window variant + for a window size of 100 can be a 100 times slower than a more specialized + version. + + Nevertheless, for small window sizes, when no custom algorithm exists, or + as a prototyping and developing tool, this function can be a good solution. + + Examples + -------- + >>> import numpy as np + >>> from numpy.lib.stride_tricks import sliding_window_view + >>> x = np.arange(6) + >>> x.shape + (6,) + >>> v = sliding_window_view(x, 3) + >>> v.shape + (4, 3) + >>> v + array([[0, 1, 2], + [1, 2, 3], + [2, 3, 4], + [3, 4, 5]]) + + This also works in more dimensions, e.g. + + >>> i, j = np.ogrid[:3, :4] + >>> x = 10*i + j + >>> x.shape + (3, 4) + >>> x + array([[ 0, 1, 2, 3], + [10, 11, 12, 13], + [20, 21, 22, 23]]) + >>> shape = (2,2) + >>> v = sliding_window_view(x, shape) + >>> v.shape + (2, 3, 2, 2) + >>> v + array([[[[ 0, 1], + [10, 11]], + [[ 1, 2], + [11, 12]], + [[ 2, 3], + [12, 13]]], + [[[10, 11], + [20, 21]], + [[11, 12], + [21, 22]], + [[12, 13], + [22, 23]]]]) + + The axis can be specified explicitly: + + >>> v = sliding_window_view(x, 3, 0) + >>> v.shape + (1, 4, 3) + >>> v + array([[[ 0, 10, 20], + [ 1, 11, 21], + [ 2, 12, 22], + [ 3, 13, 23]]]) + + The same axis can be used several times. In that case, every use reduces + the corresponding original dimension: + + >>> v = sliding_window_view(x, (2, 3), (1, 1)) + >>> v.shape + (3, 1, 2, 3) + >>> v + array([[[[ 0, 1, 2], + [ 1, 2, 3]]], + [[[10, 11, 12], + [11, 12, 13]]], + [[[20, 21, 22], + [21, 22, 23]]]]) + + Combining with stepped slicing (`::step`), this can be used to take sliding + views which skip elements: + + >>> x = np.arange(7) + >>> sliding_window_view(x, 5)[:, ::2] + array([[0, 2, 4], + [1, 3, 5], + [2, 4, 6]]) + + or views which move by multiple elements + + >>> x = np.arange(7) + >>> sliding_window_view(x, 3)[::2, :] + array([[0, 1, 2], + [2, 3, 4], + [4, 5, 6]]) + + A common application of `sliding_window_view` is the calculation of running + statistics. The simplest example is the + `moving average `_: + + >>> x = np.arange(6) + >>> x.shape + (6,) + >>> v = sliding_window_view(x, 3) + >>> v.shape + (4, 3) + >>> v + array([[0, 1, 2], + [1, 2, 3], + [2, 3, 4], + [3, 4, 5]]) + >>> moving_average = v.mean(axis=-1) + >>> moving_average + array([1., 2., 3., 4.]) + + The two examples below demonstrate the effect of ``writeable=True``. + + Creating a view with the default ``writeable=False`` and then writing to + it raises an error. + + >>> v = sliding_window_view(x, 3) + >>> v[0,1] = 10 + Traceback (most recent call last): + ... + ValueError: assignment destination is read-only + + Creating a view with ``writeable=True`` and then writing to it changes + the original array and multiple view positions. + + >>> x = np.arange(6) # reset x for the second example + >>> v = sliding_window_view(x, 3, writeable=True) + >>> v[0,1] = 10 + >>> x + array([ 0, 10, 2, 3, 4, 5]) + >>> v + array([[ 0, 10, 2], + [10, 2, 3], + [ 2, 3, 4], + [ 3, 4, 5]]) + + Note that a sliding window approach is often **not** optimal (see Notes). + """ + window_shape = (tuple(window_shape) + if np.iterable(window_shape) + else (window_shape,)) + # first convert input to array, possibly keeping subclass + x = np.array(x, copy=None, subok=subok) + + window_shape_array = np.array(window_shape) + if np.any(window_shape_array < 0): + raise ValueError('`window_shape` cannot contain negative values') + + if axis is None: + axis = tuple(range(x.ndim)) + if len(window_shape) != len(axis): + raise ValueError(f'Since axis is `None`, must provide ' + f'window_shape for all dimensions of `x`; ' + f'got {len(window_shape)} window_shape elements ' + f'and `x.ndim` is {x.ndim}.') + else: + axis = normalize_axis_tuple(axis, x.ndim, allow_duplicate=True) + if len(window_shape) != len(axis): + raise ValueError(f'Must provide matching length window_shape and ' + f'axis; got {len(window_shape)} window_shape ' + f'elements and {len(axis)} axes elements.') + + out_strides = x.strides + tuple(x.strides[ax] for ax in axis) + + # note: same axis can be windowed repeatedly + x_shape_trimmed = list(x.shape) + for ax, dim in zip(axis, window_shape): + if x_shape_trimmed[ax] < dim: + raise ValueError( + 'window shape cannot be larger than input array shape') + x_shape_trimmed[ax] -= dim - 1 + out_shape = tuple(x_shape_trimmed) + window_shape + return as_strided(x, strides=out_strides, shape=out_shape, + subok=subok, writeable=writeable) + + +def _broadcast_to(array, shape, subok, readonly): + shape = tuple(shape) if np.iterable(shape) else (shape,) + array = np.array(array, copy=None, subok=subok) + if not shape and array.shape: + raise ValueError('cannot broadcast a non-scalar to a scalar array') + if any(size < 0 for size in shape): + raise ValueError('all elements of broadcast shape must be non-' + 'negative') + extras = [] + it = np.nditer( + (array,), flags=['multi_index', 'refs_ok', 'zerosize_ok'] + extras, + op_flags=['readonly'], itershape=shape, order='C') + with it: + # never really has writebackifcopy semantics + broadcast = it.itviews[0] + result = _maybe_view_as_subclass(array, broadcast) + # In a future version this will go away + if not readonly and array.flags._writeable_no_warn: + result.flags.writeable = True + result.flags._warn_on_write = True + return result + + +def _broadcast_to_dispatcher(array, shape, subok=None): + return (array,) + + +@array_function_dispatch(_broadcast_to_dispatcher, module='numpy') +def broadcast_to(array, shape, subok=False): + """Broadcast an array to a new shape. + + Parameters + ---------- + array : array_like + The array to broadcast. + shape : tuple or int + The shape of the desired array. A single integer ``i`` is interpreted + as ``(i,)``. + subok : bool, optional + If True, then sub-classes will be passed-through, otherwise + the returned array will be forced to be a base-class array (default). + + Returns + ------- + broadcast : array + A readonly view on the original array with the given shape. It is + typically not contiguous. Furthermore, more than one element of a + broadcasted array may refer to a single memory location. + + Raises + ------ + ValueError + If the array is not compatible with the new shape according to NumPy's + broadcasting rules. + + See Also + -------- + broadcast + broadcast_arrays + broadcast_shapes + + Examples + -------- + >>> import numpy as np + >>> x = np.array([1, 2, 3]) + >>> np.broadcast_to(x, (3, 3)) + array([[1, 2, 3], + [1, 2, 3], + [1, 2, 3]]) + """ + return _broadcast_to(array, shape, subok=subok, readonly=True) + + +def _broadcast_shape(*args): + """Returns the shape of the arrays that would result from broadcasting the + supplied arrays against each other. + """ + # use the old-iterator because np.nditer does not handle size 0 arrays + # consistently + b = np.broadcast(*args[:64]) + # unfortunately, it cannot handle 64 or more arguments directly + for pos in range(64, len(args), 63): + # ironically, np.broadcast does not properly handle np.broadcast + # objects (it treats them as scalars) + # use broadcasting to avoid allocating the full array + b = broadcast_to(0, b.shape) + b = np.broadcast(b, *args[pos:(pos + 63)]) + return b.shape + + +_size0_dtype = np.dtype([]) + + +@set_module('numpy') +def broadcast_shapes(*args): + """ + Broadcast the input shapes into a single shape. + + :ref:`Learn more about broadcasting here `. + + .. versionadded:: 1.20.0 + + Parameters + ---------- + *args : tuples of ints, or ints + The shapes to be broadcast against each other. + + Returns + ------- + tuple + Broadcasted shape. + + Raises + ------ + ValueError + If the shapes are not compatible and cannot be broadcast according + to NumPy's broadcasting rules. + + See Also + -------- + broadcast + broadcast_arrays + broadcast_to + + Examples + -------- + >>> import numpy as np + >>> np.broadcast_shapes((1, 2), (3, 1), (3, 2)) + (3, 2) + + >>> np.broadcast_shapes((6, 7), (5, 6, 1), (7,), (5, 1, 7)) + (5, 6, 7) + """ + arrays = [np.empty(x, dtype=_size0_dtype) for x in args] + return _broadcast_shape(*arrays) + + +def _broadcast_arrays_dispatcher(*args, subok=None): + return args + + +@array_function_dispatch(_broadcast_arrays_dispatcher, module='numpy') +def broadcast_arrays(*args, subok=False): + """ + Broadcast any number of arrays against each other. + + Parameters + ---------- + *args : array_likes + The arrays to broadcast. + + subok : bool, optional + If True, then sub-classes will be passed-through, otherwise + the returned arrays will be forced to be a base-class array (default). + + Returns + ------- + broadcasted : tuple of arrays + These arrays are views on the original arrays. They are typically + not contiguous. Furthermore, more than one element of a + broadcasted array may refer to a single memory location. If you need + to write to the arrays, make copies first. While you can set the + ``writable`` flag True, writing to a single output value may end up + changing more than one location in the output array. + + .. deprecated:: 1.17 + The output is currently marked so that if written to, a deprecation + warning will be emitted. A future version will set the + ``writable`` flag False so writing to it will raise an error. + + See Also + -------- + broadcast + broadcast_to + broadcast_shapes + + Examples + -------- + >>> import numpy as np + >>> x = np.array([[1,2,3]]) + >>> y = np.array([[4],[5]]) + >>> np.broadcast_arrays(x, y) + (array([[1, 2, 3], + [1, 2, 3]]), + array([[4, 4, 4], + [5, 5, 5]])) + + Here is a useful idiom for getting contiguous copies instead of + non-contiguous views. + + >>> [np.array(a) for a in np.broadcast_arrays(x, y)] + [array([[1, 2, 3], + [1, 2, 3]]), + array([[4, 4, 4], + [5, 5, 5]])] + + """ + # nditer is not used here to avoid the limit of 64 arrays. + # Otherwise, something like the following one-liner would suffice: + # return np.nditer(args, flags=['multi_index', 'zerosize_ok'], + # order='C').itviews + + args = [np.array(_m, copy=None, subok=subok) for _m in args] + + shape = _broadcast_shape(*args) + + result = [array if array.shape == shape + else _broadcast_to(array, shape, subok=subok, readonly=False) + for array in args] + return tuple(result) diff --git a/python/user_packages/Python313/site-packages/numpy/lib/_stride_tricks_impl.pyi b/python/user_packages/Python313/site-packages/numpy/lib/_stride_tricks_impl.pyi new file mode 100644 index 0000000000000000000000000000000000000000..b71840820d13897fc06f5d26b816ab9e37838b5a --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/lib/_stride_tricks_impl.pyi @@ -0,0 +1,73 @@ +from collections.abc import Iterable +from typing import Any, SupportsIndex, TypeVar, overload + +from numpy import generic +from numpy._typing import ArrayLike, NDArray, _AnyShape, _ArrayLike, _ShapeLike + +__all__ = ["broadcast_to", "broadcast_arrays", "broadcast_shapes"] + +_ScalarT = TypeVar("_ScalarT", bound=generic) + +class DummyArray: + __array_interface__: dict[str, Any] + base: NDArray[Any] | None + def __init__( + self, + interface: dict[str, Any], + base: NDArray[Any] | None = None, + ) -> None: ... + +@overload +def as_strided( + x: _ArrayLike[_ScalarT], + shape: Iterable[int] | None = None, + strides: Iterable[int] | None = None, + subok: bool = False, + writeable: bool = True, +) -> NDArray[_ScalarT]: ... +@overload +def as_strided( + x: ArrayLike, + shape: Iterable[int] | None = None, + strides: Iterable[int] | None = None, + subok: bool = False, + writeable: bool = True, +) -> NDArray[Any]: ... + +@overload +def sliding_window_view( + x: _ArrayLike[_ScalarT], + window_shape: int | Iterable[int], + axis: SupportsIndex | None = None, + *, + subok: bool = False, + writeable: bool = False, +) -> NDArray[_ScalarT]: ... +@overload +def sliding_window_view( + x: ArrayLike, + window_shape: int | Iterable[int], + axis: SupportsIndex | None = None, + *, + subok: bool = False, + writeable: bool = False, +) -> NDArray[Any]: ... + +@overload +def broadcast_to( + array: _ArrayLike[_ScalarT], + shape: int | Iterable[int], + subok: bool = False, +) -> NDArray[_ScalarT]: ... +@overload +def broadcast_to( + array: ArrayLike, + shape: int | Iterable[int], + subok: bool = False, +) -> NDArray[Any]: ... + +def broadcast_shapes(*args: _ShapeLike) -> _AnyShape: ... +def broadcast_arrays(*args: ArrayLike, subok: bool = False) -> tuple[NDArray[Any], ...]: ... + +# used internally by `lib._function_base_impl._parse_input_dimensions` +def _broadcast_shape(*args: ArrayLike) -> _AnyShape: ... diff --git a/python/user_packages/Python313/site-packages/numpy/lib/_twodim_base_impl.py b/python/user_packages/Python313/site-packages/numpy/lib/_twodim_base_impl.py new file mode 100644 index 0000000000000000000000000000000000000000..dc1ee89cbc8b9468b3cb228d3569d9c5c2e20508 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/lib/_twodim_base_impl.py @@ -0,0 +1,1201 @@ +""" Basic functions for manipulating 2d arrays + +""" +import functools +import operator + +from numpy._core import iinfo, overrides +from numpy._core._multiarray_umath import _array_converter +from numpy._core.numeric import ( + arange, + asanyarray, + asarray, + diagonal, + empty, + greater_equal, + indices, + int8, + int16, + int32, + int64, + intp, + multiply, + nonzero, + ones, + promote_types, + where, + zeros, +) +from numpy._core.overrides import finalize_array_function_like, set_module +from numpy.lib._stride_tricks_impl import broadcast_to + +__all__ = [ + 'diag', 'diagflat', 'eye', 'fliplr', 'flipud', 'tri', 'triu', + 'tril', 'vander', 'histogram2d', 'mask_indices', 'tril_indices', + 'tril_indices_from', 'triu_indices', 'triu_indices_from', ] + + +array_function_dispatch = functools.partial( + overrides.array_function_dispatch, module='numpy') + + +i1 = iinfo(int8) +i2 = iinfo(int16) +i4 = iinfo(int32) + + +def _min_int(low, high): + """ get small int that fits the range """ + if high <= i1.max and low >= i1.min: + return int8 + if high <= i2.max and low >= i2.min: + return int16 + if high <= i4.max and low >= i4.min: + return int32 + return int64 + + +def _flip_dispatcher(m): + return (m,) + + +@array_function_dispatch(_flip_dispatcher) +def fliplr(m): + """ + Reverse the order of elements along axis 1 (left/right). + + For a 2-D array, this flips the entries in each row in the left/right + direction. Columns are preserved, but appear in a different order than + before. + + Parameters + ---------- + m : array_like + Input array, must be at least 2-D. + + Returns + ------- + f : ndarray + A view of `m` with the columns reversed. Since a view + is returned, this operation is :math:`\\mathcal O(1)`. + + See Also + -------- + flipud : Flip array in the up/down direction. + flip : Flip array in one or more dimensions. + rot90 : Rotate array counterclockwise. + + Notes + ----- + Equivalent to ``m[:,::-1]`` or ``np.flip(m, axis=1)``. + Requires the array to be at least 2-D. + + Examples + -------- + >>> import numpy as np + >>> A = np.diag([1.,2.,3.]) + >>> A + array([[1., 0., 0.], + [0., 2., 0.], + [0., 0., 3.]]) + >>> np.fliplr(A) + array([[0., 0., 1.], + [0., 2., 0.], + [3., 0., 0.]]) + + >>> rng = np.random.default_rng() + >>> A = rng.normal(size=(2,3,5)) + >>> np.all(np.fliplr(A) == A[:,::-1,...]) + True + + """ + m = asanyarray(m) + if m.ndim < 2: + raise ValueError("Input must be >= 2-d.") + return m[:, ::-1] + + +@array_function_dispatch(_flip_dispatcher) +def flipud(m): + """ + Reverse the order of elements along axis 0 (up/down). + + For a 2-D array, this flips the entries in each column in the up/down + direction. Rows are preserved, but appear in a different order than before. + + Parameters + ---------- + m : array_like + Input array. + + Returns + ------- + out : array_like + A view of `m` with the rows reversed. Since a view is + returned, this operation is :math:`\\mathcal O(1)`. + + See Also + -------- + fliplr : Flip array in the left/right direction. + flip : Flip array in one or more dimensions. + rot90 : Rotate array counterclockwise. + + Notes + ----- + Equivalent to ``m[::-1, ...]`` or ``np.flip(m, axis=0)``. + Requires the array to be at least 1-D. + + Examples + -------- + >>> import numpy as np + >>> A = np.diag([1.0, 2, 3]) + >>> A + array([[1., 0., 0.], + [0., 2., 0.], + [0., 0., 3.]]) + >>> np.flipud(A) + array([[0., 0., 3.], + [0., 2., 0.], + [1., 0., 0.]]) + + >>> rng = np.random.default_rng() + >>> A = rng.normal(size=(2,3,5)) + >>> np.all(np.flipud(A) == A[::-1,...]) + True + + >>> np.flipud([1,2]) + array([2, 1]) + + """ + m = asanyarray(m) + if m.ndim < 1: + raise ValueError("Input must be >= 1-d.") + return m[::-1, ...] + + +@finalize_array_function_like +@set_module('numpy') +def eye(N, M=None, k=0, dtype=float, order='C', *, device=None, like=None): + """ + Return a 2-D array with ones on the diagonal and zeros elsewhere. + + Parameters + ---------- + N : int + Number of rows in the output. + M : int, optional + Number of columns in the output. If None, defaults to `N`. + k : int, optional + Index of the diagonal: 0 (the default) refers to the main diagonal, + a positive value refers to an upper diagonal, and a negative value + to a lower diagonal. + dtype : data-type, optional + Data-type of the returned array. + order : {'C', 'F'}, optional + Whether the output should be stored in row-major (C-style) or + column-major (Fortran-style) order in memory. + device : str, optional + The device on which to place the created array. Default: None. + For Array-API interoperability only, so must be ``"cpu"`` if passed. + + .. versionadded:: 2.0.0 + ${ARRAY_FUNCTION_LIKE} + + .. versionadded:: 1.20.0 + + Returns + ------- + I : ndarray of shape (N,M) + An array where all elements are equal to zero, except for the `k`-th + diagonal, whose values are equal to one. + + See Also + -------- + identity : (almost) equivalent function + diag : diagonal 2-D array from a 1-D array specified by the user. + + Examples + -------- + >>> import numpy as np + >>> np.eye(2, dtype=int) + array([[1, 0], + [0, 1]]) + >>> np.eye(3, k=1) + array([[0., 1., 0.], + [0., 0., 1.], + [0., 0., 0.]]) + + """ + if like is not None: + return _eye_with_like( + like, N, M=M, k=k, dtype=dtype, order=order, device=device + ) + if M is None: + M = N + m = zeros((N, M), dtype=dtype, order=order, device=device) + if k >= M: + return m + # Ensure M and k are integers, so we don't get any surprise casting + # results in the expressions `M-k` and `M+1` used below. This avoids + # a problem with inputs with type (for example) np.uint64. + M = operator.index(M) + k = operator.index(k) + if k >= 0: + i = k + else: + i = (-k) * M + m[:M - k].flat[i::M + 1] = 1 + return m + + +_eye_with_like = array_function_dispatch()(eye) + + +def _diag_dispatcher(v, k=None): + return (v,) + + +@array_function_dispatch(_diag_dispatcher) +def diag(v, k=0): + """ + Extract a diagonal or construct a diagonal array. + + See the more detailed documentation for ``numpy.diagonal`` if you use this + function to extract a diagonal and wish to write to the resulting array; + whether it returns a copy or a view depends on what version of numpy you + are using. + + Parameters + ---------- + v : array_like + If `v` is a 2-D array, return a copy of its `k`-th diagonal. + If `v` is a 1-D array, return a 2-D array with `v` on the `k`-th + diagonal. + k : int, optional + Diagonal in question. The default is 0. Use `k>0` for diagonals + above the main diagonal, and `k<0` for diagonals below the main + diagonal. + + Returns + ------- + out : ndarray + The extracted diagonal or constructed diagonal array. + + See Also + -------- + diagonal : Return specified diagonals. + diagflat : Create a 2-D array with the flattened input as a diagonal. + trace : Sum along diagonals. + triu : Upper triangle of an array. + tril : Lower triangle of an array. + + Examples + -------- + >>> import numpy as np + >>> x = np.arange(9).reshape((3,3)) + >>> x + array([[0, 1, 2], + [3, 4, 5], + [6, 7, 8]]) + + >>> np.diag(x) + array([0, 4, 8]) + >>> np.diag(x, k=1) + array([1, 5]) + >>> np.diag(x, k=-1) + array([3, 7]) + + >>> np.diag(np.diag(x)) + array([[0, 0, 0], + [0, 4, 0], + [0, 0, 8]]) + + """ + v = asanyarray(v) + s = v.shape + if len(s) == 1: + n = s[0] + abs(k) + res = zeros((n, n), v.dtype) + if k >= 0: + i = k + else: + i = (-k) * n + res[:n - k].flat[i::n + 1] = v + return res + elif len(s) == 2: + return diagonal(v, k) + else: + raise ValueError("Input must be 1- or 2-d.") + + +@array_function_dispatch(_diag_dispatcher) +def diagflat(v, k=0): + """ + Create a two-dimensional array with the flattened input as a diagonal. + + Parameters + ---------- + v : array_like + Input data, which is flattened and set as the `k`-th + diagonal of the output. + k : int, optional + Diagonal to set; 0, the default, corresponds to the "main" diagonal, + a positive (negative) `k` giving the number of the diagonal above + (below) the main. + + Returns + ------- + out : ndarray + The 2-D output array. + + See Also + -------- + diag : MATLAB work-alike for 1-D and 2-D arrays. + diagonal : Return specified diagonals. + trace : Sum along diagonals. + + Examples + -------- + >>> import numpy as np + >>> np.diagflat([[1,2], [3,4]]) + array([[1, 0, 0, 0], + [0, 2, 0, 0], + [0, 0, 3, 0], + [0, 0, 0, 4]]) + + >>> np.diagflat([1,2], 1) + array([[0, 1, 0], + [0, 0, 2], + [0, 0, 0]]) + + """ + conv = _array_converter(v) + v, = conv.as_arrays(subok=False) + v = v.ravel() + s = len(v) + n = s + abs(k) + res = zeros((n, n), v.dtype) + if (k >= 0): + i = arange(0, n - k, dtype=intp) + fi = i + k + i * n + else: + i = arange(0, n + k, dtype=intp) + fi = i + (i - k) * n + res.flat[fi] = v + + return conv.wrap(res) + + +@finalize_array_function_like +@set_module('numpy') +def tri(N, M=None, k=0, dtype=float, *, like=None): + """ + An array with ones at and below the given diagonal and zeros elsewhere. + + Parameters + ---------- + N : int + Number of rows in the array. + M : int, optional + Number of columns in the array. + By default, `M` is taken equal to `N`. + k : int, optional + The sub-diagonal at and below which the array is filled. + `k` = 0 is the main diagonal, while `k` < 0 is below it, + and `k` > 0 is above. The default is 0. + dtype : dtype, optional + Data type of the returned array. The default is float. + ${ARRAY_FUNCTION_LIKE} + + .. versionadded:: 1.20.0 + + Returns + ------- + tri : ndarray of shape (N, M) + Array with its lower triangle filled with ones and zero elsewhere; + in other words ``T[i,j] == 1`` for ``j <= i + k``, 0 otherwise. + + Examples + -------- + >>> import numpy as np + >>> np.tri(3, 5, 2, dtype=int) + array([[1, 1, 1, 0, 0], + [1, 1, 1, 1, 0], + [1, 1, 1, 1, 1]]) + + >>> np.tri(3, 5, -1) + array([[0., 0., 0., 0., 0.], + [1., 0., 0., 0., 0.], + [1., 1., 0., 0., 0.]]) + + """ + if like is not None: + return _tri_with_like(like, N, M=M, k=k, dtype=dtype) + + if M is None: + M = N + + m = greater_equal.outer(arange(N, dtype=_min_int(0, N)), + arange(-k, M - k, dtype=_min_int(-k, M - k))) + + # Avoid making a copy if the requested type is already bool + m = m.astype(dtype, copy=False) + + return m + + +_tri_with_like = array_function_dispatch()(tri) + + +def _trilu_dispatcher(m, k=None): + return (m,) + + +@array_function_dispatch(_trilu_dispatcher) +def tril(m, k=0): + """ + Lower triangle of an array. + + Return a copy of an array with elements above the `k`-th diagonal zeroed. + For arrays with ``ndim`` exceeding 2, `tril` will apply to the final two + axes. + + Parameters + ---------- + m : array_like, shape (..., M, N) + Input array. + k : int, optional + Diagonal above which to zero elements. `k = 0` (the default) is the + main diagonal, `k < 0` is below it and `k > 0` is above. + + Returns + ------- + tril : ndarray, shape (..., M, N) + Lower triangle of `m`, of same shape and data-type as `m`. + + See Also + -------- + triu : same thing, only for the upper triangle + + Examples + -------- + >>> import numpy as np + >>> np.tril([[1,2,3],[4,5,6],[7,8,9],[10,11,12]], -1) + array([[ 0, 0, 0], + [ 4, 0, 0], + [ 7, 8, 0], + [10, 11, 12]]) + + >>> np.tril(np.arange(3*4*5).reshape(3, 4, 5)) + array([[[ 0, 0, 0, 0, 0], + [ 5, 6, 0, 0, 0], + [10, 11, 12, 0, 0], + [15, 16, 17, 18, 0]], + [[20, 0, 0, 0, 0], + [25, 26, 0, 0, 0], + [30, 31, 32, 0, 0], + [35, 36, 37, 38, 0]], + [[40, 0, 0, 0, 0], + [45, 46, 0, 0, 0], + [50, 51, 52, 0, 0], + [55, 56, 57, 58, 0]]]) + + """ + m = asanyarray(m) + mask = tri(*m.shape[-2:], k=k, dtype=bool) + + return where(mask, m, zeros(1, m.dtype)) + + +@array_function_dispatch(_trilu_dispatcher) +def triu(m, k=0): + """ + Upper triangle of an array. + + Return a copy of an array with the elements below the `k`-th diagonal + zeroed. For arrays with ``ndim`` exceeding 2, `triu` will apply to the + final two axes. + + Please refer to the documentation for `tril` for further details. + + See Also + -------- + tril : lower triangle of an array + + Examples + -------- + >>> import numpy as np + >>> np.triu([[1,2,3],[4,5,6],[7,8,9],[10,11,12]], -1) + array([[ 1, 2, 3], + [ 4, 5, 6], + [ 0, 8, 9], + [ 0, 0, 12]]) + + >>> np.triu(np.arange(3*4*5).reshape(3, 4, 5)) + array([[[ 0, 1, 2, 3, 4], + [ 0, 6, 7, 8, 9], + [ 0, 0, 12, 13, 14], + [ 0, 0, 0, 18, 19]], + [[20, 21, 22, 23, 24], + [ 0, 26, 27, 28, 29], + [ 0, 0, 32, 33, 34], + [ 0, 0, 0, 38, 39]], + [[40, 41, 42, 43, 44], + [ 0, 46, 47, 48, 49], + [ 0, 0, 52, 53, 54], + [ 0, 0, 0, 58, 59]]]) + + """ + m = asanyarray(m) + mask = tri(*m.shape[-2:], k=k - 1, dtype=bool) + + return where(mask, zeros(1, m.dtype), m) + + +def _vander_dispatcher(x, N=None, increasing=None): + return (x,) + + +# Originally borrowed from John Hunter and matplotlib +@array_function_dispatch(_vander_dispatcher) +def vander(x, N=None, increasing=False): + """ + Generate a Vandermonde matrix. + + The columns of the output matrix are powers of the input vector. The + order of the powers is determined by the `increasing` boolean argument. + Specifically, when `increasing` is False, the `i`-th output column is + the input vector raised element-wise to the power of ``N - i - 1``. Such + a matrix with a geometric progression in each row is named for Alexandre- + Theophile Vandermonde. + + Parameters + ---------- + x : array_like + 1-D input array. + N : int, optional + Number of columns in the output. If `N` is not specified, a square + array is returned (``N = len(x)``). + increasing : bool, optional + Order of the powers of the columns. If True, the powers increase + from left to right, if False (the default) they are reversed. + + Returns + ------- + out : ndarray + Vandermonde matrix. If `increasing` is False, the first column is + ``x^(N-1)``, the second ``x^(N-2)`` and so forth. If `increasing` is + True, the columns are ``x^0, x^1, ..., x^(N-1)``. + + See Also + -------- + polynomial.polynomial.polyvander + + Examples + -------- + >>> import numpy as np + >>> x = np.array([1, 2, 3, 5]) + >>> N = 3 + >>> np.vander(x, N) + array([[ 1, 1, 1], + [ 4, 2, 1], + [ 9, 3, 1], + [25, 5, 1]]) + + >>> np.column_stack([x**(N-1-i) for i in range(N)]) + array([[ 1, 1, 1], + [ 4, 2, 1], + [ 9, 3, 1], + [25, 5, 1]]) + + >>> x = np.array([1, 2, 3, 5]) + >>> np.vander(x) + array([[ 1, 1, 1, 1], + [ 8, 4, 2, 1], + [ 27, 9, 3, 1], + [125, 25, 5, 1]]) + >>> np.vander(x, increasing=True) + array([[ 1, 1, 1, 1], + [ 1, 2, 4, 8], + [ 1, 3, 9, 27], + [ 1, 5, 25, 125]]) + + The determinant of a square Vandermonde matrix is the product + of the differences between the values of the input vector: + + >>> np.linalg.det(np.vander(x)) + 48.000000000000043 # may vary + >>> (5-3)*(5-2)*(5-1)*(3-2)*(3-1)*(2-1) + 48 + + """ + x = asarray(x) + if x.ndim != 1: + raise ValueError("x must be a one-dimensional array or sequence.") + if N is None: + N = len(x) + + v = empty((len(x), N), dtype=promote_types(x.dtype, int)) + tmp = v[:, ::-1] if not increasing else v + + if N > 0: + tmp[:, 0] = 1 + if N > 1: + tmp[:, 1:] = x[:, None] + multiply.accumulate(tmp[:, 1:], out=tmp[:, 1:], axis=1) + + return v + + +def _histogram2d_dispatcher(x, y, bins=None, range=None, density=None, + weights=None): + yield x + yield y + + # This terrible logic is adapted from the checks in histogram2d + try: + N = len(bins) + except TypeError: + N = 1 + if N == 2: + yield from bins # bins=[x, y] + else: + yield bins + + yield weights + + +@array_function_dispatch(_histogram2d_dispatcher) +def histogram2d(x, y, bins=10, range=None, density=None, weights=None): + """ + Compute the bi-dimensional histogram of two data samples. + + Parameters + ---------- + x : array_like, shape (N,) + An array containing the x coordinates of the points to be + histogrammed. + y : array_like, shape (N,) + An array containing the y coordinates of the points to be + histogrammed. + bins : int or array_like or [int, int] or [array, array], optional + The bin specification: + + * If int, the number of bins for the two dimensions (nx=ny=bins). + * If array_like, the bin edges for the two dimensions + (x_edges=y_edges=bins). + * If [int, int], the number of bins in each dimension + (nx, ny = bins). + * If [array, array], the bin edges in each dimension + (x_edges, y_edges = bins). + * A combination [int, array] or [array, int], where int + is the number of bins and array is the bin edges. + + range : array_like, shape(2,2), optional + The leftmost and rightmost edges of the bins along each dimension + (if not specified explicitly in the `bins` parameters): + ``[[xmin, xmax], [ymin, ymax]]``. All values outside of this range + will be considered outliers and not tallied in the histogram. + density : bool, optional + If False, the default, returns the number of samples in each bin. + If True, returns the probability *density* function at the bin, + ``bin_count / sample_count / bin_area``. + weights : array_like, shape(N,), optional + An array of values ``w_i`` weighing each sample ``(x_i, y_i)``. + Weights are normalized to 1 if `density` is True. If `density` is + False, the values of the returned histogram are equal to the sum of + the weights belonging to the samples falling into each bin. + + Returns + ------- + H : ndarray, shape(nx, ny) + The bi-dimensional histogram of samples `x` and `y`. Values in `x` + are histogrammed along the first dimension and values in `y` are + histogrammed along the second dimension. + xedges : ndarray, shape(nx+1,) + The bin edges along the first dimension. + yedges : ndarray, shape(ny+1,) + The bin edges along the second dimension. + + See Also + -------- + histogram : 1D histogram + histogramdd : Multidimensional histogram + + Notes + ----- + When `density` is True, then the returned histogram is the sample + density, defined such that the sum over bins of the product + ``bin_value * bin_area`` is 1. + + Please note that the histogram does not follow the Cartesian convention + where `x` values are on the abscissa and `y` values on the ordinate + axis. Rather, `x` is histogrammed along the first dimension of the + array (vertical), and `y` along the second dimension of the array + (horizontal). This ensures compatibility with `histogramdd`. + + Examples + -------- + >>> import numpy as np + >>> from matplotlib.image import NonUniformImage + >>> import matplotlib.pyplot as plt + + Construct a 2-D histogram with variable bin width. First define the bin + edges: + + >>> xedges = [0, 1, 3, 5] + >>> yedges = [0, 2, 3, 4, 6] + + Next we create a histogram H with random bin content: + + >>> x = np.random.normal(2, 1, 100) + >>> y = np.random.normal(1, 1, 100) + >>> H, xedges, yedges = np.histogram2d(x, y, bins=(xedges, yedges)) + >>> # Histogram does not follow Cartesian convention (see Notes), + >>> # therefore transpose H for visualization purposes. + >>> H = H.T + + :func:`imshow ` can only display square bins: + + >>> fig = plt.figure(figsize=(7, 3)) + >>> ax = fig.add_subplot(131, title='imshow: square bins') + >>> plt.imshow(H, interpolation='nearest', origin='lower', + ... extent=[xedges[0], xedges[-1], yedges[0], yedges[-1]]) + + + :func:`pcolormesh ` can display actual edges: + + >>> ax = fig.add_subplot(132, title='pcolormesh: actual edges', + ... aspect='equal') + >>> X, Y = np.meshgrid(xedges, yedges) + >>> ax.pcolormesh(X, Y, H) + + + :class:`NonUniformImage ` can be used to + display actual bin edges with interpolation: + + >>> ax = fig.add_subplot(133, title='NonUniformImage: interpolated', + ... aspect='equal', xlim=xedges[[0, -1]], ylim=yedges[[0, -1]]) + >>> im = NonUniformImage(ax, interpolation='bilinear') + >>> xcenters = (xedges[:-1] + xedges[1:]) / 2 + >>> ycenters = (yedges[:-1] + yedges[1:]) / 2 + >>> im.set_data(xcenters, ycenters, H) + >>> ax.add_image(im) + >>> plt.show() + + It is also possible to construct a 2-D histogram without specifying bin + edges: + + >>> # Generate non-symmetric test data + >>> n = 10000 + >>> x = np.linspace(1, 100, n) + >>> y = 2*np.log(x) + np.random.rand(n) - 0.5 + >>> # Compute 2d histogram. Note the order of x/y and xedges/yedges + >>> H, yedges, xedges = np.histogram2d(y, x, bins=20) + + Now we can plot the histogram using + :func:`pcolormesh `, and a + :func:`hexbin ` for comparison. + + >>> # Plot histogram using pcolormesh + >>> fig, (ax1, ax2) = plt.subplots(ncols=2, sharey=True) + >>> ax1.pcolormesh(xedges, yedges, H, cmap='rainbow') + >>> ax1.plot(x, 2*np.log(x), 'k-') + >>> ax1.set_xlim(x.min(), x.max()) + >>> ax1.set_ylim(y.min(), y.max()) + >>> ax1.set_xlabel('x') + >>> ax1.set_ylabel('y') + >>> ax1.set_title('histogram2d') + >>> ax1.grid() + + >>> # Create hexbin plot for comparison + >>> ax2.hexbin(x, y, gridsize=20, cmap='rainbow') + >>> ax2.plot(x, 2*np.log(x), 'k-') + >>> ax2.set_title('hexbin') + >>> ax2.set_xlim(x.min(), x.max()) + >>> ax2.set_xlabel('x') + >>> ax2.grid() + + >>> plt.show() + """ + from numpy import histogramdd + + if len(x) != len(y): + raise ValueError('x and y must have the same length.') + + try: + N = len(bins) + except TypeError: + N = 1 + + if N not in {1, 2}: + xedges = yedges = asarray(bins) + bins = [xedges, yedges] + hist, edges = histogramdd([x, y], bins, range, density, weights) + return hist, edges[0], edges[1] + + +@set_module('numpy') +def mask_indices(n, mask_func, k=0): + """ + Return the indices to access (n, n) arrays, given a masking function. + + Assume `mask_func` is a function that, for a square array a of size + ``(n, n)`` with a possible offset argument `k`, when called as + ``mask_func(a, k)`` returns a new array with zeros in certain locations + (functions like `triu` or `tril` do precisely this). Then this function + returns the indices where the non-zero values would be located. + + Parameters + ---------- + n : int + The returned indices will be valid to access arrays of shape (n, n). + mask_func : callable + A function whose call signature is similar to that of `triu`, `tril`. + That is, ``mask_func(x, k)`` returns a boolean array, shaped like `x`. + `k` is an optional argument to the function. + k : scalar + An optional argument which is passed through to `mask_func`. Functions + like `triu`, `tril` take a second argument that is interpreted as an + offset. + + Returns + ------- + indices : tuple of arrays. + The `n` arrays of indices corresponding to the locations where + ``mask_func(np.ones((n, n)), k)`` is True. + + See Also + -------- + triu, tril, triu_indices, tril_indices + + Examples + -------- + >>> import numpy as np + + These are the indices that would allow you to access the upper triangular + part of any 3x3 array: + + >>> iu = np.mask_indices(3, np.triu) + + For example, if `a` is a 3x3 array: + + >>> a = np.arange(9).reshape(3, 3) + >>> a + array([[0, 1, 2], + [3, 4, 5], + [6, 7, 8]]) + >>> a[iu] + array([0, 1, 2, 4, 5, 8]) + + An offset can be passed also to the masking function. This gets us the + indices starting on the first diagonal right of the main one: + + >>> iu1 = np.mask_indices(3, np.triu, 1) + + with which we now extract only three elements: + + >>> a[iu1] + array([1, 2, 5]) + + """ + m = ones((n, n), int) + a = mask_func(m, k) + return nonzero(a != 0) + + +@set_module('numpy') +def tril_indices(n, k=0, m=None): + """ + Return the indices for the lower-triangle of an (n, m) array. + + Parameters + ---------- + n : int + The row dimension of the arrays for which the returned + indices will be valid. + k : int, optional + Diagonal offset (see `tril` for details). + m : int, optional + The column dimension of the arrays for which the returned + arrays will be valid. + By default `m` is taken equal to `n`. + + + Returns + ------- + inds : tuple of arrays + The row and column indices, respectively. The row indices are sorted + in non-decreasing order, and the corresponding column indices are + strictly increasing for each row. + + See also + -------- + triu_indices : similar function, for upper-triangular. + mask_indices : generic function accepting an arbitrary mask function. + tril, triu + + Examples + -------- + >>> import numpy as np + + Compute two different sets of indices to access 4x4 arrays, one for the + lower triangular part starting at the main diagonal, and one starting two + diagonals further right: + + >>> il1 = np.tril_indices(4) + >>> il1 + (array([0, 1, 1, 2, 2, 2, 3, 3, 3, 3]), array([0, 0, 1, 0, 1, 2, 0, 1, 2, 3])) + + Note that row indices (first array) are non-decreasing, and the corresponding + column indices (second array) are strictly increasing for each row. + Here is how they can be used with a sample array: + + >>> a = np.arange(16).reshape(4, 4) + >>> a + array([[ 0, 1, 2, 3], + [ 4, 5, 6, 7], + [ 8, 9, 10, 11], + [12, 13, 14, 15]]) + + Both for indexing: + + >>> a[il1] + array([ 0, 4, 5, ..., 13, 14, 15]) + + And for assigning values: + + >>> a[il1] = -1 + >>> a + array([[-1, 1, 2, 3], + [-1, -1, 6, 7], + [-1, -1, -1, 11], + [-1, -1, -1, -1]]) + + These cover almost the whole array (two diagonals right of the main one): + + >>> il2 = np.tril_indices(4, 2) + >>> a[il2] = -10 + >>> a + array([[-10, -10, -10, 3], + [-10, -10, -10, -10], + [-10, -10, -10, -10], + [-10, -10, -10, -10]]) + + """ + tri_ = tri(n, m, k=k, dtype=bool) + + return tuple(broadcast_to(inds, tri_.shape)[tri_] + for inds in indices(tri_.shape, sparse=True)) + + +def _trilu_indices_form_dispatcher(arr, k=None): + return (arr,) + + +@array_function_dispatch(_trilu_indices_form_dispatcher) +def tril_indices_from(arr, k=0): + """ + Return the indices for the lower-triangle of arr. + + See `tril_indices` for full details. + + Parameters + ---------- + arr : array_like + The indices will be valid for square arrays whose dimensions are + the same as arr. + k : int, optional + Diagonal offset (see `tril` for details). + + Examples + -------- + >>> import numpy as np + + Create a 4 by 4 array + + >>> a = np.arange(16).reshape(4, 4) + >>> a + array([[ 0, 1, 2, 3], + [ 4, 5, 6, 7], + [ 8, 9, 10, 11], + [12, 13, 14, 15]]) + + Pass the array to get the indices of the lower triangular elements. + + >>> trili = np.tril_indices_from(a) + >>> trili + (array([0, 1, 1, 2, 2, 2, 3, 3, 3, 3]), array([0, 0, 1, 0, 1, 2, 0, 1, 2, 3])) + + >>> a[trili] + array([ 0, 4, 5, 8, 9, 10, 12, 13, 14, 15]) + + This is syntactic sugar for tril_indices(). + + >>> np.tril_indices(a.shape[0]) + (array([0, 1, 1, 2, 2, 2, 3, 3, 3, 3]), array([0, 0, 1, 0, 1, 2, 0, 1, 2, 3])) + + Use the `k` parameter to return the indices for the lower triangular array + up to the k-th diagonal. + + >>> trili1 = np.tril_indices_from(a, k=1) + >>> a[trili1] + array([ 0, 1, 4, 5, 6, 8, 9, 10, 11, 12, 13, 14, 15]) + + See Also + -------- + tril_indices, tril, triu_indices_from + """ + if arr.ndim != 2: + raise ValueError("input array must be 2-d") + return tril_indices(arr.shape[-2], k=k, m=arr.shape[-1]) + + +@set_module('numpy') +def triu_indices(n, k=0, m=None): + """ + Return the indices for the upper-triangle of an (n, m) array. + + Parameters + ---------- + n : int + The size of the arrays for which the returned indices will + be valid. + k : int, optional + Diagonal offset (see `triu` for details). + m : int, optional + The column dimension of the arrays for which the returned + arrays will be valid. + By default `m` is taken equal to `n`. + + + Returns + ------- + inds : tuple, shape(2) of ndarrays, shape(`n`) + The row and column indices, respectively. The row indices are sorted + in non-decreasing order, and the corresponding column indices are + strictly increasing for each row. + + See also + -------- + tril_indices : similar function, for lower-triangular. + mask_indices : generic function accepting an arbitrary mask function. + triu, tril + + Examples + -------- + >>> import numpy as np + + Compute two different sets of indices to access 4x4 arrays, one for the + upper triangular part starting at the main diagonal, and one starting two + diagonals further right: + + >>> iu1 = np.triu_indices(4) + >>> iu1 + (array([0, 0, 0, 0, 1, 1, 1, 2, 2, 3]), array([0, 1, 2, 3, 1, 2, 3, 2, 3, 3])) + + Note that row indices (first array) are non-decreasing, and the corresponding + column indices (second array) are strictly increasing for each row. + + Here is how they can be used with a sample array: + + >>> a = np.arange(16).reshape(4, 4) + >>> a + array([[ 0, 1, 2, 3], + [ 4, 5, 6, 7], + [ 8, 9, 10, 11], + [12, 13, 14, 15]]) + + Both for indexing: + + >>> a[iu1] + array([ 0, 1, 2, ..., 10, 11, 15]) + + And for assigning values: + + >>> a[iu1] = -1 + >>> a + array([[-1, -1, -1, -1], + [ 4, -1, -1, -1], + [ 8, 9, -1, -1], + [12, 13, 14, -1]]) + + These cover only a small part of the whole array (two diagonals right + of the main one): + + >>> iu2 = np.triu_indices(4, 2) + >>> a[iu2] = -10 + >>> a + array([[ -1, -1, -10, -10], + [ 4, -1, -1, -10], + [ 8, 9, -1, -1], + [ 12, 13, 14, -1]]) + + """ + tri_ = ~tri(n, m, k=k - 1, dtype=bool) + + return tuple(broadcast_to(inds, tri_.shape)[tri_] + for inds in indices(tri_.shape, sparse=True)) + + +@array_function_dispatch(_trilu_indices_form_dispatcher) +def triu_indices_from(arr, k=0): + """ + Return the indices for the upper-triangle of arr. + + See `triu_indices` for full details. + + Parameters + ---------- + arr : ndarray, shape(N, N) + The indices will be valid for square arrays. + k : int, optional + Diagonal offset (see `triu` for details). + + Returns + ------- + triu_indices_from : tuple, shape(2) of ndarray, shape(N) + Indices for the upper-triangle of `arr`. + + Examples + -------- + >>> import numpy as np + + Create a 4 by 4 array + + >>> a = np.arange(16).reshape(4, 4) + >>> a + array([[ 0, 1, 2, 3], + [ 4, 5, 6, 7], + [ 8, 9, 10, 11], + [12, 13, 14, 15]]) + + Pass the array to get the indices of the upper triangular elements. + + >>> triui = np.triu_indices_from(a) + >>> triui + (array([0, 0, 0, 0, 1, 1, 1, 2, 2, 3]), array([0, 1, 2, 3, 1, 2, 3, 2, 3, 3])) + + >>> a[triui] + array([ 0, 1, 2, 3, 5, 6, 7, 10, 11, 15]) + + This is syntactic sugar for triu_indices(). + + >>> np.triu_indices(a.shape[0]) + (array([0, 0, 0, 0, 1, 1, 1, 2, 2, 3]), array([0, 1, 2, 3, 1, 2, 3, 2, 3, 3])) + + Use the `k` parameter to return the indices for the upper triangular array + from the k-th diagonal. + + >>> triuim1 = np.triu_indices_from(a, k=1) + >>> a[triuim1] + array([ 1, 2, 3, 6, 7, 11]) + + + See Also + -------- + triu_indices, triu, tril_indices_from + """ + if arr.ndim != 2: + raise ValueError("input array must be 2-d") + return triu_indices(arr.shape[-2], k=k, m=arr.shape[-1]) diff --git a/python/user_packages/Python313/site-packages/numpy/lib/_twodim_base_impl.pyi b/python/user_packages/Python313/site-packages/numpy/lib/_twodim_base_impl.pyi new file mode 100644 index 0000000000000000000000000000000000000000..901d0d84999496abe7ccbd0f8347f0971317ef73 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/lib/_twodim_base_impl.pyi @@ -0,0 +1,408 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Sequence +from typing import ( + Any, + Literal as L, + Never, + Protocol, + TypeAlias, + TypeVar, + overload, + type_check_only, +) + +import numpy as np +from numpy import _OrderCF +from numpy._typing import ( + ArrayLike, + DTypeLike, + NDArray, + _ArrayLike, + _DTypeLike, + _NumberLike_co, + _ScalarLike_co, + _SupportsArray, + _SupportsArrayFunc, +) + +__all__ = [ + "diag", + "diagflat", + "eye", + "fliplr", + "flipud", + "tri", + "triu", + "tril", + "vander", + "histogram2d", + "mask_indices", + "tril_indices", + "tril_indices_from", + "triu_indices", + "triu_indices_from", +] + +### + +_T = TypeVar("_T") +_ArrayT = TypeVar("_ArrayT", bound=np.ndarray) +_ScalarT = TypeVar("_ScalarT", bound=np.generic) +_ComplexT = TypeVar("_ComplexT", bound=np.complexfloating) +_InexactT = TypeVar("_InexactT", bound=np.inexact) +_NumberT = TypeVar("_NumberT", bound=np.number) +_NumberObjectT = TypeVar("_NumberObjectT", bound=np.number | np.object_) +_NumberCoT = TypeVar("_NumberCoT", bound=_Number_co) + +_Int_co: TypeAlias = np.integer | np.bool +_Float_co: TypeAlias = np.floating | _Int_co +_Number_co: TypeAlias = np.number | np.bool + +_Array1D: TypeAlias = np.ndarray[tuple[int], np.dtype[_ScalarT]] +_Array2D: TypeAlias = np.ndarray[tuple[int, int], np.dtype[_ScalarT]] +# Workaround for mypy's and pyright's lack of compliance with the typing spec for +# overloads for gradual types. This works because only `Any` and `Never` are assignable +# to `Never`. +_ArrayNoD: TypeAlias = np.ndarray[tuple[Never] | tuple[Never, Never], np.dtype[_ScalarT]] + +_ArrayLike1D: TypeAlias = _SupportsArray[np.dtype[_ScalarT]] | Sequence[_ScalarT] +_ArrayLike1DInt_co: TypeAlias = _SupportsArray[np.dtype[_Int_co]] | Sequence[int | _Int_co] +_ArrayLike1DFloat_co: TypeAlias = _SupportsArray[np.dtype[_Float_co]] | Sequence[float | _Float_co] +_ArrayLike2DFloat_co: TypeAlias = _SupportsArray[np.dtype[_Float_co]] | Sequence[_ArrayLike1DFloat_co] +_ArrayLike1DNumber_co: TypeAlias = _SupportsArray[np.dtype[_Number_co]] | Sequence[complex | _Number_co] + +# The returned arrays dtype must be compatible with `np.equal` +_MaskFunc: TypeAlias = Callable[[NDArray[np.int_], _T], NDArray[_Number_co | np.timedelta64 | np.datetime64 | np.object_]] + +_Indices2D: TypeAlias = tuple[_Array1D[np.intp], _Array1D[np.intp]] +_Histogram2D: TypeAlias = tuple[_Array2D[np.float64], _Array1D[_ScalarT], _Array1D[_ScalarT]] + +@type_check_only +class _HasShapeAndNDim(Protocol): + @property # TODO: require 2d shape once shape-typing has matured + def shape(self) -> tuple[int, ...]: ... + @property + def ndim(self) -> int: ... + +### + +# keep in sync with `flipud` +@overload +def fliplr(m: _ArrayT) -> _ArrayT: ... +@overload +def fliplr(m: _ArrayLike[_ScalarT]) -> NDArray[_ScalarT]: ... +@overload +def fliplr(m: ArrayLike) -> NDArray[Any]: ... + +# keep in sync with `fliplr` +@overload +def flipud(m: _ArrayT) -> _ArrayT: ... +@overload +def flipud(m: _ArrayLike[_ScalarT]) -> NDArray[_ScalarT]: ... +@overload +def flipud(m: ArrayLike) -> NDArray[Any]: ... + +# +@overload +def eye( + N: int, + M: int | None = None, + k: int = 0, + dtype: None = ..., # = float # stubdefaulter: ignore[missing-default] + order: _OrderCF = "C", + *, + device: L["cpu"] | None = None, + like: _SupportsArrayFunc | None = None, +) -> _Array2D[np.float64]: ... +@overload +def eye( + N: int, + M: int | None, + k: int, + dtype: _DTypeLike[_ScalarT], + order: _OrderCF = "C", + *, + device: L["cpu"] | None = None, + like: _SupportsArrayFunc | None = None, +) -> _Array2D[_ScalarT]: ... +@overload +def eye( + N: int, + M: int | None = None, + k: int = 0, + *, + dtype: _DTypeLike[_ScalarT], + order: _OrderCF = "C", + device: L["cpu"] | None = None, + like: _SupportsArrayFunc | None = None, +) -> _Array2D[_ScalarT]: ... +@overload +def eye( + N: int, + M: int | None = None, + k: int = 0, + dtype: DTypeLike | None = ..., # = float + order: _OrderCF = "C", + *, + device: L["cpu"] | None = None, + like: _SupportsArrayFunc | None = None, +) -> _Array2D[Incomplete]: ... + +# +@overload +def diag(v: _ArrayNoD[_ScalarT] | Sequence[Sequence[_ScalarT]], k: int = 0) -> NDArray[_ScalarT]: ... +@overload +def diag(v: _Array2D[_ScalarT] | Sequence[Sequence[_ScalarT]], k: int = 0) -> _Array1D[_ScalarT]: ... +@overload +def diag(v: _Array1D[_ScalarT] | Sequence[_ScalarT], k: int = 0) -> _Array2D[_ScalarT]: ... +@overload +def diag(v: Sequence[Sequence[_ScalarLike_co]], k: int = 0) -> _Array1D[Incomplete]: ... +@overload +def diag(v: Sequence[_ScalarLike_co], k: int = 0) -> _Array2D[Incomplete]: ... +@overload +def diag(v: _ArrayLike[_ScalarT], k: int = 0) -> NDArray[_ScalarT]: ... +@overload +def diag(v: ArrayLike, k: int = 0) -> NDArray[Incomplete]: ... + +# keep in sync with `numpy.ma.extras.diagflat` +@overload +def diagflat(v: _ArrayLike[_ScalarT], k: int = 0) -> _Array2D[_ScalarT]: ... +@overload +def diagflat(v: ArrayLike, k: int = 0) -> _Array2D[Incomplete]: ... + +# +@overload +def tri( + N: int, + M: int | None = None, + k: int = 0, + dtype: None = ..., # = float # stubdefaulter: ignore[missing-default] + *, + like: _SupportsArrayFunc | None = None +) -> _Array2D[np.float64]: ... +@overload +def tri( + N: int, + M: int | None, + k: int, + dtype: _DTypeLike[_ScalarT], + *, + like: _SupportsArrayFunc | None = None +) -> _Array2D[_ScalarT]: ... +@overload +def tri( + N: int, + M: int | None = None, + k: int = 0, + *, + dtype: _DTypeLike[_ScalarT], + like: _SupportsArrayFunc | None = None +) -> _Array2D[_ScalarT]: ... +@overload +def tri( + N: int, + M: int | None = None, + k: int = 0, + dtype: DTypeLike | None = ..., # = float + *, + like: _SupportsArrayFunc | None = None +) -> _Array2D[Any]: ... + +# keep in sync with `triu` +@overload +def tril(m: _ArrayT, k: int = 0) -> _ArrayT: ... +@overload +def tril(m: _ArrayLike[_ScalarT], k: int = 0) -> NDArray[_ScalarT]: ... +@overload +def tril(m: ArrayLike, k: int = 0) -> NDArray[Any]: ... + +# keep in sync with `tril` +@overload +def triu(m: _ArrayT, k: int = 0) -> _ArrayT: ... +@overload +def triu(m: _ArrayLike[_ScalarT], k: int = 0) -> NDArray[_ScalarT]: ... +@overload +def triu(m: ArrayLike, k: int = 0) -> NDArray[Any]: ... + +# we use `list` (invariant) instead of `Sequence` (covariant) to avoid overlap +@overload +def vander(x: _ArrayLike1D[_NumberObjectT], N: int | None = None, increasing: bool = False) -> _Array2D[_NumberObjectT]: ... +@overload +def vander(x: _ArrayLike1D[np.bool] | list[int], N: int | None = None, increasing: bool = False) -> _Array2D[np.int_]: ... +@overload +def vander(x: list[float], N: int | None = None, increasing: bool = False) -> _Array2D[np.float64]: ... +@overload +def vander(x: list[complex], N: int | None = None, increasing: bool = False) -> _Array2D[np.complex128]: ... +@overload # fallback +def vander(x: Sequence[_NumberLike_co], N: int | None = None, increasing: bool = False) -> _Array2D[Any]: ... + +# +@overload +def histogram2d( + x: _ArrayLike1D[_ComplexT], + y: _ArrayLike1D[_ComplexT | _Float_co], + bins: int | Sequence[int] = 10, + range: _ArrayLike2DFloat_co | None = None, + density: bool | None = None, + weights: _ArrayLike1DFloat_co | None = None, +) -> _Histogram2D[_ComplexT]: ... +@overload +def histogram2d( + x: _ArrayLike1D[_ComplexT | _Float_co], + y: _ArrayLike1D[_ComplexT], + bins: int | Sequence[int] = 10, + range: _ArrayLike2DFloat_co | None = None, + density: bool | None = None, + weights: _ArrayLike1DFloat_co | None = None, +) -> _Histogram2D[_ComplexT]: ... +@overload +def histogram2d( + x: _ArrayLike1D[_InexactT], + y: _ArrayLike1D[_InexactT | _Int_co], + bins: int | Sequence[int] = 10, + range: _ArrayLike2DFloat_co | None = None, + density: bool | None = None, + weights: _ArrayLike1DFloat_co | None = None, +) -> _Histogram2D[_InexactT]: ... +@overload +def histogram2d( + x: _ArrayLike1D[_InexactT | _Int_co], + y: _ArrayLike1D[_InexactT], + bins: int | Sequence[int] = 10, + range: _ArrayLike2DFloat_co | None = None, + density: bool | None = None, + weights: _ArrayLike1DFloat_co | None = None, +) -> _Histogram2D[_InexactT]: ... +@overload +def histogram2d( + x: _ArrayLike1DInt_co | Sequence[float], + y: _ArrayLike1DInt_co | Sequence[float], + bins: int | Sequence[int] = 10, + range: _ArrayLike2DFloat_co | None = None, + density: bool | None = None, + weights: _ArrayLike1DFloat_co | None = None, +) -> _Histogram2D[np.float64]: ... +@overload +def histogram2d( + x: Sequence[complex], + y: Sequence[complex], + bins: int | Sequence[int] = 10, + range: _ArrayLike2DFloat_co | None = None, + density: bool | None = None, + weights: _ArrayLike1DFloat_co | None = None, +) -> _Histogram2D[np.complex128 | Any]: ... +@overload +def histogram2d( + x: _ArrayLike1DNumber_co, + y: _ArrayLike1DNumber_co, + bins: _ArrayLike1D[_NumberCoT] | Sequence[_ArrayLike1D[_NumberCoT]], + range: _ArrayLike2DFloat_co | None = None, + density: bool | None = None, + weights: _ArrayLike1DFloat_co | None = None, +) -> _Histogram2D[_NumberCoT]: ... +@overload +def histogram2d( + x: _ArrayLike1D[_InexactT], + y: _ArrayLike1D[_InexactT], + bins: Sequence[_ArrayLike1D[_NumberCoT] | int], + range: _ArrayLike2DFloat_co | None = None, + density: bool | None = None, + weights: _ArrayLike1DFloat_co | None = None, +) -> _Histogram2D[_InexactT | _NumberCoT]: ... +@overload +def histogram2d( + x: _ArrayLike1D[_InexactT], + y: _ArrayLike1D[_InexactT], + bins: Sequence[_ArrayLike1DNumber_co | int], + range: _ArrayLike2DFloat_co | None = None, + density: bool | None = None, + weights: _ArrayLike1DFloat_co | None = None, +) -> _Histogram2D[_InexactT | Any]: ... +@overload +def histogram2d( + x: _ArrayLike1DInt_co | Sequence[float], + y: _ArrayLike1DInt_co | Sequence[float], + bins: Sequence[_ArrayLike1D[_NumberCoT] | int], + range: _ArrayLike2DFloat_co | None = None, + density: bool | None = None, + weights: _ArrayLike1DFloat_co | None = None, +) -> _Histogram2D[np.float64 | _NumberCoT]: ... +@overload +def histogram2d( + x: _ArrayLike1DInt_co | Sequence[float], + y: _ArrayLike1DInt_co | Sequence[float], + bins: Sequence[_ArrayLike1DNumber_co | int], + range: _ArrayLike2DFloat_co | None = None, + density: bool | None = None, + weights: _ArrayLike1DFloat_co | None = None, +) -> _Histogram2D[np.float64 | Any]: ... +@overload +def histogram2d( + x: Sequence[complex], + y: Sequence[complex], + bins: Sequence[_ArrayLike1D[_NumberCoT] | int], + range: _ArrayLike2DFloat_co | None = None, + density: bool | None = None, + weights: _ArrayLike1DFloat_co | None = None, +) -> _Histogram2D[np.complex128 | _NumberCoT]: ... +@overload +def histogram2d( + x: Sequence[complex], + y: Sequence[complex], + bins: Sequence[_ArrayLike1DNumber_co | int], + range: _ArrayLike2DFloat_co | None = None, + density: bool | None = None, + weights: _ArrayLike1DFloat_co | None = None, +) -> _Histogram2D[np.complex128 | Any]: ... +@overload +def histogram2d( + x: _ArrayLike1DNumber_co, + y: _ArrayLike1DNumber_co, + bins: Sequence[Sequence[int]], + range: _ArrayLike2DFloat_co | None = None, + density: bool | None = None, + weights: _ArrayLike1DFloat_co | None = None, +) -> _Histogram2D[np.int_]: ... +@overload +def histogram2d( + x: _ArrayLike1DNumber_co, + y: _ArrayLike1DNumber_co, + bins: Sequence[Sequence[float]], + range: _ArrayLike2DFloat_co | None = None, + density: bool | None = None, + weights: _ArrayLike1DFloat_co | None = None, +) -> _Histogram2D[np.float64 | Any]: ... +@overload +def histogram2d( + x: _ArrayLike1DNumber_co, + y: _ArrayLike1DNumber_co, + bins: Sequence[Sequence[complex]], + range: _ArrayLike2DFloat_co | None = None, + density: bool | None = None, + weights: _ArrayLike1DFloat_co | None = None, +) -> _Histogram2D[np.complex128 | Any]: ... +@overload +def histogram2d( + x: _ArrayLike1DNumber_co, + y: _ArrayLike1DNumber_co, + bins: Sequence[_ArrayLike1DNumber_co | int] | int, + range: _ArrayLike2DFloat_co | None = None, + density: bool | None = None, + weights: _ArrayLike1DFloat_co | None = None, +) -> _Histogram2D[Any]: ... + +# NOTE: we're assuming/demanding here the `mask_func` returns +# an ndarray of shape `(n, n)`; otherwise there is the possibility +# of the output tuple having more or less than 2 elements +@overload +def mask_indices(n: int, mask_func: _MaskFunc[int], k: int = 0) -> _Indices2D: ... +@overload +def mask_indices(n: int, mask_func: _MaskFunc[_T], k: _T) -> _Indices2D: ... + +# +def tril_indices(n: int, k: int = 0, m: int | None = None) -> _Indices2D: ... +def triu_indices(n: int, k: int = 0, m: int | None = None) -> _Indices2D: ... + +# these will accept anything with `shape: tuple[int, int]` and `ndim: int` attributes +def tril_indices_from(arr: _HasShapeAndNDim, k: int = 0) -> _Indices2D: ... +def triu_indices_from(arr: _HasShapeAndNDim, k: int = 0) -> _Indices2D: ... diff --git a/python/user_packages/Python313/site-packages/numpy/lib/_type_check_impl.py b/python/user_packages/Python313/site-packages/numpy/lib/_type_check_impl.py new file mode 100644 index 0000000000000000000000000000000000000000..5d52f3d2f29c2713f0d262114647af001bfa8e3a --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/lib/_type_check_impl.py @@ -0,0 +1,710 @@ +"""Automatically adapted for numpy Sep 19, 2005 by convertcode.py + +""" +import functools + +__all__ = ['iscomplexobj', 'isrealobj', 'imag', 'iscomplex', + 'isreal', 'nan_to_num', 'real', 'real_if_close', + 'typename', 'mintypecode', + 'common_type'] + +import numpy._core.numeric as _nx +from numpy._core import getlimits, overrides +from numpy._core.numeric import asanyarray, asarray, isnan, zeros +from numpy._utils import set_module + +from ._ufunclike_impl import isneginf, isposinf + +array_function_dispatch = functools.partial( + overrides.array_function_dispatch, module='numpy') + + +_typecodes_by_elsize = 'GDFgdfQqLlIiHhBb?' + + +@set_module('numpy') +def mintypecode(typechars, typeset='GDFgdf', default='d'): + """ + Return the character for the minimum-size type to which given types can + be safely cast. + + The returned type character must represent the smallest size dtype such + that an array of the returned type can handle the data from an array of + all types in `typechars` (or if `typechars` is an array, then its + dtype.char). + + Parameters + ---------- + typechars : list of str or array_like + If a list of strings, each string should represent a dtype. + If array_like, the character representation of the array dtype is used. + typeset : str or list of str, optional + The set of characters that the returned character is chosen from. + The default set is 'GDFgdf'. + default : str, optional + The default character, this is returned if none of the characters in + `typechars` matches a character in `typeset`. + + Returns + ------- + typechar : str + The character representing the minimum-size type that was found. + + See Also + -------- + dtype + + Examples + -------- + >>> import numpy as np + >>> np.mintypecode(['d', 'f', 'S']) + 'd' + >>> x = np.array([1.1, 2-3.j]) + >>> np.mintypecode(x) + 'D' + + >>> np.mintypecode('abceh', default='G') + 'G' + + """ + typecodes = ((isinstance(t, str) and t) or asarray(t).dtype.char + for t in typechars) + intersection = {t for t in typecodes if t in typeset} + if not intersection: + return default + if 'F' in intersection and 'd' in intersection: + return 'D' + return min(intersection, key=_typecodes_by_elsize.index) + + +def _real_dispatcher(val): + return (val,) + + +@array_function_dispatch(_real_dispatcher) +def real(val): + """ + Return the real part of the complex argument. + + Parameters + ---------- + val : array_like + Input array. + + Returns + ------- + out : ndarray or scalar + The real component of the complex argument. If `val` is real, the type + of `val` is used for the output. If `val` has complex elements, the + returned type is float. + + See Also + -------- + real_if_close, imag, angle + + Examples + -------- + >>> import numpy as np + >>> a = np.array([1+2j, 3+4j, 5+6j]) + >>> a.real + array([1., 3., 5.]) + >>> a.real = 9 + >>> a + array([9.+2.j, 9.+4.j, 9.+6.j]) + >>> a.real = np.array([9, 8, 7]) + >>> a + array([9.+2.j, 8.+4.j, 7.+6.j]) + >>> np.real(1 + 1j) + 1.0 + + """ + try: + return val.real + except AttributeError: + return asanyarray(val).real + + +def _imag_dispatcher(val): + return (val,) + + +@array_function_dispatch(_imag_dispatcher) +def imag(val): + """ + Return the imaginary part of the complex argument. + + Parameters + ---------- + val : array_like + Input array. + + Returns + ------- + out : ndarray or scalar + The imaginary component of the complex argument. If `val` is real, + the type of `val` is used for the output. If `val` has complex + elements, the returned type is float. + + See Also + -------- + real, angle, real_if_close + + Examples + -------- + >>> import numpy as np + >>> a = np.array([1+2j, 3+4j, 5+6j]) + >>> a.imag + array([2., 4., 6.]) + >>> a.imag = np.array([8, 10, 12]) + >>> a + array([1. +8.j, 3.+10.j, 5.+12.j]) + >>> np.imag(1 + 1j) + 1.0 + + """ + try: + return val.imag + except AttributeError: + return asanyarray(val).imag + + +def _is_type_dispatcher(x): + return (x,) + + +@array_function_dispatch(_is_type_dispatcher) +def iscomplex(x): + """ + Returns a bool array, where True if input element is complex. + + What is tested is whether the input has a non-zero imaginary part, not if + the input type is complex. + + Parameters + ---------- + x : array_like + Input array. + + Returns + ------- + out : ndarray of bools + Output array. + + See Also + -------- + isreal + iscomplexobj : Return True if x is a complex type or an array of complex + numbers. + + Examples + -------- + >>> import numpy as np + >>> np.iscomplex([1+1j, 1+0j, 4.5, 3, 2, 2j]) + array([ True, False, False, False, False, True]) + + """ + ax = asanyarray(x) + if issubclass(ax.dtype.type, _nx.complexfloating): + return ax.imag != 0 + res = zeros(ax.shape, bool) + return res[()] # convert to scalar if needed + + +@array_function_dispatch(_is_type_dispatcher) +def isreal(x): + """ + Returns a bool array, where True if input element is real. + + If element has complex type with zero imaginary part, the return value + for that element is True. + + Parameters + ---------- + x : array_like + Input array. + + Returns + ------- + out : ndarray, bool + Boolean array of same shape as `x`. + + Notes + ----- + `isreal` may behave unexpectedly for string or object arrays (see examples) + + See Also + -------- + iscomplex + isrealobj : Return True if x is not a complex type. + + Examples + -------- + >>> import numpy as np + >>> a = np.array([1+1j, 1+0j, 4.5, 3, 2, 2j], dtype=complex) + >>> np.isreal(a) + array([False, True, True, True, True, False]) + + The function does not work on string arrays. + + >>> a = np.array([2j, "a"], dtype="U") + >>> np.isreal(a) # Warns about non-elementwise comparison + False + + Returns True for all elements in input array of ``dtype=object`` even if + any of the elements is complex. + + >>> a = np.array([1, "2", 3+4j], dtype=object) + >>> np.isreal(a) + array([ True, True, True]) + + isreal should not be used with object arrays + + >>> a = np.array([1+2j, 2+1j], dtype=object) + >>> np.isreal(a) + array([ True, True]) + + """ + return imag(x) == 0 + + +@array_function_dispatch(_is_type_dispatcher) +def iscomplexobj(x): + """ + Check for a complex type or an array of complex numbers. + + The type of the input is checked, not the value. Even if the input + has an imaginary part equal to zero, `iscomplexobj` evaluates to True. + + Parameters + ---------- + x : any + The input can be of any type and shape. + + Returns + ------- + iscomplexobj : bool + The return value, True if `x` is of a complex type or has at least + one complex element. + + See Also + -------- + isrealobj, iscomplex + + Examples + -------- + >>> import numpy as np + >>> np.iscomplexobj(1) + False + >>> np.iscomplexobj(1+0j) + True + >>> np.iscomplexobj([3, 1+0j, True]) + True + + """ + try: + dtype = x.dtype + type_ = dtype.type + except AttributeError: + type_ = asarray(x).dtype.type + return issubclass(type_, _nx.complexfloating) + + +@array_function_dispatch(_is_type_dispatcher) +def isrealobj(x): + """ + Return True if x is a not complex type or an array of complex numbers. + + The type of the input is checked, not the value. So even if the input + has an imaginary part equal to zero, `isrealobj` evaluates to False + if the data type is complex. + + Parameters + ---------- + x : any + The input can be of any type and shape. + + Returns + ------- + y : bool + The return value, False if `x` is of a complex type. + + See Also + -------- + iscomplexobj, isreal + + Notes + ----- + The function is only meant for arrays with numerical values but it + accepts all other objects. Since it assumes array input, the return + value of other objects may be True. + + >>> np.isrealobj('A string') + True + >>> np.isrealobj(False) + True + >>> np.isrealobj(None) + True + + Examples + -------- + >>> import numpy as np + >>> np.isrealobj(1) + True + >>> np.isrealobj(1+0j) + False + >>> np.isrealobj([3, 1+0j, True]) + False + + """ + return not iscomplexobj(x) + +#----------------------------------------------------------------------------- + +def _getmaxmin(t): + from numpy._core import getlimits + f = getlimits.finfo(t) + return f.max, f.min + + +def _nan_to_num_dispatcher(x, copy=None, nan=None, posinf=None, neginf=None): + return (x,) + + +@array_function_dispatch(_nan_to_num_dispatcher) +def nan_to_num(x, copy=True, nan=0.0, posinf=None, neginf=None): + """ + Replace NaN with zero and infinity with large finite numbers (default + behaviour) or with the numbers defined by the user using the `nan`, + `posinf` and/or `neginf` keywords. + + If `x` is inexact, NaN is replaced by zero or by the user defined value in + `nan` keyword, infinity is replaced by the largest finite floating point + values representable by ``x.dtype`` or by the user defined value in + `posinf` keyword and -infinity is replaced by the most negative finite + floating point values representable by ``x.dtype`` or by the user defined + value in `neginf` keyword. + + For complex dtypes, the above is applied to each of the real and + imaginary components of `x` separately. + + If `x` is not inexact, then no replacements are made. + + Parameters + ---------- + x : scalar or array_like + Input data. + copy : bool, optional + Whether to create a copy of `x` (True) or to replace values + in-place (False). The in-place operation only occurs if + casting to an array does not require a copy. + Default is True. + nan : int, float, or bool or array_like of int, float, or bool, optional + Values to be used to fill NaN values. If no values are passed + then NaN values will be replaced with 0.0. + posinf : int, float, or bool or array_like of int, float, or bool, optional + Values to be used to fill positive infinity values. If no values are + passed then positive infinity values will be replaced with a very + large number. + neginf : int, float, or bool or array_like of int, float, or bool, optional + Values to be used to fill negative infinity values. If no values are + passed then negative infinity values will be replaced with a very + small (or negative) number. + + Returns + ------- + out : ndarray + `x`, with the non-finite values replaced. If `copy` is False, this may + be `x` itself. + + See Also + -------- + isinf : Shows which elements are positive or negative infinity. + isneginf : Shows which elements are negative infinity. + isposinf : Shows which elements are positive infinity. + isnan : Shows which elements are Not a Number (NaN). + isfinite : Shows which elements are finite (not NaN, not infinity) + + Notes + ----- + NumPy uses the IEEE Standard for Binary Floating-Point for Arithmetic + (IEEE 754). This means that Not a Number is not equivalent to infinity. + + Examples + -------- + >>> import numpy as np + >>> np.nan_to_num(np.inf) + 1.7976931348623157e+308 + >>> np.nan_to_num(-np.inf) + -1.7976931348623157e+308 + >>> np.nan_to_num(np.nan) + 0.0 + >>> x = np.array([np.inf, -np.inf, np.nan, -128, 128]) + >>> np.nan_to_num(x) + array([ 1.79769313e+308, -1.79769313e+308, 0.00000000e+000, # may vary + -1.28000000e+002, 1.28000000e+002]) + >>> np.nan_to_num(x, nan=-9999, posinf=33333333, neginf=33333333) + array([ 3.3333333e+07, 3.3333333e+07, -9.9990000e+03, + -1.2800000e+02, 1.2800000e+02]) + >>> nan = np.array([11, 12, -9999, 13, 14]) + >>> posinf = np.array([33333333, 11, 12, 13, 14]) + >>> neginf = np.array([11, 33333333, 12, 13, 14]) + >>> np.nan_to_num(x, nan=nan, posinf=posinf, neginf=neginf) + array([ 3.3333333e+07, 3.3333333e+07, -9.9990000e+03, -1.2800000e+02, + 1.2800000e+02]) + >>> y = np.array([complex(np.inf, np.nan), np.nan, complex(np.nan, np.inf)]) + array([ 1.79769313e+308, -1.79769313e+308, 0.00000000e+000, # may vary + -1.28000000e+002, 1.28000000e+002]) + >>> np.nan_to_num(y) + array([ 1.79769313e+308 +0.00000000e+000j, # may vary + 0.00000000e+000 +0.00000000e+000j, + 0.00000000e+000 +1.79769313e+308j]) + >>> np.nan_to_num(y, nan=111111, posinf=222222) + array([222222.+111111.j, 111111. +0.j, 111111.+222222.j]) + >>> nan = np.array([11, 12, 13]) + >>> posinf = np.array([21, 22, 23]) + >>> neginf = np.array([31, 32, 33]) + >>> np.nan_to_num(y, nan=nan, posinf=posinf, neginf=neginf) + array([21.+11.j, 12. +0.j, 13.+23.j]) + """ + x = _nx.array(x, subok=True, copy=copy) + xtype = x.dtype.type + + isscalar = (x.ndim == 0) + + if not issubclass(xtype, _nx.inexact): + return x[()] if isscalar else x + + iscomplex = issubclass(xtype, _nx.complexfloating) + + dest = (x.real, x.imag) if iscomplex else (x,) + maxf, minf = _getmaxmin(x.real.dtype) + if posinf is not None: + maxf = posinf + if neginf is not None: + minf = neginf + for d in dest: + idx_nan = isnan(d) + idx_posinf = isposinf(d) + idx_neginf = isneginf(d) + _nx.copyto(d, nan, where=idx_nan) + _nx.copyto(d, maxf, where=idx_posinf) + _nx.copyto(d, minf, where=idx_neginf) + return x[()] if isscalar else x + +#----------------------------------------------------------------------------- + +def _real_if_close_dispatcher(a, tol=None): + return (a,) + + +@array_function_dispatch(_real_if_close_dispatcher) +def real_if_close(a, tol=100): + """ + If input is complex with all imaginary parts close to zero, return + real parts. + + "Close to zero" is defined as `tol` * (machine epsilon of the type for + `a`). + + Parameters + ---------- + a : array_like + Input array. + tol : float + Tolerance in machine epsilons for the complex part of the elements + in the array. If the tolerance is <=1, then the absolute tolerance + is used. + + Returns + ------- + out : ndarray + If `a` is real, the type of `a` is used for the output. If `a` + has complex elements, the returned type is float. + + See Also + -------- + real, imag, angle + + Notes + ----- + Machine epsilon varies from machine to machine and between data types + but Python floats on most platforms have a machine epsilon equal to + 2.2204460492503131e-16. You can use 'np.finfo(float).eps' to print + out the machine epsilon for floats. + + Examples + -------- + >>> import numpy as np + >>> np.finfo(float).eps + 2.2204460492503131e-16 # may vary + + >>> np.real_if_close([2.1 + 4e-14j, 5.2 + 3e-15j], tol=1000) + array([2.1, 5.2]) + >>> np.real_if_close([2.1 + 4e-13j, 5.2 + 3e-15j], tol=1000) + array([2.1+4.e-13j, 5.2 + 3e-15j]) + + """ + a = asanyarray(a) + type_ = a.dtype.type + if not issubclass(type_, _nx.complexfloating): + return a + if tol > 1: + f = getlimits.finfo(type_) + tol = f.eps * tol + if _nx.all(_nx.absolute(a.imag) < tol): + a = a.real + return a + + +#----------------------------------------------------------------------------- + +_namefromtype = {'S1': 'character', + '?': 'bool', + 'b': 'signed char', + 'B': 'unsigned char', + 'h': 'short', + 'H': 'unsigned short', + 'i': 'integer', + 'I': 'unsigned integer', + 'l': 'long integer', + 'L': 'unsigned long integer', + 'q': 'long long integer', + 'Q': 'unsigned long long integer', + 'f': 'single precision', + 'd': 'double precision', + 'g': 'long precision', + 'F': 'complex single precision', + 'D': 'complex double precision', + 'G': 'complex long double precision', + 'S': 'string', + 'U': 'unicode', + 'V': 'void', + 'O': 'object' + } + +@set_module('numpy') +def typename(char): + """ + Return a description for the given data type code. + + Parameters + ---------- + char : str + Data type code. + + Returns + ------- + out : str + Description of the input data type code. + + See Also + -------- + dtype + + Examples + -------- + >>> import numpy as np + >>> typechars = ['S1', '?', 'B', 'D', 'G', 'F', 'I', 'H', 'L', 'O', 'Q', + ... 'S', 'U', 'V', 'b', 'd', 'g', 'f', 'i', 'h', 'l', 'q'] + >>> for typechar in typechars: + ... print(typechar, ' : ', np.typename(typechar)) + ... + S1 : character + ? : bool + B : unsigned char + D : complex double precision + G : complex long double precision + F : complex single precision + I : unsigned integer + H : unsigned short + L : unsigned long integer + O : object + Q : unsigned long long integer + S : string + U : unicode + V : void + b : signed char + d : double precision + g : long precision + f : single precision + i : integer + h : short + l : long integer + q : long long integer + + """ + return _namefromtype[char] + +#----------------------------------------------------------------------------- + + +#determine the "minimum common type" for a group of arrays. +array_type = [[_nx.float16, _nx.float32, _nx.float64, _nx.longdouble], + [None, _nx.complex64, _nx.complex128, _nx.clongdouble]] +array_precision = {_nx.float16: 0, + _nx.float32: 1, + _nx.float64: 2, + _nx.longdouble: 3, + _nx.complex64: 1, + _nx.complex128: 2, + _nx.clongdouble: 3} + + +def _common_type_dispatcher(*arrays): + return arrays + + +@array_function_dispatch(_common_type_dispatcher) +def common_type(*arrays): + """ + Return a scalar type which is common to the input arrays. + + The return type will always be an inexact (i.e. floating point) scalar + type, even if all the arrays are integer arrays. If one of the inputs is + an integer array, the minimum precision type that is returned is a + 64-bit floating point dtype. + + All input arrays except int64 and uint64 can be safely cast to the + returned dtype without loss of information. + + Parameters + ---------- + array1, array2, ... : ndarrays + Input arrays. + + Returns + ------- + out : data type code + Data type code. + + See Also + -------- + dtype, mintypecode + + Examples + -------- + >>> np.common_type(np.arange(2, dtype=np.float32)) + + >>> np.common_type(np.arange(2, dtype=np.float32), np.arange(2)) + + >>> np.common_type(np.arange(4), np.array([45, 6.j]), np.array([45.0])) + + + """ + is_complex = False + precision = 0 + for a in arrays: + t = a.dtype.type + if iscomplexobj(a): + is_complex = True + if issubclass(t, _nx.integer): + p = 2 # array_precision[_nx.double] + else: + p = array_precision.get(t) + if p is None: + raise TypeError("can't get common type for non-numeric array") + precision = max(precision, p) + if is_complex: + return array_type[1][precision] + else: + return array_type[0][precision] diff --git a/python/user_packages/Python313/site-packages/numpy/lib/_type_check_impl.pyi b/python/user_packages/Python313/site-packages/numpy/lib/_type_check_impl.pyi new file mode 100644 index 0000000000000000000000000000000000000000..eeffc8c487abc45880256a20d14a9f044557572f --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/lib/_type_check_impl.pyi @@ -0,0 +1,348 @@ +from _typeshed import Incomplete +from collections.abc import Container, Iterable +from typing import Any, Literal as L, Protocol, TypeAlias, overload, type_check_only +from typing_extensions import TypeVar + +import numpy as np +from numpy._typing import ( + ArrayLike, + NDArray, + _16Bit, + _32Bit, + _64Bit, + _ArrayLike, + _NestedSequence, + _ScalarLike_co, + _SupportsArray, +) + +__all__ = [ + "common_type", + "imag", + "iscomplex", + "iscomplexobj", + "isreal", + "isrealobj", + "mintypecode", + "nan_to_num", + "real", + "real_if_close", + "typename", +] + +_T = TypeVar("_T") +_T_co = TypeVar("_T_co", covariant=True) +_ScalarT = TypeVar("_ScalarT", bound=np.generic) +_ScalarT_co = TypeVar("_ScalarT_co", bound=np.generic, covariant=True) +_RealT = TypeVar("_RealT", bound=np.floating | np.integer | np.bool) + +_FloatMax32: TypeAlias = np.float32 | np.float16 +_ComplexMax128: TypeAlias = np.complex128 | np.complex64 +_RealMax64: TypeAlias = np.float64 | np.float32 | np.float16 | np.integer +_Real: TypeAlias = np.floating | np.integer +_InexactMax32: TypeAlias = np.inexact[_32Bit] | np.float16 +_NumberMax64: TypeAlias = np.number[_64Bit] | np.number[_32Bit] | np.number[_16Bit] | np.integer + +@type_check_only +class _HasReal(Protocol[_T_co]): + @property + def real(self, /) -> _T_co: ... + +@type_check_only +class _HasImag(Protocol[_T_co]): + @property + def imag(self, /) -> _T_co: ... + +@type_check_only +class _HasDType(Protocol[_ScalarT_co]): + @property + def dtype(self, /) -> np.dtype[_ScalarT_co]: ... + +### + +def mintypecode(typechars: Iterable[str | ArrayLike], typeset: str | Container[str] = "GDFgdf", default: str = "d") -> str: ... + +# +@overload +def real(val: _HasReal[_T]) -> _T: ... # type: ignore[overload-overlap] +@overload +def real(val: _ArrayLike[_RealT]) -> NDArray[_RealT]: ... +@overload +def real(val: ArrayLike) -> NDArray[Any]: ... + +# +@overload +def imag(val: _HasImag[_T]) -> _T: ... # type: ignore[overload-overlap] +@overload +def imag(val: _ArrayLike[_RealT]) -> NDArray[_RealT]: ... +@overload +def imag(val: ArrayLike) -> NDArray[Any]: ... + +# +@overload +def iscomplex(x: _ScalarLike_co) -> np.bool: ... +@overload +def iscomplex(x: NDArray[Any] | _NestedSequence[ArrayLike]) -> NDArray[np.bool]: ... +@overload +def iscomplex(x: ArrayLike) -> np.bool | NDArray[np.bool]: ... + +# +@overload +def isreal(x: _ScalarLike_co) -> np.bool: ... +@overload +def isreal(x: NDArray[Any] | _NestedSequence[ArrayLike]) -> NDArray[np.bool]: ... +@overload +def isreal(x: ArrayLike) -> np.bool | NDArray[np.bool]: ... + +# +def iscomplexobj(x: _HasDType[Any] | ArrayLike) -> bool: ... +def isrealobj(x: _HasDType[Any] | ArrayLike) -> bool: ... + +# +@overload +def nan_to_num( + x: _ScalarT, + copy: bool = True, + nan: float = 0.0, + posinf: float | None = None, + neginf: float | None = None, +) -> _ScalarT: ... +@overload +def nan_to_num( + x: NDArray[_ScalarT] | _NestedSequence[_ArrayLike[_ScalarT]], + copy: bool = True, + nan: float = 0.0, + posinf: float | None = None, + neginf: float | None = None, +) -> NDArray[_ScalarT]: ... +@overload +def nan_to_num( + x: _SupportsArray[np.dtype[_ScalarT]], + copy: bool = True, + nan: float = 0.0, + posinf: float | None = None, + neginf: float | None = None, +) -> _ScalarT | NDArray[_ScalarT]: ... +@overload +def nan_to_num( + x: _NestedSequence[ArrayLike], + copy: bool = True, + nan: float = 0.0, + posinf: float | None = None, + neginf: float | None = None, +) -> NDArray[Incomplete]: ... +@overload +def nan_to_num( + x: ArrayLike, + copy: bool = True, + nan: float = 0.0, + posinf: float | None = None, + neginf: float | None = None, +) -> Incomplete: ... + +# NOTE: The [overload-overlap] mypy error is a false positive +@overload +def real_if_close(a: _ArrayLike[np.complex64], tol: float = 100) -> NDArray[np.float32 | np.complex64]: ... # type: ignore[overload-overlap] +@overload +def real_if_close(a: _ArrayLike[np.complex128], tol: float = 100) -> NDArray[np.float64 | np.complex128]: ... +@overload +def real_if_close(a: _ArrayLike[np.clongdouble], tol: float = 100) -> NDArray[np.longdouble | np.clongdouble]: ... +@overload +def real_if_close(a: _ArrayLike[_RealT], tol: float = 100) -> NDArray[_RealT]: ... +@overload +def real_if_close(a: ArrayLike, tol: float = 100) -> NDArray[Any]: ... + +# +@overload +def typename(char: L["S1"]) -> L["character"]: ... +@overload +def typename(char: L["?"]) -> L["bool"]: ... +@overload +def typename(char: L["b"]) -> L["signed char"]: ... +@overload +def typename(char: L["B"]) -> L["unsigned char"]: ... +@overload +def typename(char: L["h"]) -> L["short"]: ... +@overload +def typename(char: L["H"]) -> L["unsigned short"]: ... +@overload +def typename(char: L["i"]) -> L["integer"]: ... +@overload +def typename(char: L["I"]) -> L["unsigned integer"]: ... +@overload +def typename(char: L["l"]) -> L["long integer"]: ... +@overload +def typename(char: L["L"]) -> L["unsigned long integer"]: ... +@overload +def typename(char: L["q"]) -> L["long long integer"]: ... +@overload +def typename(char: L["Q"]) -> L["unsigned long long integer"]: ... +@overload +def typename(char: L["f"]) -> L["single precision"]: ... +@overload +def typename(char: L["d"]) -> L["double precision"]: ... +@overload +def typename(char: L["g"]) -> L["long precision"]: ... +@overload +def typename(char: L["F"]) -> L["complex single precision"]: ... +@overload +def typename(char: L["D"]) -> L["complex double precision"]: ... +@overload +def typename(char: L["G"]) -> L["complex long double precision"]: ... +@overload +def typename(char: L["S"]) -> L["string"]: ... +@overload +def typename(char: L["U"]) -> L["unicode"]: ... +@overload +def typename(char: L["V"]) -> L["void"]: ... +@overload +def typename(char: L["O"]) -> L["object"]: ... + +# NOTE: The [overload-overlap] mypy errors are false positives +@overload +def common_type() -> type[np.float16]: ... +@overload +def common_type(a0: _HasDType[np.float16], /, *ai: _HasDType[np.float16]) -> type[np.float16]: ... # type: ignore[overload-overlap] +@overload +def common_type(a0: _HasDType[np.float32], /, *ai: _HasDType[_FloatMax32]) -> type[np.float32]: ... # type: ignore[overload-overlap] +@overload +def common_type( # type: ignore[overload-overlap] + a0: _HasDType[np.float64 | np.integer], + /, + *ai: _HasDType[_RealMax64], +) -> type[np.float64]: ... +@overload +def common_type( # type: ignore[overload-overlap] + a0: _HasDType[np.longdouble], + /, + *ai: _HasDType[_Real], +) -> type[np.longdouble]: ... +@overload +def common_type( # type: ignore[overload-overlap] + a0: _HasDType[np.complex64], + /, + *ai: _HasDType[_InexactMax32], +) -> type[np.complex64]: ... +@overload +def common_type( # type: ignore[overload-overlap] + a0: _HasDType[np.complex128], + /, + *ai: _HasDType[_NumberMax64], +) -> type[np.complex128]: ... +@overload +def common_type( # type: ignore[overload-overlap] + a0: _HasDType[np.clongdouble], + /, + *ai: _HasDType[np.number], +) -> type[np.clongdouble]: ... +@overload +def common_type( # type: ignore[overload-overlap] + a0: _HasDType[_FloatMax32], + array1: _HasDType[np.float32], + /, + *ai: _HasDType[_FloatMax32], +) -> type[np.float32]: ... +@overload +def common_type( + a0: _HasDType[_RealMax64], + array1: _HasDType[np.float64 | np.integer], + /, + *ai: _HasDType[_RealMax64], +) -> type[np.float64]: ... +@overload +def common_type( + a0: _HasDType[_Real], + array1: _HasDType[np.longdouble], + /, + *ai: _HasDType[_Real], +) -> type[np.longdouble]: ... +@overload +def common_type( # type: ignore[overload-overlap] + a0: _HasDType[_InexactMax32], + array1: _HasDType[np.complex64], + /, + *ai: _HasDType[_InexactMax32], +) -> type[np.complex64]: ... +@overload +def common_type( + a0: _HasDType[np.float64], + array1: _HasDType[_ComplexMax128], + /, + *ai: _HasDType[_NumberMax64], +) -> type[np.complex128]: ... +@overload +def common_type( + a0: _HasDType[_ComplexMax128], + array1: _HasDType[np.float64], + /, + *ai: _HasDType[_NumberMax64], +) -> type[np.complex128]: ... +@overload +def common_type( + a0: _HasDType[_NumberMax64], + array1: _HasDType[np.complex128], + /, + *ai: _HasDType[_NumberMax64], +) -> type[np.complex128]: ... +@overload +def common_type( + a0: _HasDType[_ComplexMax128], + array1: _HasDType[np.complex128 | np.integer], + /, + *ai: _HasDType[_NumberMax64], +) -> type[np.complex128]: ... +@overload +def common_type( + a0: _HasDType[np.complex128 | np.integer], + array1: _HasDType[_ComplexMax128], + /, + *ai: _HasDType[_NumberMax64], +) -> type[np.complex128]: ... +@overload +def common_type( + a0: _HasDType[_Real], + /, + *ai: _HasDType[_Real], +) -> type[np.floating]: ... +@overload +def common_type( + a0: _HasDType[np.number], + array1: _HasDType[np.clongdouble], + /, + *ai: _HasDType[np.number], +) -> type[np.clongdouble]: ... +@overload +def common_type( + a0: _HasDType[np.longdouble], + array1: _HasDType[np.complexfloating], + /, + *ai: _HasDType[np.number], +) -> type[np.clongdouble]: ... +@overload +def common_type( + a0: _HasDType[np.complexfloating], + array1: _HasDType[np.longdouble], + /, + *ai: _HasDType[np.number], +) -> type[np.clongdouble]: ... +@overload +def common_type( + a0: _HasDType[np.complexfloating], + array1: _HasDType[np.number], + /, + *ai: _HasDType[np.number], +) -> type[np.complexfloating]: ... +@overload +def common_type( + a0: _HasDType[np.number], + array1: _HasDType[np.complexfloating], + /, + *ai: _HasDType[np.number], +) -> type[np.complexfloating]: ... +@overload +def common_type( + a0: _HasDType[np.number], + array1: _HasDType[np.number], + /, + *ai: _HasDType[np.number], +) -> type[Any]: ... diff --git a/python/user_packages/Python313/site-packages/numpy/lib/_ufunclike_impl.py b/python/user_packages/Python313/site-packages/numpy/lib/_ufunclike_impl.py new file mode 100644 index 0000000000000000000000000000000000000000..cd9990ac308dcfd70b1be74b7fd7e4a0a3d47e07 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/lib/_ufunclike_impl.py @@ -0,0 +1,199 @@ +""" +Module of functions that are like ufuncs in acting on arrays and optionally +storing results in an output array. + +""" +__all__ = ['fix', 'isneginf', 'isposinf'] + +import numpy._core.numeric as nx +from numpy._core.overrides import array_function_dispatch + + +def _dispatcher(x, out=None): + return (x, out) + + +@array_function_dispatch(_dispatcher, verify=False, module='numpy') +def fix(x, out=None): + """ + Round to nearest integer towards zero. + + Round an array of floats element-wise to nearest integer towards zero. + The rounded values have the same data-type as the input. + + Parameters + ---------- + x : array_like + An array to be rounded + out : ndarray, optional + A location into which the result is stored. If provided, it must have + a shape that the input broadcasts to. If not provided or None, a + freshly-allocated array is returned. + + Returns + ------- + out : ndarray of floats + An array with the same dimensions and data-type as the input. + If second argument is not supplied then a new array is returned + with the rounded values. + + If a second argument is supplied the result is stored there. + The return value ``out`` is then a reference to that array. + + See Also + -------- + rint, trunc, floor, ceil + around : Round to given number of decimals + + Examples + -------- + >>> import numpy as np + >>> np.fix(3.14) + 3.0 + >>> np.fix(3) + 3 + >>> np.fix([2.1, 2.9, -2.1, -2.9]) + array([ 2., 2., -2., -2.]) + + """ + return nx.trunc(x, out=out) + + +@array_function_dispatch(_dispatcher, verify=False, module='numpy') +def isposinf(x, out=None): + """ + Test element-wise for positive infinity, return result as bool array. + + Parameters + ---------- + x : array_like + The input array. + out : array_like, optional + A location into which the result is stored. If provided, it must have a + shape that the input broadcasts to. If not provided or None, a + freshly-allocated boolean array is returned. + + Returns + ------- + out : ndarray + A boolean array with the same dimensions as the input. + If second argument is not supplied then a boolean array is returned + with values True where the corresponding element of the input is + positive infinity and values False where the element of the input is + not positive infinity. + + If a second argument is supplied the result is stored there. If the + type of that array is a numeric type the result is represented as zeros + and ones, if the type is boolean then as False and True. + The return value `out` is then a reference to that array. + + See Also + -------- + isinf, isneginf, isfinite, isnan + + Notes + ----- + NumPy uses the IEEE Standard for Binary Floating-Point for Arithmetic + (IEEE 754). + + Errors result if the second argument is also supplied when x is a scalar + input, if first and second arguments have different shapes, or if the + first argument has complex values + + Examples + -------- + >>> import numpy as np + >>> np.isposinf(np.inf) + True + >>> np.isposinf(-np.inf) + False + >>> np.isposinf([-np.inf, 0., np.inf]) + array([False, False, True]) + + >>> x = np.array([-np.inf, 0., np.inf]) + >>> y = np.array([2, 2, 2]) + >>> np.isposinf(x, y) + array([0, 0, 1]) + >>> y + array([0, 0, 1]) + + """ + is_inf = nx.isinf(x) + try: + signbit = ~nx.signbit(x) + except TypeError as e: + dtype = nx.asanyarray(x).dtype + raise TypeError(f'This operation is not supported for {dtype} values ' + 'because it would be ambiguous.') from e + else: + return nx.logical_and(is_inf, signbit, out) + + +@array_function_dispatch(_dispatcher, verify=False, module='numpy') +def isneginf(x, out=None): + """ + Test element-wise for negative infinity, return result as bool array. + + Parameters + ---------- + x : array_like + The input array. + out : array_like, optional + A location into which the result is stored. If provided, it must have a + shape that the input broadcasts to. If not provided or None, a + freshly-allocated boolean array is returned. + + Returns + ------- + out : ndarray + A boolean array with the same dimensions as the input. + If second argument is not supplied then a numpy boolean array is + returned with values True where the corresponding element of the + input is negative infinity and values False where the element of + the input is not negative infinity. + + If a second argument is supplied the result is stored there. If the + type of that array is a numeric type the result is represented as + zeros and ones, if the type is boolean then as False and True. The + return value `out` is then a reference to that array. + + See Also + -------- + isinf, isposinf, isnan, isfinite + + Notes + ----- + NumPy uses the IEEE Standard for Binary Floating-Point for Arithmetic + (IEEE 754). + + Errors result if the second argument is also supplied when x is a scalar + input, if first and second arguments have different shapes, or if the + first argument has complex values. + + Examples + -------- + >>> import numpy as np + >>> np.isneginf(-np.inf) + True + >>> np.isneginf(np.inf) + False + >>> np.isneginf([-np.inf, 0., np.inf]) + array([ True, False, False]) + + >>> x = np.array([-np.inf, 0., np.inf]) + >>> y = np.array([2, 2, 2]) + >>> np.isneginf(x, y) + array([1, 0, 0]) + >>> y + array([1, 0, 0]) + + """ + is_inf = nx.isinf(x) + try: + signbit = nx.signbit(x) + except TypeError as e: + dtype = nx.asanyarray(x).dtype + raise TypeError(f'This operation is not supported for {dtype} values ' + 'because it would be ambiguous.') from e + else: + return nx.logical_and(is_inf, signbit, out) diff --git a/python/user_packages/Python313/site-packages/numpy/lib/_ufunclike_impl.pyi b/python/user_packages/Python313/site-packages/numpy/lib/_ufunclike_impl.pyi new file mode 100644 index 0000000000000000000000000000000000000000..ad5426e8d277bc66e5dbddab76009ffbc9d05de6 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/lib/_ufunclike_impl.pyi @@ -0,0 +1,60 @@ +from typing import Any, TypeVar, overload +from typing_extensions import deprecated + +import numpy as np +from numpy import floating, object_ +from numpy._typing import ( + NDArray, + _ArrayLikeFloat_co, + _ArrayLikeObject_co, + _FloatLike_co, +) + +__all__ = ["fix", "isneginf", "isposinf"] + +_ArrayT = TypeVar("_ArrayT", bound=NDArray[Any]) + +@overload +@deprecated("np.fix will be deprecated in NumPy 2.5 in favor of np.trunc", category=PendingDeprecationWarning) +def fix(x: _FloatLike_co, out: None = None) -> floating: ... +@overload +@deprecated("np.fix will be deprecated in NumPy 2.5 in favor of np.trunc", category=PendingDeprecationWarning) +def fix(x: _ArrayLikeFloat_co, out: None = None) -> NDArray[floating]: ... +@overload +@deprecated("np.fix will be deprecated in NumPy 2.5 in favor of np.trunc", category=PendingDeprecationWarning) +def fix(x: _ArrayLikeObject_co, out: None = None) -> NDArray[object_]: ... +@overload +@deprecated("np.fix will be deprecated in NumPy 2.5 in favor of np.trunc", category=PendingDeprecationWarning) +def fix(x: _ArrayLikeFloat_co | _ArrayLikeObject_co, out: _ArrayT) -> _ArrayT: ... + +@overload +def isposinf( # type: ignore[misc] + x: _FloatLike_co, + out: None = None, +) -> np.bool: ... +@overload +def isposinf( + x: _ArrayLikeFloat_co, + out: None = None, +) -> NDArray[np.bool]: ... +@overload +def isposinf( + x: _ArrayLikeFloat_co, + out: _ArrayT, +) -> _ArrayT: ... + +@overload +def isneginf( # type: ignore[misc] + x: _FloatLike_co, + out: None = None, +) -> np.bool: ... +@overload +def isneginf( + x: _ArrayLikeFloat_co, + out: None = None, +) -> NDArray[np.bool]: ... +@overload +def isneginf( + x: _ArrayLikeFloat_co, + out: _ArrayT, +) -> _ArrayT: ... diff --git a/python/user_packages/Python313/site-packages/numpy/lib/_user_array_impl.py b/python/user_packages/Python313/site-packages/numpy/lib/_user_array_impl.py new file mode 100644 index 0000000000000000000000000000000000000000..3a4b7f4ae90120eb1196397e15084d6a0cc87f95 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/lib/_user_array_impl.py @@ -0,0 +1,310 @@ +""" +Container class for backward compatibility with NumArray. + +The user_array.container class exists for backward compatibility with NumArray +and is not meant to be used in new code. If you need to create an array +container class, we recommend either creating a class that wraps an ndarray +or subclasses ndarray. + +""" +from numpy._core import ( + absolute, + add, + arange, + array, + asarray, + bitwise_and, + bitwise_or, + bitwise_xor, + divide, + equal, + greater, + greater_equal, + invert, + left_shift, + less, + less_equal, + multiply, + not_equal, + power, + remainder, + reshape, + right_shift, + shape, + sin, + sqrt, + subtract, + transpose, +) +from numpy._core.overrides import set_module + + +@set_module("numpy.lib.user_array") +class container: + """ + container(data, dtype=None, copy=True) + + Standard container-class for easy multiple-inheritance. + + Methods + ------- + copy + byteswap + astype + + """ + def __init_subclass__(cls) -> None: + # Deprecated in NumPy 2.4, 2025-11-24 + import warnings + + warnings.warn( + "The numpy.lib.user_array.container class is deprecated and will be " + "removed in a future version.", + DeprecationWarning, + stacklevel=2, + ) + + def __init__(self, data, dtype=None, copy=True): + self.array = array(data, dtype, copy=copy) + + def __repr__(self): + if self.ndim > 0: + return self.__class__.__name__ + repr(self.array)[len("array"):] + else: + return self.__class__.__name__ + "(" + repr(self.array) + ")" + + def __array__(self, t=None): + if t: + return self.array.astype(t) + return self.array + + # Array as sequence + def __len__(self): + return len(self.array) + + def __getitem__(self, index): + return self._rc(self.array[index]) + + def __setitem__(self, index, value): + self.array[index] = asarray(value, self.dtype) + + def __abs__(self): + return self._rc(absolute(self.array)) + + def __neg__(self): + return self._rc(-self.array) + + def __add__(self, other): + return self._rc(self.array + asarray(other)) + + __radd__ = __add__ + + def __iadd__(self, other): + add(self.array, other, self.array) + return self + + def __sub__(self, other): + return self._rc(self.array - asarray(other)) + + def __rsub__(self, other): + return self._rc(asarray(other) - self.array) + + def __isub__(self, other): + subtract(self.array, other, self.array) + return self + + def __mul__(self, other): + return self._rc(multiply(self.array, asarray(other))) + + __rmul__ = __mul__ + + def __imul__(self, other): + multiply(self.array, other, self.array) + return self + + def __mod__(self, other): + return self._rc(remainder(self.array, other)) + + def __rmod__(self, other): + return self._rc(remainder(other, self.array)) + + def __imod__(self, other): + remainder(self.array, other, self.array) + return self + + def __divmod__(self, other): + return (self._rc(divide(self.array, other)), + self._rc(remainder(self.array, other))) + + def __rdivmod__(self, other): + return (self._rc(divide(other, self.array)), + self._rc(remainder(other, self.array))) + + def __pow__(self, other): + return self._rc(power(self.array, asarray(other))) + + def __rpow__(self, other): + return self._rc(power(asarray(other), self.array)) + + def __ipow__(self, other): + power(self.array, other, self.array) + return self + + def __lshift__(self, other): + return self._rc(left_shift(self.array, other)) + + def __rshift__(self, other): + return self._rc(right_shift(self.array, other)) + + def __rlshift__(self, other): + return self._rc(left_shift(other, self.array)) + + def __rrshift__(self, other): + return self._rc(right_shift(other, self.array)) + + def __ilshift__(self, other): + left_shift(self.array, other, self.array) + return self + + def __irshift__(self, other): + right_shift(self.array, other, self.array) + return self + + def __and__(self, other): + return self._rc(bitwise_and(self.array, other)) + + def __rand__(self, other): + return self._rc(bitwise_and(other, self.array)) + + def __iand__(self, other): + bitwise_and(self.array, other, self.array) + return self + + def __xor__(self, other): + return self._rc(bitwise_xor(self.array, other)) + + def __rxor__(self, other): + return self._rc(bitwise_xor(other, self.array)) + + def __ixor__(self, other): + bitwise_xor(self.array, other, self.array) + return self + + def __or__(self, other): + return self._rc(bitwise_or(self.array, other)) + + def __ror__(self, other): + return self._rc(bitwise_or(other, self.array)) + + def __ior__(self, other): + bitwise_or(self.array, other, self.array) + return self + + def __pos__(self): + return self._rc(self.array) + + def __invert__(self): + return self._rc(invert(self.array)) + + def _scalarfunc(self, func): + if self.ndim == 0: + return func(self[0]) + else: + raise TypeError( + "only rank-0 arrays can be converted to Python scalars.") + + def __complex__(self): + return self._scalarfunc(complex) + + def __float__(self): + return self._scalarfunc(float) + + def __int__(self): + return self._scalarfunc(int) + + def __hex__(self): + return self._scalarfunc(hex) + + def __oct__(self): + return self._scalarfunc(oct) + + def __lt__(self, other): + return self._rc(less(self.array, other)) + + def __le__(self, other): + return self._rc(less_equal(self.array, other)) + + def __eq__(self, other): + return self._rc(equal(self.array, other)) + + def __ne__(self, other): + return self._rc(not_equal(self.array, other)) + + def __gt__(self, other): + return self._rc(greater(self.array, other)) + + def __ge__(self, other): + return self._rc(greater_equal(self.array, other)) + + def copy(self): + "" + return self._rc(self.array.copy()) + + def tobytes(self): + "" + return self.array.tobytes() + + def byteswap(self): + "" + return self._rc(self.array.byteswap()) + + def astype(self, typecode): + "" + return self._rc(self.array.astype(typecode)) + + def _rc(self, a): + if len(shape(a)) == 0: + return a + else: + return self.__class__(a) + + def __array_wrap__(self, *args): + return self.__class__(args[0]) + + def __setattr__(self, attr, value): + if attr == 'array': + object.__setattr__(self, attr, value) + return + try: + self.array.__setattr__(attr, value) + except AttributeError: + object.__setattr__(self, attr, value) + + # Only called after other approaches fail. + def __getattr__(self, attr): + if (attr == 'array'): + return object.__getattribute__(self, attr) + return self.array.__getattribute__(attr) + + +############################################################# +# Test of class container +############################################################# +if __name__ == '__main__': + temp = reshape(arange(10000), (100, 100)) + + ua = container(temp) + # new object created begin test + print(dir(ua)) + print(shape(ua), ua.shape) # I have changed Numeric.py + + ua_small = ua[:3, :5] + print(ua_small) + # this did not change ua[0,0], which is not normal behavior + ua_small[0, 0] = 10 + print(ua_small[0, 0], ua[0, 0]) + print(sin(ua_small) / 3. * 6. + sqrt(ua_small ** 2)) + print(less(ua_small, 103), type(less(ua_small, 103))) + print(type(ua_small * reshape(arange(15), shape(ua_small)))) + print(reshape(ua_small, (5, 3))) + print(transpose(ua_small)) diff --git a/python/user_packages/Python313/site-packages/numpy/lib/_user_array_impl.pyi b/python/user_packages/Python313/site-packages/numpy/lib/_user_array_impl.pyi new file mode 100644 index 0000000000000000000000000000000000000000..1e21f1246b77a841c395c9a41ee395f7171f9622 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/lib/_user_array_impl.pyi @@ -0,0 +1,226 @@ +from _typeshed import Incomplete +from types import EllipsisType +from typing import Any, Generic, Self, SupportsIndex, TypeAlias, overload +from typing_extensions import TypeVar, deprecated, override + +import numpy as np +import numpy.typing as npt +from numpy._typing import ( + _AnyShape, + _ArrayLike, + _ArrayLikeBool_co, + _ArrayLikeInt_co, + _DTypeLike, +) + +### + +_ScalarT = TypeVar("_ScalarT", bound=np.generic) +_ShapeT = TypeVar("_ShapeT", bound=tuple[int, ...]) +_ShapeT_co = TypeVar("_ShapeT_co", bound=tuple[int, ...], default=_AnyShape, covariant=True) +_DTypeT = TypeVar("_DTypeT", bound=np.dtype) +_DTypeT_co = TypeVar("_DTypeT_co", bound=np.dtype, default=np.dtype, covariant=True) + +_BoolArrayT = TypeVar("_BoolArrayT", bound=container[Any, np.dtype[np.bool]]) +_IntegralArrayT = TypeVar("_IntegralArrayT", bound=container[Any, np.dtype[np.bool | np.integer | np.object_]]) +_RealContainerT = TypeVar( + "_RealContainerT", + bound=container[Any, np.dtype[np.bool | np.integer | np.floating | np.timedelta64 | np.object_]], +) +_NumericContainerT = TypeVar("_NumericContainerT", bound=container[Any, np.dtype[np.number | np.timedelta64 | np.object_]]) + +_ArrayInt_co: TypeAlias = npt.NDArray[np.integer | np.bool] + +_ToIndexSlice: TypeAlias = slice | EllipsisType | _ArrayInt_co | None +_ToIndexSlices: TypeAlias = _ToIndexSlice | tuple[_ToIndexSlice, ...] +_ToIndex: TypeAlias = SupportsIndex | _ToIndexSlice +_ToIndices: TypeAlias = _ToIndex | tuple[_ToIndex, ...] + +### +# pyright: reportDeprecated = false + +@deprecated("The numpy.lib.user_array.container class is deprecated and will be removed in a future version.") +class container(Generic[_ShapeT_co, _DTypeT_co]): + array: np.ndarray[_ShapeT_co, _DTypeT_co] + + @overload + def __init__( + self, + /, + data: container[_ShapeT_co, _DTypeT_co] | np.ndarray[_ShapeT_co, _DTypeT_co], + dtype: None = None, + copy: bool = True, + ) -> None: ... + @overload + def __init__( + self: container[Any, np.dtype[_ScalarT]], + /, + data: _ArrayLike[_ScalarT], + dtype: None = None, + copy: bool = True, + ) -> None: ... + @overload + def __init__( + self: container[Any, np.dtype[_ScalarT]], + /, + data: npt.ArrayLike, + dtype: _DTypeLike[_ScalarT], + copy: bool = True, + ) -> None: ... + @overload + def __init__(self, /, data: npt.ArrayLike, dtype: npt.DTypeLike | None = None, copy: bool = True) -> None: ... + + # + def __complex__(self, /) -> complex: ... + def __float__(self, /) -> float: ... + def __int__(self, /) -> int: ... + def __hex__(self, /) -> str: ... + def __oct__(self, /) -> str: ... + + # + @override + def __eq__(self, other: object, /) -> container[_ShapeT_co, np.dtype[np.bool]]: ... # type: ignore[override] # pyright: ignore[reportIncompatibleMethodOverride] + @override + def __ne__(self, other: object, /) -> container[_ShapeT_co, np.dtype[np.bool]]: ... # type: ignore[override] # pyright: ignore[reportIncompatibleMethodOverride] + + # + def __lt__(self, other: npt.ArrayLike, /) -> container[_ShapeT_co, np.dtype[np.bool]]: ... + def __le__(self, other: npt.ArrayLike, /) -> container[_ShapeT_co, np.dtype[np.bool]]: ... + def __gt__(self, other: npt.ArrayLike, /) -> container[_ShapeT_co, np.dtype[np.bool]]: ... + def __ge__(self, other: npt.ArrayLike, /) -> container[_ShapeT_co, np.dtype[np.bool]]: ... + + # + def __len__(self, /) -> int: ... + + # keep in sync with np.ndarray + @overload + def __getitem__(self, key: _ArrayInt_co | tuple[_ArrayInt_co, ...], /) -> container[_ShapeT_co, _DTypeT_co]: ... + @overload + def __getitem__(self, key: _ToIndexSlices, /) -> container[_AnyShape, _DTypeT_co]: ... + @overload + def __getitem__(self, key: _ToIndices, /) -> Any: ... + @overload + def __getitem__(self: container[Any, np.dtype[np.void]], key: list[str], /) -> container[_ShapeT_co, np.dtype[np.void]]: ... + @overload + def __getitem__(self: container[Any, np.dtype[np.void]], key: str, /) -> container[_ShapeT_co, np.dtype]: ... + + # keep in sync with np.ndarray + @overload + def __setitem__(self, index: _ToIndices, value: object, /) -> None: ... + @overload + def __setitem__(self: container[Any, np.dtype[np.void]], key: str | list[str], value: object, /) -> None: ... + + # keep in sync with np.ndarray + @overload + def __abs__(self: container[_ShapeT, np.dtype[np.complex64]], /) -> container[_ShapeT, np.dtype[np.float32]]: ... # type: ignore[overload-overlap] + @overload + def __abs__(self: container[_ShapeT, np.dtype[np.complex128]], /) -> container[_ShapeT, np.dtype[np.float64]]: ... + @overload + def __abs__(self: container[_ShapeT, np.dtype[np.complex192]], /) -> container[_ShapeT, np.dtype[np.float96]]: ... + @overload + def __abs__(self: container[_ShapeT, np.dtype[np.complex256]], /) -> container[_ShapeT, np.dtype[np.float128]]: ... + @overload + def __abs__(self: _RealContainerT, /) -> _RealContainerT: ... + + # + def __neg__(self: _NumericContainerT, /) -> _NumericContainerT: ... # noqa: PYI019 + def __pos__(self: _NumericContainerT, /) -> _NumericContainerT: ... # noqa: PYI019 + def __invert__(self: _IntegralArrayT, /) -> _IntegralArrayT: ... # noqa: PYI019 + + # TODO(jorenham): complete these binary ops + + # + def __add__(self, other: npt.ArrayLike, /) -> Incomplete: ... + def __radd__(self, other: npt.ArrayLike, /) -> Incomplete: ... + def __iadd__(self, other: npt.ArrayLike, /) -> Self: ... + + # + def __sub__(self, other: npt.ArrayLike, /) -> Incomplete: ... + def __rsub__(self, other: npt.ArrayLike, /) -> Incomplete: ... + def __isub__(self, other: npt.ArrayLike, /) -> Self: ... + + # + def __mul__(self, other: npt.ArrayLike, /) -> Incomplete: ... + def __rmul__(self, other: npt.ArrayLike, /) -> Incomplete: ... + def __imul__(self, other: npt.ArrayLike, /) -> Self: ... + + # + def __mod__(self, other: npt.ArrayLike, /) -> Incomplete: ... + def __rmod__(self, other: npt.ArrayLike, /) -> Incomplete: ... + def __imod__(self, other: npt.ArrayLike, /) -> Self: ... + + # + def __divmod__(self, other: npt.ArrayLike, /) -> tuple[Incomplete, Incomplete]: ... + def __rdivmod__(self, other: npt.ArrayLike, /) -> tuple[Incomplete, Incomplete]: ... + + # + def __pow__(self, other: npt.ArrayLike, /) -> Incomplete: ... + def __rpow__(self, other: npt.ArrayLike, /) -> Incomplete: ... + def __ipow__(self, other: npt.ArrayLike, /) -> Self: ... + + # + def __lshift__(self, other: _ArrayLikeInt_co, /) -> container[_AnyShape, np.dtype[np.integer]]: ... + def __rlshift__(self, other: _ArrayLikeInt_co, /) -> container[_AnyShape, np.dtype[np.integer]]: ... + def __ilshift__(self, other: _ArrayLikeInt_co, /) -> Self: ... + + # + def __rshift__(self, other: _ArrayLikeInt_co, /) -> container[_AnyShape, np.dtype[np.integer]]: ... + def __rrshift__(self, other: _ArrayLikeInt_co, /) -> container[_AnyShape, np.dtype[np.integer]]: ... + def __irshift__(self, other: _ArrayLikeInt_co, /) -> Self: ... + + # + @overload + def __and__( + self: container[Any, np.dtype[np.bool]], other: _ArrayLikeBool_co, / + ) -> container[_AnyShape, np.dtype[np.bool]]: ... + @overload + def __and__(self, other: _ArrayLikeInt_co, /) -> container[_AnyShape, np.dtype[np.bool | np.integer]]: ... + __rand__ = __and__ + @overload + def __iand__(self: _BoolArrayT, other: _ArrayLikeBool_co, /) -> _BoolArrayT: ... + @overload + def __iand__(self, other: _ArrayLikeInt_co, /) -> Self: ... + + # + @overload + def __xor__( + self: container[Any, np.dtype[np.bool]], other: _ArrayLikeBool_co, / + ) -> container[_AnyShape, np.dtype[np.bool]]: ... + @overload + def __xor__(self, other: _ArrayLikeInt_co, /) -> container[_AnyShape, np.dtype[np.bool | np.integer]]: ... + __rxor__ = __xor__ + @overload + def __ixor__(self: _BoolArrayT, other: _ArrayLikeBool_co, /) -> _BoolArrayT: ... + @overload + def __ixor__(self, other: _ArrayLikeInt_co, /) -> Self: ... + + # + @overload + def __or__( + self: container[Any, np.dtype[np.bool]], other: _ArrayLikeBool_co, / + ) -> container[_AnyShape, np.dtype[np.bool]]: ... + @overload + def __or__(self, other: _ArrayLikeInt_co, /) -> container[_AnyShape, np.dtype[np.bool | np.integer]]: ... + __ror__ = __or__ + @overload + def __ior__(self: _BoolArrayT, other: _ArrayLikeBool_co, /) -> _BoolArrayT: ... + @overload + def __ior__(self, other: _ArrayLikeInt_co, /) -> Self: ... + + # + @overload + def __array__(self, /, t: None = None) -> np.ndarray[_ShapeT_co, _DTypeT_co]: ... + @overload + def __array__(self, /, t: _DTypeT) -> np.ndarray[_ShapeT_co, _DTypeT]: ... + + # + @overload + def __array_wrap__(self, arg0: npt.ArrayLike, /) -> container[_ShapeT_co, _DTypeT_co]: ... + @overload + def __array_wrap__(self, a: np.ndarray[_ShapeT, _DTypeT], c: Any = ..., s: Any = ..., /) -> container[_ShapeT, _DTypeT]: ... + + # + def copy(self, /) -> Self: ... + def tobytes(self, /) -> bytes: ... + def byteswap(self, /) -> Self: ... + def astype(self, /, typecode: _DTypeLike[_ScalarT]) -> container[_ShapeT_co, np.dtype[_ScalarT]]: ... diff --git a/python/user_packages/Python313/site-packages/numpy/lib/_utils_impl.py b/python/user_packages/Python313/site-packages/numpy/lib/_utils_impl.py new file mode 100644 index 0000000000000000000000000000000000000000..eb30000a9451d8f92dd1f3e55f5525ba35dd3313 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/lib/_utils_impl.py @@ -0,0 +1,784 @@ +import functools +import os +import platform +import sys +import textwrap +import types +import warnings + +import numpy as np +from numpy._core import ndarray +from numpy._utils import set_module + +__all__ = [ + 'get_include', 'info', 'show_runtime' +] + + +@set_module('numpy') +def show_runtime(): + """ + Print information about various resources in the system + including available intrinsic support and BLAS/LAPACK library + in use + + .. versionadded:: 1.24.0 + + See Also + -------- + show_config : Show libraries in the system on which NumPy was built. + + Notes + ----- + 1. Information is derived with the help of `threadpoolctl `_ + library if available. + 2. SIMD related information is derived from ``__cpu_features__``, + ``__cpu_baseline__`` and ``__cpu_dispatch__`` + + """ + from pprint import pprint + + from numpy._core._multiarray_umath import ( + __cpu_baseline__, + __cpu_dispatch__, + __cpu_features__, + ) + config_found = [{ + "numpy_version": np.__version__, + "python": sys.version, + "uname": platform.uname(), + }] + features_found, features_not_found = [], [] + for feature in __cpu_dispatch__: + if __cpu_features__[feature]: + features_found.append(feature) + else: + features_not_found.append(feature) + config_found.append({ + "simd_extensions": { + "baseline": __cpu_baseline__, + "found": features_found, + "not_found": features_not_found + } + }) + config_found.append({ + "ignore_floating_point_errors_in_matmul": + not np._core._multiarray_umath._blas_supports_fpe(None), + }) + + try: + from threadpoolctl import threadpool_info + config_found.extend(threadpool_info()) + except ImportError: + print("WARNING: `threadpoolctl` not found in system!" + " Install it by `pip install threadpoolctl`." + " Once installed, try `np.show_runtime` again" + " for more detailed build information") + pprint(config_found) + + +@set_module('numpy') +def get_include(): + """ + Return the directory that contains the NumPy \\*.h header files. + + Extension modules that need to compile against NumPy may need to use this + function to locate the appropriate include directory. + + Notes + ----- + When using ``setuptools``, for example in ``setup.py``:: + + import numpy as np + ... + Extension('extension_name', ... + include_dirs=[np.get_include()]) + ... + + Note that a CLI tool ``numpy-config`` was introduced in NumPy 2.0, using + that is likely preferred for build systems other than ``setuptools``:: + + $ numpy-config --cflags + -I/path/to/site-packages/numpy/_core/include + + # Or rely on pkg-config: + $ export PKG_CONFIG_PATH=$(numpy-config --pkgconfigdir) + $ pkg-config --cflags + -I/path/to/site-packages/numpy/_core/include + + Examples + -------- + >>> np.get_include() + '.../site-packages/numpy/core/include' # may vary + + """ + import numpy + if numpy.show_config is None: + # running from numpy source directory + d = os.path.join(os.path.dirname(numpy.__file__), '_core', 'include') + else: + # using installed numpy core headers + import numpy._core as _core + d = os.path.join(os.path.dirname(_core.__file__), 'include') + return d + + +class _Deprecate: + """ + Decorator class to deprecate old functions. + + Refer to `deprecate` for details. + + See Also + -------- + deprecate + + """ + + def __init__(self, old_name=None, new_name=None, message=None): + self.old_name = old_name + self.new_name = new_name + self.message = message + + def __call__(self, func, *args, **kwargs): + """ + Decorator call. Refer to ``decorate``. + + """ + old_name = self.old_name + new_name = self.new_name + message = self.message + + if old_name is None: + old_name = func.__name__ + if new_name is None: + depdoc = f"`{old_name}` is deprecated!" + else: + depdoc = f"`{old_name}` is deprecated, use `{new_name}` instead!" + + if message is not None: + depdoc += "\n" + message + + @functools.wraps(func) + def newfunc(*args, **kwds): + warnings.warn(depdoc, DeprecationWarning, stacklevel=2) + return func(*args, **kwds) + + newfunc.__name__ = old_name + doc = func.__doc__ + if doc is None: + doc = depdoc + else: + lines = doc.expandtabs().split('\n') + indent = _get_indent(lines[1:]) + if lines[0].lstrip(): + # Indent the original first line to let inspect.cleandoc() + # dedent the docstring despite the deprecation notice. + doc = indent * ' ' + doc + else: + # Remove the same leading blank lines as cleandoc() would. + skip = len(lines[0]) + 1 + for line in lines[1:]: + if len(line) > indent: + break + skip += len(line) + 1 + doc = doc[skip:] + depdoc = textwrap.indent(depdoc, ' ' * indent) + doc = f'{depdoc}\n\n{doc}' + newfunc.__doc__ = doc + + return newfunc + + +def _get_indent(lines): + """ + Determines the leading whitespace that could be removed from all the lines. + """ + indent = sys.maxsize + for line in lines: + content = len(line.lstrip()) + if content: + indent = min(indent, len(line) - content) + if indent == sys.maxsize: + indent = 0 + return indent + + +def deprecate(*args, **kwargs): + """ + Issues a DeprecationWarning, adds warning to `old_name`'s + docstring, rebinds ``old_name.__name__`` and returns the new + function object. + + This function may also be used as a decorator. + + .. deprecated:: 2.0 + Use `~warnings.warn` with :exc:`DeprecationWarning` instead. + + Parameters + ---------- + func : function + The function to be deprecated. + old_name : str, optional + The name of the function to be deprecated. Default is None, in + which case the name of `func` is used. + new_name : str, optional + The new name for the function. Default is None, in which case the + deprecation message is that `old_name` is deprecated. If given, the + deprecation message is that `old_name` is deprecated and `new_name` + should be used instead. + message : str, optional + Additional explanation of the deprecation. Displayed in the + docstring after the warning. + + Returns + ------- + old_func : function + The deprecated function. + + Examples + -------- + Note that ``olduint`` returns a value after printing Deprecation + Warning: + + >>> olduint = np.lib.utils.deprecate(np.uint) + DeprecationWarning: `uint64` is deprecated! # may vary + >>> olduint(6) + 6 + + """ + # Deprecate may be run as a function or as a decorator + # If run as a function, we initialise the decorator class + # and execute its __call__ method. + + # Deprecated in NumPy 2.0, 2023-07-11 + warnings.warn( + "`deprecate` is deprecated, " + "use `warn` with `DeprecationWarning` instead. " + "(deprecated in NumPy 2.0)", + DeprecationWarning, + stacklevel=2 + ) + + if args: + fn = args[0] + args = args[1:] + + return _Deprecate(*args, **kwargs)(fn) + else: + return _Deprecate(*args, **kwargs) + + +def deprecate_with_doc(msg): + """ + Deprecates a function and includes the deprecation in its docstring. + + .. deprecated:: 2.0 + Use `~warnings.warn` with :exc:`DeprecationWarning` instead. + + This function is used as a decorator. It returns an object that can be + used to issue a DeprecationWarning, by passing the to-be decorated + function as argument, this adds warning to the to-be decorated function's + docstring and returns the new function object. + + See Also + -------- + deprecate : Decorate a function such that it issues a + :exc:`DeprecationWarning` + + Parameters + ---------- + msg : str + Additional explanation of the deprecation. Displayed in the + docstring after the warning. + + Returns + ------- + obj : object + + """ + + # Deprecated in NumPy 2.0, 2023-07-11 + warnings.warn( + "`deprecate` is deprecated, " + "use `warn` with `DeprecationWarning` instead. " + "(deprecated in NumPy 2.0)", + DeprecationWarning, + stacklevel=2 + ) + + return _Deprecate(message=msg) + + +#----------------------------------------------------------------------------- + + +# NOTE: pydoc defines a help function which works similarly to this +# except it uses a pager to take over the screen. + +# combine name and arguments and split to multiple lines of width +# characters. End lines on a comma and begin argument list indented with +# the rest of the arguments. +def _split_line(name, arguments, width): + firstwidth = len(name) + k = firstwidth + newstr = name + sepstr = ", " + arglist = arguments.split(sepstr) + for argument in arglist: + if k == firstwidth: + addstr = "" + else: + addstr = sepstr + k = k + len(argument) + len(addstr) + if k > width: + k = firstwidth + 1 + len(argument) + newstr = newstr + ",\n" + " " * (firstwidth + 2) + argument + else: + newstr = newstr + addstr + argument + return newstr + + +_namedict = None +_dictlist = None + +# Traverse all module directories underneath globals +# to see if something is defined +def _makenamedict(module='numpy'): + module = __import__(module, globals(), locals(), []) + thedict = {module.__name__: module.__dict__} + dictlist = [module.__name__] + totraverse = [module.__dict__] + while True: + if len(totraverse) == 0: + break + thisdict = totraverse.pop(0) + for x in thisdict.keys(): + if isinstance(thisdict[x], types.ModuleType): + modname = thisdict[x].__name__ + if modname not in dictlist: + moddict = thisdict[x].__dict__ + dictlist.append(modname) + totraverse.append(moddict) + thedict[modname] = moddict + return thedict, dictlist + + +def _info(obj, output=None): + """Provide information about ndarray obj. + + Parameters + ---------- + obj : ndarray + Must be ndarray, not checked. + output + Where printed output goes. + + Notes + ----- + Copied over from the numarray module prior to its removal. + Adapted somewhat as only numpy is an option now. + + Called by info. + + """ + extra = "" + tic = "" + bp = lambda x: x + cls = getattr(obj, '__class__', type(obj)) + nm = getattr(cls, '__name__', cls) + strides = obj.strides + endian = obj.dtype.byteorder + + if output is None: + output = sys.stdout + + print("class: ", nm, file=output) + print("shape: ", obj.shape, file=output) + print("strides: ", strides, file=output) + print("itemsize: ", obj.itemsize, file=output) + print("aligned: ", bp(obj.flags.aligned), file=output) + print("contiguous: ", bp(obj.flags.contiguous), file=output) + print("fortran: ", obj.flags.fortran, file=output) + print( + f"data pointer: {hex(obj.ctypes._as_parameter_.value)}{extra}", + file=output + ) + print("byteorder: ", end=' ', file=output) + if endian in ['|', '=']: + print(f"{tic}{sys.byteorder}{tic}", file=output) + byteswap = False + elif endian == '>': + print(f"{tic}big{tic}", file=output) + byteswap = sys.byteorder != "big" + else: + print(f"{tic}little{tic}", file=output) + byteswap = sys.byteorder != "little" + print("byteswap: ", bp(byteswap), file=output) + print(f"type: {obj.dtype}", file=output) + + +@set_module('numpy') +def info(object=None, maxwidth=76, output=None, toplevel='numpy'): + """ + Get help information for an array, function, class, or module. + + Parameters + ---------- + object : object or str, optional + Input object or name to get information about. If `object` is + an `ndarray` instance, information about the array is printed. + If `object` is a numpy object, its docstring is given. If it is + a string, available modules are searched for matching objects. + If None, information about `info` itself is returned. + maxwidth : int, optional + Printing width. + output : file like object, optional + File like object that the output is written to, default is + ``None``, in which case ``sys.stdout`` will be used. + The object has to be opened in 'w' or 'a' mode. + toplevel : str, optional + Start search at this level. + + Notes + ----- + When used interactively with an object, ``np.info(obj)`` is equivalent + to ``help(obj)`` on the Python prompt or ``obj?`` on the IPython + prompt. + + Examples + -------- + >>> np.info(np.polyval) # doctest: +SKIP + polyval(p, x) + Evaluate the polynomial p at x. + ... + + When using a string for `object` it is possible to get multiple results. + + >>> np.info('fft') # doctest: +SKIP + *** Found in numpy *** + Core FFT routines + ... + *** Found in numpy.fft *** + fft(a, n=None, axis=-1) + ... + *** Repeat reference found in numpy.fft.fftpack *** + *** Total of 3 references found. *** + + When the argument is an array, information about the array is printed. + + >>> a = np.array([[1 + 2j, 3, -4], [-5j, 6, 0]], dtype=np.complex64) + >>> np.info(a) + class: ndarray + shape: (2, 3) + strides: (24, 8) + itemsize: 8 + aligned: True + contiguous: True + fortran: False + data pointer: 0x562b6e0d2860 # may vary + byteorder: little + byteswap: False + type: complex64 + + """ + global _namedict, _dictlist + # Local import to speed up numpy's import time. + import inspect + import pydoc + + if (hasattr(object, '_ppimport_importer') or + hasattr(object, '_ppimport_module')): + object = object._ppimport_module + elif hasattr(object, '_ppimport_attr'): + object = object._ppimport_attr + + if output is None: + output = sys.stdout + + if object is None: + info(info) + elif isinstance(object, ndarray): + _info(object, output=output) + elif isinstance(object, str): + if _namedict is None: + _namedict, _dictlist = _makenamedict(toplevel) + numfound = 0 + objlist = [] + for namestr in _dictlist: + try: + obj = _namedict[namestr][object] + if id(obj) in objlist: + print(f"\n *** Repeat reference found in {namestr} *** ", + file=output + ) + else: + objlist.append(id(obj)) + print(f" *** Found in {namestr} ***", file=output) + info(obj) + print("-" * maxwidth, file=output) + numfound += 1 + except KeyError: + pass + if numfound == 0: + print(f"Help for {object} not found.", file=output) + else: + print("\n " + "*** Total of %d references found. ***" % numfound, + file=output + ) + + elif inspect.isfunction(object) or inspect.ismethod(object): + name = object.__name__ + try: + arguments = str(inspect.signature(object)) + except Exception: + arguments = "()" + + if len(name + arguments) > maxwidth: + argstr = _split_line(name, arguments, maxwidth) + else: + argstr = name + arguments + + print(" " + argstr + "\n", file=output) + print(inspect.getdoc(object), file=output) + + elif inspect.isclass(object): + name = object.__name__ + try: + arguments = str(inspect.signature(object)) + except Exception: + arguments = "()" + + if len(name + arguments) > maxwidth: + argstr = _split_line(name, arguments, maxwidth) + else: + argstr = name + arguments + + print(" " + argstr + "\n", file=output) + doc1 = inspect.getdoc(object) + if doc1 is None: + if hasattr(object, '__init__'): + print(inspect.getdoc(object.__init__), file=output) + else: + print(inspect.getdoc(object), file=output) + + methods = pydoc.allmethods(object) + + public_methods = [meth for meth in methods if meth[0] != '_'] + if public_methods: + print("\n\nMethods:\n", file=output) + for meth in public_methods: + thisobj = getattr(object, meth, None) + if thisobj is not None: + methstr, other = pydoc.splitdoc( + inspect.getdoc(thisobj) or "None" + ) + print(f" {meth} -- {methstr}", file=output) + + elif hasattr(object, '__doc__'): + print(inspect.getdoc(object), file=output) + + +def safe_eval(source): + """ + Protected string evaluation. + + .. deprecated:: 2.0 + Use `ast.literal_eval` instead. + + Evaluate a string containing a Python literal expression without + allowing the execution of arbitrary non-literal code. + + .. warning:: + + This function is identical to :py:meth:`ast.literal_eval` and + has the same security implications. It may not always be safe + to evaluate large input strings. + + Parameters + ---------- + source : str + The string to evaluate. + + Returns + ------- + obj : object + The result of evaluating `source`. + + Raises + ------ + SyntaxError + If the code has invalid Python syntax, or if it contains + non-literal code. + + Examples + -------- + >>> np.safe_eval('1') + 1 + >>> np.safe_eval('[1, 2, 3]') + [1, 2, 3] + >>> np.safe_eval('{"foo": ("bar", 10.0)}') + {'foo': ('bar', 10.0)} + + >>> np.safe_eval('import os') + Traceback (most recent call last): + ... + SyntaxError: invalid syntax + + >>> np.safe_eval('open("/home/user/.ssh/id_dsa").read()') + Traceback (most recent call last): + ... + ValueError: malformed node or string: <_ast.Call object at 0x...> + + """ + + # Deprecated in NumPy 2.0, 2023-07-11 + warnings.warn( + "`safe_eval` is deprecated. Use `ast.literal_eval` instead. " + "Be aware of security implications, such as memory exhaustion " + "based attacks (deprecated in NumPy 2.0)", + DeprecationWarning, + stacklevel=2 + ) + + # Local import to speed up numpy's import time. + import ast + return ast.literal_eval(source) + + +def _median_nancheck(data, result, axis): + """ + Utility function to check median result from data for NaN values at the end + and return NaN in that case. Input result can also be a MaskedArray. + + Parameters + ---------- + data : array + Sorted input data to median function + result : Array or MaskedArray + Result of median function. + axis : int + Axis along which the median was computed. + + Returns + ------- + result : scalar or ndarray + Median or NaN in axes which contained NaN in the input. If the input + was an array, NaN will be inserted in-place. If a scalar, either the + input itself or a scalar NaN. + """ + if data.size == 0: + return result + potential_nans = data.take(-1, axis=axis) + n = np.isnan(potential_nans) + # masked NaN values are ok, although for masked the copyto may fail for + # unmasked ones (this was always broken) when the result is a scalar. + if np.ma.isMaskedArray(n): + n = n.filled(False) + + if not n.any(): + return result + + # Without given output, it is possible that the current result is a + # numpy scalar, which is not writeable. If so, just return nan. + if isinstance(result, np.generic): + return potential_nans + + # Otherwise copy NaNs (if there are any) + np.copyto(result, potential_nans, where=n) + return result + +def _opt_info(): + """ + Returns a string containing the CPU features supported + by the current build. + + The format of the string can be explained as follows: + - Dispatched features supported by the running machine end with `*`. + - Dispatched features not supported by the running machine + end with `?`. + - Remaining features represent the baseline. + + Returns: + str: A formatted string indicating the supported CPU features. + """ + from numpy._core._multiarray_umath import ( + __cpu_baseline__, + __cpu_dispatch__, + __cpu_features__, + ) + + if len(__cpu_baseline__) == 0 and len(__cpu_dispatch__) == 0: + return '' + + enabled_features = ' '.join(__cpu_baseline__) + for feature in __cpu_dispatch__: + if __cpu_features__[feature]: + enabled_features += f" {feature}*" + else: + enabled_features += f" {feature}?" + + return enabled_features + +def drop_metadata(dtype, /): + """ + Returns the dtype unchanged if it contained no metadata or a copy of the + dtype if it (or any of its structure dtypes) contained metadata. + + This utility is used by `np.save` and `np.savez` to drop metadata before + saving. + + .. note:: + + Due to its limitation this function may move to a more appropriate + home or change in the future and is considered semi-public API only. + + .. warning:: + + This function does not preserve more strange things like record dtypes + and user dtypes may simply return the wrong thing. If you need to be + sure about the latter, check the result with: + ``np.can_cast(new_dtype, dtype, casting="no")``. + + """ + if dtype.fields is not None: + found_metadata = dtype.metadata is not None + + names = [] + formats = [] + offsets = [] + titles = [] + for name, field in dtype.fields.items(): + field_dt = drop_metadata(field[0]) + if field_dt is not field[0]: + found_metadata = True + + names.append(name) + formats.append(field_dt) + offsets.append(field[1]) + titles.append(None if len(field) < 3 else field[2]) + + if not found_metadata: + return dtype + + structure = { + 'names': names, 'formats': formats, 'offsets': offsets, 'titles': titles, + 'itemsize': dtype.itemsize} + + # NOTE: Could pass (dtype.type, structure) to preserve record dtypes... + return np.dtype(structure, align=dtype.isalignedstruct) + elif dtype.subdtype is not None: + # subarray dtype + subdtype, shape = dtype.subdtype + new_subdtype = drop_metadata(subdtype) + if dtype.metadata is None and new_subdtype is subdtype: + return dtype + + return np.dtype((new_subdtype, shape)) + else: + # Normal unstructured dtype + if dtype.metadata is None: + return dtype + # Note that `dt.str` doesn't round-trip e.g. for user-dtypes. + return np.dtype(dtype.str) diff --git a/python/user_packages/Python313/site-packages/numpy/lib/_utils_impl.pyi b/python/user_packages/Python313/site-packages/numpy/lib/_utils_impl.pyi new file mode 100644 index 0000000000000000000000000000000000000000..985237718961dd7abecef593f95fad806ce7983c --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/lib/_utils_impl.pyi @@ -0,0 +1,22 @@ +from _typeshed import SupportsWrite +from typing import LiteralString +from typing_extensions import TypeVar + +import numpy as np + +__all__ = ["get_include", "info", "show_runtime"] + +_ScalarOrArrayT = TypeVar("_ScalarOrArrayT", bound=np.generic | np.ndarray) +_DTypeT = TypeVar("_DTypeT", bound=np.dtype) + +### + +def get_include() -> LiteralString: ... +def show_runtime() -> None: ... +def info( + object: object = None, maxwidth: int = 76, output: SupportsWrite[str] | None = None, toplevel: str = "numpy" +) -> None: ... +def drop_metadata(dtype: _DTypeT, /) -> _DTypeT: ... + +# used internally by `lib._function_base_impl._median` +def _median_nancheck(data: np.ndarray, result: _ScalarOrArrayT, axis: int) -> _ScalarOrArrayT: ... diff --git a/python/user_packages/Python313/site-packages/numpy/lib/_version.py b/python/user_packages/Python313/site-packages/numpy/lib/_version.py new file mode 100644 index 0000000000000000000000000000000000000000..d8b2eb3b600f5b17b702c81e3f3dd1d39abad69a --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/lib/_version.py @@ -0,0 +1,153 @@ +"""Utility to compare (NumPy) version strings. + +The NumpyVersion class allows properly comparing numpy version strings. +The LooseVersion and StrictVersion classes that distutils provides don't +work; they don't recognize anything like alpha/beta/rc/dev versions. + +""" +import re + +__all__ = ['NumpyVersion'] + + +class NumpyVersion: + """Parse and compare numpy version strings. + + NumPy has the following versioning scheme (numbers given are examples; they + can be > 9 in principle): + + - Released version: '1.8.0', '1.8.1', etc. + - Alpha: '1.8.0a1', '1.8.0a2', etc. + - Beta: '1.8.0b1', '1.8.0b2', etc. + - Release candidates: '1.8.0rc1', '1.8.0rc2', etc. + - Development versions: '1.8.0.dev-f1234afa' (git commit hash appended) + - Development versions after a1: '1.8.0a1.dev-f1234afa', + '1.8.0b2.dev-f1234afa', '1.8.1rc1.dev-f1234afa', etc. + - Development versions (no git hash available): '1.8.0.dev-Unknown' + + Comparing needs to be done against a valid version string or other + `NumpyVersion` instance. Note that all development versions of the same + (pre-)release compare equal. + + Parameters + ---------- + vstring : str + NumPy version string (``np.__version__``). + + Examples + -------- + >>> from numpy.lib import NumpyVersion + >>> if NumpyVersion(np.__version__) < '1.7.0': + ... print('skip') + >>> # skip + + >>> NumpyVersion('1.7') # raises ValueError, add ".0" + Traceback (most recent call last): + ... + ValueError: Not a valid numpy version string + + """ + + __module__ = "numpy.lib" + + def __init__(self, vstring): + self.vstring = vstring + ver_main = re.match(r'\d+\.\d+\.\d+', vstring) + if not ver_main: + raise ValueError("Not a valid numpy version string") + + self.version = ver_main.group() + self.major, self.minor, self.bugfix = [int(x) for x in + self.version.split('.')] + if len(vstring) == ver_main.end(): + self.pre_release = 'final' + else: + alpha = re.match(r'a\d', vstring[ver_main.end():]) + beta = re.match(r'b\d', vstring[ver_main.end():]) + rc = re.match(r'rc\d', vstring[ver_main.end():]) + pre_rel = [m for m in [alpha, beta, rc] if m is not None] + if pre_rel: + self.pre_release = pre_rel[0].group() + else: + self.pre_release = '' + + self.is_devversion = bool(re.search(r'.dev', vstring)) + + def _compare_version(self, other): + """Compare major.minor.bugfix""" + if self.major == other.major: + if self.minor == other.minor: + if self.bugfix == other.bugfix: + vercmp = 0 + elif self.bugfix > other.bugfix: + vercmp = 1 + else: + vercmp = -1 + elif self.minor > other.minor: + vercmp = 1 + else: + vercmp = -1 + elif self.major > other.major: + vercmp = 1 + else: + vercmp = -1 + + return vercmp + + def _compare_pre_release(self, other): + """Compare alpha/beta/rc/final.""" + if self.pre_release == other.pre_release: + vercmp = 0 + elif self.pre_release == 'final': + vercmp = 1 + elif other.pre_release == 'final': + vercmp = -1 + elif self.pre_release > other.pre_release: + vercmp = 1 + else: + vercmp = -1 + + return vercmp + + def _compare(self, other): + if not isinstance(other, (str, NumpyVersion)): + raise ValueError("Invalid object to compare with NumpyVersion.") + + if isinstance(other, str): + other = NumpyVersion(other) + + vercmp = self._compare_version(other) + if vercmp == 0: + # Same x.y.z version, check for alpha/beta/rc + vercmp = self._compare_pre_release(other) + if vercmp == 0: + # Same version and same pre-release, check if dev version + if self.is_devversion is other.is_devversion: + vercmp = 0 + elif self.is_devversion: + vercmp = -1 + else: + vercmp = 1 + + return vercmp + + def __lt__(self, other): + return self._compare(other) < 0 + + def __le__(self, other): + return self._compare(other) <= 0 + + def __eq__(self, other): + return self._compare(other) == 0 + + def __ne__(self, other): + return self._compare(other) != 0 + + def __gt__(self, other): + return self._compare(other) > 0 + + def __ge__(self, other): + return self._compare(other) >= 0 + + def __repr__(self): + return f"NumpyVersion({self.vstring})" diff --git a/python/user_packages/Python313/site-packages/numpy/lib/_version.pyi b/python/user_packages/Python313/site-packages/numpy/lib/_version.pyi new file mode 100644 index 0000000000000000000000000000000000000000..4e30cf332a868efaf70993f58b7d0f82b5154d7d --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/lib/_version.pyi @@ -0,0 +1,17 @@ +__all__ = ["NumpyVersion"] + +class NumpyVersion: + vstring: str + version: str + major: int + minor: int + bugfix: int + pre_release: str + is_devversion: bool + def __init__(self, vstring: str) -> None: ... + def __lt__(self, other: str | NumpyVersion) -> bool: ... + def __le__(self, other: str | NumpyVersion) -> bool: ... + def __eq__(self, other: str | NumpyVersion) -> bool: ... # type: ignore[override] + def __ne__(self, other: str | NumpyVersion) -> bool: ... # type: ignore[override] + def __gt__(self, other: str | NumpyVersion) -> bool: ... + def __ge__(self, other: str | NumpyVersion) -> bool: ... diff --git a/python/user_packages/Python313/site-packages/numpy/lib/array_utils.py b/python/user_packages/Python313/site-packages/numpy/lib/array_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..19866b8734a395c691510d7a10bc964ec2959741 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/lib/array_utils.py @@ -0,0 +1,7 @@ +from ._array_utils_impl import ( # noqa: F401 + __all__, + __doc__, + byte_bounds, + normalize_axis_index, + normalize_axis_tuple, +) diff --git a/python/user_packages/Python313/site-packages/numpy/lib/array_utils.pyi b/python/user_packages/Python313/site-packages/numpy/lib/array_utils.pyi new file mode 100644 index 0000000000000000000000000000000000000000..231398e0035145a72010d1dc724f931c86f8d047 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/lib/array_utils.pyi @@ -0,0 +1,6 @@ +from ._array_utils_impl import ( + __all__ as __all__, + byte_bounds as byte_bounds, + normalize_axis_index as normalize_axis_index, + normalize_axis_tuple as normalize_axis_tuple, +) diff --git a/python/user_packages/Python313/site-packages/numpy/lib/format.py b/python/user_packages/Python313/site-packages/numpy/lib/format.py new file mode 100644 index 0000000000000000000000000000000000000000..d69d1f8a4ea73afd20440baff186101957c73d8c --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/lib/format.py @@ -0,0 +1,24 @@ +from ._format_impl import ( # noqa: F401 + ARRAY_ALIGN, + BUFFER_SIZE, + EXPECTED_KEYS, + GROWTH_AXIS_MAX_DIGITS, + MAGIC_LEN, + MAGIC_PREFIX, + __all__, + __doc__, + descr_to_dtype, + drop_metadata, + dtype_to_descr, + header_data_from_array_1_0, + isfileobj, + magic, + open_memmap, + read_array, + read_array_header_1_0, + read_array_header_2_0, + read_magic, + write_array, + write_array_header_1_0, + write_array_header_2_0, +) diff --git a/python/user_packages/Python313/site-packages/numpy/lib/format.pyi b/python/user_packages/Python313/site-packages/numpy/lib/format.pyi new file mode 100644 index 0000000000000000000000000000000000000000..d218b27dc119e3e873f06d088c57a2ea7485c4f5 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/lib/format.pyi @@ -0,0 +1,24 @@ +from ._format_impl import ( + ARRAY_ALIGN as ARRAY_ALIGN, + BUFFER_SIZE as BUFFER_SIZE, + EXPECTED_KEYS as EXPECTED_KEYS, + GROWTH_AXIS_MAX_DIGITS as GROWTH_AXIS_MAX_DIGITS, + MAGIC_LEN as MAGIC_LEN, + MAGIC_PREFIX as MAGIC_PREFIX, + __all__ as __all__, + __doc__ as __doc__, + descr_to_dtype as descr_to_dtype, + drop_metadata as drop_metadata, + dtype_to_descr as dtype_to_descr, + header_data_from_array_1_0 as header_data_from_array_1_0, + isfileobj as isfileobj, + magic as magic, + open_memmap as open_memmap, + read_array as read_array, + read_array_header_1_0 as read_array_header_1_0, + read_array_header_2_0 as read_array_header_2_0, + read_magic as read_magic, + write_array as write_array, + write_array_header_1_0 as write_array_header_1_0, + write_array_header_2_0 as write_array_header_2_0, +) diff --git a/python/user_packages/Python313/site-packages/numpy/lib/introspect.py b/python/user_packages/Python313/site-packages/numpy/lib/introspect.py new file mode 100644 index 0000000000000000000000000000000000000000..4fd58590370de1fad35a893b3533863c8b3d13af --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/lib/introspect.py @@ -0,0 +1,94 @@ +""" +Introspection helper functions. +""" + +__all__ = ['opt_func_info'] + + +def opt_func_info(func_name=None, signature=None): + """ + Returns a dictionary containing the currently supported CPU dispatched + features for all optimized functions. + + Parameters + ---------- + func_name : str (optional) + Regular expression to filter by function name. + + signature : str (optional) + Regular expression to filter by data type. + + Returns + ------- + dict + A dictionary where keys are optimized function names and values are + nested dictionaries indicating supported targets based on data types. + + Examples + -------- + Retrieve dispatch information for functions named 'add' or 'sub' and + data types 'float64' or 'float32': + + >>> import numpy as np + >>> dict = np.lib.introspect.opt_func_info( + ... func_name="add|abs", signature="float64|complex64" + ... ) + >>> import json + >>> print(json.dumps(dict, indent=2)) # may vary (architecture) + { + "absolute": { + "dd": { + "current": "SSE41", + "available": "SSE41 baseline(SSE SSE2 SSE3)" + }, + "Ff": { + "current": "FMA3__AVX2", + "available": "AVX512F FMA3__AVX2 baseline(SSE SSE2 SSE3)" + }, + "Dd": { + "current": "FMA3__AVX2", + "available": "AVX512F FMA3__AVX2 baseline(SSE SSE2 SSE3)" + } + }, + "add": { + "ddd": { + "current": "FMA3__AVX2", + "available": "FMA3__AVX2 baseline(SSE SSE2 SSE3)" + }, + "FFF": { + "current": "FMA3__AVX2", + "available": "FMA3__AVX2 baseline(SSE SSE2 SSE3)" + } + } + } + + """ + import re + + from numpy._core._multiarray_umath import __cpu_targets_info__ as targets, dtype + + if func_name is not None: + func_pattern = re.compile(func_name) + matching_funcs = { + k: v for k, v in targets.items() + if func_pattern.search(k) + } + else: + matching_funcs = targets + + if signature is not None: + sig_pattern = re.compile(signature) + matching_sigs = {} + for k, v in matching_funcs.items(): + matching_chars = {} + for chars, targets in v.items(): + if any( + sig_pattern.search(c) or sig_pattern.search(dtype(c).name) + for c in chars + ): + matching_chars[chars] = targets # noqa: PERF403 + if matching_chars: + matching_sigs[k] = matching_chars + else: + matching_sigs = matching_funcs + return matching_sigs diff --git a/python/user_packages/Python313/site-packages/numpy/lib/introspect.pyi b/python/user_packages/Python313/site-packages/numpy/lib/introspect.pyi new file mode 100644 index 0000000000000000000000000000000000000000..52c3fbb3940447f911594fa2f834fa3a63e053cb --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/lib/introspect.pyi @@ -0,0 +1,3 @@ +__all__ = ["opt_func_info"] + +def opt_func_info(func_name: str | None = None, signature: str | None = None) -> dict[str, dict[str, dict[str, str]]]: ... diff --git a/python/user_packages/Python313/site-packages/numpy/lib/mixins.py b/python/user_packages/Python313/site-packages/numpy/lib/mixins.py new file mode 100644 index 0000000000000000000000000000000000000000..830a617f275dbb9cf4bcec0c8f5167acd751ecad --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/lib/mixins.py @@ -0,0 +1,180 @@ +""" +Mixin classes for custom array types that don't inherit from ndarray. +""" +from numpy._core import umath as um + +__all__ = ['NDArrayOperatorsMixin'] + + +def _disables_array_ufunc(obj): + """True when __array_ufunc__ is set to None.""" + try: + return obj.__array_ufunc__ is None + except AttributeError: + return False + + +def _binary_method(ufunc, name): + """Implement a forward binary method with a ufunc, e.g., __add__.""" + def func(self, other): + if _disables_array_ufunc(other): + return NotImplemented + return ufunc(self, other) + func.__name__ = f'__{name}__' + return func + + +def _reflected_binary_method(ufunc, name): + """Implement a reflected binary method with a ufunc, e.g., __radd__.""" + def func(self, other): + if _disables_array_ufunc(other): + return NotImplemented + return ufunc(other, self) + func.__name__ = f'__r{name}__' + return func + + +def _inplace_binary_method(ufunc, name): + """Implement an in-place binary method with a ufunc, e.g., __iadd__.""" + def func(self, other): + return ufunc(self, other, out=(self,)) + func.__name__ = f'__i{name}__' + return func + + +def _numeric_methods(ufunc, name): + """Implement forward, reflected and inplace binary methods with a ufunc.""" + return (_binary_method(ufunc, name), + _reflected_binary_method(ufunc, name), + _inplace_binary_method(ufunc, name)) + + +def _unary_method(ufunc, name): + """Implement a unary special method with a ufunc.""" + def func(self): + return ufunc(self) + func.__name__ = f'__{name}__' + return func + + +class NDArrayOperatorsMixin: + """Mixin defining all operator special methods using __array_ufunc__. + + This class implements the special methods for almost all of Python's + builtin operators defined in the `operator` module, including comparisons + (``==``, ``>``, etc.) and arithmetic (``+``, ``*``, ``-``, etc.), by + deferring to the ``__array_ufunc__`` method, which subclasses must + implement. + + It is useful for writing classes that do not inherit from `numpy.ndarray`, + but that should support arithmetic and numpy universal functions like + arrays as described in :external+neps:doc:`nep-0013-ufunc-overrides`. + + As a trivial example, consider this implementation of an ``ArrayLike`` + class that simply wraps a NumPy array and ensures that the result of any + arithmetic operation is also an ``ArrayLike`` object: + + >>> import numbers + >>> class ArrayLike(np.lib.mixins.NDArrayOperatorsMixin): + ... def __init__(self, value): + ... self.value = np.asarray(value) + ... + ... # One might also consider adding the built-in list type to this + ... # list, to support operations like np.add(array_like, list) + ... _HANDLED_TYPES = (np.ndarray, numbers.Number) + ... + ... def __array_ufunc__(self, ufunc, method, *inputs, **kwargs): + ... out = kwargs.get('out', ()) + ... for x in inputs + out: + ... # Only support operations with instances of + ... # _HANDLED_TYPES. Use ArrayLike instead of type(self) + ... # for isinstance to allow subclasses that don't + ... # override __array_ufunc__ to handle ArrayLike objects. + ... if not isinstance( + ... x, self._HANDLED_TYPES + (ArrayLike,) + ... ): + ... return NotImplemented + ... + ... # Defer to the implementation of the ufunc + ... # on unwrapped values. + ... inputs = tuple(x.value if isinstance(x, ArrayLike) else x + ... for x in inputs) + ... if out: + ... kwargs['out'] = tuple( + ... x.value if isinstance(x, ArrayLike) else x + ... for x in out) + ... result = getattr(ufunc, method)(*inputs, **kwargs) + ... + ... if type(result) is tuple: + ... # multiple return values + ... return tuple(type(self)(x) for x in result) + ... elif method == 'at': + ... # no return value + ... return None + ... else: + ... # one return value + ... return type(self)(result) + ... + ... def __repr__(self): + ... return '%s(%r)' % (type(self).__name__, self.value) + + In interactions between ``ArrayLike`` objects and numbers or numpy arrays, + the result is always another ``ArrayLike``: + + >>> x = ArrayLike([1, 2, 3]) + >>> x - 1 + ArrayLike(array([0, 1, 2])) + >>> 1 - x + ArrayLike(array([ 0, -1, -2])) + >>> np.arange(3) - x + ArrayLike(array([-1, -1, -1])) + >>> x - np.arange(3) + ArrayLike(array([1, 1, 1])) + + Note that unlike ``numpy.ndarray``, ``ArrayLike`` does not allow operations + with arbitrary, unrecognized types. This ensures that interactions with + ArrayLike preserve a well-defined casting hierarchy. + + """ + + __slots__ = () + # Like np.ndarray, this mixin class implements "Option 1" from the ufunc + # overrides NEP. + + # comparisons don't have reflected and in-place versions + __lt__ = _binary_method(um.less, 'lt') + __le__ = _binary_method(um.less_equal, 'le') + __eq__ = _binary_method(um.equal, 'eq') + __ne__ = _binary_method(um.not_equal, 'ne') + __gt__ = _binary_method(um.greater, 'gt') + __ge__ = _binary_method(um.greater_equal, 'ge') + + # numeric methods + __add__, __radd__, __iadd__ = _numeric_methods(um.add, 'add') + __sub__, __rsub__, __isub__ = _numeric_methods(um.subtract, 'sub') + __mul__, __rmul__, __imul__ = _numeric_methods(um.multiply, 'mul') + __matmul__, __rmatmul__, __imatmul__ = _numeric_methods( + um.matmul, 'matmul') + __truediv__, __rtruediv__, __itruediv__ = _numeric_methods( + um.true_divide, 'truediv') + __floordiv__, __rfloordiv__, __ifloordiv__ = _numeric_methods( + um.floor_divide, 'floordiv') + __mod__, __rmod__, __imod__ = _numeric_methods(um.remainder, 'mod') + __divmod__ = _binary_method(um.divmod, 'divmod') + __rdivmod__ = _reflected_binary_method(um.divmod, 'divmod') + # __idivmod__ does not exist + # TODO: handle the optional third argument for __pow__? + __pow__, __rpow__, __ipow__ = _numeric_methods(um.power, 'pow') + __lshift__, __rlshift__, __ilshift__ = _numeric_methods( + um.left_shift, 'lshift') + __rshift__, __rrshift__, __irshift__ = _numeric_methods( + um.right_shift, 'rshift') + __and__, __rand__, __iand__ = _numeric_methods(um.bitwise_and, 'and') + __xor__, __rxor__, __ixor__ = _numeric_methods(um.bitwise_xor, 'xor') + __or__, __ror__, __ior__ = _numeric_methods(um.bitwise_or, 'or') + + # unary methods + __neg__ = _unary_method(um.negative, 'neg') + __pos__ = _unary_method(um.positive, 'pos') + __abs__ = _unary_method(um.absolute, 'abs') + __invert__ = _unary_method(um.invert, 'invert') diff --git a/python/user_packages/Python313/site-packages/numpy/lib/mixins.pyi b/python/user_packages/Python313/site-packages/numpy/lib/mixins.pyi new file mode 100644 index 0000000000000000000000000000000000000000..6facb24c570c1f94af20ad926afdfee6ccc7c3d5 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/lib/mixins.pyi @@ -0,0 +1,78 @@ +from abc import ABC, abstractmethod +from typing import Any, Literal as L, type_check_only + +from numpy import ufunc + +__all__ = ["NDArrayOperatorsMixin"] + +# NOTE: `NDArrayOperatorsMixin` is not formally an abstract baseclass, +# even though it's reliant on subclasses implementing `__array_ufunc__` + +# NOTE: The accepted input- and output-types of the various dunders are +# completely dependent on how `__array_ufunc__` is implemented. +# As such, only little type safety can be provided here. + +class NDArrayOperatorsMixin(ABC): + __slots__ = () + + @type_check_only + @abstractmethod + def __array_ufunc__( + self, + ufunc: ufunc, + method: L["__call__", "reduce", "reduceat", "accumulate", "outer", "at"], + /, + *inputs: Any, + **kwargs: Any, + ) -> Any: ... + def __lt__(self, other: Any) -> Any: ... + def __le__(self, other: Any) -> Any: ... + def __eq__(self, other: Any) -> Any: ... + def __ne__(self, other: Any) -> Any: ... + def __gt__(self, other: Any) -> Any: ... + def __ge__(self, other: Any) -> Any: ... + def __add__(self, other: Any) -> Any: ... + def __radd__(self, other: Any) -> Any: ... + def __iadd__(self, other: Any) -> Any: ... + def __sub__(self, other: Any) -> Any: ... + def __rsub__(self, other: Any) -> Any: ... + def __isub__(self, other: Any) -> Any: ... + def __mul__(self, other: Any) -> Any: ... + def __rmul__(self, other: Any) -> Any: ... + def __imul__(self, other: Any) -> Any: ... + def __matmul__(self, other: Any) -> Any: ... + def __rmatmul__(self, other: Any) -> Any: ... + def __imatmul__(self, other: Any) -> Any: ... + def __truediv__(self, other: Any) -> Any: ... + def __rtruediv__(self, other: Any) -> Any: ... + def __itruediv__(self, other: Any) -> Any: ... + def __floordiv__(self, other: Any) -> Any: ... + def __rfloordiv__(self, other: Any) -> Any: ... + def __ifloordiv__(self, other: Any) -> Any: ... + def __mod__(self, other: Any) -> Any: ... + def __rmod__(self, other: Any) -> Any: ... + def __imod__(self, other: Any) -> Any: ... + def __divmod__(self, other: Any) -> Any: ... + def __rdivmod__(self, other: Any) -> Any: ... + def __pow__(self, other: Any) -> Any: ... + def __rpow__(self, other: Any) -> Any: ... + def __ipow__(self, other: Any) -> Any: ... + def __lshift__(self, other: Any) -> Any: ... + def __rlshift__(self, other: Any) -> Any: ... + def __ilshift__(self, other: Any) -> Any: ... + def __rshift__(self, other: Any) -> Any: ... + def __rrshift__(self, other: Any) -> Any: ... + def __irshift__(self, other: Any) -> Any: ... + def __and__(self, other: Any) -> Any: ... + def __rand__(self, other: Any) -> Any: ... + def __iand__(self, other: Any) -> Any: ... + def __xor__(self, other: Any) -> Any: ... + def __rxor__(self, other: Any) -> Any: ... + def __ixor__(self, other: Any) -> Any: ... + def __or__(self, other: Any) -> Any: ... + def __ror__(self, other: Any) -> Any: ... + def __ior__(self, other: Any) -> Any: ... + def __neg__(self) -> Any: ... + def __pos__(self) -> Any: ... + def __abs__(self) -> Any: ... + def __invert__(self) -> Any: ... diff --git a/python/user_packages/Python313/site-packages/numpy/lib/npyio.py b/python/user_packages/Python313/site-packages/numpy/lib/npyio.py new file mode 100644 index 0000000000000000000000000000000000000000..6c36a6f07e5d813b212a05ea6ed2e24a16ac892e --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/lib/npyio.py @@ -0,0 +1 @@ +from ._npyio_impl import DataSource, NpzFile, __doc__ # noqa: F401 diff --git a/python/user_packages/Python313/site-packages/numpy/lib/npyio.pyi b/python/user_packages/Python313/site-packages/numpy/lib/npyio.pyi new file mode 100644 index 0000000000000000000000000000000000000000..218664db23d9ccbc110585d57465f55d28cd297c --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/lib/npyio.pyi @@ -0,0 +1,5 @@ +from numpy.lib._npyio_impl import ( + DataSource as DataSource, + NpzFile as NpzFile, + __doc__ as __doc__, +) diff --git a/python/user_packages/Python313/site-packages/numpy/lib/recfunctions.py b/python/user_packages/Python313/site-packages/numpy/lib/recfunctions.py new file mode 100644 index 0000000000000000000000000000000000000000..933468e11eb906eeed54c6b4f64269ed32336a9b --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/lib/recfunctions.py @@ -0,0 +1,1681 @@ +""" +Collection of utilities to manipulate structured arrays. + +Most of these functions were initially implemented by John Hunter for +matplotlib. They have been rewritten and extended for convenience. + +""" +import itertools + +import numpy as np +import numpy.ma as ma +import numpy.ma.mrecords as mrec +from numpy._core.overrides import array_function_dispatch +from numpy.lib._iotools import _is_string_like + +__all__ = [ + 'append_fields', 'apply_along_fields', 'assign_fields_by_name', + 'drop_fields', 'find_duplicates', 'flatten_descr', + 'get_fieldstructure', 'get_names', 'get_names_flat', + 'join_by', 'merge_arrays', 'rec_append_fields', + 'rec_drop_fields', 'rec_join', 'recursive_fill_fields', + 'rename_fields', 'repack_fields', 'require_fields', + 'stack_arrays', 'structured_to_unstructured', 'unstructured_to_structured', + ] + + +def _recursive_fill_fields_dispatcher(input, output): + return (input, output) + + +@array_function_dispatch(_recursive_fill_fields_dispatcher) +def recursive_fill_fields(input, output): + """ + Fills fields from output with fields from input, + with support for nested structures. + + Parameters + ---------- + input : ndarray + Input array. + output : ndarray + Output array. + + Notes + ----- + * `output` should be at least the same size as `input` + + Examples + -------- + >>> import numpy as np + >>> from numpy.lib import recfunctions as rfn + >>> a = np.array([(1, 10.), (2, 20.)], dtype=[('A', np.int64), ('B', np.float64)]) + >>> b = np.zeros((3,), dtype=a.dtype) + >>> rfn.recursive_fill_fields(a, b) + array([(1, 10.), (2, 20.), (0, 0.)], dtype=[('A', '>> import numpy as np + >>> dt = np.dtype([(('a', 'A'), np.int64), ('b', np.double, 3)]) + >>> dt.descr + [(('a', 'A'), '>> _get_fieldspec(dt) + [(('a', 'A'), dtype('int64')), ('b', dtype(('>> import numpy as np + >>> from numpy.lib import recfunctions as rfn + >>> rfn.get_names(np.empty((1,), dtype=[('A', int)]).dtype) + ('A',) + >>> rfn.get_names(np.empty((1,), dtype=[('A',int), ('B', float)]).dtype) + ('A', 'B') + >>> adtype = np.dtype([('a', int), ('b', [('ba', int), ('bb', int)])]) + >>> rfn.get_names(adtype) + ('a', ('b', ('ba', 'bb'))) + """ + listnames = [] + names = adtype.names + for name in names: + current = adtype[name] + if current.names is not None: + listnames.append((name, tuple(get_names(current)))) + else: + listnames.append(name) + return tuple(listnames) + + +def get_names_flat(adtype): + """ + Returns the field names of the input datatype as a tuple. Input datatype + must have fields otherwise error is raised. + Nested structure are flattened beforehand. + + Parameters + ---------- + adtype : dtype + Input datatype + + Examples + -------- + >>> import numpy as np + >>> from numpy.lib import recfunctions as rfn + >>> rfn.get_names_flat(np.empty((1,), dtype=[('A', int)]).dtype) is None + False + >>> rfn.get_names_flat(np.empty((1,), dtype=[('A',int), ('B', str)]).dtype) + ('A', 'B') + >>> adtype = np.dtype([('a', int), ('b', [('ba', int), ('bb', int)])]) + >>> rfn.get_names_flat(adtype) + ('a', 'b', 'ba', 'bb') + """ + listnames = [] + names = adtype.names + for name in names: + listnames.append(name) + current = adtype[name] + if current.names is not None: + listnames.extend(get_names_flat(current)) + return tuple(listnames) + + +def flatten_descr(ndtype): + """ + Flatten a structured data-type description. + + Examples + -------- + >>> import numpy as np + >>> from numpy.lib import recfunctions as rfn + >>> ndtype = np.dtype([('a', '>> rfn.flatten_descr(ndtype) + (('a', dtype('int32')), ('ba', dtype('float64')), ('bb', dtype('int32'))) + + """ + names = ndtype.names + if names is None: + return (('', ndtype),) + else: + descr = [] + for field in names: + (typ, _) = ndtype.fields[field] + if typ.names is not None: + descr.extend(flatten_descr(typ)) + else: + descr.append((field, typ)) + return tuple(descr) + + +def _zip_dtype(seqarrays, flatten=False): + newdtype = [] + if flatten: + for a in seqarrays: + newdtype.extend(flatten_descr(a.dtype)) + else: + for a in seqarrays: + current = a.dtype + if current.names is not None and len(current.names) == 1: + # special case - dtypes of 1 field are flattened + newdtype.extend(_get_fieldspec(current)) + else: + newdtype.append(('', current)) + return np.dtype(newdtype) + + +def _zip_descr(seqarrays, flatten=False): + """ + Combine the dtype description of a series of arrays. + + Parameters + ---------- + seqarrays : sequence of arrays + Sequence of arrays + flatten : {boolean}, optional + Whether to collapse nested descriptions. + """ + return _zip_dtype(seqarrays, flatten=flatten).descr + + +def get_fieldstructure(adtype, lastname=None, parents=None,): + """ + Returns a dictionary with fields indexing lists of their parent fields. + + This function is used to simplify access to fields nested in other fields. + + Parameters + ---------- + adtype : np.dtype + Input datatype + lastname : optional + Last processed field name (used internally during recursion). + parents : dictionary + Dictionary of parent fields (used internally during recursion). + + Examples + -------- + >>> import numpy as np + >>> from numpy.lib import recfunctions as rfn + >>> ndtype = np.dtype([('A', int), + ... ('B', [('BA', int), + ... ('BB', [('BBA', int), ('BBB', int)])])]) + >>> rfn.get_fieldstructure(ndtype) + ... # XXX: possible regression, order of BBA and BBB is swapped + {'A': [], 'B': [], 'BA': ['B'], 'BB': ['B'], 'BBA': ['B', 'BB'], 'BBB': ['B', 'BB']} + + """ + if parents is None: + parents = {} + names = adtype.names + for name in names: + current = adtype[name] + if current.names is not None: + if lastname: + parents[name] = [lastname, ] + else: + parents[name] = [] + parents.update(get_fieldstructure(current, name, parents)) + else: + lastparent = list(parents.get(lastname, []) or []) + if lastparent: + lastparent.append(lastname) + elif lastname: + lastparent = [lastname, ] + parents[name] = lastparent or [] + return parents + + +def _izip_fields_flat(iterable): + """ + Returns an iterator of concatenated fields from a sequence of arrays, + collapsing any nested structure. + + """ + for element in iterable: + if isinstance(element, np.void): + yield from _izip_fields_flat(tuple(element)) + else: + yield element + + +def _izip_fields(iterable): + """ + Returns an iterator of concatenated fields from a sequence of arrays. + + """ + for element in iterable: + if (hasattr(element, '__iter__') and + not isinstance(element, str)): + yield from _izip_fields(element) + elif isinstance(element, np.void) and len(tuple(element)) == 1: + # this statement is the same from the previous expression + yield from _izip_fields(element) + else: + yield element + + +def _izip_records(seqarrays, fill_value=None, flatten=True): + """ + Returns an iterator of concatenated items from a sequence of arrays. + + Parameters + ---------- + seqarrays : sequence of arrays + Sequence of arrays. + fill_value : {None, integer} + Value used to pad shorter iterables. + flatten : {True, False}, + Whether to + """ + + # Should we flatten the items, or just use a nested approach + if flatten: + zipfunc = _izip_fields_flat + else: + zipfunc = _izip_fields + + for tup in itertools.zip_longest(*seqarrays, fillvalue=fill_value): + yield tuple(zipfunc(tup)) + + +def _fix_output(output, usemask=True, asrecarray=False): + """ + Private function: return a recarray, a ndarray, a MaskedArray + or a MaskedRecords depending on the input parameters + """ + if not isinstance(output, ma.MaskedArray): + usemask = False + if usemask: + if asrecarray: + output = output.view(mrec.MaskedRecords) + else: + output = ma.filled(output) + if asrecarray: + output = output.view(np.recarray) + return output + + +def _fix_defaults(output, defaults=None): + """ + Update the fill_value and masked data of `output` + from the default given in a dictionary defaults. + """ + names = output.dtype.names + (data, mask, fill_value) = (output.data, output.mask, output.fill_value) + for (k, v) in (defaults or {}).items(): + if k in names: + fill_value[k] = v + data[k][mask[k]] = v + return output + + +def _merge_arrays_dispatcher(seqarrays, fill_value=None, flatten=None, + usemask=None, asrecarray=None): + return seqarrays + + +@array_function_dispatch(_merge_arrays_dispatcher) +def merge_arrays(seqarrays, fill_value=-1, flatten=False, + usemask=False, asrecarray=False): + """ + Merge arrays field by field. + + Parameters + ---------- + seqarrays : sequence of ndarrays + Sequence of arrays + fill_value : {float}, optional + Filling value used to pad missing data on the shorter arrays. + flatten : {False, True}, optional + Whether to collapse nested fields. + usemask : {False, True}, optional + Whether to return a masked array or not. + asrecarray : {False, True}, optional + Whether to return a recarray (MaskedRecords) or not. + + Examples + -------- + >>> import numpy as np + >>> from numpy.lib import recfunctions as rfn + >>> rfn.merge_arrays((np.array([1, 2]), np.array([10., 20., 30.]))) + array([( 1, 10.), ( 2, 20.), (-1, 30.)], + dtype=[('f0', '>> rfn.merge_arrays((np.array([1, 2], dtype=np.int64), + ... np.array([10., 20., 30.])), usemask=False) + array([(1, 10.0), (2, 20.0), (-1, 30.0)], + dtype=[('f0', '>> rfn.merge_arrays((np.array([1, 2]).view([('a', np.int64)]), + ... np.array([10., 20., 30.])), + ... usemask=False, asrecarray=True) + rec.array([( 1, 10.), ( 2, 20.), (-1, 30.)], + dtype=[('a', '>> import numpy as np + >>> from numpy.lib import recfunctions as rfn + >>> a = np.array([(1, (2, 3.0)), (4, (5, 6.0))], + ... dtype=[('a', np.int64), ('b', [('ba', np.double), ('bb', np.int64)])]) + >>> rfn.drop_fields(a, 'a') + array([((2., 3),), ((5., 6),)], + dtype=[('b', [('ba', '>> rfn.drop_fields(a, 'ba') + array([(1, (3,)), (4, (6,))], dtype=[('a', '>> rfn.drop_fields(a, ['ba', 'bb']) + array([(1,), (4,)], dtype=[('a', '>> import numpy as np + >>> from numpy.lib import recfunctions as rfn + >>> a = np.array([(1, (2, [3.0, 30.])), (4, (5, [6.0, 60.]))], + ... dtype=[('a', int),('b', [('ba', float), ('bb', (float, 2))])]) + >>> rfn.rename_fields(a, {'a':'A', 'bb':'BB'}) + array([(1, (2., [ 3., 30.])), (4, (5., [ 6., 60.]))], + dtype=[('A', ' 1: + data = merge_arrays(data, flatten=True, usemask=usemask, + fill_value=fill_value) + else: + data = data.pop() + # + output = ma.masked_all( + max(len(base), len(data)), + dtype=_get_fieldspec(base.dtype) + _get_fieldspec(data.dtype)) + output = recursive_fill_fields(base, output) + output = recursive_fill_fields(data, output) + # + return _fix_output(output, usemask=usemask, asrecarray=asrecarray) + + +def _rec_append_fields_dispatcher(base, names, data, dtypes=None): + yield base + yield from data + + +@array_function_dispatch(_rec_append_fields_dispatcher) +def rec_append_fields(base, names, data, dtypes=None): + """ + Add new fields to an existing array. + + The names of the fields are given with the `names` arguments, + the corresponding values with the `data` arguments. + If a single field is appended, `names`, `data` and `dtypes` do not have + to be lists but just values. + + Parameters + ---------- + base : array + Input array to extend. + names : string, sequence + String or sequence of strings corresponding to the names + of the new fields. + data : array or sequence of arrays + Array or sequence of arrays storing the fields to add to the base. + dtypes : sequence of datatypes, optional + Datatype or sequence of datatypes. + If None, the datatypes are estimated from the `data`. + + See Also + -------- + append_fields + + Returns + ------- + appended_array : np.recarray + """ + return append_fields(base, names, data=data, dtypes=dtypes, + asrecarray=True, usemask=False) + + +def _repack_fields_dispatcher(a, align=None, recurse=None): + return (a,) + + +@array_function_dispatch(_repack_fields_dispatcher) +def repack_fields(a, align=False, recurse=False): + """ + Re-pack the fields of a structured array or dtype in memory. + + The memory layout of structured datatypes allows fields at arbitrary + byte offsets. This means the fields can be separated by padding bytes, + their offsets can be non-monotonically increasing, and they can overlap. + + This method removes any overlaps and reorders the fields in memory so they + have increasing byte offsets, and adds or removes padding bytes depending + on the `align` option, which behaves like the `align` option to + `numpy.dtype`. + + If `align=False`, this method produces a "packed" memory layout in which + each field starts at the byte the previous field ended, and any padding + bytes are removed. + + If `align=True`, this methods produces an "aligned" memory layout in which + each field's offset is a multiple of its alignment, and the total itemsize + is a multiple of the largest alignment, by adding padding bytes as needed. + + Parameters + ---------- + a : ndarray or dtype + array or dtype for which to repack the fields. + align : boolean + If true, use an "aligned" memory layout, otherwise use a "packed" layout. + recurse : boolean + If True, also repack nested structures. + + Returns + ------- + repacked : ndarray or dtype + Copy of `a` with fields repacked, or `a` itself if no repacking was + needed. + + Examples + -------- + >>> import numpy as np + + >>> from numpy.lib import recfunctions as rfn + >>> def print_offsets(d): + ... print("offsets:", [d.fields[name][1] for name in d.names]) + ... print("itemsize:", d.itemsize) + ... + >>> dt = np.dtype('u1, >> dt + dtype({'names': ['f0', 'f1', 'f2'], 'formats': ['u1', '>> print_offsets(dt) + offsets: [0, 8, 16] + itemsize: 24 + >>> packed_dt = rfn.repack_fields(dt) + >>> packed_dt + dtype([('f0', 'u1'), ('f1', '>> print_offsets(packed_dt) + offsets: [0, 1, 9] + itemsize: 17 + + """ + if not isinstance(a, np.dtype): + dt = repack_fields(a.dtype, align=align, recurse=recurse) + return a.astype(dt, copy=False) + + if a.names is None: + return a + + fieldinfo = [] + for name in a.names: + tup = a.fields[name] + if recurse: + fmt = repack_fields(tup[0], align=align, recurse=True) + else: + fmt = tup[0] + + if len(tup) == 3: + name = (tup[2], name) + + fieldinfo.append((name, fmt)) + + dt = np.dtype(fieldinfo, align=align) + return np.dtype((a.type, dt)) + +def _get_fields_and_offsets(dt, offset=0): + """ + Returns a flat list of (dtype, count, offset) tuples of all the + scalar fields in the dtype "dt", including nested fields, in left + to right order. + """ + + # counts up elements in subarrays, including nested subarrays, and returns + # base dtype and count + def count_elem(dt): + count = 1 + while dt.shape != (): + for size in dt.shape: + count *= size + dt = dt.base + return dt, count + + fields = [] + for name in dt.names: + field = dt.fields[name] + f_dt, f_offset = field[0], field[1] + f_dt, n = count_elem(f_dt) + + if f_dt.names is None: + fields.append((np.dtype((f_dt, (n,))), n, f_offset + offset)) + else: + subfields = _get_fields_and_offsets(f_dt, f_offset + offset) + size = f_dt.itemsize + + for i in range(n): + if i == 0: + # optimization: avoid list comprehension if no subarray + fields.extend(subfields) + else: + fields.extend([(d, c, o + i * size) for d, c, o in subfields]) + return fields + +def _common_stride(offsets, counts, itemsize): + """ + Returns the stride between the fields, or None if the stride is not + constant. The values in "counts" designate the lengths of + subarrays. Subarrays are treated as many contiguous fields, with + always positive stride. + """ + if len(offsets) <= 1: + return itemsize + + negative = offsets[1] < offsets[0] # negative stride + if negative: + # reverse, so offsets will be ascending + it = zip(reversed(offsets), reversed(counts)) + else: + it = zip(offsets, counts) + + prev_offset = None + stride = None + for offset, count in it: + if count != 1: # subarray: always c-contiguous + if negative: + return None # subarrays can never have a negative stride + if stride is None: + stride = itemsize + if stride != itemsize: + return None + end_offset = offset + (count - 1) * itemsize + else: + end_offset = offset + + if prev_offset is not None: + new_stride = offset - prev_offset + if stride is None: + stride = new_stride + if stride != new_stride: + return None + + prev_offset = end_offset + + if negative: + return -stride + return stride + + +def _structured_to_unstructured_dispatcher(arr, dtype=None, copy=None, + casting=None): + return (arr,) + +@array_function_dispatch(_structured_to_unstructured_dispatcher) +def structured_to_unstructured(arr, dtype=None, copy=False, casting='unsafe'): + """ + Converts an n-D structured array into an (n+1)-D unstructured array. + + The new array will have a new last dimension equal in size to the + number of field-elements of the input array. If not supplied, the output + datatype is determined from the numpy type promotion rules applied to all + the field datatypes. + + Nested fields, as well as each element of any subarray fields, all count + as a single field-elements. + + Parameters + ---------- + arr : ndarray + Structured array or dtype to convert. Cannot contain object datatype. + dtype : dtype, optional + The dtype of the output unstructured array. + copy : bool, optional + If true, always return a copy. If false, a view is returned if + possible, such as when the `dtype` and strides of the fields are + suitable and the array subtype is one of `numpy.ndarray`, + `numpy.recarray` or `numpy.memmap`. + + .. versionchanged:: 1.25.0 + A view can now be returned if the fields are separated by a + uniform stride. + + casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional + See casting argument of `numpy.ndarray.astype`. Controls what kind of + data casting may occur. + + Returns + ------- + unstructured : ndarray + Unstructured array with one more dimension. + + Examples + -------- + >>> import numpy as np + + >>> from numpy.lib import recfunctions as rfn + >>> a = np.zeros(4, dtype=[('a', 'i4'), ('b', 'f4,u2'), ('c', 'f4', 2)]) + >>> a + array([(0, (0., 0), [0., 0.]), (0, (0., 0), [0., 0.]), + (0, (0., 0), [0., 0.]), (0, (0., 0), [0., 0.])], + dtype=[('a', '>> rfn.structured_to_unstructured(a) + array([[0., 0., 0., 0., 0.], + [0., 0., 0., 0., 0.], + [0., 0., 0., 0., 0.], + [0., 0., 0., 0., 0.]]) + + >>> b = np.array([(1, 2, 5), (4, 5, 7), (7, 8 ,11), (10, 11, 12)], + ... dtype=[('x', 'i4'), ('y', 'f4'), ('z', 'f8')]) + >>> np.mean(rfn.structured_to_unstructured(b[['x', 'z']]), axis=-1) + array([ 3. , 5.5, 9. , 11. ]) + + """ # noqa: E501 + if arr.dtype.names is None: + raise ValueError('arr must be a structured array') + + fields = _get_fields_and_offsets(arr.dtype) + n_fields = len(fields) + if n_fields == 0 and dtype is None: + raise ValueError("arr has no fields. Unable to guess dtype") + elif n_fields == 0: + # too many bugs elsewhere for this to work now + raise NotImplementedError("arr with no fields is not supported") + + dts, counts, offsets = zip(*fields) + names = [f'f{n}' for n in range(n_fields)] + + if dtype is None: + out_dtype = np.result_type(*[dt.base for dt in dts]) + else: + out_dtype = np.dtype(dtype) + + # Use a series of views and casts to convert to an unstructured array: + + # first view using flattened fields (doesn't work for object arrays) + # Note: dts may include a shape for subarrays + flattened_fields = np.dtype({'names': names, + 'formats': dts, + 'offsets': offsets, + 'itemsize': arr.dtype.itemsize}) + arr = arr.view(flattened_fields) + + # we only allow a few types to be unstructured by manipulating the + # strides, because we know it won't work with, for example, np.matrix nor + # np.ma.MaskedArray. + can_view = type(arr) in (np.ndarray, np.recarray, np.memmap) + if (not copy) and can_view and all(dt.base == out_dtype for dt in dts): + # all elements have the right dtype already; if they have a common + # stride, we can just return a view + common_stride = _common_stride(offsets, counts, out_dtype.itemsize) + if common_stride is not None: + wrap = arr.__array_wrap__ + + new_shape = arr.shape + (sum(counts), out_dtype.itemsize) + new_strides = arr.strides + (abs(common_stride), 1) + + arr = arr[..., np.newaxis].view(np.uint8) # view as bytes + arr = arr[..., min(offsets):] # remove the leading unused data + arr = np.lib.stride_tricks.as_strided(arr, + new_shape, + new_strides, + subok=True) + + # cast and drop the last dimension again + arr = arr.view(out_dtype)[..., 0] + + if common_stride < 0: + arr = arr[..., ::-1] # reverse, if the stride was negative + if type(arr) is not type(wrap.__self__): + # Some types (e.g. recarray) turn into an ndarray along the + # way, so we have to wrap it again in order to match the + # behavior with copy=True. + arr = wrap(arr) + return arr + + # next cast to a packed format with all fields converted to new dtype + packed_fields = np.dtype({'names': names, + 'formats': [(out_dtype, dt.shape) for dt in dts]}) + arr = arr.astype(packed_fields, copy=copy, casting=casting) + + # finally is it safe to view the packed fields as the unstructured type + return arr.view((out_dtype, (sum(counts),))) + + +def _unstructured_to_structured_dispatcher(arr, dtype=None, names=None, + align=None, copy=None, casting=None): + return (arr,) + +@array_function_dispatch(_unstructured_to_structured_dispatcher) +def unstructured_to_structured(arr, dtype=None, names=None, align=False, + copy=False, casting='unsafe'): + """ + Converts an n-D unstructured array into an (n-1)-D structured array. + + The last dimension of the input array is converted into a structure, with + number of field-elements equal to the size of the last dimension of the + input array. By default all output fields have the input array's dtype, but + an output structured dtype with an equal number of fields-elements can be + supplied instead. + + Nested fields, as well as each element of any subarray fields, all count + towards the number of field-elements. + + Parameters + ---------- + arr : ndarray + Unstructured array or dtype to convert. + dtype : dtype, optional + The structured dtype of the output array + names : list of strings, optional + If dtype is not supplied, this specifies the field names for the output + dtype, in order. The field dtypes will be the same as the input array. + align : boolean, optional + Whether to create an aligned memory layout. + copy : bool, optional + See copy argument to `numpy.ndarray.astype`. If true, always return a + copy. If false, and `dtype` requirements are satisfied, a view is + returned. + casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional + See casting argument of `numpy.ndarray.astype`. Controls what kind of + data casting may occur. + + Returns + ------- + structured : ndarray + Structured array with fewer dimensions. + + Examples + -------- + >>> import numpy as np + + >>> from numpy.lib import recfunctions as rfn + >>> dt = np.dtype([('a', 'i4'), ('b', 'f4,u2'), ('c', 'f4', 2)]) + >>> a = np.arange(20).reshape((4,5)) + >>> a + array([[ 0, 1, 2, 3, 4], + [ 5, 6, 7, 8, 9], + [10, 11, 12, 13, 14], + [15, 16, 17, 18, 19]]) + >>> rfn.unstructured_to_structured(a, dt) + array([( 0, ( 1., 2), [ 3., 4.]), ( 5, ( 6., 7), [ 8., 9.]), + (10, (11., 12), [13., 14.]), (15, (16., 17), [18., 19.])], + dtype=[('a', '>> import numpy as np + + >>> from numpy.lib import recfunctions as rfn + >>> b = np.array([(1, 2, 5), (4, 5, 7), (7, 8 ,11), (10, 11, 12)], + ... dtype=[('x', 'i4'), ('y', 'f4'), ('z', 'f8')]) + >>> rfn.apply_along_fields(np.mean, b) + array([ 2.66666667, 5.33333333, 8.66666667, 11. ]) + >>> rfn.apply_along_fields(np.mean, b[['x', 'z']]) + array([ 3. , 5.5, 9. , 11. ]) + + """ + if arr.dtype.names is None: + raise ValueError('arr must be a structured array') + + uarr = structured_to_unstructured(arr) + return func(uarr, axis=-1) + # works and avoids axis requirement, but very, very slow: + #return np.apply_along_axis(func, -1, uarr) + +def _assign_fields_by_name_dispatcher(dst, src, zero_unassigned=None): + return dst, src + +@array_function_dispatch(_assign_fields_by_name_dispatcher) +def assign_fields_by_name(dst, src, zero_unassigned=True): + """ + Assigns values from one structured array to another by field name. + + Normally in numpy >= 1.14, assignment of one structured array to another + copies fields "by position", meaning that the first field from the src is + copied to the first field of the dst, and so on, regardless of field name. + + This function instead copies "by field name", such that fields in the dst + are assigned from the identically named field in the src. This applies + recursively for nested structures. This is how structure assignment worked + in numpy >= 1.6 to <= 1.13. + + Parameters + ---------- + dst : ndarray + src : ndarray + The source and destination arrays during assignment. + zero_unassigned : bool, optional + If True, fields in the dst for which there was no matching + field in the src are filled with the value 0 (zero). This + was the behavior of numpy <= 1.13. If False, those fields + are not modified. + """ + + if dst.dtype.names is None: + dst[...] = src + return + + for name in dst.dtype.names: + if name not in src.dtype.names: + if zero_unassigned: + dst[name] = 0 + else: + assign_fields_by_name(dst[name], src[name], + zero_unassigned) + +def _require_fields_dispatcher(array, required_dtype): + return (array,) + +@array_function_dispatch(_require_fields_dispatcher) +def require_fields(array, required_dtype): + """ + Casts a structured array to a new dtype using assignment by field-name. + + This function assigns from the old to the new array by name, so the + value of a field in the output array is the value of the field with the + same name in the source array. This has the effect of creating a new + ndarray containing only the fields "required" by the required_dtype. + + If a field name in the required_dtype does not exist in the + input array, that field is created and set to 0 in the output array. + + Parameters + ---------- + a : ndarray + array to cast + required_dtype : dtype + datatype for output array + + Returns + ------- + out : ndarray + array with the new dtype, with field values copied from the fields in + the input array with the same name + + Examples + -------- + >>> import numpy as np + + >>> from numpy.lib import recfunctions as rfn + >>> a = np.ones(4, dtype=[('a', 'i4'), ('b', 'f8'), ('c', 'u1')]) + >>> rfn.require_fields(a, [('b', 'f4'), ('c', 'u1')]) + array([(1., 1), (1., 1), (1., 1), (1., 1)], + dtype=[('b', '>> rfn.require_fields(a, [('b', 'f4'), ('newf', 'u1')]) + array([(1., 0), (1., 0), (1., 0), (1., 0)], + dtype=[('b', '>> import numpy as np + >>> from numpy.lib import recfunctions as rfn + >>> x = np.array([1, 2,]) + >>> rfn.stack_arrays(x) is x + True + >>> z = np.array([('A', 1), ('B', 2)], dtype=[('A', '|S3'), ('B', float)]) + >>> zz = np.array([('a', 10., 100.), ('b', 20., 200.), ('c', 30., 300.)], + ... dtype=[('A', '|S3'), ('B', np.double), ('C', np.double)]) + >>> test = rfn.stack_arrays((z,zz)) + >>> test + masked_array(data=[(b'A', 1.0, --), (b'B', 2.0, --), (b'a', 10.0, 100.0), + (b'b', 20.0, 200.0), (b'c', 30.0, 300.0)], + mask=[(False, False, True), (False, False, True), + (False, False, False), (False, False, False), + (False, False, False)], + fill_value=(b'N/A', 1e+20, 1e+20), + dtype=[('A', 'S3'), ('B', ' '{fdtype}'") + # Only one field: use concatenate + if len(newdescr) == 1: + output = ma.concatenate(seqarrays) + else: + # + output = ma.masked_all((np.sum(nrecords),), newdescr) + offset = np.cumsum(np.r_[0, nrecords]) + seen = [] + for (a, n, i, j) in zip(seqarrays, fldnames, offset[:-1], offset[1:]): + names = a.dtype.names + if names is None: + output[f'f{len(seen)}'][i:j] = a + else: + for name in n: + output[name][i:j] = a[name] + if name not in seen: + seen.append(name) + # + return _fix_output(_fix_defaults(output, defaults), + usemask=usemask, asrecarray=asrecarray) + + +def _find_duplicates_dispatcher( + a, key=None, ignoremask=None, return_index=None): + return (a,) + + +@array_function_dispatch(_find_duplicates_dispatcher) +def find_duplicates(a, key=None, ignoremask=True, return_index=False): + """ + Find the duplicates in a structured array along a given key + + Parameters + ---------- + a : array-like + Input array + key : {string, None}, optional + Name of the fields along which to check the duplicates. + If None, the search is performed by records + ignoremask : {True, False}, optional + Whether masked data should be discarded or considered as duplicates. + return_index : {False, True}, optional + Whether to return the indices of the duplicated values. + + Examples + -------- + >>> import numpy as np + >>> from numpy.lib import recfunctions as rfn + >>> ndtype = [('a', int)] + >>> a = np.ma.array([1, 1, 1, 2, 2, 3, 3], + ... mask=[0, 0, 1, 0, 0, 0, 1]).view(ndtype) + >>> rfn.find_duplicates(a, ignoremask=True, return_index=True) + (masked_array(data=[(1,), (1,), (2,), (2,)], + mask=[(False,), (False,), (False,), (False,)], + fill_value=(999999,), + dtype=[('a', '= nb1)] - nb1 + (r1cmn, r2cmn) = (len(idx_1), len(idx_2)) + if jointype == 'inner': + (r1spc, r2spc) = (0, 0) + elif jointype == 'outer': + idx_out = idx_sort[~flag_in] + idx_1 = np.concatenate((idx_1, idx_out[(idx_out < nb1)])) + idx_2 = np.concatenate((idx_2, idx_out[(idx_out >= nb1)] - nb1)) + (r1spc, r2spc) = (len(idx_1) - r1cmn, len(idx_2) - r2cmn) + elif jointype == 'leftouter': + idx_out = idx_sort[~flag_in] + idx_1 = np.concatenate((idx_1, idx_out[(idx_out < nb1)])) + (r1spc, r2spc) = (len(idx_1) - r1cmn, 0) + # Select the entries from each input + (s1, s2) = (r1[idx_1], r2[idx_2]) + # + # Build the new description of the output array ....... + # Start with the key fields + ndtype = _get_fieldspec(r1k.dtype) + + # Add the fields from r1 + for fname, fdtype in _get_fieldspec(r1.dtype): + if fname not in key: + ndtype.append((fname, fdtype)) + + # Add the fields from r2 + for fname, fdtype in _get_fieldspec(r2.dtype): + # Have we seen the current name already ? + # we need to rebuild this list every time + names = [name for name, dtype in ndtype] + try: + nameidx = names.index(fname) + except ValueError: + #... we haven't: just add the description to the current list + ndtype.append((fname, fdtype)) + else: + # collision + _, cdtype = ndtype[nameidx] + if fname in key: + # The current field is part of the key: take the largest dtype + ndtype[nameidx] = (fname, max(fdtype, cdtype)) + else: + # The current field is not part of the key: add the suffixes, + # and place the new field adjacent to the old one + ndtype[nameidx:nameidx + 1] = [ + (fname + r1postfix, cdtype), + (fname + r2postfix, fdtype) + ] + # Rebuild a dtype from the new fields + ndtype = np.dtype(ndtype) + # Find the largest nb of common fields : + # r1cmn and r2cmn should be equal, but... + cmn = max(r1cmn, r2cmn) + # Construct an empty array + output = ma.masked_all((cmn + r1spc + r2spc,), dtype=ndtype) + names = output.dtype.names + for f in r1names: + selected = s1[f] + if f not in names or (f in r2names and not r2postfix and f not in key): + f += r1postfix + current = output[f] + current[:r1cmn] = selected[:r1cmn] + if jointype in ('outer', 'leftouter'): + current[cmn:cmn + r1spc] = selected[r1cmn:] + for f in r2names: + selected = s2[f] + if f not in names or (f in r1names and not r1postfix and f not in key): + f += r2postfix + current = output[f] + current[:r2cmn] = selected[:r2cmn] + if (jointype == 'outer') and r2spc: + current[-r2spc:] = selected[r2cmn:] + # Sort and finalize the output + output.sort(order=key) + kwargs = {'usemask': usemask, 'asrecarray': asrecarray} + return _fix_output(_fix_defaults(output, defaults), **kwargs) + + +def _rec_join_dispatcher( + key, r1, r2, jointype=None, r1postfix=None, r2postfix=None, + defaults=None): + return (r1, r2) + + +@array_function_dispatch(_rec_join_dispatcher) +def rec_join(key, r1, r2, jointype='inner', r1postfix='1', r2postfix='2', + defaults=None): + """ + Join arrays `r1` and `r2` on keys. + Alternative to join_by, that always returns a np.recarray. + + See Also + -------- + join_by : equivalent function + """ + kwargs = {'jointype': jointype, 'r1postfix': r1postfix, 'r2postfix': r2postfix, + 'defaults': defaults, 'usemask': False, 'asrecarray': True} + return join_by(key, r1, r2, **kwargs) + + +del array_function_dispatch diff --git a/python/user_packages/Python313/site-packages/numpy/lib/recfunctions.pyi b/python/user_packages/Python313/site-packages/numpy/lib/recfunctions.pyi new file mode 100644 index 0000000000000000000000000000000000000000..fe1a2ae10209330bb6c85a3044b6c57f4aeaf1f4 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/lib/recfunctions.pyi @@ -0,0 +1,444 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Iterable, Mapping, Sequence +from typing import Any, Literal, TypeAlias, overload +from typing_extensions import TypeVar + +import numpy as np +import numpy.typing as npt +from numpy._typing import _AnyShape, _DTypeLike, _DTypeLikeVoid +from numpy.ma.mrecords import MaskedRecords + +__all__ = [ + "append_fields", + "apply_along_fields", + "assign_fields_by_name", + "drop_fields", + "find_duplicates", + "flatten_descr", + "get_fieldstructure", + "get_names", + "get_names_flat", + "join_by", + "merge_arrays", + "rec_append_fields", + "rec_drop_fields", + "rec_join", + "recursive_fill_fields", + "rename_fields", + "repack_fields", + "require_fields", + "stack_arrays", + "structured_to_unstructured", + "unstructured_to_structured", +] + +_T = TypeVar("_T") +_ShapeT = TypeVar("_ShapeT", bound=tuple[int, ...]) +_ScalarT = TypeVar("_ScalarT", bound=np.generic) +_DTypeT = TypeVar("_DTypeT", bound=np.dtype) +_ArrayT = TypeVar("_ArrayT", bound=npt.NDArray[Any]) +_VoidArrayT = TypeVar("_VoidArrayT", bound=npt.NDArray[np.void]) +_NonVoidDTypeT = TypeVar("_NonVoidDTypeT", bound=_NonVoidDType) + +_OneOrMany: TypeAlias = _T | Iterable[_T] +_BuiltinSequence: TypeAlias = tuple[_T, ...] | list[_T] + +_NestedNames: TypeAlias = tuple[str | _NestedNames, ...] +_NonVoid: TypeAlias = np.bool | np.number | np.character | np.datetime64 | np.timedelta64 | np.object_ +_NonVoidDType: TypeAlias = np.dtype[_NonVoid] | np.dtypes.StringDType + +_JoinType: TypeAlias = Literal["inner", "outer", "leftouter"] + +### + +def recursive_fill_fields(input: npt.NDArray[np.void], output: _VoidArrayT) -> _VoidArrayT: ... + +# +def get_names(adtype: np.dtype[np.void]) -> _NestedNames: ... +def get_names_flat(adtype: np.dtype[np.void]) -> tuple[str, ...]: ... + +# +@overload +def flatten_descr(ndtype: _NonVoidDTypeT) -> tuple[tuple[Literal[""], _NonVoidDTypeT]]: ... +@overload +def flatten_descr(ndtype: np.dtype[np.void]) -> tuple[tuple[str, np.dtype]]: ... + +# +def get_fieldstructure( + adtype: np.dtype[np.void], + lastname: str | None = None, + parents: dict[str, list[str]] | None = None, +) -> dict[str, list[str]]: ... + +# +@overload +def merge_arrays( + seqarrays: Sequence[np.ndarray[_ShapeT, np.dtype]] | np.ndarray[_ShapeT, np.dtype], + fill_value: float = -1, + flatten: bool = False, + usemask: bool = False, + asrecarray: bool = False, +) -> np.recarray[_ShapeT, np.dtype[np.void]]: ... +@overload +def merge_arrays( + seqarrays: Sequence[npt.ArrayLike] | np.void, + fill_value: float = -1, + flatten: bool = False, + usemask: bool = False, + asrecarray: bool = False, +) -> np.recarray[_AnyShape, np.dtype[np.void]]: ... + +# +@overload +def drop_fields( + base: np.ndarray[_ShapeT, np.dtype[np.void]], + drop_names: str | Iterable[str], + usemask: bool = True, + asrecarray: Literal[False] = False, +) -> np.ndarray[_ShapeT, np.dtype[np.void]]: ... +@overload +def drop_fields( + base: np.ndarray[_ShapeT, np.dtype[np.void]], + drop_names: str | Iterable[str], + usemask: bool, + asrecarray: Literal[True], +) -> np.recarray[_ShapeT, np.dtype[np.void]]: ... +@overload +def drop_fields( + base: np.ndarray[_ShapeT, np.dtype[np.void]], + drop_names: str | Iterable[str], + usemask: bool = True, + *, + asrecarray: Literal[True], +) -> np.recarray[_ShapeT, np.dtype[np.void]]: ... + +# +@overload +def rename_fields( + base: MaskedRecords[_ShapeT, np.dtype[np.void]], + namemapper: Mapping[str, str], +) -> MaskedRecords[_ShapeT, np.dtype[np.void]]: ... +@overload +def rename_fields( + base: np.ma.MaskedArray[_ShapeT, np.dtype[np.void]], + namemapper: Mapping[str, str], +) -> np.ma.MaskedArray[_ShapeT, np.dtype[np.void]]: ... +@overload +def rename_fields( + base: np.recarray[_ShapeT, np.dtype[np.void]], + namemapper: Mapping[str, str], +) -> np.recarray[_ShapeT, np.dtype[np.void]]: ... +@overload +def rename_fields( + base: np.ndarray[_ShapeT, np.dtype[np.void]], + namemapper: Mapping[str, str], +) -> np.ndarray[_ShapeT, np.dtype[np.void]]: ... + +# +@overload +def append_fields( + base: np.ndarray[_ShapeT, np.dtype[np.void]], + names: _OneOrMany[str], + data: _OneOrMany[npt.NDArray[Any]], + dtypes: _BuiltinSequence[np.dtype] | None, + fill_value: int, + usemask: Literal[False], + asrecarray: Literal[False] = False, +) -> np.ndarray[_ShapeT, np.dtype[np.void]]: ... +@overload +def append_fields( + base: np.ndarray[_ShapeT, np.dtype[np.void]], + names: _OneOrMany[str], + data: _OneOrMany[npt.NDArray[Any]], + dtypes: _BuiltinSequence[np.dtype] | None = None, + fill_value: int = -1, + *, + usemask: Literal[False], + asrecarray: Literal[False] = False, +) -> np.ndarray[_ShapeT, np.dtype[np.void]]: ... +@overload +def append_fields( + base: np.ndarray[_ShapeT, np.dtype[np.void]], + names: _OneOrMany[str], + data: _OneOrMany[npt.NDArray[Any]], + dtypes: _BuiltinSequence[np.dtype] | None, + fill_value: int, + usemask: Literal[False], + asrecarray: Literal[True], +) -> np.recarray[_ShapeT, np.dtype[np.void]]: ... +@overload +def append_fields( + base: np.ndarray[_ShapeT, np.dtype[np.void]], + names: _OneOrMany[str], + data: _OneOrMany[npt.NDArray[Any]], + dtypes: _BuiltinSequence[np.dtype] | None = None, + fill_value: int = -1, + *, + usemask: Literal[False], + asrecarray: Literal[True], +) -> np.recarray[_ShapeT, np.dtype[np.void]]: ... +@overload +def append_fields( + base: np.ndarray[_ShapeT, np.dtype[np.void]], + names: _OneOrMany[str], + data: _OneOrMany[npt.NDArray[Any]], + dtypes: _BuiltinSequence[np.dtype] | None = None, + fill_value: int = -1, + usemask: Literal[True] = True, + asrecarray: Literal[False] = False, +) -> np.ma.MaskedArray[_ShapeT, np.dtype[np.void]]: ... +@overload +def append_fields( + base: np.ndarray[_ShapeT, np.dtype[np.void]], + names: _OneOrMany[str], + data: _OneOrMany[npt.NDArray[Any]], + dtypes: _BuiltinSequence[np.dtype] | None, + fill_value: int, + usemask: Literal[True], + asrecarray: Literal[True], +) -> MaskedRecords[_ShapeT, np.dtype[np.void]]: ... +@overload +def append_fields( + base: np.ndarray[_ShapeT, np.dtype[np.void]], + names: _OneOrMany[str], + data: _OneOrMany[npt.NDArray[Any]], + dtypes: _BuiltinSequence[np.dtype] | None = None, + fill_value: int = -1, + usemask: Literal[True] = True, + *, + asrecarray: Literal[True], +) -> MaskedRecords[_ShapeT, np.dtype[np.void]]: ... + +# +def rec_drop_fields( + base: np.ndarray[_ShapeT, np.dtype[np.void]], + drop_names: str | Iterable[str], +) -> np.recarray[_ShapeT, np.dtype[np.void]]: ... + +# +def rec_append_fields( + base: np.ndarray[_ShapeT, np.dtype[np.void]], + names: _OneOrMany[str], + data: _OneOrMany[npt.NDArray[Any]], + dtypes: _BuiltinSequence[np.dtype] | None = None, +) -> np.ma.MaskedArray[_ShapeT, np.dtype[np.void]]: ... + +# TODO(jorenham): Stop passing `void` directly once structured dtypes are implemented, +# e.g. using a `TypeVar` with constraints. +# https://github.com/numpy/numtype/issues/92 +@overload +def repack_fields(a: _DTypeT, align: bool = False, recurse: bool = False) -> _DTypeT: ... +@overload +def repack_fields(a: _ScalarT, align: bool = False, recurse: bool = False) -> _ScalarT: ... +@overload +def repack_fields(a: _ArrayT, align: bool = False, recurse: bool = False) -> _ArrayT: ... + +# TODO(jorenham): Attempt shape-typing (return type has ndim == arr.ndim + 1) +@overload +def structured_to_unstructured( + arr: npt.NDArray[np.void], + dtype: _DTypeLike[_ScalarT], + copy: bool = False, + casting: np._CastingKind = "unsafe", +) -> npt.NDArray[_ScalarT]: ... +@overload +def structured_to_unstructured( + arr: npt.NDArray[np.void], + dtype: npt.DTypeLike | None = None, + copy: bool = False, + casting: np._CastingKind = "unsafe", +) -> npt.NDArray[Any]: ... + +# +@overload +def unstructured_to_structured( + arr: npt.NDArray[Any], + dtype: npt.DTypeLike, + names: None = None, + align: bool = False, + copy: bool = False, + casting: str = "unsafe", +) -> npt.NDArray[np.void]: ... +@overload +def unstructured_to_structured( + arr: npt.NDArray[Any], + dtype: None, + names: _OneOrMany[str], + align: bool = False, + copy: bool = False, + casting: str = "unsafe", +) -> npt.NDArray[np.void]: ... +@overload +def unstructured_to_structured( + arr: npt.NDArray[Any], + dtype: None = None, + *, + names: _OneOrMany[str], + align: bool = False, + copy: bool = False, + casting: str = "unsafe", +) -> npt.NDArray[np.void]: ... + +# +def apply_along_fields( + func: Callable[[np.ndarray[_ShapeT, Any]], npt.NDArray[Any]], + arr: np.ndarray[_ShapeT, np.dtype[np.void]], +) -> np.ndarray[_ShapeT, np.dtype[np.void]]: ... + +# +def assign_fields_by_name(dst: npt.NDArray[np.void], src: npt.NDArray[np.void], zero_unassigned: bool = True) -> None: ... + +# +def require_fields( + array: np.ndarray[_ShapeT, np.dtype[np.void]], + required_dtype: _DTypeLikeVoid, +) -> np.ndarray[_ShapeT, np.dtype[np.void]]: ... + +# TODO(jorenham): Attempt shape-typing +@overload +def stack_arrays( + arrays: _ArrayT, + defaults: Mapping[str, object] | None = None, + usemask: bool = True, + asrecarray: bool = False, + autoconvert: bool = False, +) -> _ArrayT: ... +@overload +def stack_arrays( + arrays: Sequence[npt.NDArray[Any]], + defaults: Mapping[str, Incomplete] | None, + usemask: Literal[False], + asrecarray: Literal[False] = False, + autoconvert: bool = False, +) -> npt.NDArray[np.void]: ... +@overload +def stack_arrays( + arrays: Sequence[npt.NDArray[Any]], + defaults: Mapping[str, Incomplete] | None = None, + *, + usemask: Literal[False], + asrecarray: Literal[False] = False, + autoconvert: bool = False, +) -> npt.NDArray[np.void]: ... +@overload +def stack_arrays( + arrays: Sequence[npt.NDArray[Any]], + defaults: Mapping[str, Incomplete] | None = None, + *, + usemask: Literal[False], + asrecarray: Literal[True], + autoconvert: bool = False, +) -> np.recarray[_AnyShape, np.dtype[np.void]]: ... +@overload +def stack_arrays( + arrays: Sequence[npt.NDArray[Any]], + defaults: Mapping[str, Incomplete] | None = None, + usemask: Literal[True] = True, + asrecarray: Literal[False] = False, + autoconvert: bool = False, +) -> np.ma.MaskedArray[_AnyShape, np.dtype[np.void]]: ... +@overload +def stack_arrays( + arrays: Sequence[npt.NDArray[Any]], + defaults: Mapping[str, Incomplete] | None, + usemask: Literal[True], + asrecarray: Literal[True], + autoconvert: bool = False, +) -> MaskedRecords[_AnyShape, np.dtype[np.void]]: ... +@overload +def stack_arrays( + arrays: Sequence[npt.NDArray[Any]], + defaults: Mapping[str, Incomplete] | None = None, + usemask: Literal[True] = True, + *, + asrecarray: Literal[True], + autoconvert: bool = False, +) -> MaskedRecords[_AnyShape, np.dtype[np.void]]: ... + +# +@overload +def find_duplicates( + a: np.ma.MaskedArray[_ShapeT, np.dtype[np.void]], + key: str | None = None, + ignoremask: bool = True, + return_index: Literal[False] = False, +) -> np.ma.MaskedArray[_ShapeT, np.dtype[np.void]]: ... +@overload +def find_duplicates( + a: np.ma.MaskedArray[_ShapeT, np.dtype[np.void]], + key: str | None, + ignoremask: bool, + return_index: Literal[True], +) -> tuple[np.ma.MaskedArray[_ShapeT, np.dtype[np.void]], np.ndarray[_ShapeT, np.dtype[np.int_]]]: ... +@overload +def find_duplicates( + a: np.ma.MaskedArray[_ShapeT, np.dtype[np.void]], + key: str | None = None, + ignoremask: bool = True, + *, + return_index: Literal[True], +) -> tuple[np.ma.MaskedArray[_ShapeT, np.dtype[np.void]], np.ndarray[_ShapeT, np.dtype[np.int_]]]: ... + +# +@overload +def join_by( + key: str | Sequence[str], + r1: npt.NDArray[np.void], + r2: npt.NDArray[np.void], + jointype: _JoinType = "inner", + r1postfix: str = "1", + r2postfix: str = "2", + defaults: Mapping[str, object] | None = None, + *, + usemask: Literal[False], + asrecarray: Literal[False] = False, +) -> np.ndarray[tuple[int], np.dtype[np.void]]: ... +@overload +def join_by( + key: str | Sequence[str], + r1: npt.NDArray[np.void], + r2: npt.NDArray[np.void], + jointype: _JoinType = "inner", + r1postfix: str = "1", + r2postfix: str = "2", + defaults: Mapping[str, object] | None = None, + *, + usemask: Literal[False], + asrecarray: Literal[True], +) -> np.recarray[tuple[int], np.dtype[np.void]]: ... +@overload +def join_by( + key: str | Sequence[str], + r1: npt.NDArray[np.void], + r2: npt.NDArray[np.void], + jointype: _JoinType = "inner", + r1postfix: str = "1", + r2postfix: str = "2", + defaults: Mapping[str, object] | None = None, + usemask: Literal[True] = True, + asrecarray: Literal[False] = False, +) -> np.ma.MaskedArray[tuple[int], np.dtype[np.void]]: ... +@overload +def join_by( + key: str | Sequence[str], + r1: npt.NDArray[np.void], + r2: npt.NDArray[np.void], + jointype: _JoinType = "inner", + r1postfix: str = "1", + r2postfix: str = "2", + defaults: Mapping[str, object] | None = None, + usemask: Literal[True] = True, + *, + asrecarray: Literal[True], +) -> MaskedRecords[tuple[int], np.dtype[np.void]]: ... + +# +def rec_join( + key: str | Sequence[str], + r1: npt.NDArray[np.void], + r2: npt.NDArray[np.void], + jointype: _JoinType = "inner", + r1postfix: str = "1", + r2postfix: str = "2", + defaults: Mapping[str, object] | None = None, +) -> np.recarray[tuple[int], np.dtype[np.void]]: ... diff --git a/python/user_packages/Python313/site-packages/numpy/lib/scimath.py b/python/user_packages/Python313/site-packages/numpy/lib/scimath.py new file mode 100644 index 0000000000000000000000000000000000000000..94175e1c800019a7b8954a6ad480c93ca210f5b6 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/lib/scimath.py @@ -0,0 +1,13 @@ +from ._scimath_impl import ( # noqa: F401 + __all__, + __doc__, + arccos, + arcsin, + arctanh, + log, + log2, + log10, + logn, + power, + sqrt, +) diff --git a/python/user_packages/Python313/site-packages/numpy/lib/scimath.pyi b/python/user_packages/Python313/site-packages/numpy/lib/scimath.pyi new file mode 100644 index 0000000000000000000000000000000000000000..e45a10220c9bd0aae30aa270c84058c42f546dc4 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/lib/scimath.pyi @@ -0,0 +1,12 @@ +from ._scimath_impl import ( + __all__ as __all__, + arccos as arccos, + arcsin as arcsin, + arctanh as arctanh, + log as log, + log2 as log2, + log10 as log10, + logn as logn, + power as power, + sqrt as sqrt, +) diff --git a/python/user_packages/Python313/site-packages/numpy/lib/stride_tricks.py b/python/user_packages/Python313/site-packages/numpy/lib/stride_tricks.py new file mode 100644 index 0000000000000000000000000000000000000000..36d7e507577860e159a27e6d1583a13a7c3f7133 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/lib/stride_tricks.py @@ -0,0 +1 @@ +from ._stride_tricks_impl import __doc__, as_strided, sliding_window_view # noqa: F401 diff --git a/python/user_packages/Python313/site-packages/numpy/lib/stride_tricks.pyi b/python/user_packages/Python313/site-packages/numpy/lib/stride_tricks.pyi new file mode 100644 index 0000000000000000000000000000000000000000..0f83c9b10d4d8c7bbfce0faae6488860921a8ded --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/lib/stride_tricks.pyi @@ -0,0 +1,4 @@ +from numpy.lib._stride_tricks_impl import ( + as_strided as as_strided, + sliding_window_view as sliding_window_view, +) diff --git a/python/user_packages/Python313/site-packages/numpy/lib/user_array.py b/python/user_packages/Python313/site-packages/numpy/lib/user_array.py new file mode 100644 index 0000000000000000000000000000000000000000..297a3b98eb65888807ba7da7a04467d0d8b060b7 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/lib/user_array.py @@ -0,0 +1 @@ +from ._user_array_impl import __doc__, container # noqa: F401 diff --git a/python/user_packages/Python313/site-packages/numpy/lib/user_array.pyi b/python/user_packages/Python313/site-packages/numpy/lib/user_array.pyi new file mode 100644 index 0000000000000000000000000000000000000000..1236b799bd411775484ca1ca308f457d0032797c --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/lib/user_array.pyi @@ -0,0 +1 @@ +from ._user_array_impl import container as container diff --git a/python/user_packages/Python313/site-packages/numpy/linalg/__init__.py b/python/user_packages/Python313/site-packages/numpy/linalg/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..922989ace5dfc60cf9c067eb381ace0b1a28c227 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/linalg/__init__.py @@ -0,0 +1,95 @@ +""" +``numpy.linalg`` +================ + +The NumPy linear algebra functions rely on BLAS and LAPACK to provide efficient +low level implementations of standard linear algebra algorithms. Those +libraries may be provided by NumPy itself using C versions of a subset of their +reference implementations but, when possible, highly optimized libraries that +take advantage of specialized processor functionality are preferred. Examples +of such libraries are OpenBLAS, MKL (TM), and ATLAS. Because those libraries +are multithreaded and processor dependent, environmental variables and external +packages such as threadpoolctl may be needed to control the number of threads +or specify the processor architecture. + +- OpenBLAS: https://www.openblas.net/ +- threadpoolctl: https://github.com/joblib/threadpoolctl + +Please note that the most-used linear algebra functions in NumPy are present in +the main ``numpy`` namespace rather than in ``numpy.linalg``. There are: +``dot``, ``vdot``, ``inner``, ``outer``, ``matmul``, ``tensordot``, ``einsum``, +``einsum_path`` and ``kron``. + +Functions present in numpy.linalg are listed below. + + +Matrix and vector products +-------------------------- + + cross + multi_dot + matrix_power + tensordot + matmul + +Decompositions +-------------- + + cholesky + outer + qr + svd + svdvals + +Matrix eigenvalues +------------------ + + eig + eigh + eigvals + eigvalsh + +Norms and other numbers +----------------------- + + norm + matrix_norm + vector_norm + cond + det + matrix_rank + slogdet + trace (Array API compatible) + +Solving equations and inverting matrices +---------------------------------------- + + solve + tensorsolve + lstsq + inv + pinv + tensorinv + +Other matrix operations +----------------------- + + diagonal (Array API compatible) + matrix_transpose (Array API compatible) + +Exceptions +---------- + + LinAlgError + +""" +# To get sub-modules +from . import _linalg +from ._linalg import * + +__all__ = _linalg.__all__.copy() # noqa: PLE0605 + +from numpy._pytesttester import PytestTester + +test = PytestTester(__name__) +del PytestTester diff --git a/python/user_packages/Python313/site-packages/numpy/linalg/__init__.pyi b/python/user_packages/Python313/site-packages/numpy/linalg/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..6e031b4232c42323eeb2620464bb8e7fade91f1d --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/linalg/__init__.pyi @@ -0,0 +1,71 @@ +from . import _linalg as _linalg, _umath_linalg as _umath_linalg +from ._linalg import ( + cholesky, + cond, + cross, + det, + diagonal, + eig, + eigh, + eigvals, + eigvalsh, + inv, + lstsq, + matmul, + matrix_norm, + matrix_power, + matrix_rank, + matrix_transpose, + multi_dot, + norm, + outer, + pinv, + qr, + slogdet, + solve, + svd, + svdvals, + tensordot, + tensorinv, + tensorsolve, + trace, + vecdot, + vector_norm, +) + +__all__ = [ + "LinAlgError", + "cholesky", + "cond", + "cross", + "det", + "diagonal", + "eig", + "eigh", + "eigvals", + "eigvalsh", + "inv", + "lstsq", + "matmul", + "matrix_norm", + "matrix_power", + "matrix_rank", + "matrix_transpose", + "multi_dot", + "norm", + "outer", + "pinv", + "qr", + "slogdet", + "solve", + "svd", + "svdvals", + "tensordot", + "tensorinv", + "tensorsolve", + "trace", + "vecdot", + "vector_norm", +] + +class LinAlgError(ValueError): ... diff --git a/python/user_packages/Python313/site-packages/numpy/linalg/_linalg.py b/python/user_packages/Python313/site-packages/numpy/linalg/_linalg.py new file mode 100644 index 0000000000000000000000000000000000000000..937473721492c6195bc222a25aa9c5adc3f77967 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/linalg/_linalg.py @@ -0,0 +1,3657 @@ +"""Lite version of scipy.linalg. + +Notes +----- +This module is a lite version of the linalg.py module in SciPy which +contains high-level Python interface to the LAPACK library. The lite +version only accesses the following LAPACK functions: dgesv, zgesv, +dgeev, zgeev, dgesdd, zgesdd, dgelsd, zgelsd, dsyevd, zheevd, dgetrf, +zgetrf, dpotrf, zpotrf, dgeqrf, zgeqrf, zungqr, dorgqr. +""" + +__all__ = ['matrix_power', 'solve', 'tensorsolve', 'tensorinv', 'inv', + 'cholesky', 'eigvals', 'eigvalsh', 'pinv', 'slogdet', 'det', + 'svd', 'svdvals', 'eig', 'eigh', 'lstsq', 'norm', 'qr', 'cond', + 'matrix_rank', 'LinAlgError', 'multi_dot', 'trace', 'diagonal', + 'cross', 'outer', 'tensordot', 'matmul', 'matrix_transpose', + 'matrix_norm', 'vector_norm', 'vecdot'] + +import functools +import operator +import warnings +from typing import Any, NamedTuple + +from numpy._core import ( + abs, + add, + all, + amax, + amin, + argsort, + array, + asanyarray, + asarray, + atleast_2d, + cdouble, + complexfloating, + count_nonzero, + cross as _core_cross, + csingle, + diagonal as _core_diagonal, + divide, + dot, + double, + empty, + empty_like, + errstate, + finfo, + inexact, + inf, + intc, + intp, + isfinite, + isnan, + matmul as _core_matmul, + matrix_transpose as _core_matrix_transpose, + moveaxis, + multiply, + newaxis, + object_, + outer as _core_outer, + overrides, + prod, + reciprocal, + sign, + single, + sort, + sqrt, + sum, + swapaxes, + tensordot as _core_tensordot, + trace as _core_trace, + transpose as _core_transpose, + vecdot as _core_vecdot, + zeros, +) +from numpy._globals import _NoValue +from numpy._typing import NDArray +from numpy._utils import set_module +from numpy.lib._twodim_base_impl import eye, triu +from numpy.lib.array_utils import normalize_axis_index, normalize_axis_tuple +from numpy.linalg import _umath_linalg + + +class EigResult(NamedTuple): + eigenvalues: NDArray[Any] + eigenvectors: NDArray[Any] + +class EighResult(NamedTuple): + eigenvalues: NDArray[Any] + eigenvectors: NDArray[Any] + +class QRResult(NamedTuple): + Q: NDArray[Any] + R: NDArray[Any] + +class SlogdetResult(NamedTuple): + sign: NDArray[Any] + logabsdet: NDArray[Any] + +class SVDResult(NamedTuple): + U: NDArray[Any] + S: NDArray[Any] + Vh: NDArray[Any] + + +array_function_dispatch = functools.partial( + overrides.array_function_dispatch, module='numpy.linalg' +) + + +fortran_int = intc + + +@set_module('numpy.linalg') +class LinAlgError(ValueError): + """ + Generic Python-exception-derived object raised by linalg functions. + + General purpose exception class, derived from Python's ValueError + class, programmatically raised in linalg functions when a Linear + Algebra-related condition would prevent further correct execution of the + function. + + Parameters + ---------- + None + + Examples + -------- + >>> from numpy import linalg as LA + >>> LA.inv(np.zeros((2,2))) + Traceback (most recent call last): + File "", line 1, in + File "...linalg.py", line 350, + in inv return wrap(solve(a, identity(a.shape[0], dtype=a.dtype))) + File "...linalg.py", line 249, + in solve + raise LinAlgError('Singular matrix') + numpy.linalg.LinAlgError: Singular matrix + + """ + + +def _raise_linalgerror_singular(err, flag): + raise LinAlgError("Singular matrix") + +def _raise_linalgerror_nonposdef(err, flag): + raise LinAlgError("Matrix is not positive definite") + +def _raise_linalgerror_eigenvalues_nonconvergence(err, flag): + raise LinAlgError("Eigenvalues did not converge") + +def _raise_linalgerror_svd_nonconvergence(err, flag): + raise LinAlgError("SVD did not converge") + +def _raise_linalgerror_lstsq(err, flag): + raise LinAlgError("SVD did not converge in Linear Least Squares") + +def _raise_linalgerror_qr(err, flag): + raise LinAlgError("Incorrect argument found while performing " + "QR factorization") + + +def _makearray(a): + new = asarray(a) + wrap = getattr(a, "__array_wrap__", new.__array_wrap__) + return new, wrap + +def isComplexType(t): + return issubclass(t, complexfloating) + + +_real_types_map = {single: single, + double: double, + csingle: single, + cdouble: double} + +_complex_types_map = {single: csingle, + double: cdouble, + csingle: csingle, + cdouble: cdouble} + +def _realType(t, default=double): + return _real_types_map.get(t, default) + +def _complexType(t, default=cdouble): + return _complex_types_map.get(t, default) + +def _commonType(*arrays): + # in lite version, use higher precision (always double or cdouble) + result_type = single + is_complex = False + for a in arrays: + type_ = a.dtype.type + if issubclass(type_, inexact): + if isComplexType(type_): + is_complex = True + rt = _realType(type_, default=None) + if rt is double: + result_type = double + elif rt is None: + # unsupported inexact scalar + raise TypeError(f"array type {a.dtype.name} is unsupported in linalg") + else: + result_type = double + if is_complex: + result_type = _complex_types_map[result_type] + return cdouble, result_type + else: + return double, result_type + + +def _to_native_byte_order(*arrays): + ret = [] + for arr in arrays: + if arr.dtype.byteorder not in ('=', '|'): + ret.append(asarray(arr, dtype=arr.dtype.newbyteorder('='))) + else: + ret.append(arr) + if len(ret) == 1: + return ret[0] + else: + return ret + + +def _assert_2d(*arrays): + for a in arrays: + if a.ndim != 2: + raise LinAlgError('%d-dimensional array given. Array must be ' + 'two-dimensional' % a.ndim) + +def _assert_stacked_2d(*arrays): + for a in arrays: + if a.ndim < 2: + raise LinAlgError('%d-dimensional array given. Array must be ' + 'at least two-dimensional' % a.ndim) + +def _assert_stacked_square(*arrays): + for a in arrays: + try: + m, n = a.shape[-2:] + except ValueError: + raise LinAlgError('%d-dimensional array given. Array must be ' + 'at least two-dimensional' % a.ndim) + if m != n: + raise LinAlgError('Last 2 dimensions of the array must be square') + +def _assert_finite(*arrays): + for a in arrays: + if not isfinite(a).all(): + raise LinAlgError("Array must not contain infs or NaNs") + +def _is_empty_2d(arr): + # check size first for efficiency + return arr.size == 0 and prod(arr.shape[-2:]) == 0 + + +def transpose(a): + """ + Transpose each matrix in a stack of matrices. + + Unlike np.transpose, this only swaps the last two axes, rather than all of + them + + Parameters + ---------- + a : (...,M,N) array_like + + Returns + ------- + aT : (...,N,M) ndarray + """ + return swapaxes(a, -1, -2) + +# Linear equations + +def _tensorsolve_dispatcher(a, b, axes=None): + return (a, b) + + +@array_function_dispatch(_tensorsolve_dispatcher) +def tensorsolve(a, b, axes=None): + """ + Solve the tensor equation ``a x = b`` for x. + + It is assumed that all indices of `x` are summed over in the product, + together with the rightmost indices of `a`, as is done in, for example, + ``tensordot(a, x, axes=x.ndim)``. + + Parameters + ---------- + a : array_like + Coefficient tensor, of shape ``b.shape + Q``. `Q`, a tuple, equals + the shape of that sub-tensor of `a` consisting of the appropriate + number of its rightmost indices, and must be such that + ``prod(Q) == prod(b.shape)`` (in which sense `a` is said to be + 'square'). + b : array_like + Right-hand tensor, which can be of any shape. + axes : tuple of ints, optional + Axes in `a` to reorder to the right, before inversion. + If None (default), no reordering is done. + + Returns + ------- + x : ndarray, shape Q + + Raises + ------ + LinAlgError + If `a` is singular or not 'square' (in the above sense). + + See Also + -------- + numpy.tensordot, tensorinv, numpy.einsum + + Examples + -------- + >>> import numpy as np + >>> a = np.eye(2*3*4).reshape((2*3, 4, 2, 3, 4)) + >>> rng = np.random.default_rng() + >>> b = rng.normal(size=(2*3, 4)) + >>> x = np.linalg.tensorsolve(a, b) + >>> x.shape + (2, 3, 4) + >>> np.allclose(np.tensordot(a, x, axes=3), b) + True + + """ + a, wrap = _makearray(a) + b = asarray(b) + an = a.ndim + + if axes is not None: + allaxes = list(range(an)) + for k in axes: + allaxes.remove(k) + allaxes.insert(an, k) + a = a.transpose(allaxes) + + oldshape = a.shape[-(an - b.ndim):] + prod = 1 + for k in oldshape: + prod *= k + + if a.size != prod ** 2: + raise LinAlgError( + "Input arrays must satisfy the requirement \ + prod(a.shape[b.ndim:]) == prod(a.shape[:b.ndim])" + ) + + a = a.reshape(prod, prod) + b = b.ravel() + res = wrap(solve(a, b)) + res.shape = oldshape + return res + + +def _solve_dispatcher(a, b): + return (a, b) + + +@array_function_dispatch(_solve_dispatcher) +def solve(a, b): + """ + Solve a linear matrix equation, or system of linear scalar equations. + + Computes the "exact" solution, `x`, of the well-determined, i.e., full + rank, linear matrix equation `ax = b`. + + Parameters + ---------- + a : (..., M, M) array_like + Coefficient matrix. + b : {(M,), (..., M, K)}, array_like + Ordinate or "dependent variable" values. + + Returns + ------- + x : {(..., M,), (..., M, K)} ndarray + Solution to the system a x = b. Returned shape is (..., M) if b is + shape (M,) and (..., M, K) if b is (..., M, K), where the "..." part is + broadcasted between a and b. + + Raises + ------ + LinAlgError + If `a` is singular or not square. + + See Also + -------- + scipy.linalg.solve : Similar function in SciPy. + + Notes + ----- + Broadcasting rules apply, see the `numpy.linalg` documentation for + details. + + The solutions are computed using LAPACK routine ``_gesv``. + + `a` must be square and of full-rank, i.e., all rows (or, equivalently, + columns) must be linearly independent; if either is not true, use + `lstsq` for the least-squares best "solution" of the + system/equation. + + .. versionchanged:: 2.0 + + The b array is only treated as a shape (M,) column vector if it is + exactly 1-dimensional. In all other instances it is treated as a stack + of (M, K) matrices. Previously b would be treated as a stack of (M,) + vectors if b.ndim was equal to a.ndim - 1. + + References + ---------- + .. [1] G. Strang, *Linear Algebra and Its Applications*, 2nd Ed., Orlando, + FL, Academic Press, Inc., 1980, pg. 22. + + Examples + -------- + Solve the system of equations: + ``x0 + 2 * x1 = 1`` and + ``3 * x0 + 5 * x1 = 2``: + + >>> import numpy as np + >>> a = np.array([[1, 2], [3, 5]]) + >>> b = np.array([1, 2]) + >>> x = np.linalg.solve(a, b) + >>> x + array([-1., 1.]) + + Check that the solution is correct: + + >>> np.allclose(np.dot(a, x), b) + True + + """ + a, _ = _makearray(a) + _assert_stacked_square(a) + b, wrap = _makearray(b) + t, result_t = _commonType(a, b) + + # We use the b = (..., M,) logic, only if the number of extra dimensions + # match exactly + if b.ndim == 1: + gufunc = _umath_linalg.solve1 + else: + gufunc = _umath_linalg.solve + + signature = 'DD->D' if isComplexType(t) else 'dd->d' + with errstate(call=_raise_linalgerror_singular, invalid='call', + over='ignore', divide='ignore', under='ignore'): + r = gufunc(a, b, signature=signature) + + return wrap(r.astype(result_t, copy=False)) + + +def _tensorinv_dispatcher(a, ind=None): + return (a,) + + +@array_function_dispatch(_tensorinv_dispatcher) +def tensorinv(a, ind=2): + """ + Compute the 'inverse' of an N-dimensional array. + + The result is an inverse for `a` relative to the tensordot operation + ``tensordot(a, b, ind)``, i. e., up to floating-point accuracy, + ``tensordot(tensorinv(a), a, ind)`` is the "identity" tensor for the + tensordot operation. + + Parameters + ---------- + a : array_like + Tensor to 'invert'. Its shape must be 'square', i. e., + ``prod(a.shape[:ind]) == prod(a.shape[ind:])``. + ind : int, optional + Number of first indices that are involved in the inverse sum. + Must be a positive integer, default is 2. + + Returns + ------- + b : ndarray + `a`'s tensordot inverse, shape ``a.shape[ind:] + a.shape[:ind]``. + + Raises + ------ + LinAlgError + If `a` is singular or not 'square' (in the above sense). + + See Also + -------- + numpy.tensordot, tensorsolve + + Examples + -------- + >>> import numpy as np + >>> a = np.eye(4*6).reshape((4, 6, 8, 3)) + >>> ainv = np.linalg.tensorinv(a, ind=2) + >>> ainv.shape + (8, 3, 4, 6) + >>> rng = np.random.default_rng() + >>> b = rng.normal(size=(4, 6)) + >>> np.allclose(np.tensordot(ainv, b), np.linalg.tensorsolve(a, b)) + True + + >>> a = np.eye(4*6).reshape((24, 8, 3)) + >>> ainv = np.linalg.tensorinv(a, ind=1) + >>> ainv.shape + (8, 3, 24) + >>> rng = np.random.default_rng() + >>> b = rng.normal(size=24) + >>> np.allclose(np.tensordot(ainv, b, 1), np.linalg.tensorsolve(a, b)) + True + + """ + a = asarray(a) + oldshape = a.shape + prod = 1 + if ind > 0: + invshape = oldshape[ind:] + oldshape[:ind] + for k in oldshape[ind:]: + prod *= k + else: + raise ValueError("Invalid ind argument.") + a = a.reshape(prod, -1) + ia = inv(a) + return ia.reshape(*invshape) + + +# Matrix inversion + +def _unary_dispatcher(a): + return (a,) + + +@array_function_dispatch(_unary_dispatcher) +def inv(a): + """ + Compute the inverse of a matrix. + + Given a square matrix `a`, return the matrix `ainv` satisfying + ``a @ ainv = ainv @ a = eye(a.shape[0])``. + + Parameters + ---------- + a : (..., M, M) array_like + Matrix to be inverted. + + Returns + ------- + ainv : (..., M, M) ndarray or matrix + Inverse of the matrix `a`. + + Raises + ------ + LinAlgError + If `a` is not square or inversion fails. + + See Also + -------- + scipy.linalg.inv : Similar function in SciPy. + numpy.linalg.cond : Compute the condition number of a matrix. + numpy.linalg.svd : Compute the singular value decomposition of a matrix. + + Notes + ----- + Broadcasting rules apply, see the `numpy.linalg` documentation for + details. + + If `a` is detected to be singular, a `LinAlgError` is raised. If `a` is + ill-conditioned, a `LinAlgError` may or may not be raised, and results may + be inaccurate due to floating-point errors. + + References + ---------- + .. [1] Wikipedia, "Condition number", + https://en.wikipedia.org/wiki/Condition_number + + Examples + -------- + >>> import numpy as np + >>> from numpy.linalg import inv + >>> a = np.array([[1., 2.], [3., 4.]]) + >>> ainv = inv(a) + >>> np.allclose(a @ ainv, np.eye(2)) + True + >>> np.allclose(ainv @ a, np.eye(2)) + True + + If a is a matrix object, then the return value is a matrix as well: + + >>> ainv = inv(np.matrix(a)) + >>> ainv + matrix([[-2. , 1. ], + [ 1.5, -0.5]]) + + Inverses of several matrices can be computed at once: + + >>> a = np.array([[[1., 2.], [3., 4.]], [[1, 3], [3, 5]]]) + >>> inv(a) + array([[[-2. , 1. ], + [ 1.5 , -0.5 ]], + [[-1.25, 0.75], + [ 0.75, -0.25]]]) + + If a matrix is close to singular, the computed inverse may not satisfy + ``a @ ainv = ainv @ a = eye(a.shape[0])`` even if a `LinAlgError` + is not raised: + + >>> a = np.array([[2,4,6],[2,0,2],[6,8,14]]) + >>> inv(a) # No errors raised + array([[-1.12589991e+15, -5.62949953e+14, 5.62949953e+14], + [-1.12589991e+15, -5.62949953e+14, 5.62949953e+14], + [ 1.12589991e+15, 5.62949953e+14, -5.62949953e+14]]) + >>> a @ inv(a) + array([[ 0. , -0.5 , 0. ], # may vary + [-0.5 , 0.625, 0.25 ], + [ 0. , 0. , 1. ]]) + + To detect ill-conditioned matrices, you can use `numpy.linalg.cond` to + compute its *condition number* [1]_. The larger the condition number, the + more ill-conditioned the matrix is. As a rule of thumb, if the condition + number ``cond(a) = 10**k``, then you may lose up to ``k`` digits of + accuracy on top of what would be lost to the numerical method due to loss + of precision from arithmetic methods. + + >>> from numpy.linalg import cond + >>> cond(a) + np.float64(8.659885634118668e+17) # may vary + + It is also possible to detect ill-conditioning by inspecting the matrix's + singular values directly. The ratio between the largest and the smallest + singular value is the condition number: + + >>> from numpy.linalg import svd + >>> sigma = svd(a, compute_uv=False) # Do not compute singular vectors + >>> sigma.max()/sigma.min() + 8.659885634118668e+17 # may vary + + """ + a, wrap = _makearray(a) + _assert_stacked_square(a) + t, result_t = _commonType(a) + + signature = 'D->D' if isComplexType(t) else 'd->d' + with errstate(call=_raise_linalgerror_singular, invalid='call', + over='ignore', divide='ignore', under='ignore'): + ainv = _umath_linalg.inv(a, signature=signature) + return wrap(ainv.astype(result_t, copy=False)) + + +def _matrix_power_dispatcher(a, n): + return (a,) + + +@array_function_dispatch(_matrix_power_dispatcher) +def matrix_power(a, n): + """ + Raise a square matrix to the (integer) power `n`. + + For positive integers `n`, the power is computed by repeated matrix + squarings and matrix multiplications. If ``n == 0``, the identity matrix + of the same shape as M is returned. If ``n < 0``, the inverse + is computed and then raised to the ``abs(n)``. + + .. note:: Stacks of object matrices are not currently supported. + + Parameters + ---------- + a : (..., M, M) array_like + Matrix to be "powered". + n : int + The exponent can be any integer or long integer, positive, + negative, or zero. + + Returns + ------- + a**n : (..., M, M) ndarray or matrix object + The return value is the same shape and type as `M`; + if the exponent is positive or zero then the type of the + elements is the same as those of `M`. If the exponent is + negative the elements are floating-point. + + Raises + ------ + LinAlgError + For matrices that are not square or that (for negative powers) cannot + be inverted numerically. + + Examples + -------- + >>> import numpy as np + >>> from numpy.linalg import matrix_power + >>> i = np.array([[0, 1], [-1, 0]]) # matrix equiv. of the imaginary unit + >>> matrix_power(i, 3) # should = -i + array([[ 0, -1], + [ 1, 0]]) + >>> matrix_power(i, 0) + array([[1, 0], + [0, 1]]) + >>> matrix_power(i, -3) # should = 1/(-i) = i, but w/ f.p. elements + array([[ 0., 1.], + [-1., 0.]]) + + Somewhat more sophisticated example + + >>> q = np.zeros((4, 4)) + >>> q[0:2, 0:2] = -i + >>> q[2:4, 2:4] = i + >>> q # one of the three quaternion units not equal to 1 + array([[ 0., -1., 0., 0.], + [ 1., 0., 0., 0.], + [ 0., 0., 0., 1.], + [ 0., 0., -1., 0.]]) + >>> matrix_power(q, 2) # = -np.eye(4) + array([[-1., 0., 0., 0.], + [ 0., -1., 0., 0.], + [ 0., 0., -1., 0.], + [ 0., 0., 0., -1.]]) + + """ + a = asanyarray(a) + _assert_stacked_square(a) + + try: + n = operator.index(n) + except TypeError as e: + raise TypeError("exponent must be an integer") from e + + # Fall back on dot for object arrays. Object arrays are not supported by + # the current implementation of matmul using einsum + if a.dtype != object: + fmatmul = matmul + elif a.ndim == 2: + fmatmul = dot + else: + raise NotImplementedError( + "matrix_power not supported for stacks of object arrays") + + if n == 0: + a = empty_like(a) + a[...] = eye(a.shape[-2], dtype=a.dtype) + return a + + elif n < 0: + a = inv(a) + n = abs(n) + + # short-cuts. + if n == 1: + return a + + elif n == 2: + return fmatmul(a, a) + + elif n == 3: + return fmatmul(fmatmul(a, a), a) + + # Use binary decomposition to reduce the number of matrix multiplications. + # Here, we iterate over the bits of n, from LSB to MSB, raise `a` to + # increasing powers of 2, and multiply into the result as needed. + z = result = None + while n > 0: + z = a if z is None else fmatmul(z, z) + n, bit = divmod(n, 2) + if bit: + result = z if result is None else fmatmul(result, z) + + return result + + +# Cholesky decomposition + +def _cholesky_dispatcher(a, /, *, upper=None): + return (a,) + + +@array_function_dispatch(_cholesky_dispatcher) +def cholesky(a, /, *, upper=False): + """ + Cholesky decomposition. + + Return the lower or upper Cholesky decomposition, ``L * L.H`` or + ``U.H * U``, of the square matrix ``a``, where ``L`` is lower-triangular, + ``U`` is upper-triangular, and ``.H`` is the conjugate transpose operator + (which is the ordinary transpose if ``a`` is real-valued). ``a`` must be + Hermitian (symmetric if real-valued) and positive-definite. No checking is + performed to verify whether ``a`` is Hermitian or not. In addition, only + the lower or upper-triangular and diagonal elements of ``a`` are used. + Only ``L`` or ``U`` is actually returned. + + Parameters + ---------- + a : (..., M, M) array_like + Hermitian (symmetric if all elements are real), positive-definite + input matrix. + upper : bool + If ``True``, the result must be the upper-triangular Cholesky factor. + If ``False``, the result must be the lower-triangular Cholesky factor. + Default: ``False``. + + Returns + ------- + L : (..., M, M) array_like + Lower or upper-triangular Cholesky factor of `a`. Returns a matrix + object if `a` is a matrix object. + + Raises + ------ + LinAlgError + If the decomposition fails, for example, if `a` is not + positive-definite. + + See Also + -------- + scipy.linalg.cholesky : Similar function in SciPy. + scipy.linalg.cholesky_banded : Cholesky decompose a banded Hermitian + positive-definite matrix. + scipy.linalg.cho_factor : Cholesky decomposition of a matrix, to use in + `scipy.linalg.cho_solve`. + + Notes + ----- + Broadcasting rules apply, see the `numpy.linalg` documentation for + details. + + The Cholesky decomposition is often used as a fast way of solving + + .. math:: A \\mathbf{x} = \\mathbf{b} + + (when `A` is both Hermitian/symmetric and positive-definite). + + First, we solve for :math:`\\mathbf{y}` in + + .. math:: L \\mathbf{y} = \\mathbf{b}, + + and then for :math:`\\mathbf{x}` in + + .. math:: L^{H} \\mathbf{x} = \\mathbf{y}. + + Examples + -------- + >>> import numpy as np + >>> A = np.array([[1,-2j],[2j,5]]) + >>> A + array([[ 1.+0.j, -0.-2.j], + [ 0.+2.j, 5.+0.j]]) + >>> L = np.linalg.cholesky(A) + >>> L + array([[1.+0.j, 0.+0.j], + [0.+2.j, 1.+0.j]]) + >>> np.dot(L, L.T.conj()) # verify that L * L.H = A + array([[1.+0.j, 0.-2.j], + [0.+2.j, 5.+0.j]]) + >>> A = [[1,-2j],[2j,5]] # what happens if A is only array_like? + >>> np.linalg.cholesky(A) # an ndarray object is returned + array([[1.+0.j, 0.+0.j], + [0.+2.j, 1.+0.j]]) + >>> # But a matrix object is returned if A is a matrix object + >>> np.linalg.cholesky(np.matrix(A)) + matrix([[ 1.+0.j, 0.+0.j], + [ 0.+2.j, 1.+0.j]]) + >>> # The upper-triangular Cholesky factor can also be obtained. + >>> np.linalg.cholesky(A, upper=True) + array([[1.-0.j, 0.-2.j], + [0.-0.j, 1.-0.j]]) + + """ + gufunc = _umath_linalg.cholesky_up if upper else _umath_linalg.cholesky_lo + a, wrap = _makearray(a) + _assert_stacked_square(a) + t, result_t = _commonType(a) + signature = 'D->D' if isComplexType(t) else 'd->d' + with errstate(call=_raise_linalgerror_nonposdef, invalid='call', + over='ignore', divide='ignore', under='ignore'): + r = gufunc(a, signature=signature) + return wrap(r.astype(result_t, copy=False)) + + +# outer product + + +def _outer_dispatcher(x1, x2): + return (x1, x2) + + +@array_function_dispatch(_outer_dispatcher) +def outer(x1, x2, /): + """ + Compute the outer product of two vectors. + + This function is Array API compatible. Compared to ``np.outer`` + it accepts 1-dimensional inputs only. + + Parameters + ---------- + x1 : (M,) array_like + One-dimensional input array of size ``N``. + Must have a numeric data type. + x2 : (N,) array_like + One-dimensional input array of size ``M``. + Must have a numeric data type. + + Returns + ------- + out : (M, N) ndarray + ``out[i, j] = a[i] * b[j]`` + + See also + -------- + outer + + Examples + -------- + Make a (*very* coarse) grid for computing a Mandelbrot set: + + >>> rl = np.linalg.outer(np.ones((5,)), np.linspace(-2, 2, 5)) + >>> rl + array([[-2., -1., 0., 1., 2.], + [-2., -1., 0., 1., 2.], + [-2., -1., 0., 1., 2.], + [-2., -1., 0., 1., 2.], + [-2., -1., 0., 1., 2.]]) + >>> im = np.linalg.outer(1j*np.linspace(2, -2, 5), np.ones((5,))) + >>> im + array([[0.+2.j, 0.+2.j, 0.+2.j, 0.+2.j, 0.+2.j], + [0.+1.j, 0.+1.j, 0.+1.j, 0.+1.j, 0.+1.j], + [0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j], + [0.-1.j, 0.-1.j, 0.-1.j, 0.-1.j, 0.-1.j], + [0.-2.j, 0.-2.j, 0.-2.j, 0.-2.j, 0.-2.j]]) + >>> grid = rl + im + >>> grid + array([[-2.+2.j, -1.+2.j, 0.+2.j, 1.+2.j, 2.+2.j], + [-2.+1.j, -1.+1.j, 0.+1.j, 1.+1.j, 2.+1.j], + [-2.+0.j, -1.+0.j, 0.+0.j, 1.+0.j, 2.+0.j], + [-2.-1.j, -1.-1.j, 0.-1.j, 1.-1.j, 2.-1.j], + [-2.-2.j, -1.-2.j, 0.-2.j, 1.-2.j, 2.-2.j]]) + + An example using a "vector" of letters: + + >>> x = np.array(['a', 'b', 'c'], dtype=object) + >>> np.linalg.outer(x, [1, 2, 3]) + array([['a', 'aa', 'aaa'], + ['b', 'bb', 'bbb'], + ['c', 'cc', 'ccc']], dtype=object) + + """ + x1 = asanyarray(x1) + x2 = asanyarray(x2) + if x1.ndim != 1 or x2.ndim != 1: + raise ValueError( + "Input arrays must be one-dimensional, but they are " + f"{x1.ndim=} and {x2.ndim=}." + ) + return _core_outer(x1, x2, out=None) + + +# QR decomposition + + +def _qr_dispatcher(a, mode=None): + return (a,) + + +@array_function_dispatch(_qr_dispatcher) +def qr(a, mode='reduced'): + """ + Compute the qr factorization of a matrix. + + Factor the matrix `a` as *qr*, where `q` is orthonormal and `r` is + upper-triangular. + + Parameters + ---------- + a : array_like, shape (..., M, N) + An array-like object with the dimensionality of at least 2. + mode : {'reduced', 'complete', 'r', 'raw'}, optional, default: 'reduced' + If K = min(M, N), then + + * 'reduced' : returns Q, R with dimensions (..., M, K), (..., K, N) + * 'complete' : returns Q, R with dimensions (..., M, M), (..., M, N) + * 'r' : returns R only with dimensions (..., K, N) + * 'raw' : returns h, tau with dimensions (..., N, M), (..., K,) + + The options 'reduced', 'complete, and 'raw' are new in numpy 1.8, + see the notes for more information. The default is 'reduced', and to + maintain backward compatibility with earlier versions of numpy both + it and the old default 'full' can be omitted. Note that array h + returned in 'raw' mode is transposed for calling Fortran. The + 'economic' mode is deprecated. The modes 'full' and 'economic' may + be passed using only the first letter for backwards compatibility, + but all others must be spelled out. See the Notes for more + explanation. + + + Returns + ------- + Q : ndarray of float or complex, optional + A matrix with orthonormal columns. When mode = 'complete' the + result is an orthogonal/unitary matrix depending on whether or not + a is real/complex. The determinant may be either +/- 1 in that + case. In case the number of dimensions in the input array is + greater than 2 then a stack of the matrices with above properties + is returned. + R : ndarray of float or complex, optional + The upper-triangular matrix or a stack of upper-triangular + matrices if the number of dimensions in the input array is greater + than 2. + (h, tau) : ndarrays of np.double or np.cdouble, optional + The array h contains the Householder reflectors that generate q + along with r. The tau array contains scaling factors for the + reflectors. In the deprecated 'economic' mode only h is returned. + + Raises + ------ + LinAlgError + If factoring fails. + + See Also + -------- + scipy.linalg.qr : Similar function in SciPy. + scipy.linalg.rq : Compute RQ decomposition of a matrix. + + Notes + ----- + When mode is 'reduced' or 'complete', the result will be a namedtuple with + the attributes ``Q`` and ``R``. + + This is an interface to the LAPACK routines ``dgeqrf``, ``zgeqrf``, + ``dorgqr``, and ``zungqr``. + + For more information on the qr factorization, see for example: + https://en.wikipedia.org/wiki/QR_factorization + + Subclasses of `ndarray` are preserved except for the 'raw' mode. So if + `a` is of type `matrix`, all the return values will be matrices too. + + New 'reduced', 'complete', and 'raw' options for mode were added in + NumPy 1.8.0 and the old option 'full' was made an alias of 'reduced'. In + addition the options 'full' and 'economic' were deprecated. Because + 'full' was the previous default and 'reduced' is the new default, + backward compatibility can be maintained by letting `mode` default. + The 'raw' option was added so that LAPACK routines that can multiply + arrays by q using the Householder reflectors can be used. Note that in + this case the returned arrays are of type np.double or np.cdouble and + the h array is transposed to be FORTRAN compatible. No routines using + the 'raw' return are currently exposed by numpy, but some are available + in lapack_lite and just await the necessary work. + + Examples + -------- + >>> import numpy as np + >>> rng = np.random.default_rng() + >>> a = rng.normal(size=(9, 6)) + >>> Q, R = np.linalg.qr(a) + >>> np.allclose(a, np.dot(Q, R)) # a does equal QR + True + >>> R2 = np.linalg.qr(a, mode='r') + >>> np.allclose(R, R2) # mode='r' returns the same R as mode='full' + True + >>> a = np.random.normal(size=(3, 2, 2)) # Stack of 2 x 2 matrices as input + >>> Q, R = np.linalg.qr(a) + >>> Q.shape + (3, 2, 2) + >>> R.shape + (3, 2, 2) + >>> np.allclose(a, np.matmul(Q, R)) + True + + Example illustrating a common use of `qr`: solving of least squares + problems + + What are the least-squares-best `m` and `y0` in ``y = y0 + mx`` for + the following data: {(0,1), (1,0), (1,2), (2,1)}. (Graph the points + and you'll see that it should be y0 = 0, m = 1.) The answer is provided + by solving the over-determined matrix equation ``Ax = b``, where:: + + A = array([[0, 1], [1, 1], [1, 1], [2, 1]]) + x = array([[y0], [m]]) + b = array([[1], [0], [2], [1]]) + + If A = QR such that Q is orthonormal (which is always possible via + Gram-Schmidt), then ``x = inv(R) * (Q.T) * b``. (In numpy practice, + however, we simply use `lstsq`.) + + >>> A = np.array([[0, 1], [1, 1], [1, 1], [2, 1]]) + >>> A + array([[0, 1], + [1, 1], + [1, 1], + [2, 1]]) + >>> b = np.array([1, 2, 2, 3]) + >>> Q, R = np.linalg.qr(A) + >>> p = np.dot(Q.T, b) + >>> np.dot(np.linalg.inv(R), p) + array([ 1., 1.]) + + """ + if mode not in ('reduced', 'complete', 'r', 'raw'): + if mode in ('f', 'full'): + # 2013-04-01, 1.8 + msg = ( + "The 'full' option is deprecated in favor of 'reduced'.\n" + "For backward compatibility let mode default." + ) + warnings.warn(msg, DeprecationWarning, stacklevel=2) + mode = 'reduced' + elif mode in ('e', 'economic'): + # 2013-04-01, 1.8 + msg = "The 'economic' option is deprecated." + warnings.warn(msg, DeprecationWarning, stacklevel=2) + mode = 'economic' + else: + raise ValueError(f"Unrecognized mode '{mode}'") + + a, wrap = _makearray(a) + _assert_stacked_2d(a) + m, n = a.shape[-2:] + t, result_t = _commonType(a) + a = a.astype(t, copy=True) + a = _to_native_byte_order(a) + mn = min(m, n) + + signature = 'D->D' if isComplexType(t) else 'd->d' + with errstate(call=_raise_linalgerror_qr, invalid='call', + over='ignore', divide='ignore', under='ignore'): + tau = _umath_linalg.qr_r_raw(a, signature=signature) + + # handle modes that don't return q + if mode == 'r': + r = triu(a[..., :mn, :]) + r = r.astype(result_t, copy=False) + return wrap(r) + + if mode == 'raw': + q = transpose(a) + q = q.astype(result_t, copy=False) + tau = tau.astype(result_t, copy=False) + return wrap(q), tau + + if mode == 'economic': + a = a.astype(result_t, copy=False) + return wrap(a) + + # mc is the number of columns in the resulting q + # matrix. If the mode is complete then it is + # same as number of rows, and if the mode is reduced, + # then it is the minimum of number of rows and columns. + if mode == 'complete' and m > n: + mc = m + gufunc = _umath_linalg.qr_complete + else: + mc = mn + gufunc = _umath_linalg.qr_reduced + + signature = 'DD->D' if isComplexType(t) else 'dd->d' + with errstate(call=_raise_linalgerror_qr, invalid='call', + over='ignore', divide='ignore', under='ignore'): + q = gufunc(a, tau, signature=signature) + r = triu(a[..., :mc, :]) + + q = q.astype(result_t, copy=False) + r = r.astype(result_t, copy=False) + + return QRResult(wrap(q), wrap(r)) + +# Eigenvalues + + +@array_function_dispatch(_unary_dispatcher) +def eigvals(a): + """ + Compute the eigenvalues of a general matrix. + + Main difference between `eigvals` and `eig`: the eigenvectors aren't + returned. + + Parameters + ---------- + a : (..., M, M) array_like + A complex- or real-valued matrix whose eigenvalues will be computed. + + Returns + ------- + w : (..., M,) ndarray + The eigenvalues, each repeated according to its multiplicity. + They are not necessarily ordered, nor are they necessarily + real for real matrices. + + Raises + ------ + LinAlgError + If the eigenvalue computation does not converge. + + See Also + -------- + eig : eigenvalues and right eigenvectors of general arrays + eigvalsh : eigenvalues of real symmetric or complex Hermitian + (conjugate symmetric) arrays. + eigh : eigenvalues and eigenvectors of real symmetric or complex + Hermitian (conjugate symmetric) arrays. + scipy.linalg.eigvals : Similar function in SciPy. + + Notes + ----- + Broadcasting rules apply, see the `numpy.linalg` documentation for + details. + + This is implemented using the ``_geev`` LAPACK routines which compute + the eigenvalues and eigenvectors of general square arrays. + + Examples + -------- + Illustration, using the fact that the eigenvalues of a diagonal matrix + are its diagonal elements, that multiplying a matrix on the left + by an orthogonal matrix, `Q`, and on the right by `Q.T` (the transpose + of `Q`), preserves the eigenvalues of the "middle" matrix. In other words, + if `Q` is orthogonal, then ``Q * A * Q.T`` has the same eigenvalues as + ``A``: + + >>> import numpy as np + >>> from numpy import linalg as LA + >>> x = np.random.random() + >>> Q = np.array([[np.cos(x), -np.sin(x)], [np.sin(x), np.cos(x)]]) + >>> LA.norm(Q[0, :]), LA.norm(Q[1, :]), np.dot(Q[0, :],Q[1, :]) + (1.0, 1.0, 0.0) + + Now multiply a diagonal matrix by ``Q`` on one side and + by ``Q.T`` on the other: + + >>> D = np.diag((-1,1)) + >>> LA.eigvals(D) + array([-1., 1.]) + >>> A = np.dot(Q, D) + >>> A = np.dot(A, Q.T) + >>> LA.eigvals(A) + array([ 1., -1.]) # random + + """ + a, wrap = _makearray(a) + _assert_stacked_square(a) + _assert_finite(a) + t, result_t = _commonType(a) + + signature = 'D->D' if isComplexType(t) else 'd->D' + with errstate(call=_raise_linalgerror_eigenvalues_nonconvergence, + invalid='call', over='ignore', divide='ignore', + under='ignore'): + w = _umath_linalg.eigvals(a, signature=signature) + + if not isComplexType(t): + if all(w.imag == 0): + w = w.real + result_t = _realType(result_t) + else: + result_t = _complexType(result_t) + + return w.astype(result_t, copy=False) + + +def _eigvalsh_dispatcher(a, UPLO=None): + return (a,) + + +@array_function_dispatch(_eigvalsh_dispatcher) +def eigvalsh(a, UPLO='L'): + """ + Compute the eigenvalues of a complex Hermitian or real symmetric matrix. + + Main difference from eigh: the eigenvectors are not computed. + + Parameters + ---------- + a : (..., M, M) array_like + A complex- or real-valued matrix whose eigenvalues are to be + computed. + UPLO : {'L', 'U'}, optional + Specifies whether the calculation is done with the lower triangular + part of `a` ('L', default) or the upper triangular part ('U'). + Irrespective of this value only the real parts of the diagonal will + be considered in the computation to preserve the notion of a Hermitian + matrix. It therefore follows that the imaginary part of the diagonal + will always be treated as zero. + + Returns + ------- + w : (..., M,) ndarray + The eigenvalues in ascending order, each repeated according to + its multiplicity. + + Raises + ------ + LinAlgError + If the eigenvalue computation does not converge. + + See Also + -------- + eigh : eigenvalues and eigenvectors of real symmetric or complex Hermitian + (conjugate symmetric) arrays. + eigvals : eigenvalues of general real or complex arrays. + eig : eigenvalues and right eigenvectors of general real or complex + arrays. + scipy.linalg.eigvalsh : Similar function in SciPy. + + Notes + ----- + Broadcasting rules apply, see the `numpy.linalg` documentation for + details. + + The eigenvalues are computed using LAPACK routines ``_syevd``, ``_heevd``. + + Examples + -------- + >>> import numpy as np + >>> from numpy import linalg as LA + >>> a = np.array([[1, -2j], [2j, 5]]) + >>> LA.eigvalsh(a) + array([ 0.17157288, 5.82842712]) # may vary + + >>> # demonstrate the treatment of the imaginary part of the diagonal + >>> a = np.array([[5+2j, 9-2j], [0+2j, 2-1j]]) + >>> a + array([[5.+2.j, 9.-2.j], + [0.+2.j, 2.-1.j]]) + >>> # with UPLO='L' this is numerically equivalent to using LA.eigvals() + >>> # with: + >>> b = np.array([[5.+0.j, 0.-2.j], [0.+2.j, 2.-0.j]]) + >>> b + array([[5.+0.j, 0.-2.j], + [0.+2.j, 2.+0.j]]) + >>> wa = LA.eigvalsh(a) + >>> wb = LA.eigvals(b) + >>> wa + array([1., 6.]) + >>> wb + array([6.+0.j, 1.+0.j]) + + """ + UPLO = UPLO.upper() + if UPLO not in ('L', 'U'): + raise ValueError("UPLO argument must be 'L' or 'U'") + + if UPLO == 'L': + gufunc = _umath_linalg.eigvalsh_lo + else: + gufunc = _umath_linalg.eigvalsh_up + + a, wrap = _makearray(a) + _assert_stacked_square(a) + t, result_t = _commonType(a) + signature = 'D->d' if isComplexType(t) else 'd->d' + with errstate(call=_raise_linalgerror_eigenvalues_nonconvergence, + invalid='call', over='ignore', divide='ignore', + under='ignore'): + w = gufunc(a, signature=signature) + return w.astype(_realType(result_t), copy=False) + + +# Eigenvectors + + +@array_function_dispatch(_unary_dispatcher) +def eig(a): + """ + Compute the eigenvalues and right eigenvectors of a square array. + + Parameters + ---------- + a : (..., M, M) array + Matrices for which the eigenvalues and right eigenvectors will + be computed + + Returns + ------- + A namedtuple with the following attributes: + + eigenvalues : (..., M) array + The eigenvalues, each repeated according to its multiplicity. + The eigenvalues are not necessarily ordered. The resulting + array will be of complex type, unless the imaginary part is + zero in which case it will be cast to a real type. When `a` + is real the resulting eigenvalues will be real (0 imaginary + part) or occur in conjugate pairs + + eigenvectors : (..., M, M) array + The normalized (unit "length") eigenvectors, such that the + column ``eigenvectors[:,i]`` is the eigenvector corresponding to the + eigenvalue ``eigenvalues[i]``. + + Raises + ------ + LinAlgError + If the eigenvalue computation does not converge. + + See Also + -------- + eigvals : eigenvalues of a non-symmetric array. + eigh : eigenvalues and eigenvectors of a real symmetric or complex + Hermitian (conjugate symmetric) array. + eigvalsh : eigenvalues of a real symmetric or complex Hermitian + (conjugate symmetric) array. + scipy.linalg.eig : Similar function in SciPy that also solves the + generalized eigenvalue problem. + scipy.linalg.schur : Best choice for unitary and other non-Hermitian + normal matrices. + + Notes + ----- + Broadcasting rules apply, see the `numpy.linalg` documentation for + details. + + This is implemented using the ``_geev`` LAPACK routines which compute + the eigenvalues and eigenvectors of general square arrays. + + The number `w` is an eigenvalue of `a` if there exists a vector `v` such + that ``a @ v = w * v``. Thus, the arrays `a`, `eigenvalues`, and + `eigenvectors` satisfy the equations ``a @ eigenvectors[:,i] = + eigenvalues[i] * eigenvectors[:,i]`` for :math:`i \\in \\{0,...,M-1\\}`. + + The array `eigenvectors` may not be of maximum rank, that is, some of the + columns may be linearly dependent, although round-off error may obscure + that fact. If the eigenvalues are all different, then theoretically the + eigenvectors are linearly independent and `a` can be diagonalized by a + similarity transformation using `eigenvectors`, i.e, ``inv(eigenvectors) @ + a @ eigenvectors`` is diagonal. + + For non-Hermitian normal matrices the SciPy function `scipy.linalg.schur` + is preferred because the matrix `eigenvectors` is guaranteed to be + unitary, which is not the case when using `eig`. The Schur factorization + produces an upper triangular matrix rather than a diagonal matrix, but for + normal matrices only the diagonal of the upper triangular matrix is + needed, the rest is roundoff error. + + Finally, it is emphasized that `eigenvectors` consists of the *right* (as + in right-hand side) eigenvectors of `a`. A vector `y` satisfying ``y.T @ a + = z * y.T`` for some number `z` is called a *left* eigenvector of `a`, + and, in general, the left and right eigenvectors of a matrix are not + necessarily the (perhaps conjugate) transposes of each other. + + References + ---------- + G. Strang, *Linear Algebra and Its Applications*, 2nd Ed., Orlando, FL, + Academic Press, Inc., 1980, Various pp. + + Examples + -------- + >>> import numpy as np + >>> from numpy import linalg as LA + + (Almost) trivial example with real eigenvalues and eigenvectors. + + >>> eigenvalues, eigenvectors = LA.eig(np.diag((1, 2, 3))) + >>> eigenvalues + array([1., 2., 3.]) + >>> eigenvectors + array([[1., 0., 0.], + [0., 1., 0.], + [0., 0., 1.]]) + + Real matrix possessing complex eigenvalues and eigenvectors; + note that the eigenvalues are complex conjugates of each other. + + >>> eigenvalues, eigenvectors = LA.eig(np.array([[1, -1], [1, 1]])) + >>> eigenvalues + array([1.+1.j, 1.-1.j]) + >>> eigenvectors + array([[0.70710678+0.j , 0.70710678-0.j ], + [0. -0.70710678j, 0. +0.70710678j]]) + + Complex-valued matrix with real eigenvalues (but complex-valued + eigenvectors); note that ``a.conj().T == a``, i.e., `a` is Hermitian. + + >>> a = np.array([[1, 1j], [-1j, 1]]) + >>> eigenvalues, eigenvectors = LA.eig(a) + >>> eigenvalues + array([2.+0.j, 0.+0.j]) + >>> eigenvectors + array([[ 0. +0.70710678j, 0.70710678+0.j ], # may vary + [ 0.70710678+0.j , -0. +0.70710678j]]) + + Be careful about round-off error! + + >>> a = np.array([[1 + 1e-9, 0], [0, 1 - 1e-9]]) + >>> # Theor. eigenvalues are 1 +/- 1e-9 + >>> eigenvalues, eigenvectors = LA.eig(a) + >>> eigenvalues + array([1., 1.]) + >>> eigenvectors + array([[1., 0.], + [0., 1.]]) + + """ + a, wrap = _makearray(a) + _assert_stacked_square(a) + _assert_finite(a) + t, result_t = _commonType(a) + + signature = 'D->DD' if isComplexType(t) else 'd->DD' + with errstate(call=_raise_linalgerror_eigenvalues_nonconvergence, + invalid='call', over='ignore', divide='ignore', + under='ignore'): + w, vt = _umath_linalg.eig(a, signature=signature) + + if not isComplexType(t) and all(w.imag == 0.0): + w = w.real + vt = vt.real + result_t = _realType(result_t) + else: + result_t = _complexType(result_t) + + vt = vt.astype(result_t, copy=False) + return EigResult(w.astype(result_t, copy=False), wrap(vt)) + + +@array_function_dispatch(_eigvalsh_dispatcher) +def eigh(a, UPLO='L'): + """ + Return the eigenvalues and eigenvectors of a complex Hermitian + (conjugate symmetric) or a real symmetric matrix. + + Returns two objects, a 1-D array containing the eigenvalues of `a`, and + a 2-D square array or matrix (depending on the input type) of the + corresponding eigenvectors (in columns). + + Parameters + ---------- + a : (..., M, M) array + Hermitian or real symmetric matrices whose eigenvalues and + eigenvectors are to be computed. + UPLO : {'L', 'U'}, optional + Specifies whether the calculation is done with the lower triangular + part of `a` ('L', default) or the upper triangular part ('U'). + Irrespective of this value only the real parts of the diagonal will + be considered in the computation to preserve the notion of a Hermitian + matrix. It therefore follows that the imaginary part of the diagonal + will always be treated as zero. + + Returns + ------- + A namedtuple with the following attributes: + + eigenvalues : (..., M) ndarray + The eigenvalues in ascending order, each repeated according to + its multiplicity. + eigenvectors : {(..., M, M) ndarray, (..., M, M) matrix} + The column ``eigenvectors[:, i]`` is the normalized eigenvector + corresponding to the eigenvalue ``eigenvalues[i]``. Will return a + matrix object if `a` is a matrix object. + + Raises + ------ + LinAlgError + If the eigenvalue computation does not converge. + + See Also + -------- + eigvalsh : eigenvalues of real symmetric or complex Hermitian + (conjugate symmetric) arrays. + eig : eigenvalues and right eigenvectors for non-symmetric arrays. + eigvals : eigenvalues of non-symmetric arrays. + scipy.linalg.eigh : Similar function in SciPy (but also solves the + generalized eigenvalue problem). + + Notes + ----- + Broadcasting rules apply, see the `numpy.linalg` documentation for + details. + + The eigenvalues/eigenvectors are computed using LAPACK routines ``_syevd``, + ``_heevd``. + + The eigenvalues of real symmetric or complex Hermitian matrices are always + real. [1]_ The array `eigenvalues` of (column) eigenvectors is unitary and + `a`, `eigenvalues`, and `eigenvectors` satisfy the equations ``dot(a, + eigenvectors[:, i]) = eigenvalues[i] * eigenvectors[:, i]``. + + References + ---------- + .. [1] G. Strang, *Linear Algebra and Its Applications*, 2nd Ed., Orlando, + FL, Academic Press, Inc., 1980, pg. 222. + + Examples + -------- + >>> import numpy as np + >>> from numpy import linalg as LA + >>> a = np.array([[1, -2j], [2j, 5]]) + >>> a + array([[ 1.+0.j, -0.-2.j], + [ 0.+2.j, 5.+0.j]]) + >>> eigenvalues, eigenvectors = LA.eigh(a) + >>> eigenvalues + array([0.17157288, 5.82842712]) + >>> eigenvectors + array([[-0.92387953+0.j , -0.38268343+0.j ], # may vary + [ 0. +0.38268343j, 0. -0.92387953j]]) + + >>> (np.dot(a, eigenvectors[:, 0]) - + ... eigenvalues[0] * eigenvectors[:, 0]) # verify 1st eigenval/vec pair + array([5.55111512e-17+0.0000000e+00j, 0.00000000e+00+1.2490009e-16j]) + >>> (np.dot(a, eigenvectors[:, 1]) - + ... eigenvalues[1] * eigenvectors[:, 1]) # verify 2nd eigenval/vec pair + array([0.+0.j, 0.+0.j]) + + >>> A = np.matrix(a) # what happens if input is a matrix object + >>> A + matrix([[ 1.+0.j, -0.-2.j], + [ 0.+2.j, 5.+0.j]]) + >>> eigenvalues, eigenvectors = LA.eigh(A) + >>> eigenvalues + array([0.17157288, 5.82842712]) + >>> eigenvectors + matrix([[-0.92387953+0.j , -0.38268343+0.j ], # may vary + [ 0. +0.38268343j, 0. -0.92387953j]]) + + >>> # demonstrate the treatment of the imaginary part of the diagonal + >>> a = np.array([[5+2j, 9-2j], [0+2j, 2-1j]]) + >>> a + array([[5.+2.j, 9.-2.j], + [0.+2.j, 2.-1.j]]) + >>> # with UPLO='L' this is numerically equivalent to using LA.eig() with: + >>> b = np.array([[5.+0.j, 0.-2.j], [0.+2.j, 2.-0.j]]) + >>> b + array([[5.+0.j, 0.-2.j], + [0.+2.j, 2.+0.j]]) + >>> wa, va = LA.eigh(a) + >>> wb, vb = LA.eig(b) + >>> wa + array([1., 6.]) + >>> wb + array([6.+0.j, 1.+0.j]) + >>> va + array([[-0.4472136 +0.j , -0.89442719+0.j ], # may vary + [ 0. +0.89442719j, 0. -0.4472136j ]]) + >>> vb + array([[ 0.89442719+0.j , -0. +0.4472136j], + [-0. +0.4472136j, 0.89442719+0.j ]]) + + """ + UPLO = UPLO.upper() + if UPLO not in ('L', 'U'): + raise ValueError("UPLO argument must be 'L' or 'U'") + + a, wrap = _makearray(a) + _assert_stacked_square(a) + t, result_t = _commonType(a) + + if UPLO == 'L': + gufunc = _umath_linalg.eigh_lo + else: + gufunc = _umath_linalg.eigh_up + + signature = 'D->dD' if isComplexType(t) else 'd->dd' + with errstate(call=_raise_linalgerror_eigenvalues_nonconvergence, + invalid='call', over='ignore', divide='ignore', + under='ignore'): + w, vt = gufunc(a, signature=signature) + w = w.astype(_realType(result_t), copy=False) + vt = vt.astype(result_t, copy=False) + return EighResult(w, wrap(vt)) + + +# Singular value decomposition + +def _svd_dispatcher(a, full_matrices=None, compute_uv=None, hermitian=None): + return (a,) + + +@array_function_dispatch(_svd_dispatcher) +def svd(a, full_matrices=True, compute_uv=True, hermitian=False): + """ + Singular Value Decomposition. + + When `a` is a 2D array, and ``full_matrices=False``, then it is + factorized as ``u @ np.diag(s) @ vh = (u * s) @ vh``, where + `u` and the Hermitian transpose of `vh` are 2D arrays with + orthonormal columns and `s` is a 1D array of `a`'s singular + values. When `a` is higher-dimensional, SVD is applied in + stacked mode as explained below. + + Parameters + ---------- + a : (..., M, N) array_like + A real or complex array with ``a.ndim >= 2``. + full_matrices : bool, optional + If True (default), `u` and `vh` have the shapes ``(..., M, M)`` and + ``(..., N, N)``, respectively. Otherwise, the shapes are + ``(..., M, K)`` and ``(..., K, N)``, respectively, where + ``K = min(M, N)``. + compute_uv : bool, optional + Whether or not to compute `u` and `vh` in addition to `s`. True + by default. + hermitian : bool, optional + If True, `a` is assumed to be Hermitian (symmetric if real-valued), + enabling a more efficient method for finding singular values. + Defaults to False. + + Returns + ------- + U : { (..., M, M), (..., M, K) } array + Unitary array(s). The first ``a.ndim - 2`` dimensions have the same + size as those of the input `a`. The size of the last two dimensions + depends on the value of `full_matrices`. Only returned when + `compute_uv` is True. + S : (..., K) array + Vector(s) with the singular values, within each vector sorted in + descending order. The first ``a.ndim - 2`` dimensions have the same + size as those of the input `a`. + Vh : { (..., N, N), (..., K, N) } array + Unitary array(s). The first ``a.ndim - 2`` dimensions have the same + size as those of the input `a`. The size of the last two dimensions + depends on the value of `full_matrices`. Only returned when + `compute_uv` is True. + + Raises + ------ + LinAlgError + If SVD computation does not converge. + + See Also + -------- + scipy.linalg.svd : Similar function in SciPy. + scipy.linalg.svdvals : Compute singular values of a matrix. + + Notes + ----- + When `compute_uv` is True, the result is a namedtuple with the following + attribute names: `U`, `S`, and `Vh`. + + The decomposition is performed using LAPACK routine ``_gesdd``. + + SVD is usually described for the factorization of a 2D matrix :math:`A`. + The higher-dimensional case will be discussed below. In the 2D case, SVD is + written as :math:`A = U S V^H`, where :math:`A = a`, :math:`U= u`, + :math:`S= \\mathtt{np.diag}(s)` and :math:`V^H = vh`. The 1D array `s` + contains the singular values of `a` and `u` and `vh` are unitary. The rows + of `vh` are the eigenvectors of :math:`A^H A` and the columns of `u` are + the eigenvectors of :math:`A A^H`. In both cases the corresponding + (possibly non-zero) eigenvalues are given by ``s**2``. + + If `a` has more than two dimensions, then broadcasting rules apply, as + explained in :ref:`routines.linalg-broadcasting`. This means that SVD is + working in "stacked" mode: it iterates over all indices of the first + ``a.ndim - 2`` dimensions and for each combination SVD is applied to the + last two indices. The matrix `a` can be reconstructed from the + decomposition with either ``(u * s[..., None, :]) @ vh`` or + ``u @ (s[..., None] * vh)``. (The ``@`` operator can be replaced by the + function ``np.matmul`` for python versions below 3.5.) + + If `a` is a ``matrix`` object (as opposed to an ``ndarray``), then so are + all the return values. + + Examples + -------- + >>> import numpy as np + >>> rng = np.random.default_rng() + >>> a = rng.normal(size=(9, 6)) + 1j*rng.normal(size=(9, 6)) + >>> b = rng.normal(size=(2, 7, 8, 3)) + 1j*rng.normal(size=(2, 7, 8, 3)) + + + Reconstruction based on full SVD, 2D case: + + >>> U, S, Vh = np.linalg.svd(a, full_matrices=True) + >>> U.shape, S.shape, Vh.shape + ((9, 9), (6,), (6, 6)) + >>> np.allclose(a, np.dot(U[:, :6] * S, Vh)) + True + >>> smat = np.zeros((9, 6), dtype=complex) + >>> smat[:6, :6] = np.diag(S) + >>> np.allclose(a, np.dot(U, np.dot(smat, Vh))) + True + + Reconstruction based on reduced SVD, 2D case: + + >>> U, S, Vh = np.linalg.svd(a, full_matrices=False) + >>> U.shape, S.shape, Vh.shape + ((9, 6), (6,), (6, 6)) + >>> np.allclose(a, np.dot(U * S, Vh)) + True + >>> smat = np.diag(S) + >>> np.allclose(a, np.dot(U, np.dot(smat, Vh))) + True + + Reconstruction based on full SVD, 4D case: + + >>> U, S, Vh = np.linalg.svd(b, full_matrices=True) + >>> U.shape, S.shape, Vh.shape + ((2, 7, 8, 8), (2, 7, 3), (2, 7, 3, 3)) + >>> np.allclose(b, np.matmul(U[..., :3] * S[..., None, :], Vh)) + True + >>> np.allclose(b, np.matmul(U[..., :3], S[..., None] * Vh)) + True + + Reconstruction based on reduced SVD, 4D case: + + >>> U, S, Vh = np.linalg.svd(b, full_matrices=False) + >>> U.shape, S.shape, Vh.shape + ((2, 7, 8, 3), (2, 7, 3), (2, 7, 3, 3)) + >>> np.allclose(b, np.matmul(U * S[..., None, :], Vh)) + True + >>> np.allclose(b, np.matmul(U, S[..., None] * Vh)) + True + + """ + import numpy as np + a, wrap = _makearray(a) + + if hermitian: + # note: lapack svd returns eigenvalues with s ** 2 sorted descending, + # but eig returns s sorted ascending, so we re-order the eigenvalues + # and related arrays to have the correct order + if compute_uv: + s, u = eigh(a) + sgn = sign(s) + s = abs(s) + sidx = argsort(s)[..., ::-1] + sgn = np.take_along_axis(sgn, sidx, axis=-1) + s = np.take_along_axis(s, sidx, axis=-1) + u = np.take_along_axis(u, sidx[..., None, :], axis=-1) + # singular values are unsigned, move the sign into v + vt = transpose(u * sgn[..., None, :]).conjugate() + return SVDResult(wrap(u), s, wrap(vt)) + else: + s = eigvalsh(a) + s = abs(s) + return sort(s)[..., ::-1] + + _assert_stacked_2d(a) + t, result_t = _commonType(a) + + m, n = a.shape[-2:] + if compute_uv: + if full_matrices: + gufunc = _umath_linalg.svd_f + else: + gufunc = _umath_linalg.svd_s + + signature = 'D->DdD' if isComplexType(t) else 'd->ddd' + with errstate(call=_raise_linalgerror_svd_nonconvergence, + invalid='call', over='ignore', divide='ignore', + under='ignore'): + u, s, vh = gufunc(a, signature=signature) + u = u.astype(result_t, copy=False) + s = s.astype(_realType(result_t), copy=False) + vh = vh.astype(result_t, copy=False) + return SVDResult(wrap(u), s, wrap(vh)) + else: + signature = 'D->d' if isComplexType(t) else 'd->d' + with errstate(call=_raise_linalgerror_svd_nonconvergence, + invalid='call', over='ignore', divide='ignore', + under='ignore'): + s = _umath_linalg.svd(a, signature=signature) + s = s.astype(_realType(result_t), copy=False) + return s + + +def _svdvals_dispatcher(x): + return (x,) + + +@array_function_dispatch(_svdvals_dispatcher) +def svdvals(x, /): + """ + Returns the singular values of a matrix (or a stack of matrices) ``x``. + When x is a stack of matrices, the function will compute the singular + values for each matrix in the stack. + + This function is Array API compatible. + + Calling ``np.svdvals(x)`` to get singular values is the same as + ``np.svd(x, compute_uv=False, hermitian=False)``. + + Parameters + ---------- + x : (..., M, N) array_like + Input array having shape (..., M, N) and whose last two + dimensions form matrices on which to perform singular value + decomposition. Should have a floating-point data type. + + Returns + ------- + out : ndarray + An array with shape (..., K) that contains the vector(s) + of singular values of length K, where K = min(M, N). + + See Also + -------- + scipy.linalg.svdvals : Compute singular values of a matrix. + + Examples + -------- + + >>> np.linalg.svdvals([[1, 2, 3, 4, 5], + ... [1, 4, 9, 16, 25], + ... [1, 8, 27, 64, 125]]) + array([146.68862757, 5.57510612, 0.60393245]) + + Determine the rank of a matrix using singular values: + + >>> s = np.linalg.svdvals([[1, 2, 3], + ... [2, 4, 6], + ... [-1, 1, -1]]); s + array([8.38434191e+00, 1.64402274e+00, 2.31534378e-16]) + >>> np.count_nonzero(s > 1e-10) # Matrix of rank 2 + 2 + + """ + return svd(x, compute_uv=False, hermitian=False) + + +def _cond_dispatcher(x, p=None): + return (x,) + + +@array_function_dispatch(_cond_dispatcher) +def cond(x, p=None): + """ + Compute the condition number of a matrix. + + This function is capable of returning the condition number using + one of seven different norms, depending on the value of `p` (see + Parameters below). + + Parameters + ---------- + x : (..., M, N) array_like + The matrix whose condition number is sought. + p : {None, 1, -1, 2, -2, inf, -inf, 'fro'}, optional + Order of the norm used in the condition number computation: + + ===== ============================ + p norm for matrices + ===== ============================ + None 2-norm, computed directly using the ``SVD`` + 'fro' Frobenius norm + inf max(sum(abs(x), axis=1)) + -inf min(sum(abs(x), axis=1)) + 1 max(sum(abs(x), axis=0)) + -1 min(sum(abs(x), axis=0)) + 2 2-norm (largest sing. value) + -2 smallest singular value + ===== ============================ + + inf means the `numpy.inf` object, and the Frobenius norm is + the root-of-sum-of-squares norm. + + Returns + ------- + c : {float, inf} + The condition number of the matrix. May be infinite. + + See Also + -------- + numpy.linalg.norm + + Notes + ----- + The condition number of `x` is defined as the norm of `x` times the + norm of the inverse of `x` [1]_; the norm can be the usual L2-norm + (root-of-sum-of-squares) or one of a number of other matrix norms. + + References + ---------- + .. [1] G. Strang, *Linear Algebra and Its Applications*, Orlando, FL, + Academic Press, Inc., 1980, pg. 285. + + Examples + -------- + >>> import numpy as np + >>> from numpy import linalg as LA + >>> a = np.array([[1, 0, -1], [0, 1, 0], [1, 0, 1]]) + >>> a + array([[ 1, 0, -1], + [ 0, 1, 0], + [ 1, 0, 1]]) + >>> LA.cond(a) + 1.4142135623730951 + >>> LA.cond(a, 'fro') + 3.1622776601683795 + >>> LA.cond(a, np.inf) + 2.0 + >>> LA.cond(a, -np.inf) + 1.0 + >>> LA.cond(a, 1) + 2.0 + >>> LA.cond(a, -1) + 1.0 + >>> LA.cond(a, 2) + 1.4142135623730951 + >>> LA.cond(a, -2) + 0.70710678118654746 # may vary + >>> (min(LA.svd(a, compute_uv=False)) * + ... min(LA.svd(LA.inv(a), compute_uv=False))) + 0.70710678118654746 # may vary + + """ + x = asarray(x) # in case we have a matrix + if _is_empty_2d(x): + raise LinAlgError("cond is not defined on empty arrays") + if p is None or p in {2, -2}: + s = svd(x, compute_uv=False) + with errstate(all='ignore'): + if p == -2: + r = s[..., -1] / s[..., 0] + else: + r = s[..., 0] / s[..., -1] + else: + # Call inv(x) ignoring errors. The result array will + # contain nans in the entries where inversion failed. + _assert_stacked_square(x) + t, result_t = _commonType(x) + result_t = _realType(result_t) # condition number is always real + signature = 'D->D' if isComplexType(t) else 'd->d' + with errstate(all='ignore'): + invx = _umath_linalg.inv(x, signature=signature) + r = norm(x, p, axis=(-2, -1)) * norm(invx, p, axis=(-2, -1)) + r = r.astype(result_t, copy=False) + + # Convert nans to infs unless the original array had nan entries + nan_mask = isnan(r) + if nan_mask.any(): + nan_mask &= ~isnan(x).any(axis=(-2, -1)) + if r.ndim > 0: + r[nan_mask] = inf + elif nan_mask: + # Convention is to return scalars instead of 0d arrays. + r = r.dtype.type(inf) + + return r + + +def _matrix_rank_dispatcher(A, tol=None, hermitian=None, *, rtol=None): + return (A,) + + +@array_function_dispatch(_matrix_rank_dispatcher) +def matrix_rank(A, tol=None, hermitian=False, *, rtol=None): + """ + Return matrix rank of array using SVD method + + Rank of the array is the number of singular values of the array that are + greater than `tol`. + + Parameters + ---------- + A : {(M,), (..., M, N)} array_like + Input vector or stack of matrices. + tol : (...) array_like, float, optional + Threshold below which SVD values are considered zero. If `tol` is + None, and ``S`` is an array with singular values for `M`, and + ``eps`` is the epsilon value for datatype of ``S``, then `tol` is + set to ``S.max() * max(M, N) * eps``. + hermitian : bool, optional + If True, `A` is assumed to be Hermitian (symmetric if real-valued), + enabling a more efficient method for finding singular values. + Defaults to False. + rtol : (...) array_like, float, optional + Parameter for the relative tolerance component. Only ``tol`` or + ``rtol`` can be set at a time. Defaults to ``max(M, N) * eps``. + + .. versionadded:: 2.0.0 + + Returns + ------- + rank : (...) array_like + Rank of A. + + Notes + ----- + The default threshold to detect rank deficiency is a test on the magnitude + of the singular values of `A`. By default, we identify singular values + less than ``S.max() * max(M, N) * eps`` as indicating rank deficiency + (with the symbols defined above). This is the algorithm MATLAB uses [1]_. + It also appears in *Numerical recipes* in the discussion of SVD solutions + for linear least squares [2]_. + + This default threshold is designed to detect rank deficiency accounting + for the numerical errors of the SVD computation. Imagine that there + is a column in `A` that is an exact (in floating point) linear combination + of other columns in `A`. Computing the SVD on `A` will not produce + a singular value exactly equal to 0 in general: any difference of + the smallest SVD value from 0 will be caused by numerical imprecision + in the calculation of the SVD. Our threshold for small SVD values takes + this numerical imprecision into account, and the default threshold will + detect such numerical rank deficiency. The threshold may declare a matrix + `A` rank deficient even if the linear combination of some columns of `A` + is not exactly equal to another column of `A` but only numerically very + close to another column of `A`. + + We chose our default threshold because it is in wide use. Other thresholds + are possible. For example, elsewhere in the 2007 edition of *Numerical + recipes* there is an alternative threshold of ``S.max() * + np.finfo(A.dtype).eps / 2. * np.sqrt(m + n + 1.)``. The authors describe + this threshold as being based on "expected roundoff error" (p 71). + + The thresholds above deal with floating point roundoff error in the + calculation of the SVD. However, you may have more information about + the sources of error in `A` that would make you consider other tolerance + values to detect *effective* rank deficiency. The most useful measure + of the tolerance depends on the operations you intend to use on your + matrix. For example, if your data come from uncertain measurements with + uncertainties greater than floating point epsilon, choosing a tolerance + near that uncertainty may be preferable. The tolerance may be absolute + if the uncertainties are absolute rather than relative. + + References + ---------- + .. [1] MATLAB reference documentation, "Rank" + https://www.mathworks.com/help/techdoc/ref/rank.html + .. [2] W. H. Press, S. A. Teukolsky, W. T. Vetterling and B. P. Flannery, + "Numerical Recipes (3rd edition)", Cambridge University Press, 2007, + page 795. + + Examples + -------- + >>> import numpy as np + >>> from numpy.linalg import matrix_rank + >>> matrix_rank(np.eye(4)) # Full rank matrix + 4 + >>> I=np.eye(4); I[-1,-1] = 0. # rank deficient matrix + >>> matrix_rank(I) + 3 + >>> matrix_rank(np.ones((4,))) # 1 dimension - rank 1 unless all 0 + 1 + >>> matrix_rank(np.zeros((4,))) + 0 + """ + if rtol is not None and tol is not None: + raise ValueError("`tol` and `rtol` can't be both set.") + + A = asarray(A) + if A.ndim < 2: + return int(not all(A == 0)) + S = svd(A, compute_uv=False, hermitian=hermitian) + + if tol is None: + if rtol is None: + rtol = max(A.shape[-2:]) * finfo(S.dtype).eps + else: + rtol = asarray(rtol)[..., newaxis] + tol = S.max(axis=-1, keepdims=True) * rtol + else: + tol = asarray(tol)[..., newaxis] + + return count_nonzero(S > tol, axis=-1) + + +# Generalized inverse + +def _pinv_dispatcher(a, rcond=None, hermitian=None, *, rtol=None): + return (a,) + + +@array_function_dispatch(_pinv_dispatcher) +def pinv(a, rcond=None, hermitian=False, *, rtol=_NoValue): + """ + Compute the (Moore-Penrose) pseudo-inverse of a matrix. + + Calculate the generalized inverse of a matrix using its + singular-value decomposition (SVD) and including all + *large* singular values. + + Parameters + ---------- + a : (..., M, N) array_like + Matrix or stack of matrices to be pseudo-inverted. + rcond : (...) array_like of float, optional + Cutoff for small singular values. + Singular values less than or equal to + ``rcond * largest_singular_value`` are set to zero. + Broadcasts against the stack of matrices. Default: ``1e-15``. + hermitian : bool, optional + If True, `a` is assumed to be Hermitian (symmetric if real-valued), + enabling a more efficient method for finding singular values. + Defaults to False. + rtol : (...) array_like of float, optional + Same as `rcond`, but it's an Array API compatible parameter name. + Only `rcond` or `rtol` can be set at a time. If none of them are + provided then NumPy's ``1e-15`` default is used. If ``rtol=None`` + is passed then the API standard default is used. + + .. versionadded:: 2.0.0 + + Returns + ------- + B : (..., N, M) ndarray + The pseudo-inverse of `a`. If `a` is a `matrix` instance, then so + is `B`. + + Raises + ------ + LinAlgError + If the SVD computation does not converge. + + See Also + -------- + scipy.linalg.pinv : Similar function in SciPy. + scipy.linalg.pinvh : Compute the (Moore-Penrose) pseudo-inverse of a + Hermitian matrix. + + Notes + ----- + The pseudo-inverse of a matrix A, denoted :math:`A^+`, is + defined as: "the matrix that 'solves' [the least-squares problem] + :math:`Ax = b`," i.e., if :math:`\\bar{x}` is said solution, then + :math:`A^+` is that matrix such that :math:`\\bar{x} = A^+b`. + + It can be shown that if :math:`Q_1 \\Sigma Q_2^T = A` is the singular + value decomposition of A, then + :math:`A^+ = Q_2 \\Sigma^+ Q_1^T`, where :math:`Q_{1,2}` are + orthogonal matrices, :math:`\\Sigma` is a diagonal matrix consisting + of A's so-called singular values, (followed, typically, by + zeros), and then :math:`\\Sigma^+` is simply the diagonal matrix + consisting of the reciprocals of A's singular values + (again, followed by zeros). [1]_ + + References + ---------- + .. [1] G. Strang, *Linear Algebra and Its Applications*, 2nd Ed., Orlando, + FL, Academic Press, Inc., 1980, pp. 139-142. + + Examples + -------- + The following example checks that ``a * a+ * a == a`` and + ``a+ * a * a+ == a+``: + + >>> import numpy as np + >>> rng = np.random.default_rng() + >>> a = rng.normal(size=(9, 6)) + >>> B = np.linalg.pinv(a) + >>> np.allclose(a, np.dot(a, np.dot(B, a))) + True + >>> np.allclose(B, np.dot(B, np.dot(a, B))) + True + + """ + a, wrap = _makearray(a) + if rcond is None: + if rtol is _NoValue: + rcond = 1e-15 + elif rtol is None: + rcond = max(a.shape[-2:]) * finfo(a.dtype).eps + else: + rcond = rtol + elif rtol is not _NoValue: + raise ValueError("`rtol` and `rcond` can't be both set.") + else: + # NOTE: Deprecate `rcond` in a few versions. + pass + + rcond = asarray(rcond) + if _is_empty_2d(a): + m, n = a.shape[-2:] + res = empty(a.shape[:-2] + (n, m), dtype=a.dtype) + return wrap(res) + a = a.conjugate() + u, s, vt = svd(a, full_matrices=False, hermitian=hermitian) + + # discard small singular values + cutoff = rcond[..., newaxis] * amax(s, axis=-1, keepdims=True) + large = s > cutoff + s = divide(1, s, where=large, out=s) + s[~large] = 0 + + res = matmul(transpose(vt), multiply(s[..., newaxis], transpose(u))) + return wrap(res) + + +# Determinant + + +@array_function_dispatch(_unary_dispatcher) +def slogdet(a): + """ + Compute the sign and (natural) logarithm of the determinant of an array. + + If an array has a very small or very large determinant, then a call to + `det` may overflow or underflow. This routine is more robust against such + issues, because it computes the logarithm of the determinant rather than + the determinant itself. + + Parameters + ---------- + a : (..., M, M) array_like + Input array, has to be a square 2-D array. + + Returns + ------- + A namedtuple with the following attributes: + + sign : (...) array_like + A number representing the sign of the determinant. For a real matrix, + this is 1, 0, or -1. For a complex matrix, this is a complex number + with absolute value 1 (i.e., it is on the unit circle), or else 0. + logabsdet : (...) array_like + The natural log of the absolute value of the determinant. + + If the determinant is zero, then `sign` will be 0 and `logabsdet` + will be -inf. In all cases, the determinant is equal to + ``sign * np.exp(logabsdet)``. + + See Also + -------- + det + + Notes + ----- + Broadcasting rules apply, see the `numpy.linalg` documentation for + details. + + The determinant is computed via LU factorization using the LAPACK + routine ``z/dgetrf``. + + Examples + -------- + The determinant of a 2-D array ``[[a, b], [c, d]]`` is ``ad - bc``: + + >>> import numpy as np + >>> a = np.array([[1, 2], [3, 4]]) + >>> (sign, logabsdet) = np.linalg.slogdet(a) + >>> (sign, logabsdet) + (-1, 0.69314718055994529) # may vary + >>> sign * np.exp(logabsdet) + -2.0 + + Computing log-determinants for a stack of matrices: + + >>> a = np.array([ [[1, 2], [3, 4]], [[1, 2], [2, 1]], [[1, 3], [3, 1]] ]) + >>> a.shape + (3, 2, 2) + >>> sign, logabsdet = np.linalg.slogdet(a) + >>> (sign, logabsdet) + (array([-1., -1., -1.]), array([ 0.69314718, 1.09861229, 2.07944154])) + >>> sign * np.exp(logabsdet) + array([-2., -3., -8.]) + + This routine succeeds where ordinary `det` does not: + + >>> np.linalg.det(np.eye(500) * 0.1) + 0.0 + >>> np.linalg.slogdet(np.eye(500) * 0.1) + (1, -1151.2925464970228) + + """ + a = asarray(a) + _assert_stacked_square(a) + t, result_t = _commonType(a) + real_t = _realType(result_t) + signature = 'D->Dd' if isComplexType(t) else 'd->dd' + sign, logdet = _umath_linalg.slogdet(a, signature=signature) + sign = sign.astype(result_t, copy=False) + logdet = logdet.astype(real_t, copy=False) + return SlogdetResult(sign, logdet) + + +@array_function_dispatch(_unary_dispatcher) +def det(a): + """ + Compute the determinant of an array. + + Parameters + ---------- + a : (..., M, M) array_like + Input array to compute determinants for. + + Returns + ------- + det : (...) array_like + Determinant of `a`. + + See Also + -------- + slogdet : Another way to represent the determinant, more suitable + for large matrices where underflow/overflow may occur. + scipy.linalg.det : Similar function in SciPy. + + Notes + ----- + Broadcasting rules apply, see the `numpy.linalg` documentation for + details. + + The determinant is computed via LU factorization using the LAPACK + routine ``z/dgetrf``. + + Examples + -------- + The determinant of a 2-D array [[a, b], [c, d]] is ad - bc: + + >>> import numpy as np + >>> a = np.array([[1, 2], [3, 4]]) + >>> np.linalg.det(a) + -2.0 # may vary + + Computing determinants for a stack of matrices: + + >>> a = np.array([ [[1, 2], [3, 4]], [[1, 2], [2, 1]], [[1, 3], [3, 1]] ]) + >>> a.shape + (3, 2, 2) + >>> np.linalg.det(a) + array([-2., -3., -8.]) + + """ + a = asarray(a) + _assert_stacked_square(a) + t, result_t = _commonType(a) + signature = 'D->D' if isComplexType(t) else 'd->d' + r = _umath_linalg.det(a, signature=signature) + r = r.astype(result_t, copy=False) + return r + + +# Linear Least Squares + +def _lstsq_dispatcher(a, b, rcond=None): + return (a, b) + + +@array_function_dispatch(_lstsq_dispatcher) +def lstsq(a, b, rcond=None): + r""" + Return the least-squares solution to a linear matrix equation. + + Computes the vector `x` that approximately solves the equation + ``a @ x = b``. The equation may be under-, well-, or over-determined + (i.e., the number of linearly independent rows of `a` can be less than, + equal to, or greater than its number of linearly independent columns). + If `a` is square and of full rank, then `x` (but for round-off error) + is the "exact" solution of the equation. Else, `x` minimizes the + Euclidean 2-norm :math:`||b - ax||`. If there are multiple minimizing + solutions, the one with the smallest 2-norm :math:`||x||` is returned. + + Parameters + ---------- + a : (M, N) array_like + "Coefficient" matrix. + b : {(M,), (M, K)} array_like + Ordinate or "dependent variable" values. If `b` is two-dimensional, + the least-squares solution is calculated for each of the `K` columns + of `b`. + rcond : float, optional + Cut-off ratio for small singular values of `a`. + For the purposes of rank determination, singular values are treated + as zero if they are smaller than `rcond` times the largest singular + value of `a`. + The default uses the machine precision times ``max(M, N)``. Passing + ``-1`` will use machine precision. + + .. versionchanged:: 2.0 + Previously, the default was ``-1``, but a warning was given that + this would change. + + Returns + ------- + x : {(N,), (N, K)} ndarray + Least-squares solution. If `b` is two-dimensional, + the solutions are in the `K` columns of `x`. + residuals : {(1,), (K,), (0,)} ndarray + Sums of squared residuals: Squared Euclidean 2-norm for each column in + ``b - a @ x``. + If the rank of `a` is < N or M <= N, this is an empty array. + If `b` is 1-dimensional, this is a (1,) shape array. + Otherwise the shape is (K,). + rank : int + Rank of matrix `a`. + s : (min(M, N),) ndarray + Singular values of `a`. + + Raises + ------ + LinAlgError + If computation does not converge. + + See Also + -------- + scipy.linalg.lstsq : Similar function in SciPy. + + Notes + ----- + If `b` is a matrix, then all array results are returned as matrices. + + Examples + -------- + Fit a line, ``y = mx + c``, through some noisy data-points: + + >>> import numpy as np + >>> x = np.array([0, 1, 2, 3]) + >>> y = np.array([-1, 0.2, 0.9, 2.1]) + + By examining the coefficients, we see that the line should have a + gradient of roughly 1 and cut the y-axis at, more or less, -1. + + We can rewrite the line equation as ``y = Ap``, where ``A = [[x 1]]`` + and ``p = [[m], [c]]``. Now use `lstsq` to solve for `p`: + + >>> A = np.vstack([x, np.ones(len(x))]).T + >>> A + array([[ 0., 1.], + [ 1., 1.], + [ 2., 1.], + [ 3., 1.]]) + + >>> m, c = np.linalg.lstsq(A, y)[0] + >>> m, c + (1.0 -0.95) # may vary + + Plot the data along with the fitted line: + + >>> import matplotlib.pyplot as plt + >>> _ = plt.plot(x, y, 'o', label='Original data', markersize=10) + >>> _ = plt.plot(x, m*x + c, 'r', label='Fitted line') + >>> _ = plt.legend() + >>> plt.show() + + """ + a, _ = _makearray(a) + b, wrap = _makearray(b) + is_1d = b.ndim == 1 + if is_1d: + b = b[:, newaxis] + _assert_2d(a, b) + m, n = a.shape[-2:] + m2, n_rhs = b.shape[-2:] + if m != m2: + raise LinAlgError('Incompatible dimensions') + + t, result_t = _commonType(a, b) + result_real_t = _realType(result_t) + + if rcond is None: + rcond = finfo(t).eps * max(n, m) + + signature = 'DDd->Ddid' if isComplexType(t) else 'ddd->ddid' + if n_rhs == 0: + # lapack can't handle n_rhs = 0 - so allocate + # the array one larger in that axis + b = zeros(b.shape[:-2] + (m, n_rhs + 1), dtype=b.dtype) + + with errstate(call=_raise_linalgerror_lstsq, invalid='call', + over='ignore', divide='ignore', under='ignore'): + x, resids, rank, s = _umath_linalg.lstsq(a, b, rcond, + signature=signature) + if m == 0: + x[...] = 0 + if n_rhs == 0: + # remove the item we added + x = x[..., :n_rhs] + resids = resids[..., :n_rhs] + + # remove the axis we added + if is_1d: + x = x.squeeze(axis=-1) + # we probably should squeeze resids too, but we can't + # without breaking compatibility. + + # as documented + if rank != n or m <= n: + resids = array([], result_real_t) + + # coerce output arrays + s = s.astype(result_real_t, copy=False) + resids = resids.astype(result_real_t, copy=False) + # Copying lets the memory in r_parts be freed + x = x.astype(result_t, copy=True) + return wrap(x), wrap(resids), rank, s + + +def _multi_svd_norm(x, row_axis, col_axis, op, initial=None): + """Compute a function of the singular values of the 2-D matrices in `x`. + + This is a private utility function used by `numpy.linalg.norm()`. + + Parameters + ---------- + x : ndarray + row_axis, col_axis : int + The axes of `x` that hold the 2-D matrices. + op : callable + This should be either numpy.amin or `numpy.amax` or `numpy.sum`. + + Returns + ------- + result : float or ndarray + If `x` is 2-D, the return values is a float. + Otherwise, it is an array with ``x.ndim - 2`` dimensions. + The return values are either the minimum or maximum or sum of the + singular values of the matrices, depending on whether `op` + is `numpy.amin` or `numpy.amax` or `numpy.sum`. + + """ + y = moveaxis(x, (row_axis, col_axis), (-2, -1)) + result = op(svd(y, compute_uv=False), axis=-1, initial=initial) + return result + + +def _norm_dispatcher(x, ord=None, axis=None, keepdims=None): + return (x,) + + +@array_function_dispatch(_norm_dispatcher) +def norm(x, ord=None, axis=None, keepdims=False): + """ + Matrix or vector norm. + + This function is able to return one of eight different matrix norms, + or one of an infinite number of vector norms (described below), depending + on the value of the ``ord`` parameter. + + Parameters + ---------- + x : array_like + Input array. If `axis` is None, `x` must be 1-D or 2-D, unless `ord` + is None. If both `axis` and `ord` are None, the 2-norm of + ``x.ravel`` will be returned. + ord : {int, float, inf, -inf, 'fro', 'nuc'}, optional + Order of the norm (see table under ``Notes`` for what values are + supported for matrices and vectors respectively). inf means numpy's + `inf` object. The default is None. + axis : {None, int, 2-tuple of ints}, optional. + If `axis` is an integer, it specifies the axis of `x` along which to + compute the vector norms. If `axis` is a 2-tuple, it specifies the + axes that hold 2-D matrices, and the matrix norms of these matrices + are computed. If `axis` is None then either a vector norm (when `x` + is 1-D) or a matrix norm (when `x` is 2-D) is returned. The default + is None. + + keepdims : bool, optional + If this is set to True, the axes which are normed over are left in the + result as dimensions with size one. With this option the result will + broadcast correctly against the original `x`. + + Returns + ------- + n : float or ndarray + Norm of the matrix or vector(s). + + See Also + -------- + scipy.linalg.norm : Similar function in SciPy. + + Notes + ----- + For values of ``ord < 1``, the result is, strictly speaking, not a + mathematical 'norm', but it may still be useful for various numerical + purposes. + + The following norms can be calculated: + + ===== ============================ ========================== + ord norm for matrices norm for vectors + ===== ============================ ========================== + None Frobenius norm 2-norm + 'fro' Frobenius norm -- + 'nuc' nuclear norm -- + inf max(sum(abs(x), axis=1)) max(abs(x)) + -inf min(sum(abs(x), axis=1)) min(abs(x)) + 0 -- sum(x != 0) + 1 max(sum(abs(x), axis=0)) as below + -1 min(sum(abs(x), axis=0)) as below + 2 2-norm (largest sing. value) as below + -2 smallest singular value as below + other -- sum(abs(x)**ord)**(1./ord) + ===== ============================ ========================== + + The Frobenius norm is given by [1]_: + + :math:`||A||_F = [\\sum_{i,j} abs(a_{i,j})^2]^{1/2}` + + The nuclear norm is the sum of the singular values. + + Both the Frobenius and nuclear norm orders are only defined for + matrices and raise a ValueError when ``x.ndim != 2``. + + References + ---------- + .. [1] G. H. Golub and C. F. Van Loan, *Matrix Computations*, + Baltimore, MD, Johns Hopkins University Press, 1985, pg. 15 + + Examples + -------- + + >>> import numpy as np + >>> from numpy import linalg as LA + >>> a = np.arange(9) - 4 + >>> a + array([-4, -3, -2, ..., 2, 3, 4]) + >>> b = a.reshape((3, 3)) + >>> b + array([[-4, -3, -2], + [-1, 0, 1], + [ 2, 3, 4]]) + + >>> LA.norm(a) + 7.745966692414834 + >>> LA.norm(b) + 7.745966692414834 + >>> LA.norm(b, 'fro') + 7.745966692414834 + >>> LA.norm(a, np.inf) + 4.0 + >>> LA.norm(b, np.inf) + 9.0 + >>> LA.norm(a, -np.inf) + 0.0 + >>> LA.norm(b, -np.inf) + 2.0 + + >>> LA.norm(a, 1) + 20.0 + >>> LA.norm(b, 1) + 7.0 + >>> LA.norm(a, -1) + -4.6566128774142013e-010 + >>> LA.norm(b, -1) + 6.0 + >>> LA.norm(a, 2) + 7.745966692414834 + >>> LA.norm(b, 2) + 7.3484692283495345 + + >>> LA.norm(a, -2) + 0.0 + >>> LA.norm(b, -2) + 1.8570331885190563e-016 # may vary + >>> LA.norm(a, 3) + 5.8480354764257312 # may vary + >>> LA.norm(a, -3) + 0.0 + + Using the `axis` argument to compute vector norms: + + >>> c = np.array([[ 1, 2, 3], + ... [-1, 1, 4]]) + >>> LA.norm(c, axis=0) + array([ 1.41421356, 2.23606798, 5. ]) + >>> LA.norm(c, axis=1) + array([ 3.74165739, 4.24264069]) + >>> LA.norm(c, ord=1, axis=1) + array([ 6., 6.]) + + Using the `axis` argument to compute matrix norms: + + >>> m = np.arange(8).reshape(2,2,2) + >>> LA.norm(m, axis=(1,2)) + array([ 3.74165739, 11.22497216]) + >>> LA.norm(m[0, :, :]), LA.norm(m[1, :, :]) + (3.7416573867739413, 11.224972160321824) + + """ + x = asarray(x) + + if not issubclass(x.dtype.type, (inexact, object_)): + x = x.astype(float) + + # Immediately handle some default, simple, fast, and common cases. + if axis is None: + ndim = x.ndim + if ( + (ord is None) or + (ord in ('f', 'fro') and ndim == 2) or + (ord == 2 and ndim == 1) + ): + x = x.ravel(order='K') + if isComplexType(x.dtype.type): + x_real = x.real + x_imag = x.imag + sqnorm = x_real.dot(x_real) + x_imag.dot(x_imag) + else: + sqnorm = x.dot(x) + ret = sqrt(sqnorm) + if keepdims: + ret = ret.reshape(ndim * [1]) + return ret + + # Normalize the `axis` argument to a tuple. + nd = x.ndim + if axis is None: + axis = tuple(range(nd)) + elif not isinstance(axis, tuple): + try: + axis = int(axis) + except Exception as e: + raise TypeError( + "'axis' must be None, an integer or a tuple of integers" + ) from e + axis = (axis,) + + if len(axis) == 1: + if ord == inf: + return abs(x).max(axis=axis, keepdims=keepdims, initial=0) + elif ord == -inf: + return abs(x).min(axis=axis, keepdims=keepdims) + elif ord == 0: + # Zero norm + return ( + (x != 0) + .astype(x.real.dtype) + .sum(axis=axis, keepdims=keepdims) + ) + elif ord == 1: + # special case for speedup + return add.reduce(abs(x), axis=axis, keepdims=keepdims) + elif ord is None or ord == 2: + # special case for speedup + s = (x.conj() * x).real + return sqrt(add.reduce(s, axis=axis, keepdims=keepdims)) + # None of the str-type keywords for ord ('fro', 'nuc') + # are valid for vectors + elif isinstance(ord, str): + raise ValueError(f"Invalid norm order '{ord}' for vectors") + else: + absx = abs(x) + absx **= ord + ret = add.reduce(absx, axis=axis, keepdims=keepdims) + ret **= reciprocal(ord, dtype=ret.dtype) + return ret + elif len(axis) == 2: + row_axis, col_axis = axis + row_axis = normalize_axis_index(row_axis, nd) + col_axis = normalize_axis_index(col_axis, nd) + if row_axis == col_axis: + raise ValueError('Duplicate axes given.') + if ord == 2: + ret = _multi_svd_norm(x, row_axis, col_axis, amax, 0) + elif ord == -2: + ret = _multi_svd_norm(x, row_axis, col_axis, amin) + elif ord == 1: + if col_axis > row_axis: + col_axis -= 1 + ret = add.reduce(abs(x), axis=row_axis).max(axis=col_axis, initial=0) + elif ord == inf: + if row_axis > col_axis: + row_axis -= 1 + ret = add.reduce(abs(x), axis=col_axis).max(axis=row_axis, initial=0) + elif ord == -1: + if col_axis > row_axis: + col_axis -= 1 + ret = add.reduce(abs(x), axis=row_axis).min(axis=col_axis) + elif ord == -inf: + if row_axis > col_axis: + row_axis -= 1 + ret = add.reduce(abs(x), axis=col_axis).min(axis=row_axis) + elif ord in [None, 'fro', 'f']: + ret = sqrt(add.reduce((x.conj() * x).real, axis=axis)) + elif ord == 'nuc': + ret = _multi_svd_norm(x, row_axis, col_axis, sum, 0) + else: + raise ValueError("Invalid norm order for matrices.") + if keepdims: + ret_shape = list(x.shape) + ret_shape[axis[0]] = 1 + ret_shape[axis[1]] = 1 + ret = ret.reshape(ret_shape) + return ret + else: + raise ValueError("Improper number of dimensions to norm.") + + +# multi_dot + +def _multidot_dispatcher(arrays, *, out=None): + yield from arrays + yield out + + +@array_function_dispatch(_multidot_dispatcher) +def multi_dot(arrays, *, out=None): + """ + Compute the dot product of two or more arrays in a single function call, + while automatically selecting the fastest evaluation order. + + `multi_dot` chains `numpy.dot` and uses optimal parenthesization + of the matrices [1]_ [2]_. Depending on the shapes of the matrices, + this can speed up the multiplication a lot. + + If the first argument is 1-D it is treated as a row vector. + If the last argument is 1-D it is treated as a column vector. + The other arguments must be 2-D. + + Think of `multi_dot` as:: + + def multi_dot(arrays): return functools.reduce(np.dot, arrays) + + + Parameters + ---------- + arrays : sequence of array_like + If the first argument is 1-D it is treated as row vector. + If the last argument is 1-D it is treated as column vector. + The other arguments must be 2-D. + out : ndarray, optional + Output argument. This must have the exact kind that would be returned + if it was not used. In particular, it must have the right type, must be + C-contiguous, and its dtype must be the dtype that would be returned + for `dot(a, b)`. This is a performance feature. Therefore, if these + conditions are not met, an exception is raised, instead of attempting + to be flexible. + + Returns + ------- + output : ndarray + Returns the dot product of the supplied arrays. + + See Also + -------- + numpy.dot : dot multiplication with two arguments. + + References + ---------- + + .. [1] Cormen, "Introduction to Algorithms", Chapter 15.2, p. 370-378 + .. [2] https://en.wikipedia.org/wiki/Matrix_chain_multiplication + + Examples + -------- + `multi_dot` allows you to write:: + + >>> import numpy as np + >>> from numpy.linalg import multi_dot + >>> # Prepare some data + >>> A = np.random.random((10000, 100)) + >>> B = np.random.random((100, 1000)) + >>> C = np.random.random((1000, 5)) + >>> D = np.random.random((5, 333)) + >>> # the actual dot multiplication + >>> _ = multi_dot([A, B, C, D]) + + instead of:: + + >>> _ = np.dot(np.dot(np.dot(A, B), C), D) + >>> # or + >>> _ = A.dot(B).dot(C).dot(D) + + Notes + ----- + The cost for a matrix multiplication can be calculated with the + following function:: + + def cost(A, B): + return A.shape[0] * A.shape[1] * B.shape[1] + + Assume we have three matrices + :math:`A_{10 \\times 100}, B_{100 \\times 5}, C_{5 \\times 50}`. + + The costs for the two different parenthesizations are as follows:: + + cost((AB)C) = 10*100*5 + 10*5*50 = 5000 + 2500 = 7500 + cost(A(BC)) = 10*100*50 + 100*5*50 = 50000 + 25000 = 75000 + + """ + n = len(arrays) + # optimization only makes sense for len(arrays) > 2 + if n < 2: + raise ValueError("Expecting at least two arrays.") + elif n == 2: + return dot(arrays[0], arrays[1], out=out) + + arrays = [asanyarray(a) for a in arrays] + + # save original ndim to reshape the result array into the proper form later + ndim_first, ndim_last = arrays[0].ndim, arrays[-1].ndim + # Explicitly convert vectors to 2D arrays to keep the logic of the internal + # _multi_dot_* functions as simple as possible. + if arrays[0].ndim == 1: + arrays[0] = atleast_2d(arrays[0]) + if arrays[-1].ndim == 1: + arrays[-1] = atleast_2d(arrays[-1]).T + _assert_2d(*arrays) + + # _multi_dot_three is much faster than _multi_dot_matrix_chain_order + if n == 3: + result = _multi_dot_three(arrays[0], arrays[1], arrays[2], out=out) + else: + order = _multi_dot_matrix_chain_order(arrays) + result = _multi_dot(arrays, order, 0, n - 1, out=out) + + # return proper shape + if ndim_first == 1 and ndim_last == 1: + return result[0, 0] # scalar + elif ndim_first == 1 or ndim_last == 1: + return result.ravel() # 1-D + else: + return result + + +def _multi_dot_three(A, B, C, out=None): + """ + Find the best order for three arrays and do the multiplication. + + For three arguments `_multi_dot_three` is approximately 15 times faster + than `_multi_dot_matrix_chain_order` + + """ + a0, a1b0 = A.shape + b1c0, c1 = C.shape + # cost1 = cost((AB)C) = a0*a1b0*b1c0 + a0*b1c0*c1 + cost1 = a0 * b1c0 * (a1b0 + c1) + # cost2 = cost(A(BC)) = a1b0*b1c0*c1 + a0*a1b0*c1 + cost2 = a1b0 * c1 * (a0 + b1c0) + + if cost1 < cost2: + return dot(dot(A, B), C, out=out) + else: + return dot(A, dot(B, C), out=out) + + +def _multi_dot_matrix_chain_order(arrays, return_costs=False): + """ + Return a np.array that encodes the optimal order of multiplications. + + The optimal order array is then used by `_multi_dot()` to do the + multiplication. + + Also return the cost matrix if `return_costs` is `True` + + The implementation CLOSELY follows Cormen, "Introduction to Algorithms", + Chapter 15.2, p. 370-378. Note that Cormen uses 1-based indices. + + cost[i, j] = min([ + cost[prefix] + cost[suffix] + cost_mult(prefix, suffix) + for k in range(i, j)]) + + """ + n = len(arrays) + # p stores the dimensions of the matrices + # Example for p: A_{10x100}, B_{100x5}, C_{5x50} --> p = [10, 100, 5, 50] + p = [a.shape[0] for a in arrays] + [arrays[-1].shape[1]] + # m is a matrix of costs of the subproblems + # m[i,j]: min number of scalar multiplications needed to compute A_{i..j} + m = zeros((n, n), dtype=double) + # s is the actual ordering + # s[i, j] is the value of k at which we split the product A_i..A_j + s = empty((n, n), dtype=intp) + + for l in range(1, n): + for i in range(n - l): + j = i + l + m[i, j] = inf + for k in range(i, j): + q = m[i, k] + m[k + 1, j] + p[i] * p[k + 1] * p[j + 1] + if q < m[i, j]: + m[i, j] = q + s[i, j] = k # Note that Cormen uses 1-based index + + return (s, m) if return_costs else s + + +def _multi_dot(arrays, order, i, j, out=None): + """Actually do the multiplication with the given order.""" + if i == j: + # the initial call with non-None out should never get here + assert out is None + + return arrays[i] + else: + return dot(_multi_dot(arrays, order, i, order[i, j]), + _multi_dot(arrays, order, order[i, j] + 1, j), + out=out) + + +# diagonal + +def _diagonal_dispatcher(x, /, *, offset=None): + return (x,) + + +@array_function_dispatch(_diagonal_dispatcher) +def diagonal(x, /, *, offset=0): + """ + Returns specified diagonals of a matrix (or a stack of matrices) ``x``. + + This function is Array API compatible, contrary to + :py:func:`numpy.diagonal`, the matrix is assumed + to be defined by the last two dimensions. + + Parameters + ---------- + x : (...,M,N) array_like + Input array having shape (..., M, N) and whose innermost two + dimensions form MxN matrices. + offset : int, optional + Offset specifying the off-diagonal relative to the main diagonal, + where:: + + * offset = 0: the main diagonal. + * offset > 0: off-diagonal above the main diagonal. + * offset < 0: off-diagonal below the main diagonal. + + Returns + ------- + out : (...,min(N,M)) ndarray + An array containing the diagonals and whose shape is determined by + removing the last two dimensions and appending a dimension equal to + the size of the resulting diagonals. The returned array must have + the same data type as ``x``. + + See Also + -------- + numpy.diagonal + + Examples + -------- + >>> a = np.arange(4).reshape(2, 2); a + array([[0, 1], + [2, 3]]) + >>> np.linalg.diagonal(a) + array([0, 3]) + + A 3-D example: + + >>> a = np.arange(8).reshape(2, 2, 2); a + array([[[0, 1], + [2, 3]], + [[4, 5], + [6, 7]]]) + >>> np.linalg.diagonal(a) + array([[0, 3], + [4, 7]]) + + Diagonals adjacent to the main diagonal can be obtained by using the + `offset` argument: + + >>> a = np.arange(9).reshape(3, 3) + >>> a + array([[0, 1, 2], + [3, 4, 5], + [6, 7, 8]]) + >>> np.linalg.diagonal(a, offset=1) # First superdiagonal + array([1, 5]) + >>> np.linalg.diagonal(a, offset=2) # Second superdiagonal + array([2]) + >>> np.linalg.diagonal(a, offset=-1) # First subdiagonal + array([3, 7]) + >>> np.linalg.diagonal(a, offset=-2) # Second subdiagonal + array([6]) + + The anti-diagonal can be obtained by reversing the order of elements + using either `numpy.flipud` or `numpy.fliplr`. + + >>> a = np.arange(9).reshape(3, 3) + >>> a + array([[0, 1, 2], + [3, 4, 5], + [6, 7, 8]]) + >>> np.linalg.diagonal(np.fliplr(a)) # Horizontal flip + array([2, 4, 6]) + >>> np.linalg.diagonal(np.flipud(a)) # Vertical flip + array([6, 4, 2]) + + Note that the order in which the diagonal is retrieved varies depending + on the flip function. + + """ + return _core_diagonal(x, offset, axis1=-2, axis2=-1) + + +# trace + +def _trace_dispatcher(x, /, *, offset=None, dtype=None): + return (x,) + + +@array_function_dispatch(_trace_dispatcher) +def trace(x, /, *, offset=0, dtype=None): + """ + Returns the sum along the specified diagonals of a matrix + (or a stack of matrices) ``x``. + + This function is Array API compatible, contrary to + :py:func:`numpy.trace`. + + Parameters + ---------- + x : (...,M,N) array_like + Input array having shape (..., M, N) and whose innermost two + dimensions form MxN matrices. + offset : int, optional + Offset specifying the off-diagonal relative to the main diagonal, + where:: + + * offset = 0: the main diagonal. + * offset > 0: off-diagonal above the main diagonal. + * offset < 0: off-diagonal below the main diagonal. + + dtype : dtype, optional + Data type of the returned array. + + Returns + ------- + out : ndarray + An array containing the traces and whose shape is determined by + removing the last two dimensions and storing the traces in the last + array dimension. For example, if x has rank k and shape: + (I, J, K, ..., L, M, N), then an output array has rank k-2 and shape: + (I, J, K, ..., L) where:: + + out[i, j, k, ..., l] = trace(a[i, j, k, ..., l, :, :]) + + The returned array must have a data type as described by the dtype + parameter above. + + See Also + -------- + numpy.trace + + Examples + -------- + >>> np.linalg.trace(np.eye(3)) + 3.0 + >>> a = np.arange(8).reshape((2, 2, 2)) + >>> np.linalg.trace(a) + array([3, 11]) + + Trace is computed with the last two axes as the 2-d sub-arrays. + This behavior differs from :py:func:`numpy.trace` which uses the first two + axes by default. + + >>> a = np.arange(24).reshape((3, 2, 2, 2)) + >>> np.linalg.trace(a).shape + (3, 2) + + Traces adjacent to the main diagonal can be obtained by using the + `offset` argument: + + >>> a = np.arange(9).reshape((3, 3)); a + array([[0, 1, 2], + [3, 4, 5], + [6, 7, 8]]) + >>> np.linalg.trace(a, offset=1) # First superdiagonal + 6 + >>> np.linalg.trace(a, offset=2) # Second superdiagonal + 2 + >>> np.linalg.trace(a, offset=-1) # First subdiagonal + 10 + >>> np.linalg.trace(a, offset=-2) # Second subdiagonal + 6 + + """ + return _core_trace(x, offset, axis1=-2, axis2=-1, dtype=dtype) + + +# cross + +def _cross_dispatcher(x1, x2, /, *, axis=None): + return (x1, x2,) + + +@array_function_dispatch(_cross_dispatcher) +def cross(x1, x2, /, *, axis=-1): + """ + Returns the cross product of 3-element vectors. + + If ``x1`` and/or ``x2`` are multi-dimensional arrays, then + the cross-product of each pair of corresponding 3-element vectors + is independently computed. + + This function is Array API compatible, contrary to + :func:`numpy.cross`. + + Parameters + ---------- + x1 : array_like + The first input array. + x2 : array_like + The second input array. Must be compatible with ``x1`` for all + non-compute axes. The size of the axis over which to compute + the cross-product must be the same size as the respective axis + in ``x1``. + axis : int, optional + The axis (dimension) of ``x1`` and ``x2`` containing the vectors for + which to compute the cross-product. Default: ``-1``. + + Returns + ------- + out : ndarray + An array containing the cross products. + + See Also + -------- + numpy.cross + + Examples + -------- + Vector cross-product. + + >>> x = np.array([1, 2, 3]) + >>> y = np.array([4, 5, 6]) + >>> np.linalg.cross(x, y) + array([-3, 6, -3]) + + Multiple vector cross-products. Note that the direction of the cross + product vector is defined by the *right-hand rule*. + + >>> x = np.array([[1,2,3], [4,5,6]]) + >>> y = np.array([[4,5,6], [1,2,3]]) + >>> np.linalg.cross(x, y) + array([[-3, 6, -3], + [ 3, -6, 3]]) + + >>> x = np.array([[1, 2], [3, 4], [5, 6]]) + >>> y = np.array([[4, 5], [6, 1], [2, 3]]) + >>> np.linalg.cross(x, y, axis=0) + array([[-24, 6], + [ 18, 24], + [-6, -18]]) + + """ + x1 = asanyarray(x1) + x2 = asanyarray(x2) + + if x1.shape[axis] != 3 or x2.shape[axis] != 3: + raise ValueError( + "Both input arrays must be (arrays of) 3-dimensional vectors, " + f"but they are {x1.shape[axis]} and {x2.shape[axis]} " + "dimensional instead." + ) + + return _core_cross(x1, x2, axis=axis) + + +# matmul + +def _matmul_dispatcher(x1, x2, /): + return (x1, x2) + + +@array_function_dispatch(_matmul_dispatcher) +def matmul(x1, x2, /): + """ + Computes the matrix product. + + This function is Array API compatible, contrary to + :func:`numpy.matmul`. + + Parameters + ---------- + x1 : array_like + The first input array. + x2 : array_like + The second input array. + + Returns + ------- + out : ndarray + The matrix product of the inputs. + This is a scalar only when both ``x1``, ``x2`` are 1-d vectors. + + Raises + ------ + ValueError + If the last dimension of ``x1`` is not the same size as + the second-to-last dimension of ``x2``. + + If a scalar value is passed in. + + See Also + -------- + numpy.matmul + + Examples + -------- + For 2-D arrays it is the matrix product: + + >>> a = np.array([[1, 0], + ... [0, 1]]) + >>> b = np.array([[4, 1], + ... [2, 2]]) + >>> np.linalg.matmul(a, b) + array([[4, 1], + [2, 2]]) + + For 2-D mixed with 1-D, the result is the usual. + + >>> a = np.array([[1, 0], + ... [0, 1]]) + >>> b = np.array([1, 2]) + >>> np.linalg.matmul(a, b) + array([1, 2]) + >>> np.linalg.matmul(b, a) + array([1, 2]) + + + Broadcasting is conventional for stacks of arrays + + >>> a = np.arange(2 * 2 * 4).reshape((2, 2, 4)) + >>> b = np.arange(2 * 2 * 4).reshape((2, 4, 2)) + >>> np.linalg.matmul(a,b).shape + (2, 2, 2) + >>> np.linalg.matmul(a, b)[0, 1, 1] + 98 + >>> sum(a[0, 1, :] * b[0 , :, 1]) + 98 + + Vector, vector returns the scalar inner product, but neither argument + is complex-conjugated: + + >>> np.linalg.matmul([2j, 3j], [2j, 3j]) + (-13+0j) + + Scalar multiplication raises an error. + + >>> np.linalg.matmul([1,2], 3) + Traceback (most recent call last): + ... + ValueError: matmul: Input operand 1 does not have enough dimensions ... + + """ + return _core_matmul(x1, x2) + + +# tensordot + +def _tensordot_dispatcher(x1, x2, /, *, axes=None): + return (x1, x2) + + +@array_function_dispatch(_tensordot_dispatcher) +def tensordot(x1, x2, /, *, axes=2): + return _core_tensordot(x1, x2, axes=axes) + + +tensordot.__doc__ = _core_tensordot.__doc__ + + +# matrix_transpose + +def _matrix_transpose_dispatcher(x): + return (x,) + +@array_function_dispatch(_matrix_transpose_dispatcher) +def matrix_transpose(x, /): + return _core_matrix_transpose(x) + + +matrix_transpose.__doc__ = f"""{_core_matrix_transpose.__doc__} + + Notes + ----- + This function is an alias of `numpy.matrix_transpose`. +""" + + +# matrix_norm + +def _matrix_norm_dispatcher(x, /, *, keepdims=None, ord=None): + return (x,) + +@array_function_dispatch(_matrix_norm_dispatcher) +def matrix_norm(x, /, *, keepdims=False, ord="fro"): + """ + Computes the matrix norm of a matrix (or a stack of matrices) ``x``. + + This function is Array API compatible. + + Parameters + ---------- + x : array_like + Input array having shape (..., M, N) and whose two innermost + dimensions form ``MxN`` matrices. + keepdims : bool, optional + If this is set to True, the axes which are normed over are left in + the result as dimensions with size one. Default: False. + ord : {1, -1, 2, -2, inf, -inf, 'fro', 'nuc'}, optional + The order of the norm. For details see the table under ``Notes`` + in `numpy.linalg.norm`. + + See Also + -------- + numpy.linalg.norm : Generic norm function + + Examples + -------- + >>> from numpy import linalg as LA + >>> a = np.arange(9) - 4 + >>> a + array([-4, -3, -2, ..., 2, 3, 4]) + >>> b = a.reshape((3, 3)) + >>> b + array([[-4, -3, -2], + [-1, 0, 1], + [ 2, 3, 4]]) + + >>> LA.matrix_norm(b) + 7.745966692414834 + >>> LA.matrix_norm(b, ord='fro') + 7.745966692414834 + >>> LA.matrix_norm(b, ord=np.inf) + 9.0 + >>> LA.matrix_norm(b, ord=-np.inf) + 2.0 + + >>> LA.matrix_norm(b, ord=1) + 7.0 + >>> LA.matrix_norm(b, ord=-1) + 6.0 + >>> LA.matrix_norm(b, ord=2) + 7.3484692283495345 + >>> LA.matrix_norm(b, ord=-2) + 1.8570331885190563e-016 # may vary + + """ + x = asanyarray(x) + return norm(x, axis=(-2, -1), keepdims=keepdims, ord=ord) + + +# vector_norm + +def _vector_norm_dispatcher(x, /, *, axis=None, keepdims=None, ord=None): + return (x,) + +@array_function_dispatch(_vector_norm_dispatcher) +def vector_norm(x, /, *, axis=None, keepdims=False, ord=2): + """ + Computes the vector norm of a vector (or batch of vectors) ``x``. + + This function is Array API compatible. + + Parameters + ---------- + x : array_like + Input array. + axis : {None, int, 2-tuple of ints}, optional + If an integer, ``axis`` specifies the axis (dimension) along which + to compute vector norms. If an n-tuple, ``axis`` specifies the axes + (dimensions) along which to compute batched vector norms. If ``None``, + the vector norm must be computed over all array values (i.e., + equivalent to computing the vector norm of a flattened array). + Default: ``None``. + keepdims : bool, optional + If this is set to True, the axes which are normed over are left in + the result as dimensions with size one. Default: False. + ord : {int, float, inf, -inf}, optional + The order of the norm. For details see the table under ``Notes`` + in `numpy.linalg.norm`. + + See Also + -------- + numpy.linalg.norm : Generic norm function + + Examples + -------- + >>> from numpy import linalg as LA + >>> a = np.arange(9) + 1 + >>> a + array([1, 2, 3, 4, 5, 6, 7, 8, 9]) + >>> b = a.reshape((3, 3)) + >>> b + array([[1, 2, 3], + [4, 5, 6], + [7, 8, 9]]) + + >>> LA.vector_norm(b) + 16.881943016134134 + >>> LA.vector_norm(b, ord=np.inf) + 9.0 + >>> LA.vector_norm(b, ord=-np.inf) + 1.0 + + >>> LA.vector_norm(b, ord=0) + 9.0 + >>> LA.vector_norm(b, ord=1) + 45.0 + >>> LA.vector_norm(b, ord=-1) + 0.3534857623790153 + >>> LA.vector_norm(b, ord=2) + 16.881943016134134 + >>> LA.vector_norm(b, ord=-2) + 0.8058837395885292 + + """ + x = asanyarray(x) + shape = list(x.shape) + if axis is None: + # Note: np.linalg.norm() doesn't handle 0-D arrays + x = x.ravel() + _axis = 0 + elif isinstance(axis, tuple): + # Note: The axis argument supports any number of axes, whereas + # np.linalg.norm() only supports a single axis for vector norm. + normalized_axis = normalize_axis_tuple(axis, x.ndim) + rest = tuple(i for i in range(x.ndim) if i not in normalized_axis) + newshape = axis + rest + x = _core_transpose(x, newshape).reshape( + ( + prod([x.shape[i] for i in axis], dtype=int), + *[x.shape[i] for i in rest] + ) + ) + _axis = 0 + else: + _axis = axis + + res = norm(x, axis=_axis, ord=ord) + + if keepdims: + # We can't reuse np.linalg.norm(keepdims) because of the reshape hacks + # above to avoid matrix norm logic. + _axis = normalize_axis_tuple( + range(len(shape)) if axis is None else axis, len(shape) + ) + for i in _axis: + shape[i] = 1 + res = res.reshape(tuple(shape)) + + return res + + +# vecdot + +def _vecdot_dispatcher(x1, x2, /, *, axis=None): + return (x1, x2) + +@array_function_dispatch(_vecdot_dispatcher) +def vecdot(x1, x2, /, *, axis=-1): + """ + Computes the vector dot product. + + This function is restricted to arguments compatible with the Array API, + contrary to :func:`numpy.vecdot`. + + Let :math:`\\mathbf{a}` be a vector in ``x1`` and :math:`\\mathbf{b}` be + a corresponding vector in ``x2``. The dot product is defined as: + + .. math:: + \\mathbf{a} \\cdot \\mathbf{b} = \\sum_{i=0}^{n-1} \\overline{a_i}b_i + + over the dimension specified by ``axis`` and where :math:`\\overline{a_i}` + denotes the complex conjugate if :math:`a_i` is complex and the identity + otherwise. + + Parameters + ---------- + x1 : array_like + First input array. + x2 : array_like + Second input array. + axis : int, optional + Axis over which to compute the dot product. Default: ``-1``. + + Returns + ------- + output : ndarray + The vector dot product of the input. + + See Also + -------- + numpy.vecdot + + Examples + -------- + Get the projected size along a given normal for an array of vectors. + + >>> v = np.array([[0., 5., 0.], [0., 0., 10.], [0., 6., 8.]]) + >>> n = np.array([0., 0.6, 0.8]) + >>> np.linalg.vecdot(v, n) + array([ 3., 8., 10.]) + + """ + return _core_vecdot(x1, x2, axis=axis) diff --git a/python/user_packages/Python313/site-packages/numpy/linalg/_linalg.pyi b/python/user_packages/Python313/site-packages/numpy/linalg/_linalg.pyi new file mode 100644 index 0000000000000000000000000000000000000000..4dd7efadf40e76d12fbf6f474edbfba98e10c20f --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/linalg/_linalg.pyi @@ -0,0 +1,548 @@ +from collections.abc import Iterable +from typing import ( + Any, + Literal as L, + NamedTuple, + Never, + SupportsIndex, + SupportsInt, + TypeAlias, + TypeVar, + overload, +) + +import numpy as np +from numpy import ( + complex128, + complexfloating, + float64, + floating, + int32, + object_, + signedinteger, + timedelta64, + unsignedinteger, + vecdot, +) +from numpy._core.fromnumeric import matrix_transpose +from numpy._globals import _NoValueType +from numpy._typing import ( + ArrayLike, + DTypeLike, + NDArray, + _ArrayLike, + _ArrayLikeBool_co, + _ArrayLikeComplex_co, + _ArrayLikeFloat_co, + _ArrayLikeInt_co, + _ArrayLikeNumber_co, + _ArrayLikeObject_co, + _ArrayLikeTD64_co, + _ArrayLikeUInt_co, + _NestedSequence, + _ShapeLike, +) +from numpy.linalg import LinAlgError + +__all__ = [ + "matrix_power", + "solve", + "tensorsolve", + "tensorinv", + "inv", + "cholesky", + "eigvals", + "eigvalsh", + "pinv", + "slogdet", + "det", + "svd", + "svdvals", + "eig", + "eigh", + "lstsq", + "norm", + "qr", + "cond", + "matrix_rank", + "LinAlgError", + "multi_dot", + "trace", + "diagonal", + "cross", + "outer", + "tensordot", + "matmul", + "matrix_transpose", + "matrix_norm", + "vector_norm", + "vecdot", +] + +_NumberT = TypeVar("_NumberT", bound=np.number) +_NumericScalarT = TypeVar("_NumericScalarT", bound=np.number | np.timedelta64 | np.object_) + +_ModeKind: TypeAlias = L["reduced", "complete", "r", "raw"] + +### + +fortran_int = np.intc + +class EigResult(NamedTuple): + eigenvalues: NDArray[Any] + eigenvectors: NDArray[Any] + +class EighResult(NamedTuple): + eigenvalues: NDArray[Any] + eigenvectors: NDArray[Any] + +class QRResult(NamedTuple): + Q: NDArray[Any] + R: NDArray[Any] + +class SlogdetResult(NamedTuple): + # TODO: `sign` and `logabsdet` are scalars for input 2D arrays and + # a `(x.ndim - 2)`` dimensionl arrays otherwise + sign: Any + logabsdet: Any + +class SVDResult(NamedTuple): + U: NDArray[Any] + S: NDArray[Any] + Vh: NDArray[Any] + +@overload +def tensorsolve( + a: _ArrayLikeInt_co, + b: _ArrayLikeInt_co, + axes: Iterable[int] | None = None, +) -> NDArray[float64]: ... +@overload +def tensorsolve( + a: _ArrayLikeFloat_co, + b: _ArrayLikeFloat_co, + axes: Iterable[int] | None = None, +) -> NDArray[floating]: ... +@overload +def tensorsolve( + a: _ArrayLikeComplex_co, + b: _ArrayLikeComplex_co, + axes: Iterable[int] | None = None, +) -> NDArray[complexfloating]: ... + +@overload +def solve( + a: _ArrayLikeInt_co, + b: _ArrayLikeInt_co, +) -> NDArray[float64]: ... +@overload +def solve( + a: _ArrayLikeFloat_co, + b: _ArrayLikeFloat_co, +) -> NDArray[floating]: ... +@overload +def solve( + a: _ArrayLikeComplex_co, + b: _ArrayLikeComplex_co, +) -> NDArray[complexfloating]: ... + +@overload +def tensorinv( + a: _ArrayLikeInt_co, + ind: int = 2, +) -> NDArray[float64]: ... +@overload +def tensorinv( + a: _ArrayLikeFloat_co, + ind: int = 2, +) -> NDArray[floating]: ... +@overload +def tensorinv( + a: _ArrayLikeComplex_co, + ind: int = 2, +) -> NDArray[complexfloating]: ... + +@overload +def inv(a: _ArrayLikeInt_co) -> NDArray[float64]: ... +@overload +def inv(a: _ArrayLikeFloat_co) -> NDArray[floating]: ... +@overload +def inv(a: _ArrayLikeComplex_co) -> NDArray[complexfloating]: ... + +# TODO: The supported input and output dtypes are dependent on the value of `n`. +# For example: `n < 0` always casts integer types to float64 +def matrix_power( + a: _ArrayLikeComplex_co | _ArrayLikeObject_co, + n: SupportsIndex, +) -> NDArray[Any]: ... + +@overload +def cholesky(a: _ArrayLikeInt_co, /, *, upper: bool = False) -> NDArray[float64]: ... +@overload +def cholesky(a: _ArrayLikeFloat_co, /, *, upper: bool = False) -> NDArray[floating]: ... +@overload +def cholesky(a: _ArrayLikeComplex_co, /, *, upper: bool = False) -> NDArray[complexfloating]: ... + +@overload +def outer(x1: _ArrayLike[Never], x2: _ArrayLike[Never], /) -> NDArray[Any]: ... +@overload +def outer(x1: _ArrayLikeBool_co, x2: _ArrayLikeBool_co, /) -> NDArray[np.bool]: ... +@overload +def outer(x1: _ArrayLike[_NumberT], x2: _ArrayLike[_NumberT], /) -> NDArray[_NumberT]: ... +@overload +def outer(x1: _ArrayLikeUInt_co, x2: _ArrayLikeUInt_co, /) -> NDArray[unsignedinteger]: ... +@overload +def outer(x1: _ArrayLikeInt_co, x2: _ArrayLikeInt_co, /) -> NDArray[signedinteger]: ... +@overload +def outer(x1: _ArrayLikeFloat_co, x2: _ArrayLikeFloat_co, /) -> NDArray[floating]: ... +@overload +def outer(x1: _ArrayLikeComplex_co, x2: _ArrayLikeComplex_co, /) -> NDArray[complexfloating]: ... +@overload +def outer(x1: _ArrayLikeTD64_co, x2: _ArrayLikeTD64_co, /) -> NDArray[timedelta64]: ... +@overload +def outer(x1: _ArrayLikeObject_co, x2: _ArrayLikeObject_co, /) -> NDArray[object_]: ... +@overload +def outer( + x1: _ArrayLikeComplex_co | _ArrayLikeTD64_co | _ArrayLikeObject_co, + x2: _ArrayLikeComplex_co | _ArrayLikeTD64_co | _ArrayLikeObject_co, + /, +) -> NDArray[Any]: ... + +@overload +def qr(a: _ArrayLikeInt_co, mode: _ModeKind = "reduced") -> QRResult: ... +@overload +def qr(a: _ArrayLikeFloat_co, mode: _ModeKind = "reduced") -> QRResult: ... +@overload +def qr(a: _ArrayLikeComplex_co, mode: _ModeKind = "reduced") -> QRResult: ... + +@overload +def eigvals(a: _ArrayLikeInt_co) -> NDArray[float64] | NDArray[complex128]: ... +@overload +def eigvals(a: _ArrayLikeFloat_co) -> NDArray[floating] | NDArray[complexfloating]: ... +@overload +def eigvals(a: _ArrayLikeComplex_co) -> NDArray[complexfloating]: ... + +@overload +def eigvalsh(a: _ArrayLikeInt_co, UPLO: L["L", "U", "l", "u"] = "L") -> NDArray[float64]: ... +@overload +def eigvalsh(a: _ArrayLikeComplex_co, UPLO: L["L", "U", "l", "u"] = "L") -> NDArray[floating]: ... + +@overload +def eig(a: _ArrayLikeInt_co) -> EigResult: ... +@overload +def eig(a: _ArrayLikeFloat_co) -> EigResult: ... +@overload +def eig(a: _ArrayLikeComplex_co) -> EigResult: ... + +@overload +def eigh( + a: _ArrayLikeInt_co, + UPLO: L["L", "U", "l", "u"] = "L", +) -> EighResult: ... +@overload +def eigh( + a: _ArrayLikeFloat_co, + UPLO: L["L", "U", "l", "u"] = "L", +) -> EighResult: ... +@overload +def eigh( + a: _ArrayLikeComplex_co, + UPLO: L["L", "U", "l", "u"] = "L", +) -> EighResult: ... + +@overload +def svd( + a: _ArrayLikeInt_co, + full_matrices: bool = True, + compute_uv: L[True] = True, + hermitian: bool = False, +) -> SVDResult: ... +@overload +def svd( + a: _ArrayLikeFloat_co, + full_matrices: bool = True, + compute_uv: L[True] = True, + hermitian: bool = False, +) -> SVDResult: ... +@overload +def svd( + a: _ArrayLikeComplex_co, + full_matrices: bool = True, + compute_uv: L[True] = True, + hermitian: bool = False, +) -> SVDResult: ... +@overload +def svd( + a: _ArrayLikeInt_co, + full_matrices: bool = True, + *, + compute_uv: L[False], + hermitian: bool = False, +) -> NDArray[float64]: ... +@overload +def svd( + a: _ArrayLikeInt_co, + full_matrices: bool, + compute_uv: L[False], + hermitian: bool = False, +) -> NDArray[float64]: ... +@overload +def svd( + a: _ArrayLikeComplex_co, + full_matrices: bool = True, + *, + compute_uv: L[False], + hermitian: bool = False, +) -> NDArray[floating]: ... +@overload +def svd( + a: _ArrayLikeComplex_co, + full_matrices: bool, + compute_uv: L[False], + hermitian: bool = False, +) -> NDArray[floating]: ... + +# the ignored `overload-overlap` mypy error below is a false-positive +@overload +def svdvals( # type: ignore[overload-overlap] + x: _ArrayLike[np.float64 | np.complex128 | np.integer | np.bool] | _NestedSequence[complex], / +) -> NDArray[np.float64]: ... +@overload +def svdvals(x: _ArrayLike[np.float32 | np.complex64], /) -> NDArray[np.float32]: ... +@overload +def svdvals(x: _ArrayLikeNumber_co, /) -> NDArray[floating]: ... + +# TODO: Returns a scalar for 2D arrays and +# a `(x.ndim - 2)`` dimensionl array otherwise +def cond(x: _ArrayLikeComplex_co, p: float | L["fro", "nuc"] | None = None) -> Any: ... + +# TODO: Returns `int` for <2D arrays and `intp` otherwise +def matrix_rank( + A: _ArrayLikeComplex_co, + tol: _ArrayLikeFloat_co | None = None, + hermitian: bool = False, + *, + rtol: _ArrayLikeFloat_co | None = None, +) -> Any: ... + +@overload +def pinv( + a: _ArrayLikeInt_co, + rcond: _ArrayLikeFloat_co | None = None, + hermitian: bool = False, + *, + rtol: _ArrayLikeFloat_co | _NoValueType = ..., +) -> NDArray[float64]: ... +@overload +def pinv( + a: _ArrayLikeFloat_co, + rcond: _ArrayLikeFloat_co | None = None, + hermitian: bool = False, + *, + rtol: _ArrayLikeFloat_co | _NoValueType = ..., +) -> NDArray[floating]: ... +@overload +def pinv( + a: _ArrayLikeComplex_co, + rcond: _ArrayLikeFloat_co | None = None, + hermitian: bool = False, + *, + rtol: _ArrayLikeFloat_co | _NoValueType = ..., +) -> NDArray[complexfloating]: ... + +# TODO: Returns a 2-tuple of scalars for 2D arrays and +# a 2-tuple of `(a.ndim - 2)`` dimensionl arrays otherwise +def slogdet(a: _ArrayLikeComplex_co) -> SlogdetResult: ... + +# TODO: Returns a 2-tuple of scalars for 2D arrays and +# a 2-tuple of `(a.ndim - 2)`` dimensionl arrays otherwise +def det(a: _ArrayLikeComplex_co) -> Any: ... + +@overload +def lstsq(a: _ArrayLikeInt_co, b: _ArrayLikeInt_co, rcond: float | None = None) -> tuple[ + NDArray[float64], + NDArray[float64], + int32, + NDArray[float64], +]: ... +@overload +def lstsq(a: _ArrayLikeFloat_co, b: _ArrayLikeFloat_co, rcond: float | None = None) -> tuple[ + NDArray[floating], + NDArray[floating], + int32, + NDArray[floating], +]: ... +@overload +def lstsq(a: _ArrayLikeComplex_co, b: _ArrayLikeComplex_co, rcond: float | None = None) -> tuple[ + NDArray[complexfloating], + NDArray[floating], + int32, + NDArray[floating], +]: ... + +@overload +def norm( + x: ArrayLike, + ord: float | L["fro", "nuc"] | None = None, + axis: None = None, + keepdims: L[False] = False, +) -> floating: ... +@overload +def norm( + x: ArrayLike, + ord: float | L["fro", "nuc"] | None, + axis: SupportsInt | SupportsIndex | tuple[int, ...] | None, + keepdims: bool = False, +) -> Any: ... +@overload +def norm( + x: ArrayLike, + ord: float | L["fro", "nuc"] | None = None, + *, + axis: SupportsInt | SupportsIndex | tuple[int, ...] | None, + keepdims: bool = False, +) -> Any: ... + +@overload +def matrix_norm( + x: ArrayLike, + /, + *, + ord: float | L["fro", "nuc"] | None = "fro", + keepdims: L[False] = False, +) -> floating: ... +@overload +def matrix_norm( + x: ArrayLike, + /, + *, + ord: float | L["fro", "nuc"] | None = "fro", + keepdims: bool = False, +) -> Any: ... + +@overload +def vector_norm( + x: ArrayLike, + /, + *, + axis: None = None, + ord: float | None = 2, + keepdims: L[False] = False, +) -> floating: ... +@overload +def vector_norm( + x: ArrayLike, + /, + *, + axis: SupportsInt | SupportsIndex | tuple[int, ...], + ord: float | None = 2, + keepdims: bool = False, +) -> Any: ... + +# keep in sync with numpy._core.numeric.tensordot (ignoring `/, *`) +@overload +def tensordot( + a: _ArrayLike[_NumericScalarT], + b: _ArrayLike[_NumericScalarT], + /, + *, + axes: int | tuple[_ShapeLike, _ShapeLike] = 2, +) -> NDArray[_NumericScalarT]: ... +@overload +def tensordot( + a: _ArrayLikeBool_co, + b: _ArrayLikeBool_co, + /, + *, + axes: int | tuple[_ShapeLike, _ShapeLike] = 2, +) -> NDArray[np.bool_]: ... +@overload +def tensordot( + a: _ArrayLikeInt_co, + b: _ArrayLikeInt_co, + /, + *, + axes: int | tuple[_ShapeLike, _ShapeLike] = 2, +) -> NDArray[np.int_ | Any]: ... +@overload +def tensordot( + a: _ArrayLikeFloat_co, + b: _ArrayLikeFloat_co, + /, + *, + axes: int | tuple[_ShapeLike, _ShapeLike] = 2, +) -> NDArray[np.float64 | Any]: ... +@overload +def tensordot( + a: _ArrayLikeComplex_co, + b: _ArrayLikeComplex_co, + /, + *, + axes: int | tuple[_ShapeLike, _ShapeLike] = 2, +) -> NDArray[np.complex128 | Any]: ... + +# TODO: Returns a scalar or array +def multi_dot( + arrays: Iterable[_ArrayLikeComplex_co | _ArrayLikeObject_co | _ArrayLikeTD64_co], + *, + out: NDArray[Any] | None = None, +) -> Any: ... + +def diagonal( + x: ArrayLike, # >= 2D array + /, + *, + offset: SupportsIndex = 0, +) -> NDArray[Any]: ... + +def trace( + x: ArrayLike, # >= 2D array + /, + *, + offset: SupportsIndex = 0, + dtype: DTypeLike | None = None, +) -> Any: ... + +@overload +def cross( + x1: _ArrayLikeUInt_co, + x2: _ArrayLikeUInt_co, + /, + *, + axis: int = -1, +) -> NDArray[unsignedinteger]: ... +@overload +def cross( + x1: _ArrayLikeInt_co, + x2: _ArrayLikeInt_co, + /, + *, + axis: int = -1, +) -> NDArray[signedinteger]: ... +@overload +def cross( + x1: _ArrayLikeFloat_co, + x2: _ArrayLikeFloat_co, + /, + *, + axis: int = -1, +) -> NDArray[floating]: ... +@overload +def cross( + x1: _ArrayLikeComplex_co, + x2: _ArrayLikeComplex_co, + /, + *, + axis: int = -1, +) -> NDArray[complexfloating]: ... + +@overload +def matmul(x1: _ArrayLike[_NumberT], x2: _ArrayLike[_NumberT], /) -> NDArray[_NumberT]: ... +@overload +def matmul(x1: _ArrayLikeUInt_co, x2: _ArrayLikeUInt_co, /) -> NDArray[unsignedinteger]: ... +@overload +def matmul(x1: _ArrayLikeInt_co, x2: _ArrayLikeInt_co, /) -> NDArray[signedinteger]: ... +@overload +def matmul(x1: _ArrayLikeFloat_co, x2: _ArrayLikeFloat_co, /) -> NDArray[floating]: ... +@overload +def matmul(x1: _ArrayLikeComplex_co, x2: _ArrayLikeComplex_co, /) -> NDArray[complexfloating]: ... diff --git a/python/user_packages/Python313/site-packages/numpy/linalg/_umath_linalg.cp313-win_amd64.lib b/python/user_packages/Python313/site-packages/numpy/linalg/_umath_linalg.cp313-win_amd64.lib new file mode 100644 index 0000000000000000000000000000000000000000..4bc4b98defdedef5c67e7725fac8296afb4bc7f0 Binary files /dev/null and b/python/user_packages/Python313/site-packages/numpy/linalg/_umath_linalg.cp313-win_amd64.lib differ diff --git a/python/user_packages/Python313/site-packages/numpy/linalg/_umath_linalg.pyi b/python/user_packages/Python313/site-packages/numpy/linalg/_umath_linalg.pyi new file mode 100644 index 0000000000000000000000000000000000000000..17ef482fead20ddae9bcfc53eae59ec2eefec9f2 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/linalg/_umath_linalg.pyi @@ -0,0 +1,60 @@ +from typing import Final, Literal as L + +import numpy as np +from numpy._typing._ufunc import _GUFunc_Nin2_Nout1 + +__version__: Final[str] = ... +_ilp64: Final[bool] = ... + +### +# 1 -> 1 + +# (m,m) -> () +det: Final[np.ufunc] = ... +# (m,m) -> (m) +cholesky_lo: Final[np.ufunc] = ... +cholesky_up: Final[np.ufunc] = ... +eigvals: Final[np.ufunc] = ... +eigvalsh_lo: Final[np.ufunc] = ... +eigvalsh_up: Final[np.ufunc] = ... +# (m,m) -> (m,m) +inv: Final[np.ufunc] = ... +# (m,n) -> (p) +qr_r_raw: Final[np.ufunc] = ... +svd: Final[np.ufunc] = ... + +### +# 1 -> 2 + +# (m,m) -> (), () +slogdet: Final[np.ufunc] = ... +# (m,m) -> (m), (m,m) +eig: Final[np.ufunc] = ... +eigh_lo: Final[np.ufunc] = ... +eigh_up: Final[np.ufunc] = ... + +### +# 2 -> 1 + +# (m,n), (n) -> (m,m) +qr_complete: Final[_GUFunc_Nin2_Nout1[L["qr_complete"], L[2], None, L["(m,n),(n)->(m,m)"]]] = ... +# (m,n), (k) -> (m,k) +qr_reduced: Final[_GUFunc_Nin2_Nout1[L["qr_reduced"], L[2], None, L["(m,n),(k)->(m,k)"]]] = ... +# (m,m), (m,n) -> (m,n) +solve: Final[_GUFunc_Nin2_Nout1[L["solve"], L[4], None, L["(m,m),(m,n)->(m,n)"]]] = ... +# (m,m), (m) -> (m) +solve1: Final[_GUFunc_Nin2_Nout1[L["solve1"], L[4], None, L["(m,m),(m)->(m)"]]] = ... + +### +# 1 -> 3 + +# (m,n) -> (m,m), (p), (n,n) +svd_f: Final[np.ufunc] = ... +# (m,n) -> (m,p), (p), (p,n) +svd_s: Final[np.ufunc] = ... + +### +# 3 -> 4 + +# (m,n), (m,k), () -> (n,k), (k), (), (p) +lstsq: Final[np.ufunc] = ... diff --git a/python/user_packages/Python313/site-packages/numpy/linalg/lapack_lite.cp313-win_amd64.lib b/python/user_packages/Python313/site-packages/numpy/linalg/lapack_lite.cp313-win_amd64.lib new file mode 100644 index 0000000000000000000000000000000000000000..e286d1fe63f891d8e35688f77937e0927aef1e24 Binary files /dev/null and b/python/user_packages/Python313/site-packages/numpy/linalg/lapack_lite.cp313-win_amd64.lib differ diff --git a/python/user_packages/Python313/site-packages/numpy/linalg/lapack_lite.cp313-win_amd64.pyd b/python/user_packages/Python313/site-packages/numpy/linalg/lapack_lite.cp313-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..44d73914afb078f5ad1e7237015919d13e807862 Binary files /dev/null and b/python/user_packages/Python313/site-packages/numpy/linalg/lapack_lite.cp313-win_amd64.pyd differ diff --git a/python/user_packages/Python313/site-packages/numpy/linalg/lapack_lite.pyi b/python/user_packages/Python313/site-packages/numpy/linalg/lapack_lite.pyi new file mode 100644 index 0000000000000000000000000000000000000000..c341ab8f09b7ccde79adee71d625348d3e726a23 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/linalg/lapack_lite.pyi @@ -0,0 +1,143 @@ +from typing import Final, TypedDict, type_check_only + +import numpy as np +from numpy._typing import NDArray + +from ._linalg import fortran_int + +### + +@type_check_only +class _GELSD(TypedDict): + m: int + n: int + nrhs: int + lda: int + ldb: int + rank: int + lwork: int + info: int + +@type_check_only +class _DGELSD(_GELSD): + dgelsd_: int + rcond: float + +@type_check_only +class _ZGELSD(_GELSD): + zgelsd_: int + +@type_check_only +class _GEQRF(TypedDict): + m: int + n: int + lda: int + lwork: int + info: int + +@type_check_only +class _DGEQRF(_GEQRF): + dgeqrf_: int + +@type_check_only +class _ZGEQRF(_GEQRF): + zgeqrf_: int + +@type_check_only +class _DORGQR(TypedDict): + dorgqr_: int + info: int + +@type_check_only +class _ZUNGQR(TypedDict): + zungqr_: int + info: int + +### + +_ilp64: Final[bool] = ... + +class LapackError(Exception): ... + +def dgelsd( + m: int, + n: int, + nrhs: int, + a: NDArray[np.float64], + lda: int, + b: NDArray[np.float64], + ldb: int, + s: NDArray[np.float64], + rcond: float, + rank: int, + work: NDArray[np.float64], + lwork: int, + iwork: NDArray[fortran_int], + info: int, +) -> _DGELSD: ... +def zgelsd( + m: int, + n: int, + nrhs: int, + a: NDArray[np.complex128], + lda: int, + b: NDArray[np.complex128], + ldb: int, + s: NDArray[np.float64], + rcond: float, + rank: int, + work: NDArray[np.complex128], + lwork: int, + rwork: NDArray[np.float64], + iwork: NDArray[fortran_int], + info: int, +) -> _ZGELSD: ... + +# +def dgeqrf( + m: int, + n: int, + a: NDArray[np.float64], # in/out, shape: (lda, n) + lda: int, + tau: NDArray[np.float64], # out, shape: (min(m, n),) + work: NDArray[np.float64], # out, shape: (max(1, lwork),) + lwork: int, + info: int, # out +) -> _DGEQRF: ... +def zgeqrf( + m: int, + n: int, + a: NDArray[np.complex128], # in/out, shape: (lda, n) + lda: int, + tau: NDArray[np.complex128], # out, shape: (min(m, n),) + work: NDArray[np.complex128], # out, shape: (max(1, lwork),) + lwork: int, + info: int, # out +) -> _ZGEQRF: ... + +# +def dorgqr( + m: int, # >=0 + n: int, # m >= n >= 0 + k: int, # n >= k >= 0 + a: NDArray[np.float64], # in/out, shape: (lda, n) + lda: int, # >= max(1, m) + tau: NDArray[np.float64], # in, shape: (k,) + work: NDArray[np.float64], # out, shape: (max(1, lwork),) + lwork: int, + info: int, # out +) -> _DORGQR: ... +def zungqr( + m: int, + n: int, + k: int, + a: NDArray[np.complex128], + lda: int, + tau: NDArray[np.complex128], + work: NDArray[np.complex128], + lwork: int, + info: int, +) -> _ZUNGQR: ... + +# +def xerbla(srname: object, info: int) -> None: ... diff --git a/python/user_packages/Python313/site-packages/numpy/ma/API_CHANGES.txt b/python/user_packages/Python313/site-packages/numpy/ma/API_CHANGES.txt new file mode 100644 index 0000000000000000000000000000000000000000..48c420ed33554f657ec5a0e2d63635aa1b97f061 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/ma/API_CHANGES.txt @@ -0,0 +1,135 @@ +.. -*- rest -*- + +================================================== +API changes in the new masked array implementation +================================================== + +Masked arrays are subclasses of ndarray +--------------------------------------- + +Contrary to the original implementation, masked arrays are now regular +ndarrays:: + + >>> x = masked_array([1,2,3],mask=[0,0,1]) + >>> print isinstance(x, numpy.ndarray) + True + + +``_data`` returns a view of the masked array +-------------------------------------------- + +Masked arrays are composed of a ``_data`` part and a ``_mask``. Accessing the +``_data`` part will return a regular ndarray or any of its subclass, depending +on the initial data:: + + >>> x = masked_array(numpy.matrix([[1,2],[3,4]]),mask=[[0,0],[0,1]]) + >>> print x._data + [[1 2] + [3 4]] + >>> print type(x._data) + + + +In practice, ``_data`` is implemented as a property, not as an attribute. +Therefore, you cannot access it directly, and some simple tests such as the +following one will fail:: + + >>>x._data is x._data + False + + +``filled(x)`` can return a subclass of ndarray +---------------------------------------------- +The function ``filled(a)`` returns an array of the same type as ``a._data``:: + + >>> x = masked_array(numpy.matrix([[1,2],[3,4]]),mask=[[0,0],[0,1]]) + >>> y = filled(x) + >>> print type(y) + + >>> print y + matrix([[ 1, 2], + [ 3, 999999]]) + + +``put``, ``putmask`` behave like their ndarray counterparts +----------------------------------------------------------- + +Previously, ``putmask`` was used like this:: + + mask = [False,True,True] + x = array([1,4,7],mask=mask) + putmask(x,mask,[3]) + +which translated to:: + + x[~mask] = [3] + +(Note that a ``True``-value in a mask suppresses a value.) + +In other words, the mask had the same length as ``x``, whereas +``values`` had ``sum(~mask)`` elements. + +Now, the behaviour is similar to that of ``ndarray.putmask``, where +the mask and the values are both the same length as ``x``, i.e. + +:: + + putmask(x,mask,[3,0,0]) + + +``fill_value`` is a property +---------------------------- + +``fill_value`` is no longer a method, but a property:: + + >>> print x.fill_value + 999999 + +``cumsum`` and ``cumprod`` ignore missing values +------------------------------------------------ + +Missing values are assumed to be the identity element, i.e. 0 for +``cumsum`` and 1 for ``cumprod``:: + + >>> x = N.ma.array([1,2,3,4],mask=[False,True,False,False]) + >>> print x + [1 -- 3 4] + >>> print x.cumsum() + [1 -- 4 8] + >> print x.cumprod() + [1 -- 3 12] + +``bool(x)`` raises a ValueError +------------------------------- + +Masked arrays now behave like regular ``ndarrays``, in that they cannot be +converted to booleans: + +:: + + >>> x = N.ma.array([1,2,3]) + >>> bool(x) + Traceback (most recent call last): + File "", line 1, in + ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() + + +================================== +New features (non exhaustive list) +================================== + +``mr_`` +------- + +``mr_`` mimics the behavior of ``r_`` for masked arrays:: + + >>> np.ma.mr_[3,4,5] + masked_array(data = [3 4 5], + mask = False, + fill_value=999999) + + +``anom`` +-------- + +The ``anom`` method returns the deviations from the average (anomalies). diff --git a/python/user_packages/Python313/site-packages/numpy/ma/LICENSE b/python/user_packages/Python313/site-packages/numpy/ma/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..f165a0f6dbf57b89e2f6e23b9f042750dde3caab --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/ma/LICENSE @@ -0,0 +1,24 @@ +* Copyright (c) 2006, University of Georgia and Pierre G.F. Gerard-Marchant +* All rights reserved. +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the University of Georgia nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \ No newline at end of file diff --git a/python/user_packages/Python313/site-packages/numpy/ma/README.rst b/python/user_packages/Python313/site-packages/numpy/ma/README.rst new file mode 100644 index 0000000000000000000000000000000000000000..0f39221be7fbcf95ecce6b296cbd16c44ac241e1 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/ma/README.rst @@ -0,0 +1,236 @@ +================================== +A guide to masked arrays in NumPy +================================== + +.. Contents:: + +See http://www.scipy.org/scipy/numpy/wiki/MaskedArray (dead link) +for updates of this document. + + +History +------- + +As a regular user of MaskedArray, I (Pierre G.F. Gerard-Marchant) became +increasingly frustrated with the subclassing of masked arrays (even if +I can only blame my inexperience). I needed to develop a class of arrays +that could store some additional information along with numerical values, +while keeping the possibility for missing data (picture storing a series +of dates along with measurements, what would later become the `TimeSeries +Scikit `__ +(dead link). + +I started to implement such a class, but then quickly realized that +any additional information disappeared when processing these subarrays +(for example, adding a constant value to a subarray would erase its +dates). I ended up writing the equivalent of *numpy.core.ma* for my +particular class, ufuncs included. Everything went fine until I needed to +subclass my new class, when more problems showed up: some attributes of +the new subclass were lost during processing. I identified the culprit as +MaskedArray, which returns masked ndarrays when I expected masked +arrays of my class. I was preparing myself to rewrite *numpy.core.ma* +when I forced myself to learn how to subclass ndarrays. As I became more +familiar with the *__new__* and *__array_finalize__* methods, +I started to wonder why masked arrays were objects, and not ndarrays, +and whether it wouldn't be more convenient for subclassing if they did +behave like regular ndarrays. + +The new *maskedarray* is what I eventually come up with. The +main differences with the initial *numpy.core.ma* package are +that MaskedArray is now a subclass of *ndarray* and that the +*_data* section can now be any subclass of *ndarray*. Apart from a +couple of issues listed below, the behavior of the new MaskedArray +class reproduces the old one. Initially the *maskedarray* +implementation was marginally slower than *numpy.ma* in some areas, +but work is underway to speed it up; the expectation is that it can be +made substantially faster than the present *numpy.ma*. + + +Note that if the subclass has some special methods and +attributes, they are not propagated to the masked version: +this would require a modification of the *__getattribute__* +method (first trying *ndarray.__getattribute__*, then trying +*self._data.__getattribute__* if an exception is raised in the first +place), which really slows things down. + +Main differences +---------------- + + * The *_data* part of the masked array can be any subclass of ndarray (but not recarray, cf below). + * *fill_value* is now a property, not a function. + * in the majority of cases, the mask is forced to *nomask* when no value is actually masked. A notable exception is when a masked array (with no masked values) has just been unpickled. + * I got rid of the *share_mask* flag, I never understood its purpose. + * *put*, *putmask* and *take* now mimic the ndarray methods, to avoid unpleasant surprises. Moreover, *put* and *putmask* both update the mask when needed. * if *a* is a masked array, *bool(a)* raises a *ValueError*, as it does with ndarrays. + * in the same way, the comparison of two masked arrays is a masked array, not a boolean + * *filled(a)* returns an array of the same subclass as *a._data*, and no test is performed on whether it is contiguous or not. + * the mask is always printed, even if it's *nomask*, which makes things easy (for me at least) to remember that a masked array is used. + * *cumsum* works as if the *_data* array was filled with 0. The mask is preserved, but not updated. + * *cumprod* works as if the *_data* array was filled with 1. The mask is preserved, but not updated. + +New features +------------ + +This list is non-exhaustive... + + * the *mr_* function mimics *r_* for masked arrays. + * the *anom* method returns the anomalies (deviations from the average) + +Using the new package with numpy.core.ma +---------------------------------------- + +I tried to make sure that the new package can understand old masked +arrays. Unfortunately, there's no upward compatibility. + +For example: + +>>> import numpy.core.ma as old_ma +>>> import maskedarray as new_ma +>>> x = old_ma.array([1,2,3,4,5], mask=[0,0,1,0,0]) +>>> x +array(data = + [ 1 2 999999 4 5], + mask = + [False False True False False], + fill_value=999999) +>>> y = new_ma.array([1,2,3,4,5], mask=[0,0,1,0,0]) +>>> y +array(data = [1 2 -- 4 5], + mask = [False False True False False], + fill_value=999999) +>>> x==y +array(data = + [True True True True True], + mask = + [False False True False False], + fill_value=?) +>>> old_ma.getmask(x) == new_ma.getmask(x) +array([True, True, True, True, True]) +>>> old_ma.getmask(y) == new_ma.getmask(y) +array([True, True, False, True, True]) +>>> old_ma.getmask(y) +False + + +Using maskedarray with matplotlib +--------------------------------- + +Starting with matplotlib 0.91.2, the masked array importing will work with +the maskedarray branch) as well as with earlier versions. + +By default matplotlib still uses numpy.ma, but there is an rcParams setting +that you can use to select maskedarray instead. In the matplotlibrc file +you will find:: + + #maskedarray : False # True to use external maskedarray module + # instead of numpy.ma; this is a temporary # + setting for testing maskedarray. + + +Uncomment and set to True to select maskedarray everywhere. +Alternatively, you can test a script with maskedarray by using a +command-line option, e.g.:: + + python simple_plot.py --maskedarray + + +Masked records +-------------- + +Like *numpy.ma.core*, the *ndarray*-based implementation +of MaskedArray is limited when working with records: you can +mask any record of the array, but not a field in a record. If you +need this feature, you may want to give the *mrecords* package +a try (available in the *maskedarray* directory in the scipy +sandbox). This module defines a new class, *MaskedRecord*. An +instance of this class accepts a *recarray* as data, and uses two +masks: the *fieldmask* has as many entries as records in the array, +each entry with the same fields as a record, but of boolean types: +they indicate whether the field is masked or not; a record entry +is flagged as masked in the *mask* array if all the fields are +masked. A few examples in the file should give you an idea of what +can be done. Note that *mrecords* is still experimental... + +Optimizing maskedarray +---------------------- + +Should masked arrays be filled before processing or not? +-------------------------------------------------------- + +In the current implementation, most operations on masked arrays involve +the following steps: + + * the input arrays are filled + * the operation is performed on the filled arrays + * the mask is set for the results, from the combination of the input masks and the mask corresponding to the domain of the operation. + +For example, consider the division of two masked arrays:: + + import numpy + import maskedarray as ma + x = ma.array([1,2,3,4],mask=[1,0,0,0], dtype=numpy.float64) + y = ma.array([-1,0,1,2], mask=[0,0,0,1], dtype=numpy.float64) + +The division of x by y is then computed as:: + + d1 = x.filled(0) # d1 = array([0., 2., 3., 4.]) + d2 = y.filled(1) # array([-1., 0., 1., 1.]) + m = ma.mask_or(ma.getmask(x), ma.getmask(y)) # m = + array([True,False,False,True]) + dm = ma.divide.domain(d1,d2) # array([False, True, False, False]) + result = (d1/d2).view(MaskedArray) # masked_array([-0. inf, 3., 4.]) + result._mask = logical_or(m, dm) + +Note that a division by zero takes place. To avoid it, we can consider +to fill the input arrays, taking the domain mask into account, so that:: + + d1 = x._data.copy() # d1 = array([1., 2., 3., 4.]) + d2 = y._data.copy() # array([-1., 0., 1., 2.]) + dm = ma.divide.domain(d1,d2) # array([False, True, False, False]) + numpy.putmask(d2, dm, 1) # d2 = array([-1., 1., 1., 2.]) + m = ma.mask_or(ma.getmask(x), ma.getmask(y)) # m = + array([True,False,False,True]) + result = (d1/d2).view(MaskedArray) # masked_array([-1. 0., 3., 2.]) + result._mask = logical_or(m, dm) + +Note that the *.copy()* is required to avoid updating the inputs with +*putmask*. The *.filled()* method also involves a *.copy()*. + +A third possibility consists in avoid filling the arrays:: + + d1 = x._data # d1 = array([1., 2., 3., 4.]) + d2 = y._data # array([-1., 0., 1., 2.]) + dm = ma.divide.domain(d1,d2) # array([False, True, False, False]) + m = ma.mask_or(ma.getmask(x), ma.getmask(y)) # m = + array([True,False,False,True]) + result = (d1/d2).view(MaskedArray) # masked_array([-1. inf, 3., 2.]) + result._mask = logical_or(m, dm) + +Note that here again the division by zero takes place. + +A quick benchmark gives the following results: + + * *numpy.ma.divide* : 2.69 ms per loop + * classical division : 2.21 ms per loop + * division w/ prefilling : 2.34 ms per loop + * division w/o filling : 1.55 ms per loop + +So, is it worth filling the arrays beforehand ? Yes, if we are interested +in avoiding floating-point exceptions that may fill the result with infs +and nans. No, if we are only interested into speed... + + +Thanks +------ + +I'd like to thank Paul Dubois, Travis Oliphant and Sasha for the +original masked array package: without you, I would never have started +that (it might be argued that I shouldn't have anyway, but that's +another story...). I also wish to extend these thanks to Reggie Dugard +and Eric Firing for their suggestions and numerous improvements. + + +Revision notes +-------------- + + * 08/25/2007 : Creation of this page + * 01/23/2007 : The package has been moved to the SciPy sandbox, and is regularly updated: please check out your SVN version! diff --git a/python/user_packages/Python313/site-packages/numpy/ma/__init__.py b/python/user_packages/Python313/site-packages/numpy/ma/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a7bf916dee43fab000ebf9a0bf2f3a438910a6af --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/ma/__init__.py @@ -0,0 +1,53 @@ +""" +============= +Masked Arrays +============= + +Arrays sometimes contain invalid or missing data. When doing operations +on such arrays, we wish to suppress invalid values, which is the purpose masked +arrays fulfill (an example of typical use is given below). + +For example, examine the following array: + +>>> x = np.array([2, 1, 3, np.nan, 5, 2, 3, np.nan]) + +When we try to calculate the mean of the data, the result is undetermined: + +>>> np.mean(x) +nan + +The mean is calculated using roughly ``np.sum(x)/len(x)``, but since +any number added to ``NaN`` [1]_ produces ``NaN``, this doesn't work. Enter +masked arrays: + +>>> m = np.ma.masked_array(x, np.isnan(x)) +>>> m +masked_array(data=[2.0, 1.0, 3.0, --, 5.0, 2.0, 3.0, --], + mask=[False, False, False, True, False, False, False, True], + fill_value=1e+20) + +Here, we construct a masked array that suppress all ``NaN`` values. We +may now proceed to calculate the mean of the other values: + +>>> np.mean(m) +2.6666666666666665 + +.. [1] Not-a-Number, a floating point value that is the result of an + invalid operation. + +.. moduleauthor:: Pierre Gerard-Marchant +.. moduleauthor:: Jarrod Millman + +""" +from . import core, extras +from .core import * +from .extras import * + +__all__ = ['core', 'extras'] +__all__ += core.__all__ +__all__ += extras.__all__ + +from numpy._pytesttester import PytestTester + +test = PytestTester(__name__) +del PytestTester diff --git a/python/user_packages/Python313/site-packages/numpy/ma/__init__.pyi b/python/user_packages/Python313/site-packages/numpy/ma/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..da977f948327851667b1ab3e3cf346554992861e --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/ma/__init__.pyi @@ -0,0 +1,458 @@ +from . import core, extras +from .core import ( + MAError, + MaskedArray, + MaskError, + MaskType, + abs, + absolute, + add, + all, + allclose, + allequal, + alltrue, + amax, + amin, + angle, + anom, + anomalies, + any, + append, + arange, + arccos, + arccosh, + arcsin, + arcsinh, + arctan, + arctan2, + arctanh, + argmax, + argmin, + argsort, + around, + array, + asanyarray, + asarray, + bitwise_and, + bitwise_or, + bitwise_xor, + bool_, + ceil, + choose, + clip, + common_fill_value, + compress, + compressed, + concatenate, + conjugate, + convolve, + copy, + correlate, + cos, + cosh, + count, + cumprod, + cumsum, + default_fill_value, + diag, + diagonal, + diff, + divide, + empty, + empty_like, + equal, + exp, + expand_dims, + fabs, + filled, + fix_invalid, + flatten_mask, + flatten_structured_array, + floor, + floor_divide, + fmod, + frombuffer, + fromflex, + fromfunction, + getdata, + getmask, + getmaskarray, + greater, + greater_equal, + harden_mask, + hypot, + identity, + ids, + indices, + inner, + innerproduct, + is_mask, + is_masked, + isarray, + isMA, + isMaskedArray, + left_shift, + less, + less_equal, + log, + log2, + log10, + logical_and, + logical_not, + logical_or, + logical_xor, + make_mask, + make_mask_descr, + make_mask_none, + mask_or, + masked, + masked_array, + masked_equal, + masked_greater, + masked_greater_equal, + masked_inside, + masked_invalid, + masked_less, + masked_less_equal, + masked_not_equal, + masked_object, + masked_outside, + masked_print_option, + masked_singleton, + masked_values, + masked_where, + max, + maximum, + maximum_fill_value, + mean, + min, + minimum, + minimum_fill_value, + mod, + multiply, + mvoid, + ndim, + negative, + nomask, + nonzero, + not_equal, + ones, + ones_like, + outer, + outerproduct, + power, + prod, + product, + ptp, + put, + putmask, + ravel, + remainder, + repeat, + reshape, + resize, + right_shift, + round, + round_, + set_fill_value, + shape, + sin, + sinh, + size, + soften_mask, + sometrue, + sort, + sqrt, + squeeze, + std, + subtract, + sum, + swapaxes, + take, + tan, + tanh, + trace, + transpose, + true_divide, + var, + where, + zeros, + zeros_like, +) +from .extras import ( + apply_along_axis, + apply_over_axes, + atleast_1d, + atleast_2d, + atleast_3d, + average, + clump_masked, + clump_unmasked, + column_stack, + compress_cols, + compress_nd, + compress_rowcols, + compress_rows, + corrcoef, + count_masked, + cov, + diagflat, + dot, + dstack, + ediff1d, + flatnotmasked_contiguous, + flatnotmasked_edges, + hsplit, + hstack, + in1d, + intersect1d, + isin, + mask_cols, + mask_rowcols, + mask_rows, + masked_all, + masked_all_like, + median, + mr_, + ndenumerate, + notmasked_contiguous, + notmasked_edges, + polyfit, + row_stack, + setdiff1d, + setxor1d, + stack, + union1d, + unique, + vander, + vstack, +) + +__all__ = [ + "core", + "extras", + "MAError", + "MaskError", + "MaskType", + "MaskedArray", + "abs", + "absolute", + "add", + "all", + "allclose", + "allequal", + "alltrue", + "amax", + "amin", + "angle", + "anom", + "anomalies", + "any", + "append", + "arange", + "arccos", + "arccosh", + "arcsin", + "arcsinh", + "arctan", + "arctan2", + "arctanh", + "argmax", + "argmin", + "argsort", + "around", + "array", + "asanyarray", + "asarray", + "bitwise_and", + "bitwise_or", + "bitwise_xor", + "bool_", + "ceil", + "choose", + "clip", + "common_fill_value", + "compress", + "compressed", + "concatenate", + "conjugate", + "convolve", + "copy", + "correlate", + "cos", + "cosh", + "count", + "cumprod", + "cumsum", + "default_fill_value", + "diag", + "diagonal", + "diff", + "divide", + "empty", + "empty_like", + "equal", + "exp", + "expand_dims", + "fabs", + "filled", + "fix_invalid", + "flatten_mask", + "flatten_structured_array", + "floor", + "floor_divide", + "fmod", + "frombuffer", + "fromflex", + "fromfunction", + "getdata", + "getmask", + "getmaskarray", + "greater", + "greater_equal", + "harden_mask", + "hypot", + "identity", + "ids", + "indices", + "inner", + "innerproduct", + "isMA", + "isMaskedArray", + "is_mask", + "is_masked", + "isarray", + "left_shift", + "less", + "less_equal", + "log", + "log10", + "log2", + "logical_and", + "logical_not", + "logical_or", + "logical_xor", + "make_mask", + "make_mask_descr", + "make_mask_none", + "mask_or", + "masked", + "masked_array", + "masked_equal", + "masked_greater", + "masked_greater_equal", + "masked_inside", + "masked_invalid", + "masked_less", + "masked_less_equal", + "masked_not_equal", + "masked_object", + "masked_outside", + "masked_print_option", + "masked_singleton", + "masked_values", + "masked_where", + "max", + "maximum", + "maximum_fill_value", + "mean", + "min", + "minimum", + "minimum_fill_value", + "mod", + "multiply", + "mvoid", + "ndim", + "negative", + "nomask", + "nonzero", + "not_equal", + "ones", + "ones_like", + "outer", + "outerproduct", + "power", + "prod", + "product", + "ptp", + "put", + "putmask", + "ravel", + "remainder", + "repeat", + "reshape", + "resize", + "right_shift", + "round", + "round_", + "set_fill_value", + "shape", + "sin", + "sinh", + "size", + "soften_mask", + "sometrue", + "sort", + "sqrt", + "squeeze", + "std", + "subtract", + "sum", + "swapaxes", + "take", + "tan", + "tanh", + "trace", + "transpose", + "true_divide", + "var", + "where", + "zeros", + "zeros_like", + "apply_along_axis", + "apply_over_axes", + "atleast_1d", + "atleast_2d", + "atleast_3d", + "average", + "clump_masked", + "clump_unmasked", + "column_stack", + "compress_cols", + "compress_nd", + "compress_rowcols", + "compress_rows", + "count_masked", + "corrcoef", + "cov", + "diagflat", + "dot", + "dstack", + "ediff1d", + "flatnotmasked_contiguous", + "flatnotmasked_edges", + "hsplit", + "hstack", + "isin", + "in1d", + "intersect1d", + "mask_cols", + "mask_rowcols", + "mask_rows", + "masked_all", + "masked_all_like", + "median", + "mr_", + "ndenumerate", + "notmasked_contiguous", + "notmasked_edges", + "polyfit", + "row_stack", + "setdiff1d", + "setxor1d", + "stack", + "unique", + "union1d", + "vander", + "vstack", +] diff --git a/python/user_packages/Python313/site-packages/numpy/ma/core.py b/python/user_packages/Python313/site-packages/numpy/ma/core.py new file mode 100644 index 0000000000000000000000000000000000000000..e272d2f6adcb7c8e7cd0521fabc56278be2a2e93 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/ma/core.py @@ -0,0 +1,8929 @@ +""" +numpy.ma : a package to handle missing or invalid values. + +This package was initially written for numarray by Paul F. Dubois +at Lawrence Livermore National Laboratory. +In 2006, the package was completely rewritten by Pierre Gerard-Marchant +(University of Georgia) to make the MaskedArray class a subclass of ndarray, +and to improve support of structured arrays. + + +Copyright 1999, 2000, 2001 Regents of the University of California. +Released for unlimited redistribution. + +* Adapted for numpy_core 2005 by Travis Oliphant and (mainly) Paul Dubois. +* Subclassing of the base `ndarray` 2006 by Pierre Gerard-Marchant + (pgmdevlist_AT_gmail_DOT_com) +* Improvements suggested by Reggie Dugard (reggie_AT_merfinllc_DOT_com) + +.. moduleauthor:: Pierre Gerard-Marchant + +""" +import builtins +import functools +import inspect +import operator +import re +import textwrap +import warnings + +import numpy as np +import numpy._core.numerictypes as ntypes +import numpy._core.umath as umath +from numpy import ( + _NoValue, + amax, + amin, + angle, + array as narray, # noqa: F401 + bool_, + expand_dims, + finfo, # noqa: F401 + iinfo, # noqa: F401 + iscomplexobj, + ndarray, +) +from numpy._core import multiarray as mu +from numpy._core.numeric import normalize_axis_tuple +from numpy._utils import set_module + +__all__ = [ + 'MAError', 'MaskError', 'MaskType', 'MaskedArray', 'abs', 'absolute', + 'add', 'all', 'allclose', 'allequal', 'alltrue', 'amax', 'amin', + 'angle', 'anom', 'anomalies', 'any', 'append', 'arange', 'arccos', + 'arccosh', 'arcsin', 'arcsinh', 'arctan', 'arctan2', 'arctanh', + 'argmax', 'argmin', 'argsort', 'around', 'array', 'asanyarray', + 'asarray', 'bitwise_and', 'bitwise_or', 'bitwise_xor', 'bool_', 'ceil', + 'choose', 'clip', 'common_fill_value', 'compress', 'compressed', + 'concatenate', 'conjugate', 'convolve', 'copy', 'correlate', 'cos', 'cosh', + 'count', 'cumprod', 'cumsum', 'default_fill_value', 'diag', 'diagonal', + 'diff', 'divide', 'empty', 'empty_like', 'equal', 'exp', + 'expand_dims', 'fabs', 'filled', 'fix_invalid', 'flatten_mask', + 'flatten_structured_array', 'floor', 'floor_divide', 'fmod', + 'frombuffer', 'fromflex', 'fromfunction', 'getdata', 'getmask', + 'getmaskarray', 'greater', 'greater_equal', 'harden_mask', 'hypot', + 'identity', 'ids', 'indices', 'inner', 'innerproduct', 'isMA', + 'isMaskedArray', 'is_mask', 'is_masked', 'isarray', 'left_shift', + 'less', 'less_equal', 'log', 'log10', 'log2', + 'logical_and', 'logical_not', 'logical_or', 'logical_xor', 'make_mask', + 'make_mask_descr', 'make_mask_none', 'mask_or', 'masked', + 'masked_array', 'masked_equal', 'masked_greater', + 'masked_greater_equal', 'masked_inside', 'masked_invalid', + 'masked_less', 'masked_less_equal', 'masked_not_equal', + 'masked_object', 'masked_outside', 'masked_print_option', + 'masked_singleton', 'masked_values', 'masked_where', 'max', 'maximum', + 'maximum_fill_value', 'mean', 'min', 'minimum', 'minimum_fill_value', + 'mod', 'multiply', 'mvoid', 'ndim', 'negative', 'nomask', 'nonzero', + 'not_equal', 'ones', 'ones_like', 'outer', 'outerproduct', 'power', 'prod', + 'product', 'ptp', 'put', 'putmask', 'ravel', 'remainder', + 'repeat', 'reshape', 'resize', 'right_shift', 'round', 'round_', + 'set_fill_value', 'shape', 'sin', 'sinh', 'size', 'soften_mask', + 'sometrue', 'sort', 'sqrt', 'squeeze', 'std', 'subtract', 'sum', + 'swapaxes', 'take', 'tan', 'tanh', 'trace', 'transpose', 'true_divide', + 'var', 'where', 'zeros', 'zeros_like', + ] + +MaskType = np.bool +nomask = MaskType(0) + +class MaskedArrayFutureWarning(FutureWarning): + pass + +def _deprecate_argsort_axis(arr): + """ + Adjust the axis passed to argsort, warning if necessary + + Parameters + ---------- + arr + The array which argsort was called on + + np.ma.argsort has a long-term bug where the default of the axis argument + is wrong (gh-8701), which now must be kept for backwards compatibility. + Thankfully, this only makes a difference when arrays are 2- or more- + dimensional, so we only need a warning then. + """ + if arr.ndim <= 1: + # no warning needed - but switch to -1 anyway, to avoid surprising + # subclasses, which are more likely to implement scalar axes. + return -1 + else: + # 2017-04-11, Numpy 1.13.0, gh-8701: warn on axis default + warnings.warn( + "In the future the default for argsort will be axis=-1, not the " + "current None, to match its documentation and np.argsort. " + "Explicitly pass -1 or None to silence this warning.", + MaskedArrayFutureWarning, stacklevel=3) + return None + + +def doc_note(initialdoc, note): + """ + Adds a Notes section to an existing docstring. + + """ + if initialdoc is None: + return + if note is None: + return initialdoc + + notesplit = re.split(r'\n\s*?Notes\n\s*?-----', inspect.cleandoc(initialdoc)) + notedoc = f"\n\nNotes\n-----\n{inspect.cleandoc(note)}\n" + + return ''.join(notesplit[:1] + [notedoc] + notesplit[1:]) + + +############################################################################### +# Exceptions # +############################################################################### + + +class MAError(Exception): + """ + Class for masked array related errors. + + """ + pass + + +class MaskError(MAError): + """ + Class for mask related errors. + + """ + pass + + +############################################################################### +# Filling options # +############################################################################### + + +# b: boolean - c: complex - f: floats - i: integer - O: object - S: string +default_filler = {'b': True, + 'c': 1.e20 + 0.0j, + 'f': 1.e20, + 'i': 999999, + 'O': '?', + 'S': b'N/A', + 'u': 999999, + 'V': b'???', + 'U': 'N/A', + 'T': 'N/A' + } + +# Add datetime64 and timedelta64 types +for v in ["Y", "M", "W", "D", "h", "m", "s", "ms", "us", "ns", "ps", + "fs", "as"]: + default_filler["M8[" + v + "]"] = np.datetime64("NaT", v) + default_filler["m8[" + v + "]"] = np.timedelta64("NaT", v) + +float_types_list = [np.half, np.single, np.double, np.longdouble, + np.csingle, np.cdouble, np.clongdouble] + +_minvals: dict[type, int] = {} +_maxvals: dict[type, int] = {} + +for sctype in ntypes.sctypeDict.values(): + scalar_dtype = np.dtype(sctype) + + if scalar_dtype.kind in "Mm": + info = np.iinfo(np.int64) + min_val, max_val = info.min + 1, info.max + elif np.issubdtype(scalar_dtype, np.integer): + info = np.iinfo(sctype) + min_val, max_val = info.min, info.max + elif np.issubdtype(scalar_dtype, np.floating): + info = np.finfo(sctype) + min_val, max_val = info.min, info.max + elif scalar_dtype.kind == "b": + min_val, max_val = 0, 1 + else: + min_val, max_val = None, None + + _minvals[sctype] = min_val + _maxvals[sctype] = max_val + +max_filler = _minvals +max_filler.update([(k, -np.inf) for k in float_types_list[:4]]) +max_filler.update([(k, complex(-np.inf, -np.inf)) for k in float_types_list[-3:]]) + +min_filler = _maxvals +min_filler.update([(k, +np.inf) for k in float_types_list[:4]]) +min_filler.update([(k, complex(+np.inf, +np.inf)) for k in float_types_list[-3:]]) + +del float_types_list + +def _recursive_fill_value(dtype, f): + """ + Recursively produce a fill value for `dtype`, calling f on scalar dtypes + """ + if dtype.names is not None: + # We wrap into `array` here, which ensures we use NumPy cast rules + # for integer casts, this allows the use of 99999 as a fill value + # for int8. + # TODO: This is probably a mess, but should best preserve behavior? + vals = tuple( + np.array(_recursive_fill_value(dtype[name], f)) + for name in dtype.names) + return np.array(vals, dtype=dtype)[()] # decay to void scalar from 0d + elif dtype.subdtype: + subtype, shape = dtype.subdtype + subval = _recursive_fill_value(subtype, f) + return np.full(shape, subval) + else: + return f(dtype) + + +def _get_dtype_of(obj): + """ Convert the argument for *_fill_value into a dtype """ + if isinstance(obj, np.dtype): + return obj + elif hasattr(obj, 'dtype'): + return obj.dtype + else: + return np.asanyarray(obj).dtype + + +def default_fill_value(obj): + """ + Return the default fill value for the argument object. + + The default filling value depends on the datatype of the input + array or the type of the input scalar: + + =========== ======== + datatype default + =========== ======== + bool True + int 999999 + float 1.e20 + complex 1.e20+0j + object '?' + string 'N/A' + StringDType 'N/A' + =========== ======== + + For structured types, a structured scalar is returned, with each field the + default fill value for its type. + + For subarray types, the fill value is an array of the same size containing + the default scalar fill value. + + Parameters + ---------- + obj : ndarray, dtype or scalar + The array data-type or scalar for which the default fill value + is returned. + + Returns + ------- + fill_value : scalar + The default fill value. + + Examples + -------- + >>> import numpy as np + >>> np.ma.default_fill_value(1) + 999999 + >>> np.ma.default_fill_value(np.array([1.1, 2., np.pi])) + 1e+20 + >>> np.ma.default_fill_value(np.dtype(complex)) + (1e+20+0j) + + """ + def _scalar_fill_value(dtype): + if dtype.kind in 'Mm': + return default_filler.get(dtype.str[1:], '?') + else: + return default_filler.get(dtype.kind, '?') + + dtype = _get_dtype_of(obj) + return _recursive_fill_value(dtype, _scalar_fill_value) + + +def _extremum_fill_value(obj, extremum, extremum_name): + + def _scalar_fill_value(dtype): + try: + return extremum[dtype.type] + except KeyError as e: + raise TypeError( + f"Unsuitable type {dtype} for calculating {extremum_name}." + ) from None + + dtype = _get_dtype_of(obj) + return _recursive_fill_value(dtype, _scalar_fill_value) + + +def minimum_fill_value(obj): + """ + Return the maximum value that can be represented by the dtype of an object. + + This function is useful for calculating a fill value suitable for + taking the minimum of an array with a given dtype. + + Parameters + ---------- + obj : ndarray, dtype or scalar + An object that can be queried for it's numeric type. + + Returns + ------- + val : scalar + The maximum representable value. + + Raises + ------ + TypeError + If `obj` isn't a suitable numeric type. + + See Also + -------- + maximum_fill_value : The inverse function. + set_fill_value : Set the filling value of a masked array. + MaskedArray.fill_value : Return current fill value. + + Examples + -------- + >>> import numpy as np + >>> import numpy.ma as ma + >>> a = np.int8() + >>> ma.minimum_fill_value(a) + 127 + >>> a = np.int32() + >>> ma.minimum_fill_value(a) + 2147483647 + + An array of numeric data can also be passed. + + >>> a = np.array([1, 2, 3], dtype=np.int8) + >>> ma.minimum_fill_value(a) + 127 + >>> a = np.array([1, 2, 3], dtype=np.float32) + >>> ma.minimum_fill_value(a) + inf + + """ + return _extremum_fill_value(obj, min_filler, "minimum") + + +def maximum_fill_value(obj): + """ + Return the minimum value that can be represented by the dtype of an object. + + This function is useful for calculating a fill value suitable for + taking the maximum of an array with a given dtype. + + Parameters + ---------- + obj : ndarray, dtype or scalar + An object that can be queried for it's numeric type. + + Returns + ------- + val : scalar + The minimum representable value. + + Raises + ------ + TypeError + If `obj` isn't a suitable numeric type. + + See Also + -------- + minimum_fill_value : The inverse function. + set_fill_value : Set the filling value of a masked array. + MaskedArray.fill_value : Return current fill value. + + Examples + -------- + >>> import numpy as np + >>> import numpy.ma as ma + >>> a = np.int8() + >>> ma.maximum_fill_value(a) + -128 + >>> a = np.int32() + >>> ma.maximum_fill_value(a) + -2147483648 + + An array of numeric data can also be passed. + + >>> a = np.array([1, 2, 3], dtype=np.int8) + >>> ma.maximum_fill_value(a) + -128 + >>> a = np.array([1, 2, 3], dtype=np.float32) + >>> ma.maximum_fill_value(a) + -inf + + """ + return _extremum_fill_value(obj, max_filler, "maximum") + + +def _recursive_set_fill_value(fillvalue, dt): + """ + Create a fill value for a structured dtype. + + Parameters + ---------- + fillvalue : scalar or array_like + Scalar or array representing the fill value. If it is of shorter + length than the number of fields in dt, it will be resized. + dt : dtype + The structured dtype for which to create the fill value. + + Returns + ------- + val : tuple + A tuple of values corresponding to the structured fill value. + + """ + fillvalue = np.resize(fillvalue, len(dt.names)) + output_value = [] + for (fval, name) in zip(fillvalue, dt.names): + cdtype = dt[name] + if cdtype.subdtype: + cdtype = cdtype.subdtype[0] + + if cdtype.names is not None: + output_value.append(tuple(_recursive_set_fill_value(fval, cdtype))) + else: + output_value.append(np.array(fval, dtype=cdtype).item()) + return tuple(output_value) + + +def _check_fill_value(fill_value, ndtype): + """ + Private function validating the given `fill_value` for the given dtype. + + If fill_value is None, it is set to the default corresponding to the dtype. + + If fill_value is not None, its value is forced to the given dtype. + + The result is always a 0d array. + + """ + ndtype = np.dtype(ndtype) + if fill_value is None: + fill_value = default_fill_value(ndtype) + # TODO: It seems better to always store a valid fill_value, the oddity + # about is that `_fill_value = None` would behave even more + # different then. + # (e.g. this allows arr_uint8.astype(int64) to have the default + # fill value again...) + # The one thing that changed in 2.0/2.1 around cast safety is that the + # default `int(99...)` is not a same-kind cast anymore, so if we + # have a uint, use the default uint. + if ndtype.kind == "u": + fill_value = np.uint(fill_value) + elif ndtype.names is not None: + if isinstance(fill_value, (ndarray, np.void)): + try: + fill_value = np.asarray(fill_value, dtype=ndtype) + except ValueError as e: + err_msg = "Unable to transform %s to dtype %s" + raise ValueError(err_msg % (fill_value, ndtype)) from e + else: + fill_value = np.asarray(fill_value, dtype=object) + fill_value = np.array(_recursive_set_fill_value(fill_value, ndtype), + dtype=ndtype) + elif isinstance(fill_value, str) and (ndtype.char not in 'OSTVU'): + # Note this check doesn't work if fill_value is not a scalar + err_msg = "Cannot set fill value of string with array of dtype %s" + raise TypeError(err_msg % ndtype) + else: + # In case we want to convert 1e20 to int. + # Also in case of converting string arrays. + try: + fill_value = np.asarray(fill_value, dtype=ndtype) + except (OverflowError, ValueError) as e: + # Raise TypeError instead of OverflowError or ValueError. + # OverflowError is seldom used, and the real problem here is + # that the passed fill_value is not compatible with the ndtype. + err_msg = "Cannot convert fill_value %s to dtype %s" + raise TypeError(err_msg % (fill_value, ndtype)) from e + return np.array(fill_value) + + +def set_fill_value(a, fill_value): + """ + Set the filling value of a, if a is a masked array. + + This function changes the fill value of the masked array `a` in place. + If `a` is not a masked array, the function returns silently, without + doing anything. + + Parameters + ---------- + a : array_like + Input array. + fill_value : dtype + Filling value. A consistency test is performed to make sure + the value is compatible with the dtype of `a`. + + Returns + ------- + None + Nothing returned by this function. + + See Also + -------- + maximum_fill_value : Return the default fill value for a dtype. + MaskedArray.fill_value : Return current fill value. + MaskedArray.set_fill_value : Equivalent method. + + Examples + -------- + >>> import numpy as np + >>> import numpy.ma as ma + >>> a = np.arange(5) + >>> a + array([0, 1, 2, 3, 4]) + >>> a = ma.masked_where(a < 3, a) + >>> a + masked_array(data=[--, --, --, 3, 4], + mask=[ True, True, True, False, False], + fill_value=999999) + >>> ma.set_fill_value(a, -999) + >>> a + masked_array(data=[--, --, --, 3, 4], + mask=[ True, True, True, False, False], + fill_value=-999) + + Nothing happens if `a` is not a masked array. + + >>> a = list(range(5)) + >>> a + [0, 1, 2, 3, 4] + >>> ma.set_fill_value(a, 100) + >>> a + [0, 1, 2, 3, 4] + >>> a = np.arange(5) + >>> a + array([0, 1, 2, 3, 4]) + >>> ma.set_fill_value(a, 100) + >>> a + array([0, 1, 2, 3, 4]) + + """ + if isinstance(a, MaskedArray): + a.set_fill_value(fill_value) + + +def get_fill_value(a): + """ + Return the filling value of a, if any. Otherwise, returns the + default filling value for that type. + + """ + if isinstance(a, MaskedArray): + result = a.fill_value + else: + result = default_fill_value(a) + return result + + +def common_fill_value(a, b): + """ + Return the common filling value of two masked arrays, if any. + + If ``a.fill_value == b.fill_value``, return the fill value, + otherwise return None. + + Parameters + ---------- + a, b : MaskedArray + The masked arrays for which to compare fill values. + + Returns + ------- + fill_value : scalar or None + The common fill value, or None. + + Examples + -------- + >>> import numpy as np + >>> x = np.ma.array([0, 1.], fill_value=3) + >>> y = np.ma.array([0, 1.], fill_value=3) + >>> np.ma.common_fill_value(x, y) + 3.0 + + """ + t1 = get_fill_value(a) + t2 = get_fill_value(b) + if t1 == t2: + return t1 + return None + + +def filled(a, fill_value=None): + """ + Return input as an `~numpy.ndarray`, with masked values replaced by + `fill_value`. + + If `a` is not a `MaskedArray`, `a` itself is returned. + If `a` is a `MaskedArray` with no masked values, then ``a.data`` is + returned. + If `a` is a `MaskedArray` and `fill_value` is None, `fill_value` is set to + ``a.fill_value``. + + Parameters + ---------- + a : MaskedArray or array_like + An input object. + fill_value : array_like, optional. + Can be scalar or non-scalar. If non-scalar, the + resulting filled array should be broadcastable + over input array. Default is None. + + Returns + ------- + a : ndarray + The filled array. + + See Also + -------- + compressed + + Examples + -------- + >>> import numpy as np + >>> import numpy.ma as ma + >>> x = ma.array(np.arange(9).reshape(3, 3), mask=[[1, 0, 0], + ... [1, 0, 0], + ... [0, 0, 0]]) + >>> x.filled() + array([[999999, 1, 2], + [999999, 4, 5], + [ 6, 7, 8]]) + >>> x.filled(fill_value=333) + array([[333, 1, 2], + [333, 4, 5], + [ 6, 7, 8]]) + >>> x.filled(fill_value=np.arange(3)) + array([[0, 1, 2], + [0, 4, 5], + [6, 7, 8]]) + + """ + if hasattr(a, 'filled'): + return a.filled(fill_value) + + elif isinstance(a, ndarray): + # Should we check for contiguity ? and a.flags['CONTIGUOUS']: + return a + elif isinstance(a, dict): + return np.array(a, 'O') + else: + return np.array(a) + + +def get_masked_subclass(*arrays): + """ + Return the youngest subclass of MaskedArray from a list of (masked) arrays. + + In case of siblings, the first listed takes over. + + """ + if len(arrays) == 1: + arr = arrays[0] + if isinstance(arr, MaskedArray): + rcls = type(arr) + else: + rcls = MaskedArray + else: + arrcls = [type(a) for a in arrays] + rcls = arrcls[0] + if not issubclass(rcls, MaskedArray): + rcls = MaskedArray + for cls in arrcls[1:]: + if issubclass(cls, rcls): + rcls = cls + # Don't return MaskedConstant as result: revert to MaskedArray + if rcls.__name__ == 'MaskedConstant': + return MaskedArray + return rcls + + +def getdata(a, subok=True): + """ + Return the data of a masked array as an ndarray. + + Return the data of `a` (if any) as an ndarray if `a` is a ``MaskedArray``, + else return `a` as a ndarray or subclass (depending on `subok`) if not. + + Parameters + ---------- + a : array_like + Input ``MaskedArray``, alternatively a ndarray or a subclass thereof. + subok : bool + Whether to force the output to be a `pure` ndarray (False) or to + return a subclass of ndarray if appropriate (True, default). + + See Also + -------- + getmask : Return the mask of a masked array, or nomask. + getmaskarray : Return the mask of a masked array, or full array of False. + + Examples + -------- + >>> import numpy as np + >>> import numpy.ma as ma + >>> a = ma.masked_equal([[1,2],[3,4]], 2) + >>> a + masked_array( + data=[[1, --], + [3, 4]], + mask=[[False, True], + [False, False]], + fill_value=2) + >>> ma.getdata(a) + array([[1, 2], + [3, 4]]) + + Equivalently use the ``MaskedArray`` `data` attribute. + + >>> a.data + array([[1, 2], + [3, 4]]) + + """ + try: + data = a._data + except AttributeError: + data = np.array(a, copy=None, subok=subok) + if not subok: + return data.view(ndarray) + return data + + +get_data = getdata + + +def fix_invalid(a, mask=nomask, copy=True, fill_value=None): + """ + Return input with invalid data masked and replaced by a fill value. + + Invalid data means values of `nan`, `inf`, etc. + + Parameters + ---------- + a : array_like + Input array, a (subclass of) ndarray. + mask : sequence, optional + Mask. Must be convertible to an array of booleans with the same + shape as `data`. True indicates a masked (i.e. invalid) data. + copy : bool, optional + Whether to use a copy of `a` (True) or to fix `a` in place (False). + Default is True. + fill_value : scalar, optional + Value used for fixing invalid data. Default is None, in which case + the ``a.fill_value`` is used. + + Returns + ------- + b : MaskedArray + The input array with invalid entries fixed. + + Notes + ----- + A copy is performed by default. + + Examples + -------- + >>> import numpy as np + >>> x = np.ma.array([1., -1, np.nan, np.inf], mask=[1] + [0]*3) + >>> x + masked_array(data=[--, -1.0, nan, inf], + mask=[ True, False, False, False], + fill_value=1e+20) + >>> np.ma.fix_invalid(x) + masked_array(data=[--, -1.0, --, --], + mask=[ True, False, True, True], + fill_value=1e+20) + + >>> fixed = np.ma.fix_invalid(x) + >>> fixed.data + array([ 1.e+00, -1.e+00, 1.e+20, 1.e+20]) + >>> x.data + array([ 1., -1., nan, inf]) + + """ + a = masked_array(a, copy=copy, mask=mask, subok=True) + invalid = np.logical_not(np.isfinite(a._data)) + if not invalid.any(): + return a + a._mask |= invalid + if fill_value is None: + fill_value = a.fill_value + a._data[invalid] = fill_value + return a + +def is_string_or_list_of_strings(val): + return (isinstance(val, str) or + (isinstance(val, list) and val and + builtins.all(isinstance(s, str) for s in val))) + +############################################################################### +# Ufuncs # +############################################################################### + + +ufunc_domain = {} +ufunc_fills = {} + + +class _DomainCheckInterval: + """ + Define a valid interval, so that : + + ``domain_check_interval(a,b)(x) == True`` where + ``x < a`` or ``x > b``. + + """ + + def __init__(self, a, b): + "domain_check_interval(a,b)(x) = true where x < a or y > b" + if a > b: + (a, b) = (b, a) + self.a = a + self.b = b + + def __call__(self, x): + "Execute the call behavior." + # nans at masked positions cause RuntimeWarnings, even though + # they are masked. To avoid this we suppress warnings. + with np.errstate(invalid='ignore'): + return umath.logical_or(umath.greater(x, self.b), + umath.less(x, self.a)) + + +class _DomainTan: + """ + Define a valid interval for the `tan` function, so that: + + ``domain_tan(eps) = True`` where ``abs(cos(x)) < eps`` + + """ + + def __init__(self, eps): + "domain_tan(eps) = true where abs(cos(x)) < eps)" + self.eps = eps + + def __call__(self, x): + "Executes the call behavior." + with np.errstate(invalid='ignore'): + return umath.less(umath.absolute(umath.cos(x)), self.eps) + + +class _DomainSafeDivide: + """ + Define a domain for safe division. + + """ + + def __init__(self, tolerance=None): + self.tolerance = tolerance + + def __call__(self, a, b): + # Delay the selection of the tolerance to here in order to reduce numpy + # import times. The calculation of these parameters is a substantial + # component of numpy's import time. + if self.tolerance is None: + self.tolerance = np.finfo(float).tiny + # don't call ma ufuncs from __array_wrap__ which would fail for scalars + a, b = np.asarray(a), np.asarray(b) + with np.errstate(all='ignore'): + return umath.absolute(a) * self.tolerance >= umath.absolute(b) + + +class _DomainGreater: + """ + DomainGreater(v)(x) is True where x <= v. + + """ + + def __init__(self, critical_value): + "DomainGreater(v)(x) = true where x <= v" + self.critical_value = critical_value + + def __call__(self, x): + "Executes the call behavior." + with np.errstate(invalid='ignore'): + return umath.less_equal(x, self.critical_value) + + +class _DomainGreaterEqual: + """ + DomainGreaterEqual(v)(x) is True where x < v. + + """ + + def __init__(self, critical_value): + "DomainGreaterEqual(v)(x) = true where x < v" + self.critical_value = critical_value + + def __call__(self, x): + "Executes the call behavior." + with np.errstate(invalid='ignore'): + return umath.less(x, self.critical_value) + + +class _MaskedUFunc: + def __init__(self, ufunc): + self.f = ufunc + self.__doc__ = ufunc.__doc__ + self.__name__ = ufunc.__name__ + self.__qualname__ = ufunc.__qualname__ + + def __str__(self): + return f"Masked version of {self.f}" + + +class _MaskedUnaryOperation(_MaskedUFunc): + """ + Defines masked version of unary operations, where invalid values are + pre-masked. + + Parameters + ---------- + mufunc : callable + The function for which to define a masked version. Made available + as ``_MaskedUnaryOperation.f``. + fill : scalar, optional + Filling value, default is 0. + domain : class instance + Domain for the function. Should be one of the ``_Domain*`` + classes. Default is None. + + """ + + def __init__(self, mufunc, fill=0, domain=None): + super().__init__(mufunc) + self.fill = fill + self.domain = domain + ufunc_domain[mufunc] = domain + ufunc_fills[mufunc] = fill + + def __call__(self, a, *args, **kwargs): + """ + Execute the call behavior. + + """ + d = getdata(a) + # Deal with domain + if self.domain is not None: + # Case 1.1. : Domained function + # nans at masked positions cause RuntimeWarnings, even though + # they are masked. To avoid this we suppress warnings. + with np.errstate(divide='ignore', invalid='ignore'): + result = self.f(d, *args, **kwargs) + # Make a mask + m = ~umath.isfinite(result) + m |= self.domain(d) + m |= getmask(a) + else: + # Case 1.2. : Function without a domain + # Get the result and the mask + with np.errstate(divide='ignore', invalid='ignore'): + result = self.f(d, *args, **kwargs) + m = getmask(a) + + if not result.ndim: + # Case 2.1. : The result is scalarscalar + if m: + return masked + return result + + if m is not nomask: + # Case 2.2. The result is an array + # We need to fill the invalid data back w/ the input Now, + # that's plain silly: in C, we would just skip the element and + # keep the original, but we do have to do it that way in Python + + # In case result has a lower dtype than the inputs (as in + # equal) + try: + np.copyto(result, d, where=m) + except TypeError: + pass + # Transform to + masked_result = result.view(get_masked_subclass(a)) + masked_result._mask = m + masked_result._update_from(a) + return masked_result + + +class _MaskedBinaryOperation(_MaskedUFunc): + """ + Define masked version of binary operations, where invalid + values are pre-masked. + + Parameters + ---------- + mbfunc : function + The function for which to define a masked version. Made available + as ``_MaskedBinaryOperation.f``. + domain : class instance + Default domain for the function. Should be one of the ``_Domain*`` + classes. Default is None. + fillx : scalar, optional + Filling value for the first argument, default is 0. + filly : scalar, optional + Filling value for the second argument, default is 0. + + """ + + def __init__(self, mbfunc, fillx=0, filly=0): + """ + abfunc(fillx, filly) must be defined. + + abfunc(x, filly) = x for all x to enable reduce. + + """ + super().__init__(mbfunc) + self.fillx = fillx + self.filly = filly + ufunc_domain[mbfunc] = None + ufunc_fills[mbfunc] = (fillx, filly) + + def __call__(self, a, b, *args, **kwargs): + """ + Execute the call behavior. + + """ + # Get the data, as ndarray + (da, db) = (getdata(a), getdata(b)) + # Get the result + with np.errstate(): + np.seterr(divide='ignore', invalid='ignore') + result = self.f(da, db, *args, **kwargs) + # Get the mask for the result + (ma, mb) = (getmask(a), getmask(b)) + if ma is nomask: + if mb is nomask: + m = nomask + else: + m = umath.logical_or(getmaskarray(a), mb) + elif mb is nomask: + m = umath.logical_or(ma, getmaskarray(b)) + else: + m = umath.logical_or(ma, mb) + + # Case 1. : scalar + if not result.ndim: + if m: + return masked + return result + + # Case 2. : array + # Revert result to da where masked + if m is not nomask and m.any(): + # any errors, just abort; impossible to guarantee masked values + try: + np.copyto(result, da, casting='unsafe', where=m) + except Exception: + pass + + # Transforms to a (subclass of) MaskedArray + masked_result = result.view(get_masked_subclass(a, b)) + masked_result._mask = m + if isinstance(a, MaskedArray): + masked_result._update_from(a) + elif isinstance(b, MaskedArray): + masked_result._update_from(b) + return masked_result + + def reduce(self, target, axis=0, dtype=None): + """ + Reduce `target` along the given `axis`. + + """ + tclass = get_masked_subclass(target) + m = getmask(target) + t = filled(target, self.filly) + if t.shape == (): + t = t.reshape(1) + if m is not nomask: + m = make_mask(m, copy=True) + m.shape = (1,) + + if m is nomask: + tr = self.f.reduce(t, axis) + mr = nomask + else: + tr = self.f.reduce(t, axis, dtype=dtype) + mr = umath.logical_and.reduce(m, axis) + + if not tr.shape: + if mr: + return masked + else: + return tr + masked_tr = tr.view(tclass) + masked_tr._mask = mr + return masked_tr + + def outer(self, a, b): + """ + Return the function applied to the outer product of a and b. + + """ + (da, db) = (getdata(a), getdata(b)) + d = self.f.outer(da, db) + ma = getmask(a) + mb = getmask(b) + if ma is nomask and mb is nomask: + m = nomask + else: + ma = getmaskarray(a) + mb = getmaskarray(b) + m = umath.logical_or.outer(ma, mb) + if (not m.ndim) and m: + return masked + if m is not nomask: + np.copyto(d, da, where=m) + if not d.shape: + return d + masked_d = d.view(get_masked_subclass(a, b)) + masked_d._mask = m + return masked_d + + def accumulate(self, target, axis=0): + """Accumulate `target` along `axis` after filling with y fill + value. + + """ + tclass = get_masked_subclass(target) + t = filled(target, self.filly) + result = self.f.accumulate(t, axis) + masked_result = result.view(tclass) + return masked_result + + +class _DomainedBinaryOperation(_MaskedUFunc): + """ + Define binary operations that have a domain, like divide. + + They have no reduce, outer or accumulate. + + Parameters + ---------- + mbfunc : function + The function for which to define a masked version. Made available + as ``_DomainedBinaryOperation.f``. + domain : class instance + Default domain for the function. Should be one of the ``_Domain*`` + classes. + fillx : scalar, optional + Filling value for the first argument, default is 0. + filly : scalar, optional + Filling value for the second argument, default is 0. + + """ + + def __init__(self, dbfunc, domain, fillx=0, filly=0): + """abfunc(fillx, filly) must be defined. + abfunc(x, filly) = x for all x to enable reduce. + """ + super().__init__(dbfunc) + self.domain = domain + self.fillx = fillx + self.filly = filly + ufunc_domain[dbfunc] = domain + ufunc_fills[dbfunc] = (fillx, filly) + + def __call__(self, a, b, *args, **kwargs): + "Execute the call behavior." + # Get the data + (da, db) = (getdata(a), getdata(b)) + # Get the result + with np.errstate(divide='ignore', invalid='ignore'): + result = self.f(da, db, *args, **kwargs) + # Get the mask as a combination of the source masks and invalid + m = ~umath.isfinite(result) + m |= getmask(a) + m |= getmask(b) + # Apply the domain + domain = ufunc_domain.get(self.f, None) + if domain is not None: + m |= domain(da, db) + # Take care of the scalar case first + if not m.ndim: + if m: + return masked + else: + return result + # When the mask is True, put back da if possible + # any errors, just abort; impossible to guarantee masked values + try: + np.copyto(result, 0, casting='unsafe', where=m) + # avoid using "*" since this may be overlaid + masked_da = umath.multiply(m, da) + # only add back if it can be cast safely + if np.can_cast(masked_da.dtype, result.dtype, casting='safe'): + result += masked_da + except Exception: + pass + + # Transforms to a (subclass of) MaskedArray + masked_result = result.view(get_masked_subclass(a, b)) + masked_result._mask = m + if isinstance(a, MaskedArray): + masked_result._update_from(a) + elif isinstance(b, MaskedArray): + masked_result._update_from(b) + return masked_result + + +# Unary ufuncs +exp = _MaskedUnaryOperation(umath.exp) +conjugate = _MaskedUnaryOperation(umath.conjugate) +sin = _MaskedUnaryOperation(umath.sin) +cos = _MaskedUnaryOperation(umath.cos) +arctan = _MaskedUnaryOperation(umath.arctan) +arcsinh = _MaskedUnaryOperation(umath.arcsinh) +sinh = _MaskedUnaryOperation(umath.sinh) +cosh = _MaskedUnaryOperation(umath.cosh) +tanh = _MaskedUnaryOperation(umath.tanh) +abs = absolute = _MaskedUnaryOperation(umath.absolute) +angle = _MaskedUnaryOperation(angle) +fabs = _MaskedUnaryOperation(umath.fabs) +negative = _MaskedUnaryOperation(umath.negative) +floor = _MaskedUnaryOperation(umath.floor) +ceil = _MaskedUnaryOperation(umath.ceil) +around = _MaskedUnaryOperation(np.around) +logical_not = _MaskedUnaryOperation(umath.logical_not) + +# Domained unary ufuncs +sqrt = _MaskedUnaryOperation(umath.sqrt, 0.0, + _DomainGreaterEqual(0.0)) +log = _MaskedUnaryOperation(umath.log, 1.0, + _DomainGreater(0.0)) +log2 = _MaskedUnaryOperation(umath.log2, 1.0, + _DomainGreater(0.0)) +log10 = _MaskedUnaryOperation(umath.log10, 1.0, + _DomainGreater(0.0)) +tan = _MaskedUnaryOperation(umath.tan, 0.0, + _DomainTan(1e-35)) +arcsin = _MaskedUnaryOperation(umath.arcsin, 0.0, + _DomainCheckInterval(-1.0, 1.0)) +arccos = _MaskedUnaryOperation(umath.arccos, 0.0, + _DomainCheckInterval(-1.0, 1.0)) +arccosh = _MaskedUnaryOperation(umath.arccosh, 1.0, + _DomainGreaterEqual(1.0)) +arctanh = _MaskedUnaryOperation(umath.arctanh, 0.0, + _DomainCheckInterval(-1.0 + 1e-15, 1.0 - 1e-15)) + +# Binary ufuncs +add = _MaskedBinaryOperation(umath.add) +subtract = _MaskedBinaryOperation(umath.subtract) +multiply = _MaskedBinaryOperation(umath.multiply, 1, 1) +arctan2 = _MaskedBinaryOperation(umath.arctan2, 0.0, 1.0) +equal = _MaskedBinaryOperation(umath.equal) +equal.reduce = None +not_equal = _MaskedBinaryOperation(umath.not_equal) +not_equal.reduce = None +less_equal = _MaskedBinaryOperation(umath.less_equal) +less_equal.reduce = None +greater_equal = _MaskedBinaryOperation(umath.greater_equal) +greater_equal.reduce = None +less = _MaskedBinaryOperation(umath.less) +less.reduce = None +greater = _MaskedBinaryOperation(umath.greater) +greater.reduce = None +logical_and = _MaskedBinaryOperation(umath.logical_and) +alltrue = _MaskedBinaryOperation(umath.logical_and, 1, 1).reduce +logical_or = _MaskedBinaryOperation(umath.logical_or) +sometrue = logical_or.reduce +logical_xor = _MaskedBinaryOperation(umath.logical_xor) +bitwise_and = _MaskedBinaryOperation(umath.bitwise_and) +bitwise_or = _MaskedBinaryOperation(umath.bitwise_or) +bitwise_xor = _MaskedBinaryOperation(umath.bitwise_xor) +hypot = _MaskedBinaryOperation(umath.hypot) + +# Domained binary ufuncs +divide = _DomainedBinaryOperation(umath.divide, _DomainSafeDivide(), 0, 1) +true_divide = divide # Just an alias for divide. +floor_divide = _DomainedBinaryOperation(umath.floor_divide, + _DomainSafeDivide(), 0, 1) +remainder = _DomainedBinaryOperation(umath.remainder, + _DomainSafeDivide(), 0, 1) +fmod = _DomainedBinaryOperation(umath.fmod, _DomainSafeDivide(), 0, 1) +mod = remainder + +############################################################################### +# Mask creation functions # +############################################################################### + + +def _replace_dtype_fields_recursive(dtype, primitive_dtype): + "Private function allowing recursion in _replace_dtype_fields." + _recurse = _replace_dtype_fields_recursive + + # Do we have some name fields ? + if dtype.names is not None: + descr = [] + for name in dtype.names: + field = dtype.fields[name] + if len(field) == 3: + # Prepend the title to the name + name = (field[-1], name) + descr.append((name, _recurse(field[0], primitive_dtype))) + new_dtype = np.dtype(descr) + + # Is this some kind of composite a la (float,2) + elif dtype.subdtype: + descr = list(dtype.subdtype) + descr[0] = _recurse(dtype.subdtype[0], primitive_dtype) + new_dtype = np.dtype(tuple(descr)) + + # this is a primitive type, so do a direct replacement + else: + new_dtype = primitive_dtype + + # preserve identity of dtypes + if new_dtype == dtype: + new_dtype = dtype + + return new_dtype + + +def _replace_dtype_fields(dtype, primitive_dtype): + """ + Construct a dtype description list from a given dtype. + + Returns a new dtype object, with all fields and subtypes in the given type + recursively replaced with `primitive_dtype`. + + Arguments are coerced to dtypes first. + """ + dtype = np.dtype(dtype) + primitive_dtype = np.dtype(primitive_dtype) + return _replace_dtype_fields_recursive(dtype, primitive_dtype) + + +def make_mask_descr(ndtype): + """ + Construct a dtype description list from a given dtype. + + Returns a new dtype object, with the type of all fields in `ndtype` to a + boolean type. Field names are not altered. + + Parameters + ---------- + ndtype : dtype + The dtype to convert. + + Returns + ------- + result : dtype + A dtype that looks like `ndtype`, the type of all fields is boolean. + + Examples + -------- + >>> import numpy as np + >>> import numpy.ma as ma + >>> dtype = np.dtype({'names':['foo', 'bar'], + ... 'formats':[np.float32, np.int64]}) + >>> dtype + dtype([('foo', '>> ma.make_mask_descr(dtype) + dtype([('foo', '|b1'), ('bar', '|b1')]) + >>> ma.make_mask_descr(np.float32) + dtype('bool') + + """ + return _replace_dtype_fields(ndtype, MaskType) + + +def getmask(a): + """ + Return the mask of a masked array, or nomask. + + Return the mask of `a` as an ndarray if `a` is a `MaskedArray` and the + mask is not `nomask`, else return `nomask`. To guarantee a full array + of booleans of the same shape as a, use `getmaskarray`. + + Parameters + ---------- + a : array_like + Input `MaskedArray` for which the mask is required. + + See Also + -------- + getdata : Return the data of a masked array as an ndarray. + getmaskarray : Return the mask of a masked array, or full array of False. + + Examples + -------- + >>> import numpy as np + >>> import numpy.ma as ma + >>> a = ma.masked_equal([[1,2],[3,4]], 2) + >>> a + masked_array( + data=[[1, --], + [3, 4]], + mask=[[False, True], + [False, False]], + fill_value=2) + >>> ma.getmask(a) + array([[False, True], + [False, False]]) + + Equivalently use the `MaskedArray` `mask` attribute. + + >>> a.mask + array([[False, True], + [False, False]]) + + Result when mask == `nomask` + + >>> b = ma.masked_array([[1,2],[3,4]]) + >>> b + masked_array( + data=[[1, 2], + [3, 4]], + mask=False, + fill_value=999999) + >>> ma.nomask + False + >>> ma.getmask(b) == ma.nomask + True + >>> b.mask == ma.nomask + True + + """ + return getattr(a, '_mask', nomask) + + +get_mask = getmask + + +def getmaskarray(arr): + """ + Return the mask of a masked array, or full boolean array of False. + + Return the mask of `arr` as an ndarray if `arr` is a `MaskedArray` and + the mask is not `nomask`, else return a full boolean array of False of + the same shape as `arr`. + + Parameters + ---------- + arr : array_like + Input `MaskedArray` for which the mask is required. + + See Also + -------- + getmask : Return the mask of a masked array, or nomask. + getdata : Return the data of a masked array as an ndarray. + + Examples + -------- + >>> import numpy as np + >>> import numpy.ma as ma + >>> a = ma.masked_equal([[1,2],[3,4]], 2) + >>> a + masked_array( + data=[[1, --], + [3, 4]], + mask=[[False, True], + [False, False]], + fill_value=2) + >>> ma.getmaskarray(a) + array([[False, True], + [False, False]]) + + Result when mask == ``nomask`` + + >>> b = ma.masked_array([[1,2],[3,4]]) + >>> b + masked_array( + data=[[1, 2], + [3, 4]], + mask=False, + fill_value=999999) + >>> ma.getmaskarray(b) + array([[False, False], + [False, False]]) + + """ + mask = getmask(arr) + if mask is nomask: + mask = make_mask_none(np.shape(arr), getattr(arr, 'dtype', None)) + return mask + + +def is_mask(m): + """ + Return True if m is a valid, standard mask. + + This function does not check the contents of the input, only that the + type is MaskType. In particular, this function returns False if the + mask has a flexible dtype. + + Parameters + ---------- + m : array_like + Array to test. + + Returns + ------- + result : bool + True if `m.dtype.type` is MaskType, False otherwise. + + See Also + -------- + ma.isMaskedArray : Test whether input is an instance of MaskedArray. + + Examples + -------- + >>> import numpy as np + >>> import numpy.ma as ma + >>> m = ma.masked_equal([0, 1, 0, 2, 3], 0) + >>> m + masked_array(data=[--, 1, --, 2, 3], + mask=[ True, False, True, False, False], + fill_value=0) + >>> ma.is_mask(m) + False + >>> ma.is_mask(m.mask) + True + + Input must be an ndarray (or have similar attributes) + for it to be considered a valid mask. + + >>> m = [False, True, False] + >>> ma.is_mask(m) + False + >>> m = np.array([False, True, False]) + >>> m + array([False, True, False]) + >>> ma.is_mask(m) + True + + Arrays with complex dtypes don't return True. + + >>> dtype = np.dtype({'names':['monty', 'pithon'], + ... 'formats':[bool, bool]}) + >>> dtype + dtype([('monty', '|b1'), ('pithon', '|b1')]) + >>> m = np.array([(True, False), (False, True), (True, False)], + ... dtype=dtype) + >>> m + array([( True, False), (False, True), ( True, False)], + dtype=[('monty', '?'), ('pithon', '?')]) + >>> ma.is_mask(m) + False + + """ + try: + return m.dtype.type is MaskType + except AttributeError: + return False + + +def _shrink_mask(m): + """ + Shrink a mask to nomask if possible + """ + if m.dtype.names is None and not m.any(): + return nomask + else: + return m + + +def make_mask(m, copy=False, shrink=True, dtype=MaskType): + """ + Create a boolean mask from an array. + + Return `m` as a boolean mask, creating a copy if necessary or requested. + The function can accept any sequence that is convertible to integers, + or ``nomask``. Does not require that contents must be 0s and 1s, values + of 0 are interpreted as False, everything else as True. + + Parameters + ---------- + m : array_like + Potential mask. + copy : bool, optional + Whether to return a copy of `m` (True) or `m` itself (False). + shrink : bool, optional + Whether to shrink `m` to ``nomask`` if all its values are False. + dtype : dtype, optional + Data-type of the output mask. By default, the output mask has a + dtype of MaskType (bool). If the dtype is flexible, each field has + a boolean dtype. This is ignored when `m` is ``nomask``, in which + case ``nomask`` is always returned. + + Returns + ------- + result : ndarray + A boolean mask derived from `m`. + + Examples + -------- + >>> import numpy as np + >>> import numpy.ma as ma + >>> m = [True, False, True, True] + >>> ma.make_mask(m) + array([ True, False, True, True]) + >>> m = [1, 0, 1, 1] + >>> ma.make_mask(m) + array([ True, False, True, True]) + >>> m = [1, 0, 2, -3] + >>> ma.make_mask(m) + array([ True, False, True, True]) + + Effect of the `shrink` parameter. + + >>> m = np.zeros(4) + >>> m + array([0., 0., 0., 0.]) + >>> ma.make_mask(m) + False + >>> ma.make_mask(m, shrink=False) + array([False, False, False, False]) + + Using a flexible `dtype`. + + >>> m = [1, 0, 1, 1] + >>> n = [0, 1, 0, 0] + >>> arr = [] + >>> for man, mouse in zip(m, n): + ... arr.append((man, mouse)) + >>> arr + [(1, 0), (0, 1), (1, 0), (1, 0)] + >>> dtype = np.dtype({'names':['man', 'mouse'], + ... 'formats':[np.int64, np.int64]}) + >>> arr = np.array(arr, dtype=dtype) + >>> arr + array([(1, 0), (0, 1), (1, 0), (1, 0)], + dtype=[('man', '>> ma.make_mask(arr, dtype=dtype) + array([(True, False), (False, True), (True, False), (True, False)], + dtype=[('man', '|b1'), ('mouse', '|b1')]) + + """ + if m is nomask: + return nomask + + # Make sure the input dtype is valid. + dtype = make_mask_descr(dtype) + + # legacy boolean special case: "existence of fields implies true" + if isinstance(m, ndarray) and m.dtype.fields and dtype == np.bool: + return np.ones(m.shape, dtype=dtype) + + # Fill the mask in case there are missing data; turn it into an ndarray. + copy = None if not copy else True + result = np.array(filled(m, True), copy=copy, dtype=dtype, subok=True) + # Bas les masques ! + if shrink: + result = _shrink_mask(result) + return result + + +def make_mask_none(newshape, dtype=None): + """ + Return a boolean mask of the given shape, filled with False. + + This function returns a boolean ndarray with all entries False, that can + be used in common mask manipulations. If a complex dtype is specified, the + type of each field is converted to a boolean type. + + Parameters + ---------- + newshape : tuple + A tuple indicating the shape of the mask. + dtype : {None, dtype}, optional + If None, use a MaskType instance. Otherwise, use a new datatype with + the same fields as `dtype`, converted to boolean types. + + Returns + ------- + result : ndarray + An ndarray of appropriate shape and dtype, filled with False. + + See Also + -------- + make_mask : Create a boolean mask from an array. + make_mask_descr : Construct a dtype description list from a given dtype. + + Examples + -------- + >>> import numpy as np + >>> import numpy.ma as ma + >>> ma.make_mask_none((3,)) + array([False, False, False]) + + Defining a more complex dtype. + + >>> dtype = np.dtype({'names':['foo', 'bar'], + ... 'formats':[np.float32, np.int64]}) + >>> dtype + dtype([('foo', '>> ma.make_mask_none((3,), dtype=dtype) + array([(False, False), (False, False), (False, False)], + dtype=[('foo', '|b1'), ('bar', '|b1')]) + + """ + if dtype is None: + result = np.zeros(newshape, dtype=MaskType) + else: + result = np.zeros(newshape, dtype=make_mask_descr(dtype)) + return result + + +def _recursive_mask_or(m1, m2, newmask): + names = m1.dtype.names + for name in names: + current1 = m1[name] + if current1.dtype.names is not None: + _recursive_mask_or(current1, m2[name], newmask[name]) + else: + umath.logical_or(current1, m2[name], newmask[name]) + + +def mask_or(m1, m2, copy=False, shrink=True): + """ + Combine two masks with the ``logical_or`` operator. + + The result may be a view on `m1` or `m2` if the other is `nomask` + (i.e. False). + + Parameters + ---------- + m1, m2 : array_like + Input masks. + copy : bool, optional + If copy is False and one of the inputs is `nomask`, return a view + of the other input mask. Defaults to False. + shrink : bool, optional + Whether to shrink the output to `nomask` if all its values are + False. Defaults to True. + + Returns + ------- + mask : output mask + The result masks values that are masked in either `m1` or `m2`. + + Raises + ------ + ValueError + If `m1` and `m2` have different flexible dtypes. + + Examples + -------- + >>> import numpy as np + >>> m1 = np.ma.make_mask([0, 1, 1, 0]) + >>> m2 = np.ma.make_mask([1, 0, 0, 0]) + >>> np.ma.mask_or(m1, m2) + array([ True, True, True, False]) + + """ + + if (m1 is nomask) or (m1 is False): + dtype = getattr(m2, 'dtype', MaskType) + return make_mask(m2, copy=copy, shrink=shrink, dtype=dtype) + if (m2 is nomask) or (m2 is False): + dtype = getattr(m1, 'dtype', MaskType) + return make_mask(m1, copy=copy, shrink=shrink, dtype=dtype) + if m1 is m2 and is_mask(m1): + return _shrink_mask(m1) if shrink else m1 + (dtype1, dtype2) = (getattr(m1, 'dtype', None), getattr(m2, 'dtype', None)) + if dtype1 != dtype2: + raise ValueError(f"Incompatible dtypes '{dtype1}'<>'{dtype2}'") + if dtype1.names is not None: + # Allocate an output mask array with the properly broadcast shape. + newmask = np.empty(np.broadcast(m1, m2).shape, dtype1) + _recursive_mask_or(m1, m2, newmask) + return newmask + return make_mask(umath.logical_or(m1, m2), copy=copy, shrink=shrink) + + +def flatten_mask(mask): + """ + Returns a completely flattened version of the mask, where nested fields + are collapsed. + + Parameters + ---------- + mask : array_like + Input array, which will be interpreted as booleans. + + Returns + ------- + flattened_mask : ndarray of bools + The flattened input. + + Examples + -------- + >>> import numpy as np + >>> mask = np.array([0, 0, 1]) + >>> np.ma.flatten_mask(mask) + array([False, False, True]) + + >>> mask = np.array([(0, 0), (0, 1)], dtype=[('a', bool), ('b', bool)]) + >>> np.ma.flatten_mask(mask) + array([False, False, False, True]) + + >>> mdtype = [('a', bool), ('b', [('ba', bool), ('bb', bool)])] + >>> mask = np.array([(0, (0, 0)), (0, (0, 1))], dtype=mdtype) + >>> np.ma.flatten_mask(mask) + array([False, False, False, False, False, True]) + + """ + + def _flatmask(mask): + "Flatten the mask and returns a (maybe nested) sequence of booleans." + mnames = mask.dtype.names + if mnames is not None: + return [flatten_mask(mask[name]) for name in mnames] + else: + return mask + + def _flatsequence(sequence): + "Generates a flattened version of the sequence." + try: + for element in sequence: + if hasattr(element, '__iter__'): + yield from _flatsequence(element) + else: + yield element + except TypeError: + yield sequence + + mask = np.asarray(mask) + flattened = _flatsequence(_flatmask(mask)) + return np.array(list(flattened), dtype=bool) + + +def _check_mask_axis(mask, axis, keepdims=np._NoValue): + "Check whether there are masked values along the given axis" + kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims} + if mask is not nomask: + return mask.all(axis=axis, **kwargs) + return nomask + + +############################################################################### +# Masking functions # +############################################################################### + +def masked_where(condition, a, copy=True): + """ + Mask an array where a condition is met. + + Return `a` as an array masked where `condition` is True. + Any masked values of `a` or `condition` are also masked in the output. + + Parameters + ---------- + condition : array_like + Masking condition. When `condition` tests floating point values for + equality, consider using ``masked_values`` instead. + a : array_like + Array to mask. + copy : bool + If True (default) make a copy of `a` in the result. If False modify + `a` in place and return a view. + + Returns + ------- + result : MaskedArray + The result of masking `a` where `condition` is True. + + See Also + -------- + masked_values : Mask using floating point equality. + masked_equal : Mask where equal to a given value. + masked_not_equal : Mask where *not* equal to a given value. + masked_less_equal : Mask where less than or equal to a given value. + masked_greater_equal : Mask where greater than or equal to a given value. + masked_less : Mask where less than a given value. + masked_greater : Mask where greater than a given value. + masked_inside : Mask inside a given interval. + masked_outside : Mask outside a given interval. + masked_invalid : Mask invalid values (NaNs or infs). + + Examples + -------- + >>> import numpy as np + >>> import numpy.ma as ma + >>> a = np.arange(4) + >>> a + array([0, 1, 2, 3]) + >>> ma.masked_where(a <= 2, a) + masked_array(data=[--, --, --, 3], + mask=[ True, True, True, False], + fill_value=999999) + + Mask array `b` conditional on `a`. + + >>> b = ['a', 'b', 'c', 'd'] + >>> ma.masked_where(a == 2, b) + masked_array(data=['a', 'b', --, 'd'], + mask=[False, False, True, False], + fill_value='N/A', + dtype='>> c = ma.masked_where(a <= 2, a) + >>> c + masked_array(data=[--, --, --, 3], + mask=[ True, True, True, False], + fill_value=999999) + >>> c[0] = 99 + >>> c + masked_array(data=[99, --, --, 3], + mask=[False, True, True, False], + fill_value=999999) + >>> a + array([0, 1, 2, 3]) + >>> c = ma.masked_where(a <= 2, a, copy=False) + >>> c[0] = 99 + >>> c + masked_array(data=[99, --, --, 3], + mask=[False, True, True, False], + fill_value=999999) + >>> a + array([99, 1, 2, 3]) + + When `condition` or `a` contain masked values. + + >>> a = np.arange(4) + >>> a = ma.masked_where(a == 2, a) + >>> a + masked_array(data=[0, 1, --, 3], + mask=[False, False, True, False], + fill_value=999999) + >>> b = np.arange(4) + >>> b = ma.masked_where(b == 0, b) + >>> b + masked_array(data=[--, 1, 2, 3], + mask=[ True, False, False, False], + fill_value=999999) + >>> ma.masked_where(a == 3, b) + masked_array(data=[--, 1, --, --], + mask=[ True, False, True, True], + fill_value=999999) + + """ + # Make sure that condition is a valid standard-type mask. + cond = make_mask(condition, shrink=False) + a = np.array(a, copy=copy, subok=True) + + (cshape, ashape) = (cond.shape, a.shape) + if cshape and cshape != ashape: + raise IndexError("Inconsistent shape between the condition and the input" + " (got %s and %s)" % (cshape, ashape)) + if hasattr(a, '_mask'): + cond = mask_or(cond, a._mask) + cls = type(a) + else: + cls = MaskedArray + result = a.view(cls) + # Assign to *.mask so that structured masks are handled correctly. + result.mask = _shrink_mask(cond) + # There is no view of a boolean so when 'a' is a MaskedArray with nomask + # the update to the result's mask has no effect. + if not copy and hasattr(a, '_mask') and getmask(a) is nomask: + a._mask = result._mask.view() + return result + + +def masked_greater(x, value, copy=True): + """ + Mask an array where greater than a given value. + + This function is a shortcut to ``masked_where``, with + `condition` = (x > value). + + See Also + -------- + masked_where : Mask where a condition is met. + + Examples + -------- + >>> import numpy as np + >>> import numpy.ma as ma + >>> a = np.arange(4) + >>> a + array([0, 1, 2, 3]) + >>> ma.masked_greater(a, 2) + masked_array(data=[0, 1, 2, --], + mask=[False, False, False, True], + fill_value=999999) + + """ + return masked_where(greater(x, value), x, copy=copy) + + +def masked_greater_equal(x, value, copy=True): + """ + Mask an array where greater than or equal to a given value. + + This function is a shortcut to ``masked_where``, with + `condition` = (x >= value). + + See Also + -------- + masked_where : Mask where a condition is met. + + Examples + -------- + >>> import numpy as np + >>> import numpy.ma as ma + >>> a = np.arange(4) + >>> a + array([0, 1, 2, 3]) + >>> ma.masked_greater_equal(a, 2) + masked_array(data=[0, 1, --, --], + mask=[False, False, True, True], + fill_value=999999) + + """ + return masked_where(greater_equal(x, value), x, copy=copy) + + +def masked_less(x, value, copy=True): + """ + Mask an array where less than a given value. + + This function is a shortcut to ``masked_where``, with + `condition` = (x < value). + + See Also + -------- + masked_where : Mask where a condition is met. + + Examples + -------- + >>> import numpy as np + >>> import numpy.ma as ma + >>> a = np.arange(4) + >>> a + array([0, 1, 2, 3]) + >>> ma.masked_less(a, 2) + masked_array(data=[--, --, 2, 3], + mask=[ True, True, False, False], + fill_value=999999) + + """ + return masked_where(less(x, value), x, copy=copy) + + +def masked_less_equal(x, value, copy=True): + """ + Mask an array where less than or equal to a given value. + + This function is a shortcut to ``masked_where``, with + `condition` = (x <= value). + + See Also + -------- + masked_where : Mask where a condition is met. + + Examples + -------- + >>> import numpy as np + >>> import numpy.ma as ma + >>> a = np.arange(4) + >>> a + array([0, 1, 2, 3]) + >>> ma.masked_less_equal(a, 2) + masked_array(data=[--, --, --, 3], + mask=[ True, True, True, False], + fill_value=999999) + + """ + return masked_where(less_equal(x, value), x, copy=copy) + + +def masked_not_equal(x, value, copy=True): + """ + Mask an array where *not* equal to a given value. + + This function is a shortcut to ``masked_where``, with + `condition` = (x != value). + + See Also + -------- + masked_where : Mask where a condition is met. + + Examples + -------- + >>> import numpy as np + >>> import numpy.ma as ma + >>> a = np.arange(4) + >>> a + array([0, 1, 2, 3]) + >>> ma.masked_not_equal(a, 2) + masked_array(data=[--, --, 2, --], + mask=[ True, True, False, True], + fill_value=999999) + + """ + return masked_where(not_equal(x, value), x, copy=copy) + + +def masked_equal(x, value, copy=True): + """ + Mask an array where equal to a given value. + + Return a MaskedArray, masked where the data in array `x` are + equal to `value`. The fill_value of the returned MaskedArray + is set to `value`. + + For floating point arrays, consider using ``masked_values(x, value)``. + + See Also + -------- + masked_where : Mask where a condition is met. + masked_values : Mask using floating point equality. + + Examples + -------- + >>> import numpy as np + >>> import numpy.ma as ma + >>> a = np.arange(4) + >>> a + array([0, 1, 2, 3]) + >>> ma.masked_equal(a, 2) + masked_array(data=[0, 1, --, 3], + mask=[False, False, True, False], + fill_value=2) + + """ + output = masked_where(equal(x, value), x, copy=copy) + output.fill_value = value + return output + + +def masked_inside(x, v1, v2, copy=True): + """ + Mask an array inside a given interval. + + Shortcut to ``masked_where``, where `condition` is True for `x` inside + the interval [v1,v2] (v1 <= x <= v2). The boundaries `v1` and `v2` + can be given in either order. + + See Also + -------- + masked_where : Mask where a condition is met. + + Notes + ----- + The array `x` is prefilled with its filling value. + + Examples + -------- + >>> import numpy as np + >>> import numpy.ma as ma + >>> x = [0.31, 1.2, 0.01, 0.2, -0.4, -1.1] + >>> ma.masked_inside(x, -0.3, 0.3) + masked_array(data=[0.31, 1.2, --, --, -0.4, -1.1], + mask=[False, False, True, True, False, False], + fill_value=1e+20) + + The order of `v1` and `v2` doesn't matter. + + >>> ma.masked_inside(x, 0.3, -0.3) + masked_array(data=[0.31, 1.2, --, --, -0.4, -1.1], + mask=[False, False, True, True, False, False], + fill_value=1e+20) + + """ + if v2 < v1: + (v1, v2) = (v2, v1) + xf = filled(x) + condition = (xf >= v1) & (xf <= v2) + return masked_where(condition, x, copy=copy) + + +def masked_outside(x, v1, v2, copy=True): + """ + Mask an array outside a given interval. + + Shortcut to ``masked_where``, where `condition` is True for `x` outside + the interval [v1,v2] (x < v1)|(x > v2). + The boundaries `v1` and `v2` can be given in either order. + + See Also + -------- + masked_where : Mask where a condition is met. + + Notes + ----- + The array `x` is prefilled with its filling value. + + Examples + -------- + >>> import numpy as np + >>> import numpy.ma as ma + >>> x = [0.31, 1.2, 0.01, 0.2, -0.4, -1.1] + >>> ma.masked_outside(x, -0.3, 0.3) + masked_array(data=[--, --, 0.01, 0.2, --, --], + mask=[ True, True, False, False, True, True], + fill_value=1e+20) + + The order of `v1` and `v2` doesn't matter. + + >>> ma.masked_outside(x, 0.3, -0.3) + masked_array(data=[--, --, 0.01, 0.2, --, --], + mask=[ True, True, False, False, True, True], + fill_value=1e+20) + + """ + if v2 < v1: + (v1, v2) = (v2, v1) + xf = filled(x) + condition = (xf < v1) | (xf > v2) + return masked_where(condition, x, copy=copy) + + +def masked_object(x, value, copy=True, shrink=True): + """ + Mask the array `x` where the data are exactly equal to value. + + This function is similar to `masked_values`, but only suitable + for object arrays: for floating point, use `masked_values` instead. + + Parameters + ---------- + x : array_like + Array to mask + value : object + Comparison value + copy : {True, False}, optional + Whether to return a copy of `x`. + shrink : {True, False}, optional + Whether to collapse a mask full of False to nomask + + Returns + ------- + result : MaskedArray + The result of masking `x` where equal to `value`. + + See Also + -------- + masked_where : Mask where a condition is met. + masked_equal : Mask where equal to a given value (integers). + masked_values : Mask using floating point equality. + + Examples + -------- + >>> import numpy as np + >>> import numpy.ma as ma + >>> food = np.array(['green_eggs', 'ham'], dtype=object) + >>> # don't eat spoiled food + >>> eat = ma.masked_object(food, 'green_eggs') + >>> eat + masked_array(data=[--, 'ham'], + mask=[ True, False], + fill_value='green_eggs', + dtype=object) + >>> # plain ol` ham is boring + >>> fresh_food = np.array(['cheese', 'ham', 'pineapple'], dtype=object) + >>> eat = ma.masked_object(fresh_food, 'green_eggs') + >>> eat + masked_array(data=['cheese', 'ham', 'pineapple'], + mask=False, + fill_value='green_eggs', + dtype=object) + + Note that `mask` is set to ``nomask`` if possible. + + >>> eat + masked_array(data=['cheese', 'ham', 'pineapple'], + mask=False, + fill_value='green_eggs', + dtype=object) + + """ + if isMaskedArray(x): + condition = umath.equal(x._data, value) + mask = x._mask + else: + condition = umath.equal(np.asarray(x), value) + mask = nomask + mask = mask_or(mask, make_mask(condition, shrink=shrink)) + return masked_array(x, mask=mask, copy=copy, fill_value=value) + + +def masked_values(x, value, rtol=1e-5, atol=1e-8, copy=True, shrink=True): + """ + Mask using floating point equality. + + Return a MaskedArray, masked where the data in array `x` are approximately + equal to `value`, determined using `isclose`. The default tolerances for + `masked_values` are the same as those for `isclose`. + + For integer types, exact equality is used, in the same way as + `masked_equal`. + + The fill_value is set to `value` and the mask is set to ``nomask`` if + possible. + + Parameters + ---------- + x : array_like + Array to mask. + value : float + Masking value. + rtol, atol : float, optional + Tolerance parameters passed on to `isclose` + copy : bool, optional + Whether to return a copy of `x`. + shrink : bool, optional + Whether to collapse a mask full of False to ``nomask``. + + Returns + ------- + result : MaskedArray + The result of masking `x` where approximately equal to `value`. + + See Also + -------- + masked_where : Mask where a condition is met. + masked_equal : Mask where equal to a given value (integers). + + Examples + -------- + >>> import numpy as np + >>> import numpy.ma as ma + >>> x = np.array([1, 1.1, 2, 1.1, 3]) + >>> ma.masked_values(x, 1.1) + masked_array(data=[1.0, --, 2.0, --, 3.0], + mask=[False, True, False, True, False], + fill_value=1.1) + + Note that `mask` is set to ``nomask`` if possible. + + >>> ma.masked_values(x, 2.1) + masked_array(data=[1. , 1.1, 2. , 1.1, 3. ], + mask=False, + fill_value=2.1) + + Unlike `masked_equal`, `masked_values` can perform approximate equalities. + + >>> ma.masked_values(x, 2.1, atol=1e-1) + masked_array(data=[1.0, 1.1, --, 1.1, 3.0], + mask=[False, False, True, False, False], + fill_value=2.1) + + """ + xnew = filled(x, value) + if np.issubdtype(xnew.dtype, np.floating): + mask = np.isclose(xnew, value, atol=atol, rtol=rtol) + else: + mask = umath.equal(xnew, value) + ret = masked_array(xnew, mask=mask, copy=copy, fill_value=value) + if shrink: + ret.shrink_mask() + return ret + + +def masked_invalid(a, copy=True): + """ + Mask an array where invalid values occur (NaNs or infs). + + This function is a shortcut to ``masked_where``, with + `condition` = ~(np.isfinite(a)). Any pre-existing mask is conserved. + Only applies to arrays with a dtype where NaNs or infs make sense + (i.e. floating point types), but accepts any array_like object. + + See Also + -------- + masked_where : Mask where a condition is met. + + Examples + -------- + >>> import numpy as np + >>> import numpy.ma as ma + >>> a = np.arange(5, dtype=float) + >>> a[2] = np.nan + >>> a[3] = np.inf + >>> a + array([ 0., 1., nan, inf, 4.]) + >>> ma.masked_invalid(a) + masked_array(data=[0.0, 1.0, --, --, 4.0], + mask=[False, False, True, True, False], + fill_value=1e+20) + + """ + a = np.array(a, copy=None, subok=True) + res = masked_where(~(np.isfinite(a)), a, copy=copy) + # masked_invalid previously never returned nomask as a mask and doing so + # threw off matplotlib (gh-22842). So use shrink=False: + if res._mask is nomask: + res._mask = make_mask_none(res.shape, res.dtype) + return res + +############################################################################### +# Printing options # +############################################################################### + + +class _MaskedPrintOption: + """ + Handle the string used to represent missing data in a masked array. + + """ + + def __init__(self, display): + """ + Create the masked_print_option object. + + """ + self._display = display + self._enabled = True + + def display(self): + """ + Display the string to print for masked values. + + """ + return self._display + + def set_display(self, s): + """ + Set the string to print for masked values. + + """ + self._display = s + + def enabled(self): + """ + Is the use of the display value enabled? + + """ + return self._enabled + + def enable(self, shrink=1): + """ + Set the enabling shrink to `shrink`. + + """ + self._enabled = shrink + + def __str__(self): + return str(self._display) + + __repr__ = __str__ + + +# if you single index into a masked location you get this object. +masked_print_option = _MaskedPrintOption('--') + + +def _recursive_printoption(result, mask, printopt): + """ + Puts printoptions in result where mask is True. + + Private function allowing for recursion + + """ + names = result.dtype.names + if names is not None: + for name in names: + curdata = result[name] + curmask = mask[name] + _recursive_printoption(curdata, curmask, printopt) + else: + np.copyto(result, printopt, where=mask) + + +# For better or worse, these end in a newline +_legacy_print_templates = { + 'long_std': textwrap.dedent("""\ + masked_%(name)s(data = + %(data)s, + %(nlen)s mask = + %(mask)s, + %(nlen)s fill_value = %(fill)s) + """), + 'long_flx': textwrap.dedent("""\ + masked_%(name)s(data = + %(data)s, + %(nlen)s mask = + %(mask)s, + %(nlen)s fill_value = %(fill)s, + %(nlen)s dtype = %(dtype)s) + """), + 'short_std': textwrap.dedent("""\ + masked_%(name)s(data = %(data)s, + %(nlen)s mask = %(mask)s, + %(nlen)s fill_value = %(fill)s) + """), + 'short_flx': textwrap.dedent("""\ + masked_%(name)s(data = %(data)s, + %(nlen)s mask = %(mask)s, + %(nlen)s fill_value = %(fill)s, + %(nlen)s dtype = %(dtype)s) + """) +} + +############################################################################### +# MaskedArray class # +############################################################################### + + +def _recursive_filled(a, mask, fill_value): + """ + Recursively fill `a` with `fill_value`. + + """ + names = a.dtype.names + for name in names: + current = a[name] + if current.dtype.names is not None: + _recursive_filled(current, mask[name], fill_value[name]) + else: + np.copyto(current, fill_value[name], where=mask[name]) + + +def flatten_structured_array(a): + """ + Flatten a structured array. + + The data type of the output is chosen such that it can represent all of the + (nested) fields. + + Parameters + ---------- + a : structured array + + Returns + ------- + output : masked array or ndarray + A flattened masked array if the input is a masked array, otherwise a + standard ndarray. + + Examples + -------- + >>> import numpy as np + >>> ndtype = [('a', int), ('b', float)] + >>> a = np.array([(1, 1), (2, 2)], dtype=ndtype) + >>> np.ma.flatten_structured_array(a) + array([[1., 1.], + [2., 2.]]) + + """ + + def flatten_sequence(iterable): + """ + Flattens a compound of nested iterables. + + """ + for elm in iter(iterable): + if hasattr(elm, "__iter__") and not isinstance(elm, (str, bytes)): + yield from flatten_sequence(elm) + else: + yield elm + + a = np.asanyarray(a) + inishape = a.shape + a = a.ravel() + if isinstance(a, MaskedArray): + out = np.array([tuple(flatten_sequence(d.item())) for d in a._data]) + out = out.view(MaskedArray) + out._mask = np.array([tuple(flatten_sequence(d.item())) + for d in getmaskarray(a)]) + else: + out = np.array([tuple(flatten_sequence(d.item())) for d in a]) + if len(inishape) > 1: + newshape = list(out.shape) + newshape[0] = inishape + out.shape = tuple(flatten_sequence(newshape)) + return out + + +def _arraymethod(funcname, onmask=True): + """ + Return a class method wrapper around a basic array method. + + Creates a class method which returns a masked array, where the new + ``_data`` array is the output of the corresponding basic method called + on the original ``_data``. + + If `onmask` is True, the new mask is the output of the method called + on the initial mask. Otherwise, the new mask is just a reference + to the initial mask. + + Parameters + ---------- + funcname : str + Name of the function to apply on data. + onmask : bool + Whether the mask must be processed also (True) or left + alone (False). Default is True. Make available as `_onmask` + attribute. + + Returns + ------- + method : instancemethod + Class method wrapper of the specified basic array method. + + """ + def wrapped_method(self, *args, **params): + result = getattr(self._data, funcname)(*args, **params) + result = result.view(type(self)) + result._update_from(self) + mask = self._mask + if not onmask: + result.__setmask__(mask) + elif mask is not nomask: + # __setmask__ makes a copy, which we don't want + result._mask = getattr(mask, funcname)(*args, **params) + return result + methdoc = getattr(ndarray, funcname, None) or getattr(np, funcname, None) + if methdoc is not None: + wrapped_method.__doc__ = methdoc.__doc__ + wrapped_method.__name__ = funcname + return wrapped_method + + +class MaskedIterator: + """ + Flat iterator object to iterate over masked arrays. + + A `MaskedIterator` iterator is returned by ``x.flat`` for any masked array + `x`. It allows iterating over the array as if it were a 1-D array, + either in a for-loop or by calling its `next` method. + + Iteration is done in C-contiguous style, with the last index varying the + fastest. The iterator can also be indexed using basic slicing or + advanced indexing. + + See Also + -------- + MaskedArray.flat : Return a flat iterator over an array. + MaskedArray.flatten : Returns a flattened copy of an array. + + Notes + ----- + `MaskedIterator` is not exported by the `ma` module. Instead of + instantiating a `MaskedIterator` directly, use `MaskedArray.flat`. + + Examples + -------- + >>> import numpy as np + >>> x = np.ma.array(arange(6).reshape(2, 3)) + >>> fl = x.flat + >>> type(fl) + + >>> for item in fl: + ... print(item) + ... + 0 + 1 + 2 + 3 + 4 + 5 + + Extracting more than a single element b indexing the `MaskedIterator` + returns a masked array: + + >>> fl[2:4] + masked_array(data = [2 3], + mask = False, + fill_value = 999999) + + """ + + def __init__(self, ma): + self.ma = ma + self.dataiter = ma._data.flat + + if ma._mask is nomask: + self.maskiter = None + else: + self.maskiter = ma._mask.flat + + def __iter__(self): + return self + + def __getitem__(self, indx): + result = self.dataiter.__getitem__(indx).view(type(self.ma)) + if self.maskiter is not None: + _mask = self.maskiter.__getitem__(indx) + if isinstance(_mask, ndarray): + # set shape to match that of data; this is needed for matrices + _mask.shape = result.shape + result._mask = _mask + elif isinstance(_mask, np.void): + return mvoid(result, mask=_mask, hardmask=self.ma._hardmask) + elif _mask: # Just a scalar, masked + return masked + return result + + # This won't work if ravel makes a copy + def __setitem__(self, index, value): + self.dataiter[index] = getdata(value) + if self.maskiter is not None: + self.maskiter[index] = getmaskarray(value) + + def __next__(self): + """ + Return the next value, or raise StopIteration. + + Examples + -------- + >>> import numpy as np + >>> x = np.ma.array([3, 2], mask=[0, 1]) + >>> fl = x.flat + >>> next(fl) + 3 + >>> next(fl) + masked + >>> next(fl) + Traceback (most recent call last): + ... + StopIteration + + """ + d = next(self.dataiter) + if self.maskiter is not None: + m = next(self.maskiter) + if isinstance(m, np.void): + return mvoid(d, mask=m, hardmask=self.ma._hardmask) + elif m: # Just a scalar, masked + return masked + return d + + +@set_module("numpy.ma") +class MaskedArray(ndarray): + """ + An array class with possibly masked values. + + Masked values of True exclude the corresponding element from any + computation. + + Construction:: + + x = MaskedArray(data, mask=nomask, dtype=None, copy=False, subok=True, + ndmin=0, fill_value=None, keep_mask=True, hard_mask=None, + shrink=True, order=None) + + Parameters + ---------- + data : array_like + Input data. + mask : sequence, optional + Mask. Must be convertible to an array of booleans with the same + shape as `data`. True indicates a masked (i.e. invalid) data. + dtype : dtype, optional + Data type of the output. + If `dtype` is None, the type of the data argument (``data.dtype``) + is used. If `dtype` is not None and different from ``data.dtype``, + a copy is performed. + copy : bool, optional + Whether to copy the input data (True), or to use a reference instead. + Default is False. + subok : bool, optional + Whether to return a subclass of `MaskedArray` if possible (True) or a + plain `MaskedArray`. Default is True. + ndmin : int, optional + Minimum number of dimensions. Default is 0. + fill_value : scalar, optional + Value used to fill in the masked values when necessary. + If None, a default based on the data-type is used. + keep_mask : bool, optional + Whether to combine `mask` with the mask of the input data, if any + (True), or to use only `mask` for the output (False). Default is True. + hard_mask : bool, optional + Whether to use a hard mask or not. With a hard mask, masked values + cannot be unmasked. Default is False. + shrink : bool, optional + Whether to force compression of an empty mask. Default is True. + order : {'C', 'F', 'A'}, optional + Specify the order of the array. If order is 'C', then the array + will be in C-contiguous order (last-index varies the fastest). + If order is 'F', then the returned array will be in + Fortran-contiguous order (first-index varies the fastest). + If order is 'A' (default), then the returned array may be + in any order (either C-, Fortran-contiguous, or even discontiguous), + unless a copy is required, in which case it will be C-contiguous. + + Examples + -------- + >>> import numpy as np + + The ``mask`` can be initialized with an array of boolean values + with the same shape as ``data``. + + >>> data = np.arange(6).reshape((2, 3)) + >>> np.ma.MaskedArray(data, mask=[[False, True, False], + ... [False, False, True]]) + masked_array( + data=[[0, --, 2], + [3, 4, --]], + mask=[[False, True, False], + [False, False, True]], + fill_value=999999) + + Alternatively, the ``mask`` can be initialized to homogeneous boolean + array with the same shape as ``data`` by passing in a scalar + boolean value: + + >>> np.ma.MaskedArray(data, mask=False) + masked_array( + data=[[0, 1, 2], + [3, 4, 5]], + mask=[[False, False, False], + [False, False, False]], + fill_value=999999) + + >>> np.ma.MaskedArray(data, mask=True) + masked_array( + data=[[--, --, --], + [--, --, --]], + mask=[[ True, True, True], + [ True, True, True]], + fill_value=999999, + dtype=int64) + + .. note:: + The recommended practice for initializing ``mask`` with a scalar + boolean value is to use ``True``/``False`` rather than + ``np.True_``/``np.False_``. The reason is :attr:`nomask` + is represented internally as ``np.False_``. + + >>> np.False_ is np.ma.nomask + True + + """ + + __array_priority__ = 15 + _defaultmask = nomask + _defaulthardmask = False + _baseclass = ndarray + + # Maximum number of elements per axis used when printing an array. The + # 1d case is handled separately because we need more values in this case. + _print_width = 100 + _print_width_1d = 1500 + + def __new__(cls, data=None, mask=nomask, dtype=None, copy=False, + subok=True, ndmin=0, fill_value=None, keep_mask=True, + hard_mask=None, shrink=True, order=None): + """ + Create a new masked array from scratch. + + Notes + ----- + A masked array can also be created by taking a .view(MaskedArray). + + """ + # Process data. + copy = None if not copy else True + _data = np.array(data, dtype=dtype, copy=copy, + order=order, subok=True, ndmin=ndmin) + _baseclass = getattr(data, '_baseclass', type(_data)) + # Check that we're not erasing the mask. + if isinstance(data, MaskedArray) and (data.shape != _data.shape): + copy = True + + # Here, we copy the _view_, so that we can attach new properties to it + # we must never do .view(MaskedConstant), as that would create a new + # instance of np.ma.masked, which make identity comparison fail + if isinstance(data, cls) and subok and not isinstance(data, MaskedConstant): + _data = ndarray.view(_data, type(data)) + else: + _data = ndarray.view(_data, cls) + + # Handle the case where data is not a subclass of ndarray, but + # still has the _mask attribute like MaskedArrays + if hasattr(data, '_mask') and not isinstance(data, ndarray): + _data._mask = data._mask + # FIXME: should we set `_data._sharedmask = True`? + # Process mask. + # Type of the mask + mdtype = make_mask_descr(_data.dtype) + if mask is nomask: + # Case 1. : no mask in input. + # Erase the current mask ? + if not keep_mask: + # With a reduced version + if shrink: + _data._mask = nomask + # With full version + else: + _data._mask = np.zeros(_data.shape, dtype=mdtype) + # Check whether we missed something + elif isinstance(data, (tuple, list)): + try: + # If data is a sequence of masked array + mask = np.array( + [getmaskarray(np.asanyarray(m, dtype=_data.dtype)) + for m in data], dtype=mdtype) + except (ValueError, TypeError): + # If data is nested + mask = nomask + # Force shrinking of the mask if needed (and possible) + if (mdtype == MaskType) and mask.any(): + _data._mask = mask + _data._sharedmask = False + else: + _data._sharedmask = not copy + if copy: + _data._mask = _data._mask.copy() + # Reset the shape of the original mask + if getmask(data) is not nomask: + # gh-21022 encounters an issue here + # because data._mask.shape is not writeable, but + # the op was also pointless in that case, because + # the shapes were the same, so we can at least + # avoid that path + if data._mask.shape != data.shape: + data._mask.shape = data.shape + else: + # Case 2. : With a mask in input. + # If mask is boolean, create an array of True or False + + # if users pass `mask=None` be forgiving here and cast it False + # for speed; although the default is `mask=nomask` and can differ. + if mask is None: + mask = False + + if mask is True and mdtype == MaskType: + mask = np.ones(_data.shape, dtype=mdtype) + elif mask is False and mdtype == MaskType: + mask = np.zeros(_data.shape, dtype=mdtype) + else: + # Read the mask with the current mdtype + try: + mask = np.array(mask, copy=copy, dtype=mdtype) + # Or assume it's a sequence of bool/int + except TypeError: + mask = np.array([tuple([m] * len(mdtype)) for m in mask], + dtype=mdtype) + # Make sure the mask and the data have the same shape + if mask.shape != _data.shape: + (nd, nm) = (_data.size, mask.size) + if nm == 1: + mask = np.resize(mask, _data.shape) + elif nm == nd: + mask = np.reshape(mask, _data.shape) + else: + msg = (f"Mask and data not compatible:" + f" data size is {nd}, mask size is {nm}.") + raise MaskError(msg) + copy = True + # Set the mask to the new value + if _data._mask is nomask: + _data._mask = mask + _data._sharedmask = not copy + elif not keep_mask: + _data._mask = mask + _data._sharedmask = not copy + else: + if _data.dtype.names is not None: + def _recursive_or(a, b): + "do a|=b on each field of a, recursively" + for name in a.dtype.names: + (af, bf) = (a[name], b[name]) + if af.dtype.names is not None: + _recursive_or(af, bf) + else: + af |= bf + + _recursive_or(_data._mask, mask) + else: + _data._mask = np.logical_or(mask, _data._mask) + _data._sharedmask = False + + # Update fill_value. + if fill_value is None: + fill_value = getattr(data, '_fill_value', None) + # But don't run the check unless we have something to check. + if fill_value is not None: + _data._fill_value = _check_fill_value(fill_value, _data.dtype) + # Process extra options .. + if hard_mask is None: + _data._hardmask = getattr(data, '_hardmask', False) + else: + _data._hardmask = hard_mask + _data._baseclass = _baseclass + return _data + + def _update_from(self, obj): + """ + Copies some attributes of obj to self. + + """ + if isinstance(obj, ndarray): + _baseclass = type(obj) + else: + _baseclass = ndarray + # We need to copy the _basedict to avoid backward propagation + _optinfo = {} + _optinfo.update(getattr(obj, '_optinfo', {})) + _optinfo.update(getattr(obj, '_basedict', {})) + if not isinstance(obj, MaskedArray): + _optinfo.update(getattr(obj, '__dict__', {})) + _dict = {'_fill_value': getattr(obj, '_fill_value', None), + '_hardmask': getattr(obj, '_hardmask', False), + '_sharedmask': getattr(obj, '_sharedmask', False), + '_isfield': getattr(obj, '_isfield', False), + '_baseclass': getattr(obj, '_baseclass', _baseclass), + '_optinfo': _optinfo, + '_basedict': _optinfo} + self.__dict__.update(_dict) + self.__dict__.update(_optinfo) + + def __array_finalize__(self, obj): + """ + Finalizes the masked array. + + """ + # Get main attributes. + self._update_from(obj) + + # We have to decide how to initialize self.mask, based on + # obj.mask. This is very difficult. There might be some + # correspondence between the elements in the array we are being + # created from (= obj) and us. Or there might not. This method can + # be called in all kinds of places for all kinds of reasons -- could + # be empty_like, could be slicing, could be a ufunc, could be a view. + # The numpy subclassing interface simply doesn't give us any way + # to know, which means that at best this method will be based on + # guesswork and heuristics. To make things worse, there isn't even any + # clear consensus about what the desired behavior is. For instance, + # most users think that np.empty_like(marr) -- which goes via this + # method -- should return a masked array with an empty mask (see + # gh-3404 and linked discussions), but others disagree, and they have + # existing code which depends on empty_like returning an array that + # matches the input mask. + # + # Historically our algorithm was: if the template object mask had the + # same *number of elements* as us, then we used *it's mask object + # itself* as our mask, so that writes to us would also write to the + # original array. This is horribly broken in multiple ways. + # + # Now what we do instead is, if the template object mask has the same + # number of elements as us, and we do not have the same base pointer + # as the template object (b/c views like arr[...] should keep the same + # mask), then we make a copy of the template object mask and use + # that. This is also horribly broken but somewhat less so. Maybe. + if isinstance(obj, ndarray): + # XX: This looks like a bug -- shouldn't it check self.dtype + # instead? + if obj.dtype.names is not None: + _mask = getmaskarray(obj) + else: + _mask = getmask(obj) + + # If self and obj point to exactly the same data, then probably + # self is a simple view of obj (e.g., self = obj[...]), so they + # should share the same mask. (This isn't 100% reliable, e.g. self + # could be the first row of obj, or have strange strides, but as a + # heuristic it's not bad.) In all other cases, we make a copy of + # the mask, so that future modifications to 'self' do not end up + # side-effecting 'obj' as well. + if (_mask is not nomask and obj.__array_interface__["data"][0] + != self.__array_interface__["data"][0]): + # We should make a copy. But we could get here via astype, + # in which case the mask might need a new dtype as well + # (e.g., changing to or from a structured dtype), and the + # order could have changed. So, change the mask type if + # needed and use astype instead of copy. + if self.dtype == obj.dtype: + _mask_dtype = _mask.dtype + else: + _mask_dtype = make_mask_descr(self.dtype) + + if self.flags.c_contiguous: + order = "C" + elif self.flags.f_contiguous: + order = "F" + else: + order = "K" + + _mask = _mask.astype(_mask_dtype, order) + else: + # Take a view so shape changes, etc., do not propagate back. + _mask = _mask.view() + else: + _mask = nomask + + self._mask = _mask + # Finalize the mask + if self._mask is not nomask: + try: + self._mask.shape = self.shape + except ValueError: + self._mask = nomask + except (TypeError, AttributeError): + # When _mask.shape is not writable (because it's a void) + pass + + # Finalize the fill_value + if self._fill_value is not None: + self._fill_value = _check_fill_value(self._fill_value, self.dtype) + elif self.dtype.names is not None: + # Finalize the default fill_value for structured arrays + self._fill_value = _check_fill_value(None, self.dtype) + + def __array_wrap__(self, obj, context=None, return_scalar=False): + """ + Special hook for ufuncs. + + Wraps the numpy array and sets the mask according to context. + + """ + if obj is self: # for in-place operations + result = obj + else: + result = obj.view(type(self)) + result._update_from(self) + + if context is not None: + result._mask = result._mask.copy() + func, args, out_i = context + # args sometimes contains outputs (gh-10459), which we don't want + input_args = args[:func.nin] + m = functools.reduce(mask_or, [getmaskarray(arg) for arg in input_args]) + # Get the domain mask + domain = ufunc_domain.get(func) + if domain is not None: + # Take the domain, and make sure it's a ndarray + with np.errstate(divide='ignore', invalid='ignore'): + # The result may be masked for two (unary) domains. + # That can't really be right as some domains drop + # the mask and some don't behaving differently here. + d = domain(*input_args).astype(bool, copy=False) + d = filled(d, True) + + if d.any(): + # Fill the result where the domain is wrong + try: + # Binary domain: take the last value + fill_value = ufunc_fills[func][-1] + except TypeError: + # Unary domain: just use this one + fill_value = ufunc_fills[func] + except KeyError: + # Domain not recognized, use fill_value instead + fill_value = self.fill_value + + np.copyto(result, fill_value, where=d) + + # Update the mask + if m is nomask: + m = d + else: + # Don't modify inplace, we risk back-propagation + m = (m | d) + + # Make sure the mask has the proper size + if result is not self and result.shape == () and m: + return masked + else: + result._mask = m + result._sharedmask = False + + return result + + def view(self, dtype=None, type=None, fill_value=None): + """ + Return a view of the MaskedArray data. + + Parameters + ---------- + dtype : data-type or ndarray sub-class, optional + Data-type descriptor of the returned view, e.g., float32 or int16. + The default, None, results in the view having the same data-type + as `a`. As with ``ndarray.view``, dtype can also be specified as + an ndarray sub-class, which then specifies the type of the + returned object (this is equivalent to setting the ``type`` + parameter). + type : Python type, optional + Type of the returned view, either ndarray or a subclass. The + default None results in type preservation. + fill_value : scalar, optional + The value to use for invalid entries (None by default). + If None, then this argument is inferred from the passed `dtype`, or + in its absence the original array, as discussed in the notes below. + + See Also + -------- + numpy.ndarray.view : Equivalent method on ndarray object. + + Notes + ----- + + ``a.view()`` is used two different ways: + + ``a.view(some_dtype)`` or ``a.view(dtype=some_dtype)`` constructs a view + of the array's memory with a different data-type. This can cause a + reinterpretation of the bytes of memory. + + ``a.view(ndarray_subclass)`` or ``a.view(type=ndarray_subclass)`` just + returns an instance of `ndarray_subclass` that looks at the same array + (same shape, dtype, etc.) This does not cause a reinterpretation of the + memory. + + If `fill_value` is not specified, but `dtype` is specified (and is not + an ndarray sub-class), the `fill_value` of the MaskedArray will be + reset. If neither `fill_value` nor `dtype` are specified (or if + `dtype` is an ndarray sub-class), then the fill value is preserved. + Finally, if `fill_value` is specified, but `dtype` is not, the fill + value is set to the specified value. + + For ``a.view(some_dtype)``, if ``some_dtype`` has a different number of + bytes per entry than the previous dtype (for example, converting a + regular array to a structured array), then the behavior of the view + cannot be predicted just from the superficial appearance of ``a`` (shown + by ``print(a)``). It also depends on exactly how ``a`` is stored in + memory. Therefore if ``a`` is C-ordered versus fortran-ordered, versus + defined as a slice or transpose, etc., the view may give different + results. + """ + + if dtype is None: + if type is None: + output = ndarray.view(self) + else: + output = ndarray.view(self, type) + elif type is None: + try: + if issubclass(dtype, ndarray): + output = ndarray.view(self, dtype) + dtype = None + else: + output = ndarray.view(self, dtype) + except TypeError: + output = ndarray.view(self, dtype) + else: + output = ndarray.view(self, dtype, type) + + # also make the mask be a view (so attr changes to the view's + # mask do no affect original object's mask) + # (especially important to avoid affecting np.masked singleton) + if getmask(output) is not nomask: + output._mask = output._mask.view() + + # Make sure to reset the _fill_value if needed + if getattr(output, '_fill_value', None) is not None: + if fill_value is None: + if dtype is None: + pass # leave _fill_value as is + else: + output._fill_value = None + else: + output.fill_value = fill_value + return output + + def __getitem__(self, indx): + """ + x.__getitem__(y) <==> x[y] + + Return the item described by i, as a masked array. + + """ + # We could directly use ndarray.__getitem__ on self. + # But then we would have to modify __array_finalize__ to prevent the + # mask of being reshaped if it hasn't been set up properly yet + # So it's easier to stick to the current version + dout = self.data[indx] + _mask = self._mask + + def _is_scalar(m): + return not isinstance(m, np.ndarray) + + def _scalar_heuristic(arr, elem): + """ + Return whether `elem` is a scalar result of indexing `arr`, or None + if undecidable without promoting nomask to a full mask + """ + # obviously a scalar + if not isinstance(elem, np.ndarray): + return True + + # object array scalar indexing can return anything + elif arr.dtype.type is np.object_: + if arr.dtype is not elem.dtype: + # elem is an array, but dtypes do not match, so must be + # an element + return True + + # well-behaved subclass that only returns 0d arrays when + # expected - this is not a scalar + elif type(arr).__getitem__ == ndarray.__getitem__: + return False + + return None + + if _mask is not nomask: + # _mask cannot be a subclass, so it tells us whether we should + # expect a scalar. It also cannot be of dtype object. + mout = _mask[indx] + scalar_expected = _is_scalar(mout) + + else: + # attempt to apply the heuristic to avoid constructing a full mask + mout = nomask + scalar_expected = _scalar_heuristic(self.data, dout) + if scalar_expected is None: + # heuristics have failed + # construct a full array, so we can be certain. This is costly. + # we could also fall back on ndarray.__getitem__(self.data, indx) + scalar_expected = _is_scalar(getmaskarray(self)[indx]) + + # Did we extract a single item? + if scalar_expected: + # A record + if isinstance(dout, np.void): + # We should always re-cast to mvoid, otherwise users can + # change masks on rows that already have masked values, but not + # on rows that have no masked values, which is inconsistent. + return mvoid(dout, mask=mout, hardmask=self._hardmask) + + # special case introduced in gh-5962 + elif (self.dtype.type is np.object_ and + isinstance(dout, np.ndarray) and + dout is not masked): + # If masked, turn into a MaskedArray, with everything masked. + if mout: + return MaskedArray(dout, mask=True) + else: + return dout + + # Just a scalar + elif mout: + return masked + else: + return dout + else: + # Force dout to MA + dout = dout.view(type(self)) + # Inherit attributes from self + dout._update_from(self) + # Check the fill_value + if is_string_or_list_of_strings(indx): + if self._fill_value is not None: + dout._fill_value = self._fill_value[indx] + + # Something like gh-15895 has happened if this check fails. + # _fill_value should always be an ndarray. + if not isinstance(dout._fill_value, np.ndarray): + raise RuntimeError('Internal NumPy error.') + # If we're indexing a multidimensional field in a + # structured array (such as dtype("(2,)i2,(2,)i1")), + # dimensionality goes up (M[field].ndim == M.ndim + + # M.dtype[field].ndim). That's fine for + # M[field] but problematic for M[field].fill_value + # which should have shape () to avoid breaking several + # methods. There is no great way out, so set to + # first element. See issue #6723. + if dout._fill_value.ndim > 0: + if not (dout._fill_value == + dout._fill_value.flat[0]).all(): + warnings.warn( + "Upon accessing multidimensional field " + f"{indx!s}, need to keep dimensionality " + "of fill_value at 0. Discarding " + "heterogeneous fill_value and setting " + f"all to {dout._fill_value[0]!s}.", + stacklevel=2) + # Need to use `.flat[0:1].squeeze(...)` instead of just + # `.flat[0]` to ensure the result is a 0d array and not + # a scalar. + dout._fill_value = dout._fill_value.flat[0:1].squeeze(axis=0) + dout._isfield = True + # Update the mask if needed + if mout is not nomask: + # set shape to match that of data; this is needed for matrices + dout._mask = reshape(mout, dout.shape) + dout._sharedmask = True + # Note: Don't try to check for m.any(), that'll take too long + return dout + + # setitem may put NaNs into integer arrays or occasionally overflow a + # float. But this may happen in masked values, so avoid otherwise + # correct warnings (as is typical also in masked calculations). + @np.errstate(over='ignore', invalid='ignore') + def __setitem__(self, indx, value): + """ + x.__setitem__(i, y) <==> x[i]=y + + Set item described by index. If value is masked, masks those + locations. + + """ + if self is masked: + raise MaskError('Cannot alter the masked element.') + _data = self._data + _mask = self._mask + if isinstance(indx, str): + _data[indx] = value + if _mask is nomask: + self._mask = _mask = make_mask_none(self.shape, self.dtype) + _mask[indx] = getmask(value) + return + + _dtype = _data.dtype + + if value is masked: + # The mask wasn't set: create a full version. + if _mask is nomask: + _mask = self._mask = make_mask_none(self.shape, _dtype) + # Now, set the mask to its value. + if _dtype.names is not None: + _mask[indx] = tuple([True] * len(_dtype.names)) + else: + _mask[indx] = True + return + + # Get the _data part of the new value + dval = getattr(value, '_data', value) + # Get the _mask part of the new value + mval = getmask(value) + if _dtype.names is not None and mval is nomask: + mval = tuple([False] * len(_dtype.names)) + if _mask is nomask: + # Set the data, then the mask + _data[indx] = dval + if mval is not nomask: + _mask = self._mask = make_mask_none(self.shape, _dtype) + _mask[indx] = mval + elif not self._hardmask: + # Set the data, then the mask + if (isinstance(indx, masked_array) and + not isinstance(value, masked_array)): + _data[indx.data] = dval + else: + _data[indx] = dval + _mask[indx] = mval + elif hasattr(indx, 'dtype') and (indx.dtype == MaskType): + indx = indx * umath.logical_not(_mask) + _data[indx] = dval + else: + if _dtype.names is not None: + err_msg = "Flexible 'hard' masks are not yet supported." + raise NotImplementedError(err_msg) + mindx = mask_or(_mask[indx], mval, copy=True) + dindx = self._data[indx] + if dindx.size > 1: + np.copyto(dindx, dval, where=~mindx) + elif mindx is nomask: + dindx = dval + _data[indx] = dindx + _mask[indx] = mindx + return + + # Define so that we can overwrite the setter. + @property + def dtype(self): + return super().dtype + + @dtype.setter + def dtype(self, dtype): + super(MaskedArray, type(self)).dtype.__set__(self, dtype) + if self._mask is not nomask: + self._mask = self._mask.view(make_mask_descr(dtype), ndarray) + # Try to reset the shape of the mask (if we don't have a void). + # This raises a ValueError if the dtype change won't work. + try: + self._mask.shape = self.shape + except (AttributeError, TypeError): + pass + + @property + def shape(self): + return super().shape + + @shape.setter + def shape(self, shape): + super(MaskedArray, type(self)).shape.__set__(self, shape) + # Cannot use self._mask, since it may not (yet) exist when a + # masked matrix sets the shape. + if getmask(self) is not nomask: + self._mask.shape = self.shape + + def __setmask__(self, mask, copy=False): + """ + Set the mask. + + """ + idtype = self.dtype + current_mask = self._mask + if mask is masked: + mask = True + + if current_mask is nomask: + # Make sure the mask is set + # Just don't do anything if there's nothing to do. + if mask is nomask: + return + current_mask = self._mask = make_mask_none(self.shape, idtype) + + if idtype.names is None: + # No named fields. + # Hardmask: don't unmask the data + if self._hardmask: + current_mask |= mask + # Softmask: set everything to False + # If it's obviously a compatible scalar, use a quick update + # method. + elif isinstance(mask, (int, float, np.bool, np.number)): + current_mask[...] = mask + # Otherwise fall back to the slower, general purpose way. + else: + current_mask.flat = mask + else: + # Named fields w/ + mdtype = current_mask.dtype + mask = np.asarray(mask) + # Mask is a singleton + if not mask.ndim: + # It's a boolean : make a record + if mask.dtype.kind == 'b': + mask = np.array(tuple([mask.item()] * len(mdtype)), + dtype=mdtype) + # It's a record: make sure the dtype is correct + else: + mask = mask.astype(mdtype) + # Mask is a sequence + else: + # Make sure the new mask is a ndarray with the proper dtype + try: + copy = None if not copy else True + mask = np.array(mask, copy=copy, dtype=mdtype) + # Or assume it's a sequence of bool/int + except TypeError: + mask = np.array([tuple([m] * len(mdtype)) for m in mask], + dtype=mdtype) + # Hardmask: don't unmask the data + if self._hardmask: + for n in idtype.names: + current_mask[n] |= mask[n] + # Softmask: set everything to False + # If it's obviously a compatible scalar, use a quick update + # method. + elif isinstance(mask, (int, float, np.bool, np.number)): + current_mask[...] = mask + # Otherwise fall back to the slower, general purpose way. + else: + current_mask.flat = mask + # Reshape if needed + if current_mask.shape: + current_mask.shape = self.shape + return + + _set_mask = __setmask__ + + @property + def mask(self): + """ Current mask. """ + + # We could try to force a reshape, but that wouldn't work in some + # cases. + # Return a view so that the dtype and shape cannot be changed in place + # This still preserves nomask by identity + return self._mask.view() + + @mask.setter + def mask(self, value): + self.__setmask__(value) + + @property + def recordmask(self): + """ + Get or set the mask of the array if it has no named fields. For + structured arrays, returns a ndarray of booleans where entries are + ``True`` if **all** the fields are masked, ``False`` otherwise: + + >>> x = np.ma.array([(1, 1), (2, 2), (3, 3), (4, 4), (5, 5)], + ... mask=[(0, 0), (1, 0), (1, 1), (0, 1), (0, 0)], + ... dtype=[('a', int), ('b', int)]) + >>> x.recordmask + array([False, False, True, False, False]) + """ + + _mask = self._mask.view(ndarray) + if _mask.dtype.names is None: + return _mask + return np.all(flatten_structured_array(_mask), axis=-1) + + @recordmask.setter + def recordmask(self, mask): + raise NotImplementedError("Coming soon: setting the mask per records!") + + def harden_mask(self): + """ + Force the mask to hard, preventing unmasking by assignment. + + Whether the mask of a masked array is hard or soft is determined by + its `~ma.MaskedArray.hardmask` property. `harden_mask` sets + `~ma.MaskedArray.hardmask` to ``True`` (and returns the modified + self). + + See Also + -------- + ma.MaskedArray.hardmask + ma.MaskedArray.soften_mask + + """ + self._hardmask = True + return self + + def soften_mask(self): + """ + Force the mask to soft (default), allowing unmasking by assignment. + + Whether the mask of a masked array is hard or soft is determined by + its `~ma.MaskedArray.hardmask` property. `soften_mask` sets + `~ma.MaskedArray.hardmask` to ``False`` (and returns the modified + self). + + See Also + -------- + ma.MaskedArray.hardmask + ma.MaskedArray.harden_mask + + """ + self._hardmask = False + return self + + @property + def hardmask(self): + """ + Specifies whether values can be unmasked through assignments. + + By default, assigning definite values to masked array entries will + unmask them. When `hardmask` is ``True``, the mask will not change + through assignments. + + See Also + -------- + ma.MaskedArray.harden_mask + ma.MaskedArray.soften_mask + + Examples + -------- + >>> import numpy as np + >>> x = np.arange(10) + >>> m = np.ma.masked_array(x, x>5) + >>> assert not m.hardmask + + Since `m` has a soft mask, assigning an element value unmasks that + element: + + >>> m[8] = 42 + >>> m + masked_array(data=[0, 1, 2, 3, 4, 5, --, --, 42, --], + mask=[False, False, False, False, False, False, + True, True, False, True], + fill_value=999999) + + After hardening, the mask is not affected by assignments: + + >>> hardened = np.ma.harden_mask(m) + >>> assert m.hardmask and hardened is m + >>> m[:] = 23 + >>> m + masked_array(data=[23, 23, 23, 23, 23, 23, --, --, 23, --], + mask=[False, False, False, False, False, False, + True, True, False, True], + fill_value=999999) + + """ + return self._hardmask + + def unshare_mask(self): + """ + Copy the mask and set the `sharedmask` flag to ``False``. + + Whether the mask is shared between masked arrays can be seen from + the `sharedmask` property. `unshare_mask` ensures the mask is not + shared. A copy of the mask is only made if it was shared. + + See Also + -------- + sharedmask + + """ + if self._sharedmask: + self._mask = self._mask.copy() + self._sharedmask = False + return self + + @property + def sharedmask(self): + """ Share status of the mask (read-only). """ + return self._sharedmask + + def shrink_mask(self): + """ + Reduce a mask to nomask when possible. + + Parameters + ---------- + None + + Returns + ------- + result : MaskedArray + A :class:`~ma.MaskedArray` object. + + Examples + -------- + >>> import numpy as np + >>> x = np.ma.array([[1,2 ], [3, 4]], mask=[0]*4) + >>> x.mask + array([[False, False], + [False, False]]) + >>> x.shrink_mask() + masked_array( + data=[[1, 2], + [3, 4]], + mask=False, + fill_value=999999) + >>> x.mask + False + + """ + self._mask = _shrink_mask(self._mask) + return self + + @property + def baseclass(self): + """ Class of the underlying data (read-only). """ + return self._baseclass + + def _get_data(self): + """ + Returns the underlying data, as a view of the masked array. + + If the underlying data is a subclass of :class:`numpy.ndarray`, it is + returned as such. + + >>> x = np.ma.array(np.matrix([[1, 2], [3, 4]]), mask=[[0, 1], [1, 0]]) + >>> x.data + matrix([[1, 2], + [3, 4]]) + + The type of the data can be accessed through the :attr:`baseclass` + attribute. + """ + return ndarray.view(self, self._baseclass) + + _data = property(fget=_get_data) + data = property(fget=_get_data) + + @property + def flat(self): + """ Return a flat iterator, or set a flattened version of self to value. """ + return MaskedIterator(self) + + @flat.setter + def flat(self, value): + y = self.ravel() + y[:] = value + + @property + def fill_value(self): + """ + The filling value of the masked array is a scalar. When setting, None + will set to a default based on the data type. + + Examples + -------- + >>> import numpy as np + >>> for dt in [np.int32, np.int64, np.float64, np.complex128]: + ... np.ma.array([0, 1], dtype=dt).get_fill_value() + ... + np.int64(999999) + np.int64(999999) + np.float64(1e+20) + np.complex128(1e+20+0j) + + >>> x = np.ma.array([0, 1.], fill_value=-np.inf) + >>> x.fill_value + np.float64(-inf) + >>> x.fill_value = np.pi + >>> x.fill_value + np.float64(3.1415926535897931) + + Reset to default: + + >>> x.fill_value = None + >>> x.fill_value + np.float64(1e+20) + + """ + if self._fill_value is None: + self._fill_value = _check_fill_value(None, self.dtype) + + # Temporary workaround to account for the fact that str and bytes + # scalars cannot be indexed with (), whereas all other numpy + # scalars can. See issues #7259 and #7267. + # The if-block can be removed after #7267 has been fixed. + if isinstance(self._fill_value, ndarray): + return self._fill_value[()] + return self._fill_value + + @fill_value.setter + def fill_value(self, value=None): + target = _check_fill_value(value, self.dtype) + if not target.ndim == 0: + # 2019-11-12, 1.18.0 + warnings.warn( + "Non-scalar arrays for the fill value are deprecated. Use " + "arrays with scalar values instead. The filled function " + "still supports any array as `fill_value`.", + DeprecationWarning, stacklevel=2) + + _fill_value = self._fill_value + if _fill_value is None: + # Create the attribute if it was undefined + self._fill_value = target + else: + # Don't overwrite the attribute, just fill it (for propagation) + _fill_value[()] = target + + # kept for compatibility + get_fill_value = fill_value.fget + set_fill_value = fill_value.fset + + def filled(self, fill_value=None): + """ + Return a copy of self, with masked values filled with a given value. + **However**, if there are no masked values to fill, self will be + returned instead as an ndarray. + + Parameters + ---------- + fill_value : array_like, optional + The value to use for invalid entries. Can be scalar or non-scalar. + If non-scalar, the resulting ndarray must be broadcastable over + input array. Default is None, in which case, the `fill_value` + attribute of the array is used instead. + + Returns + ------- + filled_array : ndarray + A copy of ``self`` with invalid entries replaced by *fill_value* + (be it the function argument or the attribute of ``self``), or + ``self`` itself as an ndarray if there are no invalid entries to + be replaced. + + Notes + ----- + The result is **not** a MaskedArray! + + Examples + -------- + >>> import numpy as np + >>> x = np.ma.array([1,2,3,4,5], mask=[0,0,1,0,1], fill_value=-999) + >>> x.filled() + array([ 1, 2, -999, 4, -999]) + >>> x.filled(fill_value=1000) + array([ 1, 2, 1000, 4, 1000]) + >>> type(x.filled()) + + + Subclassing is preserved. This means that if, e.g., the data part of + the masked array is a recarray, `filled` returns a recarray: + + >>> x = np.array([(-1, 2), (-3, 4)], dtype='i8,i8').view(np.recarray) + >>> m = np.ma.array(x, mask=[(True, False), (False, True)]) + >>> m.filled() + rec.array([(999999, 2), ( -3, 999999)], + dtype=[('f0', '>> import numpy as np + >>> x = np.ma.array(np.arange(5), mask=[0]*2 + [1]*3) + >>> x.compressed() + array([0, 1]) + >>> type(x.compressed()) + + + N-D arrays are compressed to 1-D. + + >>> arr = [[1, 2], [3, 4]] + >>> mask = [[1, 0], [0, 1]] + >>> x = np.ma.array(arr, mask=mask) + >>> x.compressed() + array([2, 3]) + + """ + data = ndarray.ravel(self._data) + if self._mask is not nomask: + data = data.compress(np.logical_not(ndarray.ravel(self._mask))) + return data + + def compress(self, condition, axis=None, out=None): + """ + Return `a` where condition is ``True``. + + If condition is a `~ma.MaskedArray`, missing values are considered + as ``False``. + + Parameters + ---------- + condition : var + Boolean 1-d array selecting which entries to return. If len(condition) + is less than the size of a along the axis, then output is truncated + to length of condition array. + axis : {None, int}, optional + Axis along which the operation must be performed. + out : {None, ndarray}, optional + Alternative output array in which to place the result. It must have + the same shape as the expected output but the type will be cast if + necessary. + + Returns + ------- + result : MaskedArray + A :class:`~ma.MaskedArray` object. + + Notes + ----- + Please note the difference with :meth:`compressed` ! + The output of :meth:`compress` has a mask, the output of + :meth:`compressed` does not. + + Examples + -------- + >>> import numpy as np + >>> x = np.ma.array([[1,2,3],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4) + >>> x + masked_array( + data=[[1, --, 3], + [--, 5, --], + [7, --, 9]], + mask=[[False, True, False], + [ True, False, True], + [False, True, False]], + fill_value=999999) + >>> x.compress([1, 0, 1]) + masked_array(data=[1, 3], + mask=[False, False], + fill_value=999999) + + >>> x.compress([1, 0, 1], axis=1) + masked_array( + data=[[1, 3], + [--, --], + [7, 9]], + mask=[[False, False], + [ True, True], + [False, False]], + fill_value=999999) + + """ + # Get the basic components + (_data, _mask) = (self._data, self._mask) + + # Force the condition to a regular ndarray and forget the missing + # values. + condition = np.asarray(condition) + + _new = _data.compress(condition, axis=axis, out=out).view(type(self)) + _new._update_from(self) + if _mask is not nomask: + _new._mask = _mask.compress(condition, axis=axis) + return _new + + def _insert_masked_print(self): + """ + Replace masked values with masked_print_option, casting all innermost + dtypes to object. + """ + if masked_print_option.enabled(): + mask = self._mask + if mask is nomask: + res = self._data + else: + # convert to object array to make filled work + data = self._data + # For big arrays, to avoid a costly conversion to the + # object dtype, extract the corners before the conversion. + print_width = (self._print_width if self.ndim > 1 + else self._print_width_1d) + for axis in range(self.ndim): + if data.shape[axis] > print_width: + ind = print_width // 2 + arr = np.split(data, (ind, -ind), axis=axis) + data = np.concatenate((arr[0], arr[2]), axis=axis) + arr = np.split(mask, (ind, -ind), axis=axis) + mask = np.concatenate((arr[0], arr[2]), axis=axis) + + rdtype = _replace_dtype_fields(self.dtype, "O") + res = data.astype(rdtype) + _recursive_printoption(res, mask, masked_print_option) + else: + res = self.filled(self.fill_value) + return res + + def __str__(self): + return str(self._insert_masked_print()) + + def __repr__(self): + """ + Literal string representation. + + """ + if self._baseclass is np.ndarray: + name = 'array' + else: + name = self._baseclass.__name__ + + # 2016-11-19: Demoted to legacy format + if np._core.arrayprint._get_legacy_print_mode() <= 113: + is_long = self.ndim > 1 + parameters = { + 'name': name, + 'nlen': " " * len(name), + 'data': str(self), + 'mask': str(self._mask), + 'fill': str(self.fill_value), + 'dtype': str(self.dtype) + } + is_structured = bool(self.dtype.names) + key = '{}_{}'.format( + 'long' if is_long else 'short', + 'flx' if is_structured else 'std' + ) + return _legacy_print_templates[key] % parameters + + prefix = f"masked_{name}(" + + dtype_needed = ( + not np._core.arrayprint.dtype_is_implied(self.dtype) or + np.all(self.mask) or + self.size == 0 + ) + + # determine which keyword args need to be shown + keys = ['data', 'mask', 'fill_value'] + if dtype_needed: + keys.append('dtype') + + # array has only one row (non-column) + is_one_row = builtins.all(dim == 1 for dim in self.shape[:-1]) + + # choose what to indent each keyword with + min_indent = 2 + if is_one_row: + # first key on the same line as the type, remaining keys + # aligned by equals + indents = {} + indents[keys[0]] = prefix + for k in keys[1:]: + n = builtins.max(min_indent, len(prefix + keys[0]) - len(k)) + indents[k] = ' ' * n + prefix = '' # absorbed into the first indent + else: + # each key on its own line, indented by two spaces + indents = dict.fromkeys(keys, ' ' * min_indent) + prefix = prefix + '\n' # first key on the next line + + # format the field values + reprs = {} + reprs['data'] = np.array2string( + self._insert_masked_print(), + separator=", ", + prefix=indents['data'] + 'data=', + suffix=',') + reprs['mask'] = np.array2string( + self._mask, + separator=", ", + prefix=indents['mask'] + 'mask=', + suffix=',') + + if self._fill_value is None: + self.fill_value # initialize fill_value # noqa: B018 + + if (self._fill_value.dtype.kind in ("S", "U") + and self.dtype.kind == self._fill_value.dtype.kind): + # Allow strings: "N/A" has length 3 so would mismatch. + fill_repr = repr(self.fill_value.item()) + elif self._fill_value.dtype == self.dtype and not self.dtype == object: + # Guess that it is OK to use the string as item repr. To really + # fix this, it needs new logic (shared with structured scalars) + fill_repr = str(self.fill_value) + else: + fill_repr = repr(self.fill_value) + + reprs['fill_value'] = fill_repr + if dtype_needed: + reprs['dtype'] = np._core.arrayprint.dtype_short_repr(self.dtype) + + # join keys with values and indentations + result = ',\n'.join( + f'{indents[k]}{k}={reprs[k]}' + for k in keys + ) + return prefix + result + ')' + + def _delegate_binop(self, other): + # This emulates the logic in + # private/binop_override.h:forward_binop_should_defer + if isinstance(other, type(self)): + return False + array_ufunc = getattr(other, "__array_ufunc__", False) + if array_ufunc is False: + other_priority = getattr(other, "__array_priority__", -1000000) + return self.__array_priority__ < other_priority + else: + # If array_ufunc is not None, it will be called inside the ufunc; + # None explicitly tells us to not call the ufunc, i.e., defer. + return array_ufunc is None + + def _comparison(self, other, compare): + """Compare self with other using operator.eq or operator.ne. + + When either of the elements is masked, the result is masked as well, + but the underlying boolean data are still set, with self and other + considered equal if both are masked, and unequal otherwise. + + For structured arrays, all fields are combined, with masked values + ignored. The result is masked if all fields were masked, with self + and other considered equal only if both were fully masked. + """ + omask = getmask(other) + smask = self.mask + mask = mask_or(smask, omask, copy=True) + + odata = getdata(other) + if mask.dtype.names is not None: + # only == and != are reasonably defined for structured dtypes, + # so give up early for all other comparisons: + if compare not in (operator.eq, operator.ne): + return NotImplemented + # For possibly masked structured arrays we need to be careful, + # since the standard structured array comparison will use all + # fields, masked or not. To avoid masked fields influencing the + # outcome, we set all masked fields in self to other, so they'll + # count as equal. To prepare, we ensure we have the right shape. + broadcast_shape = np.broadcast(self, odata).shape + sbroadcast = np.broadcast_to(self, broadcast_shape, subok=True) + sbroadcast._mask = mask + sdata = sbroadcast.filled(odata) + # Now take care of the mask; the merged mask should have an item + # masked if all fields were masked (in one and/or other). + mask = (mask == np.ones((), mask.dtype)) + # Ensure we can compare masks below if other was not masked. + if omask is np.False_: + omask = np.zeros((), smask.dtype) + + else: + # For regular arrays, just use the data as they come. + sdata = self.data + + check = compare(sdata, odata) + + if isinstance(check, (np.bool, bool)): + return masked if mask else check + + if mask is not nomask: + if compare in (operator.eq, operator.ne): + # Adjust elements that were masked, which should be treated + # as equal if masked in both, unequal if masked in one. + # Note that this works automatically for structured arrays too. + # Ignore this for operations other than `==` and `!=` + check = np.where(mask, compare(smask, omask), check) + + if mask.shape != check.shape: + # Guarantee consistency of the shape, making a copy since the + # the mask may need to get written to later. + mask = np.broadcast_to(mask, check.shape).copy() + + check = check.view(type(self)) + check._update_from(self) + check._mask = mask + + # Cast fill value to np.bool if needed. If it cannot be cast, the + # default boolean fill value is used. + if check._fill_value is not None: + try: + fill = _check_fill_value(check._fill_value, np.bool) + except (TypeError, ValueError): + fill = _check_fill_value(None, np.bool) + check._fill_value = fill + + return check + + def __eq__(self, other): + """Check whether other equals self elementwise. + + When either of the elements is masked, the result is masked as well, + but the underlying boolean data are still set, with self and other + considered equal if both are masked, and unequal otherwise. + + For structured arrays, all fields are combined, with masked values + ignored. The result is masked if all fields were masked, with self + and other considered equal only if both were fully masked. + """ + return self._comparison(other, operator.eq) + + def __ne__(self, other): + """Check whether other does not equal self elementwise. + + When either of the elements is masked, the result is masked as well, + but the underlying boolean data are still set, with self and other + considered equal if both are masked, and unequal otherwise. + + For structured arrays, all fields are combined, with masked values + ignored. The result is masked if all fields were masked, with self + and other considered equal only if both were fully masked. + """ + return self._comparison(other, operator.ne) + + # All other comparisons: + def __le__(self, other): + return self._comparison(other, operator.le) + + def __lt__(self, other): + return self._comparison(other, operator.lt) + + def __ge__(self, other): + return self._comparison(other, operator.ge) + + def __gt__(self, other): + return self._comparison(other, operator.gt) + + def __add__(self, other): + """ + Add self to other, and return a new masked array. + + """ + if self._delegate_binop(other): + return NotImplemented + return add(self, other) + + def __radd__(self, other): + """ + Add other to self, and return a new masked array. + + """ + # In analogy with __rsub__ and __rdiv__, use original order: + # we get here from `other + self`. + return add(other, self) + + def __sub__(self, other): + """ + Subtract other from self, and return a new masked array. + + """ + if self._delegate_binop(other): + return NotImplemented + return subtract(self, other) + + def __rsub__(self, other): + """ + Subtract self from other, and return a new masked array. + + """ + return subtract(other, self) + + def __mul__(self, other): + "Multiply self by other, and return a new masked array." + if self._delegate_binop(other): + return NotImplemented + return multiply(self, other) + + def __rmul__(self, other): + """ + Multiply other by self, and return a new masked array. + + """ + # In analogy with __rsub__ and __rdiv__, use original order: + # we get here from `other * self`. + return multiply(other, self) + + def __truediv__(self, other): + """ + Divide other into self, and return a new masked array. + + """ + if self._delegate_binop(other): + return NotImplemented + return true_divide(self, other) + + def __rtruediv__(self, other): + """ + Divide self into other, and return a new masked array. + + """ + return true_divide(other, self) + + def __floordiv__(self, other): + """ + Divide other into self, and return a new masked array. + + """ + if self._delegate_binop(other): + return NotImplemented + return floor_divide(self, other) + + def __rfloordiv__(self, other): + """ + Divide self into other, and return a new masked array. + + """ + return floor_divide(other, self) + + def __pow__(self, other): + """ + Raise self to the power other, masking the potential NaNs/Infs + + """ + if self._delegate_binop(other): + return NotImplemented + return power(self, other) + + def __rpow__(self, other): + """ + Raise other to the power self, masking the potential NaNs/Infs + + """ + return power(other, self) + + def __iadd__(self, other): + """ + Add other to self in-place. + + """ + m = getmask(other) + if self._mask is nomask: + if m is not nomask and m.any(): + self._mask = make_mask_none(self.shape, self.dtype) + self._mask += m + elif m is not nomask: + self._mask += m + other_data = getdata(other) + other_data = np.where(self._mask, other_data.dtype.type(0), other_data) + self._data.__iadd__(other_data) + return self + + def __isub__(self, other): + """ + Subtract other from self in-place. + + """ + m = getmask(other) + if self._mask is nomask: + if m is not nomask and m.any(): + self._mask = make_mask_none(self.shape, self.dtype) + self._mask += m + elif m is not nomask: + self._mask += m + other_data = getdata(other) + other_data = np.where(self._mask, other_data.dtype.type(0), other_data) + self._data.__isub__(other_data) + return self + + def __imul__(self, other): + """ + Multiply self by other in-place. + + """ + m = getmask(other) + if self._mask is nomask: + if m is not nomask and m.any(): + self._mask = make_mask_none(self.shape, self.dtype) + self._mask += m + elif m is not nomask: + self._mask += m + other_data = getdata(other) + other_data = np.where(self._mask, other_data.dtype.type(1), other_data) + self._data.__imul__(other_data) + return self + + def __ifloordiv__(self, other): + """ + Floor divide self by other in-place. + + """ + other_data = getdata(other) + dom_mask = _DomainSafeDivide().__call__(self._data, other_data) + other_mask = getmask(other) + new_mask = mask_or(other_mask, dom_mask) + # The following 3 lines control the domain filling + if dom_mask.any(): + (_, fval) = ufunc_fills[np.floor_divide] + other_data = np.where( + dom_mask, other_data.dtype.type(fval), other_data) + self._mask |= new_mask + other_data = np.where(self._mask, other_data.dtype.type(1), other_data) + self._data.__ifloordiv__(other_data) + return self + + def __itruediv__(self, other): + """ + True divide self by other in-place. + + """ + other_data = getdata(other) + dom_mask = _DomainSafeDivide().__call__(self._data, other_data) + other_mask = getmask(other) + new_mask = mask_or(other_mask, dom_mask) + # The following 3 lines control the domain filling + if dom_mask.any(): + (_, fval) = ufunc_fills[np.true_divide] + other_data = np.where( + dom_mask, other_data.dtype.type(fval), other_data) + self._mask |= new_mask + other_data = np.where(self._mask, other_data.dtype.type(1), other_data) + self._data.__itruediv__(other_data) + return self + + def __ipow__(self, other): + """ + Raise self to the power other, in place. + + """ + other_data = getdata(other) + other_data = np.where(self._mask, other_data.dtype.type(1), other_data) + other_mask = getmask(other) + with np.errstate(divide='ignore', invalid='ignore'): + self._data.__ipow__(other_data) + invalid = np.logical_not(np.isfinite(self._data)) + if invalid.any(): + if self._mask is not nomask: + self._mask |= invalid + else: + self._mask = invalid + np.copyto(self._data, self.fill_value, where=invalid) + new_mask = mask_or(other_mask, invalid) + self._mask = mask_or(self._mask, new_mask) + return self + + def __float__(self): + """ + Convert to float. + + """ + if self.size > 1: + raise TypeError("Only length-1 arrays can be converted " + "to Python scalars") + elif self._mask: + warnings.warn("Warning: converting a masked element to nan.", stacklevel=2) + return np.nan + return float(self.item()) + + def __int__(self): + """ + Convert to int. + + """ + if self.size > 1: + raise TypeError("Only length-1 arrays can be converted " + "to Python scalars") + elif self._mask: + raise MaskError('Cannot convert masked element to a Python int.') + return int(self.item()) + + @property + def imag(self): + """ + The imaginary part of the masked array. + + This property is a view on the imaginary part of this `MaskedArray`. + + See Also + -------- + real + + Examples + -------- + >>> import numpy as np + >>> x = np.ma.array([1+1.j, -2j, 3.45+1.6j], mask=[False, True, False]) + >>> x.imag + masked_array(data=[1.0, --, 1.6], + mask=[False, True, False], + fill_value=1e+20) + + """ + result = self._data.imag.view(type(self)) + result.__setmask__(self._mask) + return result + + # kept for compatibility + get_imag = imag.fget + + @property + def real(self): + """ + The real part of the masked array. + + This property is a view on the real part of this `MaskedArray`. + + See Also + -------- + imag + + Examples + -------- + >>> import numpy as np + >>> x = np.ma.array([1+1.j, -2j, 3.45+1.6j], mask=[False, True, False]) + >>> x.real + masked_array(data=[1.0, --, 3.45], + mask=[False, True, False], + fill_value=1e+20) + + """ + result = self._data.real.view(type(self)) + result.__setmask__(self._mask) + return result + + # kept for compatibility + get_real = real.fget + + def count(self, axis=None, keepdims=np._NoValue): + """ + Count the non-masked elements of the array along the given axis. + + Parameters + ---------- + axis : None or int or tuple of ints, optional + Axis or axes along which the count is performed. + The default, None, performs the count over all + the dimensions of the input array. `axis` may be negative, in + which case it counts from the last to the first axis. + If this is a tuple of ints, the count is performed on multiple + axes, instead of a single axis or all the axes as before. + keepdims : bool, optional + If this is set to True, the axes which are reduced are left + in the result as dimensions with size one. With this option, + the result will broadcast correctly against the array. + + Returns + ------- + result : ndarray or scalar + An array with the same shape as the input array, with the specified + axis removed. If the array is a 0-d array, or if `axis` is None, a + scalar is returned. + + See Also + -------- + ma.count_masked : Count masked elements in array or along a given axis. + + Examples + -------- + >>> import numpy.ma as ma + >>> a = ma.arange(6).reshape((2, 3)) + >>> a[1, :] = ma.masked + >>> a + masked_array( + data=[[0, 1, 2], + [--, --, --]], + mask=[[False, False, False], + [ True, True, True]], + fill_value=999999) + >>> a.count() + 3 + + When the `axis` keyword is specified an array of appropriate size is + returned. + + >>> a.count(axis=0) + array([1, 1, 1]) + >>> a.count(axis=1) + array([3, 0]) + + """ + kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims} + + m = self._mask + # special case for matrices (we assume no other subclasses modify + # their dimensions) + if isinstance(self.data, np.matrix): + if m is nomask: + m = np.zeros(self.shape, dtype=np.bool) + m = m.view(type(self.data)) + + if m is nomask: + # compare to _count_reduce_items in _methods.py + + if self.shape == (): + if axis not in (None, 0): + raise np.exceptions.AxisError(axis=axis, ndim=self.ndim) + return 1 + elif axis is None: + if kwargs.get('keepdims'): + return np.array(self.size, dtype=np.intp, ndmin=self.ndim) + return self.size + + axes = normalize_axis_tuple(axis, self.ndim) + items = 1 + for ax in axes: + items *= self.shape[ax] + + if kwargs.get('keepdims'): + out_dims = list(self.shape) + for a in axes: + out_dims[a] = 1 + else: + out_dims = [d for n, d in enumerate(self.shape) + if n not in axes] + # make sure to return a 0-d array if axis is supplied + return np.full(out_dims, items, dtype=np.intp) + + # take care of the masked singleton + if self is masked: + return 0 + + return (~m).sum(axis=axis, dtype=np.intp, **kwargs) + + def ravel(self, order='C'): + """ + Returns a 1D version of self, as a view. + + Parameters + ---------- + order : {'C', 'F', 'A', 'K'}, optional + The elements of `a` are read using this index order. 'C' means to + index the elements in C-like order, with the last axis index + changing fastest, back to the first axis index changing slowest. + 'F' means to index the elements in Fortran-like index order, with + the first index changing fastest, and the last index changing + slowest. Note that the 'C' and 'F' options take no account of the + memory layout of the underlying array, and only refer to the order + of axis indexing. 'A' means to read the elements in Fortran-like + index order if `m` is Fortran *contiguous* in memory, C-like order + otherwise. 'K' means to read the elements in the order they occur + in memory, except for reversing the data when strides are negative. + By default, 'C' index order is used. + (Masked arrays currently use 'A' on the data when 'K' is passed.) + + Returns + ------- + MaskedArray + Output view is of shape ``(self.size,)`` (or + ``(np.ma.product(self.shape),)``). + + Examples + -------- + >>> import numpy as np + >>> x = np.ma.array([[1,2,3],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4) + >>> x + masked_array( + data=[[1, --, 3], + [--, 5, --], + [7, --, 9]], + mask=[[False, True, False], + [ True, False, True], + [False, True, False]], + fill_value=999999) + >>> x.ravel() + masked_array(data=[1, --, 3, --, 5, --, 7, --, 9], + mask=[False, True, False, True, False, True, False, True, + False], + fill_value=999999) + + """ + # The order of _data and _mask could be different (it shouldn't be + # normally). Passing order `K` or `A` would be incorrect. + # So we ignore the mask memory order. + # TODO: We don't actually support K, so use A instead. We could + # try to guess this correct by sorting strides or deprecate. + if order in "kKaA": + order = "F" if self._data.flags.fnc else "C" + r = ndarray.ravel(self._data, order=order).view(type(self)) + r._update_from(self) + if self._mask is not nomask: + r._mask = ndarray.ravel(self._mask, order=order).reshape(r.shape) + else: + r._mask = nomask + return r + + def reshape(self, *s, **kwargs): + """ + Give a new shape to the array without changing its data. + + Returns a masked array containing the same data, but with a new shape. + The result is a view on the original array; if this is not possible, a + ValueError is raised. + + Parameters + ---------- + shape : int or tuple of ints + The new shape should be compatible with the original shape. If an + integer is supplied, then the result will be a 1-D array of that + length. + order : {'C', 'F'}, optional + Determines whether the array data should be viewed as in C + (row-major) or FORTRAN (column-major) order. + + Returns + ------- + reshaped_array : array + A new view on the array. + + See Also + -------- + reshape : Equivalent function in the masked array module. + numpy.ndarray.reshape : Equivalent method on ndarray object. + numpy.reshape : Equivalent function in the NumPy module. + + Notes + ----- + The reshaping operation cannot guarantee that a copy will not be made, + to modify the shape in place, use ``a.shape = s`` + + Examples + -------- + >>> import numpy as np + >>> x = np.ma.array([[1,2],[3,4]], mask=[1,0,0,1]) + >>> x + masked_array( + data=[[--, 2], + [3, --]], + mask=[[ True, False], + [False, True]], + fill_value=999999) + >>> x = x.reshape((4,1)) + >>> x + masked_array( + data=[[--], + [2], + [3], + [--]], + mask=[[ True], + [False], + [False], + [ True]], + fill_value=999999) + + """ + result = self._data.reshape(*s, **kwargs).view(type(self)) + result._update_from(self) + mask = self._mask + if mask is not nomask: + result._mask = mask.reshape(*s, **kwargs) + return result + + def resize(self, newshape, refcheck=True, order=False): + """ + .. warning:: + + This method does nothing, except raise a ValueError exception. A + masked array does not own its data and therefore cannot safely be + resized in place. Use the `numpy.ma.resize` function instead. + + This method is difficult to implement safely and may be deprecated in + future releases of NumPy. + + """ + # Note : the 'order' keyword looks broken, let's just drop it + errmsg = "A masked array does not own its data "\ + "and therefore cannot be resized.\n" \ + "Use the numpy.ma.resize function instead." + raise ValueError(errmsg) + + def put(self, indices, values, mode='raise'): + """ + Set storage-indexed locations to corresponding values. + + Sets self._data.flat[n] = values[n] for each n in indices. + If `values` is shorter than `indices` then it will repeat. + If `values` has some masked values, the initial mask is updated + in consequence, else the corresponding values are unmasked. + + Parameters + ---------- + indices : 1-D array_like + Target indices, interpreted as integers. + values : array_like + Values to place in self._data copy at target indices. + mode : {'raise', 'wrap', 'clip'}, optional + Specifies how out-of-bounds indices will behave. + 'raise' : raise an error. + 'wrap' : wrap around. + 'clip' : clip to the range. + + Notes + ----- + `values` can be a scalar or length 1 array. + + Examples + -------- + >>> import numpy as np + >>> x = np.ma.array([[1,2,3],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4) + >>> x + masked_array( + data=[[1, --, 3], + [--, 5, --], + [7, --, 9]], + mask=[[False, True, False], + [ True, False, True], + [False, True, False]], + fill_value=999999) + >>> x.put([0,4,8],[10,20,30]) + >>> x + masked_array( + data=[[10, --, 3], + [--, 20, --], + [7, --, 30]], + mask=[[False, True, False], + [ True, False, True], + [False, True, False]], + fill_value=999999) + + >>> x.put(4,999) + >>> x + masked_array( + data=[[10, --, 3], + [--, 999, --], + [7, --, 30]], + mask=[[False, True, False], + [ True, False, True], + [False, True, False]], + fill_value=999999) + + """ + # Hard mask: Get rid of the values/indices that fall on masked data + if self._hardmask and self._mask is not nomask: + mask = self._mask[indices] + indices = narray(indices, copy=None) + values = narray(values, copy=None, subok=True) + values.resize(indices.shape) + indices = indices[~mask] + values = values[~mask] + + self._data.put(indices, values, mode=mode) + + # short circuit if neither self nor values are masked + if self._mask is nomask and getmask(values) is nomask: + return + + m = getmaskarray(self) + + if getmask(values) is nomask: + m.put(indices, False, mode=mode) + else: + m.put(indices, values._mask, mode=mode) + m = make_mask(m, copy=False, shrink=True) + self._mask = m + return + + def ids(self): + """ + Return the addresses of the data and mask areas. + + Parameters + ---------- + None + + Examples + -------- + >>> import numpy as np + >>> x = np.ma.array([1, 2, 3], mask=[0, 1, 1]) + >>> x.ids() + (166670640, 166659832) # may vary + + If the array has no mask, the address of `nomask` is returned. This address + is typically not close to the data in memory: + + >>> x = np.ma.array([1, 2, 3]) + >>> x.ids() + (166691080, 3083169284) # may vary + + """ + if self._mask is nomask: + return (self.ctypes.data, id(nomask)) + return (self.ctypes.data, self._mask.ctypes.data) + + def iscontiguous(self): + """ + Return a boolean indicating whether the data is contiguous. + + Parameters + ---------- + None + + Examples + -------- + >>> import numpy as np + >>> x = np.ma.array([1, 2, 3]) + >>> x.iscontiguous() + True + + `iscontiguous` returns one of the flags of the masked array: + + >>> x.flags + C_CONTIGUOUS : True + F_CONTIGUOUS : True + OWNDATA : False + WRITEABLE : True + ALIGNED : True + WRITEBACKIFCOPY : False + + """ + return self.flags['CONTIGUOUS'] + + def all(self, axis=None, out=None, keepdims=np._NoValue): + """ + Returns True if all elements evaluate to True. + + The output array is masked where all the values along the given axis + are masked: if the output would have been a scalar and that all the + values are masked, then the output is `masked`. + + Refer to `numpy.all` for full documentation. + + See Also + -------- + numpy.ndarray.all : corresponding function for ndarrays + numpy.all : equivalent function + + Examples + -------- + >>> import numpy as np + >>> np.ma.array([1,2,3]).all() + True + >>> a = np.ma.array([1,2,3], mask=True) + >>> (a.all() is np.ma.masked) + True + + """ + kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims} + + mask = _check_mask_axis(self._mask, axis, **kwargs) + if out is None: + d = self.filled(True).all(axis=axis, **kwargs).view(type(self)) + if d.ndim: + d.__setmask__(mask) + elif mask: + return masked + return d + self.filled(True).all(axis=axis, out=out, **kwargs) + if isinstance(out, MaskedArray): + if out.ndim or mask: + out.__setmask__(mask) + return out + + def any(self, axis=None, out=None, keepdims=np._NoValue): + """ + Returns True if any of the elements of `a` evaluate to True. + + Masked values are considered as False during computation. + + Refer to `numpy.any` for full documentation. + + See Also + -------- + numpy.ndarray.any : corresponding function for ndarrays + numpy.any : equivalent function + + """ + kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims} + + mask = _check_mask_axis(self._mask, axis, **kwargs) + if out is None: + d = self.filled(False).any(axis=axis, **kwargs).view(type(self)) + if d.ndim: + d.__setmask__(mask) + elif mask: + d = masked + return d + self.filled(False).any(axis=axis, out=out, **kwargs) + if isinstance(out, MaskedArray): + if out.ndim or mask: + out.__setmask__(mask) + return out + + def nonzero(self): + """ + Return the indices of unmasked elements that are not zero. + + Returns a tuple of arrays, one for each dimension, containing the + indices of the non-zero elements in that dimension. The corresponding + non-zero values can be obtained with:: + + a[a.nonzero()] + + To group the indices by element, rather than dimension, use + instead:: + + np.transpose(a.nonzero()) + + The result of this is always a 2d array, with a row for each non-zero + element. + + Parameters + ---------- + None + + Returns + ------- + tuple_of_arrays : tuple + Indices of elements that are non-zero. + + See Also + -------- + numpy.nonzero : + Function operating on ndarrays. + flatnonzero : + Return indices that are non-zero in the flattened version of the input + array. + numpy.ndarray.nonzero : + Equivalent ndarray method. + count_nonzero : + Counts the number of non-zero elements in the input array. + + Examples + -------- + >>> import numpy as np + >>> import numpy.ma as ma + >>> x = ma.array(np.eye(3)) + >>> x + masked_array( + data=[[1., 0., 0.], + [0., 1., 0.], + [0., 0., 1.]], + mask=False, + fill_value=1e+20) + >>> x.nonzero() + (array([0, 1, 2]), array([0, 1, 2])) + + Masked elements are ignored. + + >>> x[1, 1] = ma.masked + >>> x + masked_array( + data=[[1.0, 0.0, 0.0], + [0.0, --, 0.0], + [0.0, 0.0, 1.0]], + mask=[[False, False, False], + [False, True, False], + [False, False, False]], + fill_value=1e+20) + >>> x.nonzero() + (array([0, 2]), array([0, 2])) + + Indices can also be grouped by element. + + >>> np.transpose(x.nonzero()) + array([[0, 0], + [2, 2]]) + + A common use for ``nonzero`` is to find the indices of an array, where + a condition is True. Given an array `a`, the condition `a` > 3 is a + boolean array and since False is interpreted as 0, ma.nonzero(a > 3) + yields the indices of the `a` where the condition is true. + + >>> a = ma.array([[1,2,3],[4,5,6],[7,8,9]]) + >>> a > 3 + masked_array( + data=[[False, False, False], + [ True, True, True], + [ True, True, True]], + mask=False, + fill_value=True) + >>> ma.nonzero(a > 3) + (array([1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2])) + + The ``nonzero`` method of the condition array can also be called. + + >>> (a > 3).nonzero() + (array([1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2])) + + """ + return np.asarray(self.filled(0)).nonzero() + + def trace(self, offset=0, axis1=0, axis2=1, dtype=None, out=None): + """ + (this docstring should be overwritten) + """ + # !!!: implement out + test! + m = self._mask + if m is nomask: + result = super().trace(offset=offset, axis1=axis1, axis2=axis2, + out=out) + return result.astype(dtype) + else: + D = self.diagonal(offset=offset, axis1=axis1, axis2=axis2) + return D.astype(dtype).filled(0).sum(axis=-1, out=out) + trace.__doc__ = ndarray.trace.__doc__ + + def dot(self, b, out=None, strict=False): + """ + a.dot(b, out=None) + + Masked dot product of two arrays. Note that `out` and `strict` are + located in different positions than in `ma.dot`. In order to + maintain compatibility with the functional version, it is + recommended that the optional arguments be treated as keyword only. + At some point that may be mandatory. + + Parameters + ---------- + b : masked_array_like + Inputs array. + out : masked_array, optional + Output argument. This must have the exact kind that would be + returned if it was not used. In particular, it must have the + right type, must be C-contiguous, and its dtype must be the + dtype that would be returned for `ma.dot(a,b)`. This is a + performance feature. Therefore, if these conditions are not + met, an exception is raised, instead of attempting to be + flexible. + strict : bool, optional + Whether masked data are propagated (True) or set to 0 (False) + for the computation. Default is False. Propagating the mask + means that if a masked value appears in a row or column, the + whole row or column is considered masked. + + See Also + -------- + numpy.ma.dot : equivalent function + + """ + return dot(self, b, out=out, strict=strict) + + def sum(self, axis=None, dtype=None, out=None, keepdims=np._NoValue): + """ + Return the sum of the array elements over the given axis. + + Masked elements are set to 0 internally. + + Refer to `numpy.sum` for full documentation. + + See Also + -------- + numpy.ndarray.sum : corresponding function for ndarrays + numpy.sum : equivalent function + + Examples + -------- + >>> import numpy as np + >>> x = np.ma.array([[1,2,3],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4) + >>> x + masked_array( + data=[[1, --, 3], + [--, 5, --], + [7, --, 9]], + mask=[[False, True, False], + [ True, False, True], + [False, True, False]], + fill_value=999999) + >>> x.sum() + 25 + >>> x.sum(axis=1) + masked_array(data=[4, 5, 16], + mask=[False, False, False], + fill_value=999999) + >>> x.sum(axis=0) + masked_array(data=[8, 5, 12], + mask=[False, False, False], + fill_value=999999) + >>> print(type(x.sum(axis=0, dtype=np.int64)[0])) + + + """ + kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims} + + _mask = self._mask + newmask = _check_mask_axis(_mask, axis, **kwargs) + # No explicit output + if out is None: + result = self.filled(0).sum(axis, dtype=dtype, **kwargs) + rndim = getattr(result, 'ndim', 0) + if rndim: + result = result.view(type(self)) + result.__setmask__(newmask) + elif newmask: + result = masked + return result + # Explicit output + result = self.filled(0).sum(axis, dtype=dtype, out=out, **kwargs) + if isinstance(out, MaskedArray): + outmask = getmask(out) + if outmask is nomask: + outmask = out._mask = make_mask_none(out.shape) + outmask.flat = newmask + return out + + def cumsum(self, axis=None, dtype=None, out=None): + """ + Return the cumulative sum of the array elements over the given axis. + + Masked values are set to 0 internally during the computation. + However, their position is saved, and the result will be masked at + the same locations. + + Refer to `numpy.cumsum` for full documentation. + + Notes + ----- + The mask is lost if `out` is not a valid :class:`ma.MaskedArray` ! + + Arithmetic is modular when using integer types, and no error is + raised on overflow. + + See Also + -------- + numpy.ndarray.cumsum : corresponding function for ndarrays + numpy.cumsum : equivalent function + + Examples + -------- + >>> import numpy as np + >>> marr = np.ma.array(np.arange(10), mask=[0,0,0,1,1,1,0,0,0,0]) + >>> marr.cumsum() + masked_array(data=[0, 1, 3, --, --, --, 9, 16, 24, 33], + mask=[False, False, False, True, True, True, False, False, + False, False], + fill_value=999999) + + """ + result = self.filled(0).cumsum(axis=axis, dtype=dtype, out=out) + if out is not None: + if isinstance(out, MaskedArray): + out.__setmask__(self.mask) + return out + result = result.view(type(self)) + result.__setmask__(self._mask) + return result + + def prod(self, axis=None, dtype=None, out=None, keepdims=np._NoValue): + """ + Return the product of the array elements over the given axis. + + Masked elements are set to 1 internally for computation. + + Refer to `numpy.prod` for full documentation. + + Notes + ----- + Arithmetic is modular when using integer types, and no error is raised + on overflow. + + See Also + -------- + numpy.ndarray.prod : corresponding function for ndarrays + numpy.prod : equivalent function + """ + kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims} + + _mask = self._mask + newmask = _check_mask_axis(_mask, axis, **kwargs) + # No explicit output + if out is None: + result = self.filled(1).prod(axis, dtype=dtype, **kwargs) + rndim = getattr(result, 'ndim', 0) + if rndim: + result = result.view(type(self)) + result.__setmask__(newmask) + elif newmask: + result = masked + return result + # Explicit output + result = self.filled(1).prod(axis, dtype=dtype, out=out, **kwargs) + if isinstance(out, MaskedArray): + outmask = getmask(out) + if outmask is nomask: + outmask = out._mask = make_mask_none(out.shape) + outmask.flat = newmask + return out + product = prod + + def cumprod(self, axis=None, dtype=None, out=None): + """ + Return the cumulative product of the array elements over the given axis. + + Masked values are set to 1 internally during the computation. + However, their position is saved, and the result will be masked at + the same locations. + + Refer to `numpy.cumprod` for full documentation. + + Notes + ----- + The mask is lost if `out` is not a valid MaskedArray ! + + Arithmetic is modular when using integer types, and no error is + raised on overflow. + + See Also + -------- + numpy.ndarray.cumprod : corresponding function for ndarrays + numpy.cumprod : equivalent function + """ + result = self.filled(1).cumprod(axis=axis, dtype=dtype, out=out) + if out is not None: + if isinstance(out, MaskedArray): + out.__setmask__(self._mask) + return out + result = result.view(type(self)) + result.__setmask__(self._mask) + return result + + def mean(self, axis=None, dtype=None, out=None, keepdims=np._NoValue): + """ + Returns the average of the array elements along given axis. + + Masked entries are ignored, and result elements which are not + finite will be masked. + + Refer to `numpy.mean` for full documentation. + + See Also + -------- + numpy.ndarray.mean : corresponding function for ndarrays + numpy.mean : Equivalent function + numpy.ma.average : Weighted average. + + Examples + -------- + >>> import numpy as np + >>> a = np.ma.array([1,2,3], mask=[False, False, True]) + >>> a + masked_array(data=[1, 2, --], + mask=[False, False, True], + fill_value=999999) + >>> a.mean() + 1.5 + + """ + kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims} + if self._mask is nomask: + result = super().mean(axis=axis, dtype=dtype, **kwargs)[()] + else: + is_float16_result = False + if dtype is None: + if issubclass(self.dtype.type, (ntypes.integer, ntypes.bool)): + dtype = mu.dtype('f8') + elif issubclass(self.dtype.type, ntypes.float16): + dtype = mu.dtype('f4') + is_float16_result = True + dsum = self.sum(axis=axis, dtype=dtype, **kwargs) + cnt = self.count(axis=axis, **kwargs) + if cnt.shape == () and (cnt == 0): + result = masked + elif is_float16_result: + result = self.dtype.type(dsum * 1. / cnt) + else: + result = dsum * 1. / cnt + if out is not None: + out.flat = result + if isinstance(out, MaskedArray): + outmask = getmask(out) + if outmask is nomask: + outmask = out._mask = make_mask_none(out.shape) + outmask.flat = getmask(result) + return out + return result + + def anom(self, axis=None, dtype=None): + """ + Compute the anomalies (deviations from the arithmetic mean) + along the given axis. + + Returns an array of anomalies, with the same shape as the input and + where the arithmetic mean is computed along the given axis. + + Parameters + ---------- + axis : int, optional + Axis over which the anomalies are taken. + The default is to use the mean of the flattened array as reference. + dtype : dtype, optional + Type to use in computing the variance. For arrays of integer type + the default is float32; for arrays of float types it is the same as + the array type. + + See Also + -------- + mean : Compute the mean of the array. + + Examples + -------- + >>> import numpy as np + >>> a = np.ma.array([1,2,3]) + >>> a.anom() + masked_array(data=[-1., 0., 1.], + mask=False, + fill_value=1e+20) + + """ + m = self.mean(axis, dtype) + if not axis: + return self - m + else: + return self - expand_dims(m, axis) + + def var(self, axis=None, dtype=None, out=None, ddof=0, + keepdims=np._NoValue, mean=np._NoValue): + """ + Returns the variance of the array elements along given axis. + + Masked entries are ignored, and result elements which are not + finite will be masked. + + Refer to `numpy.var` for full documentation. + + See Also + -------- + numpy.ndarray.var : corresponding function for ndarrays + numpy.var : Equivalent function + """ + kwargs = {} + + if keepdims is not np._NoValue: + kwargs['keepdims'] = keepdims + + # Easy case: nomask, business as usual + if self._mask is nomask: + + if mean is not np._NoValue: + kwargs['mean'] = mean + + ret = super().var(axis=axis, dtype=dtype, out=out, ddof=ddof, + **kwargs)[()] + if out is not None: + if isinstance(out, MaskedArray): + out.__setmask__(nomask) + return out + return ret + + # Some data are masked, yay! + cnt = self.count(axis=axis, **kwargs) - ddof + + if mean is not np._NoValue: + danom = self - mean + else: + danom = self - self.mean(axis, dtype, keepdims=True) + + if iscomplexobj(self): + danom = umath.absolute(danom) ** 2 + else: + danom *= danom + dvar = divide(danom.sum(axis, **kwargs), cnt).view(type(self)) + # Apply the mask if it's not a scalar + if dvar.ndim: + dvar._mask = mask_or(self._mask.all(axis, **kwargs), (cnt <= 0)) + dvar._update_from(self) + elif getmask(dvar): + # Make sure that masked is returned when the scalar is masked. + dvar = masked + if out is not None: + if isinstance(out, MaskedArray): + out.flat = 0 + out.__setmask__(True) + elif out.dtype.kind in 'biu': + errmsg = "Masked data information would be lost in one or "\ + "more location." + raise MaskError(errmsg) + else: + out.flat = np.nan + return out + # In case with have an explicit output + if out is not None: + # Set the data + out.flat = dvar + # Set the mask if needed + if isinstance(out, MaskedArray): + out.__setmask__(dvar.mask) + return out + return dvar + var.__doc__ = np.var.__doc__ + + def std(self, axis=None, dtype=None, out=None, ddof=0, + keepdims=np._NoValue, mean=np._NoValue): + """ + Returns the standard deviation of the array elements along given axis. + + Masked entries are ignored. + + Refer to `numpy.std` for full documentation. + + See Also + -------- + numpy.ndarray.std : corresponding function for ndarrays + numpy.std : Equivalent function + """ + kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims} + + dvar = self.var(axis, dtype, out, ddof, **kwargs) + if dvar is not masked: + if out is not None: + np.power(out, 0.5, out=out, casting='unsafe') + return out + dvar = sqrt(dvar) + return dvar + + def round(self, decimals=0, out=None): + """ + Return each element rounded to the given number of decimals. + + Refer to `numpy.around` for full documentation. + + See Also + -------- + numpy.ndarray.round : corresponding function for ndarrays + numpy.around : equivalent function + + Examples + -------- + >>> import numpy as np + >>> import numpy.ma as ma + >>> x = ma.array([1.35, 2.5, 1.5, 1.75, 2.25, 2.75], + ... mask=[0, 0, 0, 1, 0, 0]) + >>> ma.round(x) + masked_array(data=[1.0, 2.0, 2.0, --, 2.0, 3.0], + mask=[False, False, False, True, False, False], + fill_value=1e+20) + + """ + result = self._data.round(decimals=decimals, out=out).view(type(self)) + if result.ndim > 0: + result._mask = self._mask + result._update_from(self) + elif self._mask: + # Return masked when the scalar is masked + result = masked + # No explicit output: we're done + if out is None: + return result + if isinstance(out, MaskedArray): + out.__setmask__(self._mask) + return out + + def argsort(self, axis=np._NoValue, kind=None, order=None, endwith=True, + fill_value=None, *, stable=False): + """ + Return an ndarray of indices that sort the array along the + specified axis. Masked values are filled beforehand to + `fill_value`. + + Parameters + ---------- + axis : int, optional + Axis along which to sort. If None, the default, the flattened array + is used. + kind : {'quicksort', 'mergesort', 'heapsort', 'stable'}, optional + The sorting algorithm used. + order : str or list of str, optional + When `a` is an array with fields defined, this argument specifies + which fields to compare first, second, etc. Not all fields need be + specified. + endwith : {True, False}, optional + Whether missing values (if any) should be treated as the largest values + (True) or the smallest values (False) + When the array contains unmasked values at the same extremes of the + datatype, the ordering of these values and the masked values is + undefined. + fill_value : scalar or None, optional + Value used internally for the masked values. + If ``fill_value`` is not None, it supersedes ``endwith``. + stable : bool, optional + Only for compatibility with ``np.argsort``. Ignored. + + Returns + ------- + index_array : ndarray, int + Array of indices that sort `a` along the specified axis. + In other words, ``a[index_array]`` yields a sorted `a`. + + See Also + -------- + ma.MaskedArray.sort : Describes sorting algorithms used. + lexsort : Indirect stable sort with multiple keys. + numpy.ndarray.sort : Inplace sort. + + Notes + ----- + See `sort` for notes on the different sorting algorithms. + + Examples + -------- + >>> import numpy as np + >>> a = np.ma.array([3,2,1], mask=[False, False, True]) + >>> a + masked_array(data=[3, 2, --], + mask=[False, False, True], + fill_value=999999) + >>> a.argsort() + array([1, 0, 2]) + + """ + if stable: + raise ValueError( + "`stable` parameter is not supported for masked arrays." + ) + + # 2017-04-11, Numpy 1.13.0, gh-8701: warn on axis default + if axis is np._NoValue: + axis = _deprecate_argsort_axis(self) + + if fill_value is None: + if endwith: + # nan > inf + if np.issubdtype(self.dtype, np.floating): + fill_value = np.nan + else: + fill_value = minimum_fill_value(self) + else: + fill_value = maximum_fill_value(self) + + filled = self.filled(fill_value) + return filled.argsort(axis=axis, kind=kind, order=order) + + def argmin(self, axis=None, fill_value=None, out=None, *, + keepdims=np._NoValue): + """ + Return array of indices to the minimum values along the given axis. + + Parameters + ---------- + axis : {None, integer} + If None, the index is into the flattened array, otherwise along + the specified axis + fill_value : scalar or None, optional + Value used to fill in the masked values. If None, the output of + minimum_fill_value(self._data) is used instead. + out : {None, array}, optional + Array into which the result can be placed. Its type is preserved + and it must be of the right shape to hold the output. + + Returns + ------- + ndarray or scalar + If multi-dimension input, returns a new ndarray of indices to the + minimum values along the given axis. Otherwise, returns a scalar + of index to the minimum values along the given axis. + + Examples + -------- + >>> import numpy as np + >>> x = np.ma.array(np.arange(4), mask=[1,1,0,0]) + >>> x.shape = (2,2) + >>> x + masked_array( + data=[[--, --], + [2, 3]], + mask=[[ True, True], + [False, False]], + fill_value=999999) + >>> x.argmin(axis=0, fill_value=-1) + array([0, 0]) + >>> x.argmin(axis=0, fill_value=9) + array([1, 1]) + + """ + if fill_value is None: + fill_value = minimum_fill_value(self) + d = self.filled(fill_value).view(ndarray) + keepdims = False if keepdims is np._NoValue else bool(keepdims) + return d.argmin(axis, out=out, keepdims=keepdims) + + def argmax(self, axis=None, fill_value=None, out=None, *, + keepdims=np._NoValue): + """ + Returns array of indices of the maximum values along the given axis. + Masked values are treated as if they had the value fill_value. + + Parameters + ---------- + axis : {None, integer} + If None, the index is into the flattened array, otherwise along + the specified axis + fill_value : scalar or None, optional + Value used to fill in the masked values. If None, the output of + maximum_fill_value(self._data) is used instead. + out : {None, array}, optional + Array into which the result can be placed. Its type is preserved + and it must be of the right shape to hold the output. + + Returns + ------- + index_array : {integer_array} + + Examples + -------- + >>> import numpy as np + >>> a = np.arange(6).reshape(2,3) + >>> a.argmax() + 5 + >>> a.argmax(0) + array([1, 1, 1]) + >>> a.argmax(1) + array([2, 2]) + + """ + if fill_value is None: + fill_value = maximum_fill_value(self._data) + d = self.filled(fill_value).view(ndarray) + keepdims = False if keepdims is np._NoValue else bool(keepdims) + return d.argmax(axis, out=out, keepdims=keepdims) + + def sort(self, axis=-1, kind=None, order=None, endwith=True, + fill_value=None, *, stable=False): + """ + Sort the array, in-place + + Parameters + ---------- + a : array_like + Array to be sorted. + axis : int, optional + Axis along which to sort. If None, the array is flattened before + sorting. The default is -1, which sorts along the last axis. + kind : {'quicksort', 'mergesort', 'heapsort', 'stable'}, optional + The sorting algorithm used. + order : list, optional + When `a` is a structured array, this argument specifies which fields + to compare first, second, and so on. This list does not need to + include all of the fields. + endwith : {True, False}, optional + Whether missing values (if any) should be treated as the largest values + (True) or the smallest values (False) + When the array contains unmasked values sorting at the same extremes of the + datatype, the ordering of these values and the masked values is + undefined. + fill_value : scalar or None, optional + Value used internally for the masked values. + If ``fill_value`` is not None, it supersedes ``endwith``. + stable : bool, optional + Only for compatibility with ``np.sort``. Ignored. + + See Also + -------- + numpy.ndarray.sort : Method to sort an array in-place. + argsort : Indirect sort. + lexsort : Indirect stable sort on multiple keys. + searchsorted : Find elements in a sorted array. + + Notes + ----- + See ``sort`` for notes on the different sorting algorithms. + + Examples + -------- + >>> import numpy as np + >>> a = np.ma.array([1, 2, 5, 4, 3],mask=[0, 1, 0, 1, 0]) + >>> # Default + >>> a.sort() + >>> a + masked_array(data=[1, 3, 5, --, --], + mask=[False, False, False, True, True], + fill_value=999999) + + >>> a = np.ma.array([1, 2, 5, 4, 3],mask=[0, 1, 0, 1, 0]) + >>> # Put missing values in the front + >>> a.sort(endwith=False) + >>> a + masked_array(data=[--, --, 1, 3, 5], + mask=[ True, True, False, False, False], + fill_value=999999) + + >>> a = np.ma.array([1, 2, 5, 4, 3],mask=[0, 1, 0, 1, 0]) + >>> # fill_value takes over endwith + >>> a.sort(endwith=False, fill_value=3) + >>> a + masked_array(data=[1, --, --, 3, 5], + mask=[False, True, True, False, False], + fill_value=999999) + + """ + if stable: + raise ValueError( + "`stable` parameter is not supported for masked arrays." + ) + + if self._mask is nomask: + ndarray.sort(self, axis=axis, kind=kind, order=order) + return + + if self is masked: + return + + sidx = self.argsort(axis=axis, kind=kind, order=order, + fill_value=fill_value, endwith=endwith) + + self[...] = np.take_along_axis(self, sidx, axis=axis) + + def min(self, axis=None, out=None, fill_value=None, keepdims=np._NoValue): + """ + Return the minimum along a given axis. + + Parameters + ---------- + axis : None or int or tuple of ints, optional + Axis along which to operate. By default, ``axis`` is None and the + flattened input is used. + If this is a tuple of ints, the minimum is selected over multiple + axes, instead of a single axis or all the axes as before. + out : array_like, optional + Alternative output array in which to place the result. Must be of + the same shape and buffer length as the expected output. + fill_value : scalar or None, optional + Value used to fill in the masked values. + If None, use the output of `minimum_fill_value`. + keepdims : bool, optional + If this is set to True, the axes which are reduced are left + in the result as dimensions with size one. With this option, + the result will broadcast correctly against the array. + + Returns + ------- + amin : array_like + New array holding the result. + If ``out`` was specified, ``out`` is returned. + + See Also + -------- + ma.minimum_fill_value + Returns the minimum filling value for a given datatype. + + Examples + -------- + >>> import numpy.ma as ma + >>> x = [[1., -2., 3.], [0.2, -0.7, 0.1]] + >>> mask = [[1, 1, 0], [0, 0, 1]] + >>> masked_x = ma.masked_array(x, mask) + >>> masked_x + masked_array( + data=[[--, --, 3.0], + [0.2, -0.7, --]], + mask=[[ True, True, False], + [False, False, True]], + fill_value=1e+20) + >>> ma.min(masked_x) + -0.7 + >>> ma.min(masked_x, axis=-1) + masked_array(data=[3.0, -0.7], + mask=[False, False], + fill_value=1e+20) + >>> ma.min(masked_x, axis=0, keepdims=True) + masked_array(data=[[0.2, -0.7, 3.0]], + mask=[[False, False, False]], + fill_value=1e+20) + >>> mask = [[1, 1, 1,], [1, 1, 1]] + >>> masked_x = ma.masked_array(x, mask) + >>> ma.min(masked_x, axis=0) + masked_array(data=[--, --, --], + mask=[ True, True, True], + fill_value=1e+20, + dtype=float64) + """ + kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims} + + _mask = self._mask + newmask = _check_mask_axis(_mask, axis, **kwargs) + if fill_value is None: + fill_value = minimum_fill_value(self) + # No explicit output + if out is None: + result = self.filled(fill_value).min( + axis=axis, out=out, **kwargs).view(type(self)) + if result.ndim: + # Set the mask + result.__setmask__(newmask) + # Get rid of Infs + if newmask.ndim: + np.copyto(result, result.fill_value, where=newmask) + elif newmask: + result = masked + return result + # Explicit output + self.filled(fill_value).min(axis=axis, out=out, **kwargs) + if isinstance(out, MaskedArray): + outmask = getmask(out) + if outmask is nomask: + outmask = out._mask = make_mask_none(out.shape) + outmask.flat = newmask + else: + if out.dtype.kind in 'biu': + errmsg = "Masked data information would be lost in one or more"\ + " location." + raise MaskError(errmsg) + np.copyto(out, np.nan, where=newmask) + return out + + def max(self, axis=None, out=None, fill_value=None, keepdims=np._NoValue): + """ + Return the maximum along a given axis. + + Parameters + ---------- + axis : None or int or tuple of ints, optional + Axis along which to operate. By default, ``axis`` is None and the + flattened input is used. + If this is a tuple of ints, the maximum is selected over multiple + axes, instead of a single axis or all the axes as before. + out : array_like, optional + Alternative output array in which to place the result. Must + be of the same shape and buffer length as the expected output. + fill_value : scalar or None, optional + Value used to fill in the masked values. + If None, use the output of maximum_fill_value(). + keepdims : bool, optional + If this is set to True, the axes which are reduced are left + in the result as dimensions with size one. With this option, + the result will broadcast correctly against the array. + + Returns + ------- + amax : array_like + New array holding the result. + If ``out`` was specified, ``out`` is returned. + + See Also + -------- + ma.maximum_fill_value + Returns the maximum filling value for a given datatype. + + Examples + -------- + >>> import numpy.ma as ma + >>> x = [[-1., 2.5], [4., -2.], [3., 0.]] + >>> mask = [[0, 0], [1, 0], [1, 0]] + >>> masked_x = ma.masked_array(x, mask) + >>> masked_x + masked_array( + data=[[-1.0, 2.5], + [--, -2.0], + [--, 0.0]], + mask=[[False, False], + [ True, False], + [ True, False]], + fill_value=1e+20) + >>> ma.max(masked_x) + 2.5 + >>> ma.max(masked_x, axis=0) + masked_array(data=[-1.0, 2.5], + mask=[False, False], + fill_value=1e+20) + >>> ma.max(masked_x, axis=1, keepdims=True) + masked_array( + data=[[2.5], + [-2.0], + [0.0]], + mask=[[False], + [False], + [False]], + fill_value=1e+20) + >>> mask = [[1, 1], [1, 1], [1, 1]] + >>> masked_x = ma.masked_array(x, mask) + >>> ma.max(masked_x, axis=1) + masked_array(data=[--, --, --], + mask=[ True, True, True], + fill_value=1e+20, + dtype=float64) + """ + kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims} + + _mask = self._mask + newmask = _check_mask_axis(_mask, axis, **kwargs) + if fill_value is None: + fill_value = maximum_fill_value(self) + # No explicit output + if out is None: + result = self.filled(fill_value).max( + axis=axis, out=out, **kwargs).view(type(self)) + if result.ndim: + # Set the mask + result.__setmask__(newmask) + # Get rid of Infs + if newmask.ndim: + np.copyto(result, result.fill_value, where=newmask) + elif newmask: + result = masked + return result + # Explicit output + self.filled(fill_value).max(axis=axis, out=out, **kwargs) + if isinstance(out, MaskedArray): + outmask = getmask(out) + if outmask is nomask: + outmask = out._mask = make_mask_none(out.shape) + outmask.flat = newmask + else: + + if out.dtype.kind in 'biu': + errmsg = "Masked data information would be lost in one or more"\ + " location." + raise MaskError(errmsg) + np.copyto(out, np.nan, where=newmask) + return out + + def ptp(self, axis=None, out=None, fill_value=None, keepdims=False): + """ + Return (maximum - minimum) along the given dimension + (i.e. peak-to-peak value). + + .. warning:: + `ptp` preserves the data type of the array. This means the + return value for an input of signed integers with n bits + (e.g. `np.int8`, `np.int16`, etc) is also a signed integer + with n bits. In that case, peak-to-peak values greater than + ``2**(n-1)-1`` will be returned as negative values. An example + with a work-around is shown below. + + Parameters + ---------- + axis : {None, int}, optional + Axis along which to find the peaks. If None (default) the + flattened array is used. + out : {None, array_like}, optional + Alternative output array in which to place the result. It must + have the same shape and buffer length as the expected output + but the type will be cast if necessary. + fill_value : scalar or None, optional + Value used to fill in the masked values. + keepdims : bool, optional + If this is set to True, the axes which are reduced are left + in the result as dimensions with size one. With this option, + the result will broadcast correctly against the array. + + Returns + ------- + ptp : ndarray. + A new array holding the result, unless ``out`` was + specified, in which case a reference to ``out`` is returned. + + Examples + -------- + >>> import numpy as np + >>> x = np.ma.MaskedArray([[4, 9, 2, 10], + ... [6, 9, 7, 12]]) + + >>> x.ptp(axis=1) + masked_array(data=[8, 6], + mask=False, + fill_value=999999) + + >>> x.ptp(axis=0) + masked_array(data=[2, 0, 5, 2], + mask=False, + fill_value=999999) + + >>> x.ptp() + 10 + + This example shows that a negative value can be returned when + the input is an array of signed integers. + + >>> y = np.ma.MaskedArray([[1, 127], + ... [0, 127], + ... [-1, 127], + ... [-2, 127]], dtype=np.int8) + >>> y.ptp(axis=1) + masked_array(data=[ 126, 127, -128, -127], + mask=False, + fill_value=np.int64(999999), + dtype=int8) + + A work-around is to use the `view()` method to view the result as + unsigned integers with the same bit width: + + >>> y.ptp(axis=1).view(np.uint8) + masked_array(data=[126, 127, 128, 129], + mask=False, + fill_value=np.uint64(999999), + dtype=uint8) + """ + if out is None: + result = self.max(axis=axis, fill_value=fill_value, + keepdims=keepdims) + result -= self.min(axis=axis, fill_value=fill_value, + keepdims=keepdims) + return result + out.flat = self.max(axis=axis, out=out, fill_value=fill_value, + keepdims=keepdims) + min_value = self.min(axis=axis, fill_value=fill_value, + keepdims=keepdims) + np.subtract(out, min_value, out=out, casting='unsafe') + return out + + def partition(self, *args, **kwargs): + warnings.warn("Warning: 'partition' will ignore the 'mask' " + f"of the {self.__class__.__name__}.", + stacklevel=2) + return super().partition(*args, **kwargs) + + def argpartition(self, *args, **kwargs): + warnings.warn("Warning: 'argpartition' will ignore the 'mask' " + f"of the {self.__class__.__name__}.", + stacklevel=2) + return super().argpartition(*args, **kwargs) + + def take(self, indices, axis=None, out=None, mode='raise'): + """ + Take elements from a masked array along an axis. + + This function does the same thing as "fancy" indexing (indexing arrays + using arrays) for masked arrays. It can be easier to use if you need + elements along a given axis. + + Parameters + ---------- + a : masked_array + The source masked array. + indices : array_like + The indices of the values to extract. Also allow scalars for indices. + axis : int, optional + The axis over which to select values. By default, the flattened + input array is used. + out : MaskedArray, optional + If provided, the result will be placed in this array. It should + be of the appropriate shape and dtype. Note that `out` is always + buffered if `mode='raise'`; use other modes for better performance. + mode : {'raise', 'wrap', 'clip'}, optional + Specifies how out-of-bounds indices will behave. + + * 'raise' -- raise an error (default) + * 'wrap' -- wrap around + * 'clip' -- clip to the range + + 'clip' mode means that all indices that are too large are replaced + by the index that addresses the last element along that axis. Note + that this disables indexing with negative numbers. + + Returns + ------- + out : MaskedArray + The returned array has the same type as `a`. + + See Also + -------- + numpy.take : Equivalent function for ndarrays. + compress : Take elements using a boolean mask. + take_along_axis : Take elements by matching the array and the index arrays. + + Notes + ----- + This function behaves similarly to `numpy.take`, but it handles masked + values. The mask is retained in the output array, and masked values + in the input array remain masked in the output. + + Examples + -------- + >>> import numpy as np + >>> a = np.ma.array([4, 3, 5, 7, 6, 8], mask=[0, 0, 1, 0, 1, 0]) + >>> indices = [0, 1, 4] + >>> np.ma.take(a, indices) + masked_array(data=[4, 3, --], + mask=[False, False, True], + fill_value=999999) + + When `indices` is not one-dimensional, the output also has these dimensions: + + >>> np.ma.take(a, [[0, 1], [2, 3]]) + masked_array(data=[[4, 3], + [--, 7]], + mask=[[False, False], + [ True, False]], + fill_value=999999) + """ + (_data, _mask) = (self._data, self._mask) + cls = type(self) + # Make sure the indices are not masked + maskindices = getmask(indices) + if maskindices is not nomask: + indices = indices.filled(0) + # Get the data, promoting scalars to 0d arrays with [...] so that + # .view works correctly + if out is None: + out = _data.take(indices, axis=axis, mode=mode)[...].view(cls) + else: + np.take(_data, indices, axis=axis, mode=mode, out=out) + # Get the mask + if isinstance(out, MaskedArray): + if _mask is nomask: + outmask = maskindices + else: + outmask = _mask.take(indices, axis=axis, mode=mode) + outmask |= maskindices + out.__setmask__(outmask) + # demote 0d arrays back to scalars, for consistency with ndarray.take + return out[()] + + # Array methods + copy = _arraymethod('copy') + diagonal = _arraymethod('diagonal') + flatten = _arraymethod('flatten') + repeat = _arraymethod('repeat') + squeeze = _arraymethod('squeeze') + swapaxes = _arraymethod('swapaxes') + T = property(fget=lambda self: self.transpose()) + transpose = _arraymethod('transpose') + + @property + def mT(self): + """ + Return the matrix-transpose of the masked array. + + The matrix transpose is the transpose of the last two dimensions, even + if the array is of higher dimension. + + .. versionadded:: 2.0 + + Returns + ------- + result: MaskedArray + The masked array with the last two dimensions transposed + + Raises + ------ + ValueError + If the array is of dimension less than 2. + + See Also + -------- + ndarray.mT: + Equivalent method for arrays + """ + + if self.ndim < 2: + raise ValueError("matrix transpose with ndim < 2 is undefined") + + if self._mask is nomask: + return masked_array(data=self._data.mT) + else: + return masked_array(data=self.data.mT, mask=self.mask.mT) + + def tolist(self, fill_value=None): + """ + Return the data portion of the masked array as a hierarchical Python list. + + Data items are converted to the nearest compatible Python type. + Masked values are converted to `fill_value`. If `fill_value` is None, + the corresponding entries in the output list will be ``None``. + + Parameters + ---------- + fill_value : scalar, optional + The value to use for invalid entries. Default is None. + + Returns + ------- + result : list + The Python list representation of the masked array. + + Examples + -------- + >>> import numpy as np + >>> x = np.ma.array([[1,2,3], [4,5,6], [7,8,9]], mask=[0] + [1,0]*4) + >>> x.tolist() + [[1, None, 3], [None, 5, None], [7, None, 9]] + >>> x.tolist(-999) + [[1, -999, 3], [-999, 5, -999], [7, -999, 9]] + + """ + _mask = self._mask + # No mask ? Just return .data.tolist ? + if _mask is nomask: + return self._data.tolist() + # Explicit fill_value: fill the array and get the list + if fill_value is not None: + return self.filled(fill_value).tolist() + # Structured array. + names = self.dtype.names + if names: + result = self._data.astype([(_, object) for _ in names]) + for n in names: + result[n][_mask[n]] = None + return result.tolist() + # Standard arrays. + if _mask is nomask: + return [None] + # Set temps to save time when dealing w/ marrays. + inishape = self.shape + result = np.array(self._data.ravel(), dtype=object) + result[_mask.ravel()] = None + result.shape = inishape + return result.tolist() + + def tobytes(self, fill_value=None, order='C'): + """ + Return the array data as a string containing the raw bytes in the array. + + The array is filled with a fill value before the string conversion. + + Parameters + ---------- + fill_value : scalar, optional + Value used to fill in the masked values. Default is None, in which + case `MaskedArray.fill_value` is used. + order : {'C','F','A'}, optional + Order of the data item in the copy. Default is 'C'. + + - 'C' -- C order (row major). + - 'F' -- Fortran order (column major). + - 'A' -- Any, current order of array. + - None -- Same as 'A'. + + See Also + -------- + numpy.ndarray.tobytes + tolist, tofile + + Notes + ----- + As for `ndarray.tobytes`, information about the shape, dtype, etc., + but also about `fill_value`, will be lost. + + Examples + -------- + >>> import numpy as np + >>> x = np.ma.array(np.array([[1, 2], [3, 4]]), mask=[[0, 1], [1, 0]]) + >>> x.tobytes() + b'\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00?B\\x0f\\x00\\x00\\x00\\x00\\x00?B\\x0f\\x00\\x00\\x00\\x00\\x00\\x04\\x00\\x00\\x00\\x00\\x00\\x00\\x00' + + """ + return self.filled(fill_value).tobytes(order=order) + + def tofile(self, fid, sep="", format="%s"): + """ + Save a masked array to a file in binary format. + + .. warning:: + This function is not implemented yet. + + Raises + ------ + NotImplementedError + When `tofile` is called. + + """ + raise NotImplementedError("MaskedArray.tofile() not implemented yet.") + + def toflex(self): + """ + Transforms a masked array into a flexible-type array. + + The flexible type array that is returned will have two fields: + + * the ``_data`` field stores the ``_data`` part of the array. + * the ``_mask`` field stores the ``_mask`` part of the array. + + Parameters + ---------- + None + + Returns + ------- + record : ndarray + A new flexible-type `ndarray` with two fields: the first element + containing a value, the second element containing the corresponding + mask boolean. The returned record shape matches self.shape. + + Notes + ----- + A side-effect of transforming a masked array into a flexible `ndarray` is + that meta information (``fill_value``, ...) will be lost. + + Examples + -------- + >>> import numpy as np + >>> x = np.ma.array([[1,2,3],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4) + >>> x + masked_array( + data=[[1, --, 3], + [--, 5, --], + [7, --, 9]], + mask=[[False, True, False], + [ True, False, True], + [False, True, False]], + fill_value=999999) + >>> x.toflex() + array([[(1, False), (2, True), (3, False)], + [(4, True), (5, False), (6, True)], + [(7, False), (8, True), (9, False)]], + dtype=[('_data', 'i2", (2,))]) + # x = A[0]; y = x["A"]; then y.mask["A"].size==2 + # and we can not say masked/unmasked. + # The result is no longer mvoid! + # See also issue #6724. + return masked_array( + data=self._data[indx], mask=m[indx], + fill_value=self._fill_value[indx], + hard_mask=self._hardmask) + if m is not nomask and m[indx]: + return masked + return self._data[indx] + + def __setitem__(self, indx, value): + self._data[indx] = value + if self._hardmask: + self._mask[indx] |= getattr(value, "_mask", False) + else: + self._mask[indx] = getattr(value, "_mask", False) + + def __str__(self): + m = self._mask + if m is nomask: + return str(self._data) + + rdtype = _replace_dtype_fields(self._data.dtype, "O") + data_arr = super()._data + res = data_arr.astype(rdtype) + _recursive_printoption(res, self._mask, masked_print_option) + return str(res) + + __repr__ = __str__ + + def __iter__(self): + "Defines an iterator for mvoid" + (_data, _mask) = (self._data, self._mask) + if _mask is nomask: + yield from _data + else: + for (d, m) in zip(_data, _mask): + if m: + yield masked + else: + yield d + + def __len__(self): + return self._data.__len__() + + def filled(self, fill_value=None): + """ + Return a copy with masked fields filled with a given value. + + Parameters + ---------- + fill_value : array_like, optional + The value to use for invalid entries. Can be scalar or + non-scalar. If latter is the case, the filled array should + be broadcastable over input array. Default is None, in + which case the `fill_value` attribute is used instead. + + Returns + ------- + filled_void + A `np.void` object + + See Also + -------- + MaskedArray.filled + + """ + return asarray(self).filled(fill_value)[()] + + def tolist(self): + """ + Transforms the mvoid object into a tuple. + + Masked fields are replaced by None. + + Returns + ------- + returned_tuple + Tuple of fields + """ + _mask = self._mask + if _mask is nomask: + return self._data.tolist() + result = [] + for (d, m) in zip(self._data, self._mask): + if m: + result.append(None) + else: + # .item() makes sure we return a standard Python object + result.append(d.item()) + return tuple(result) + + +############################################################################## +# Shortcuts # +############################################################################## + + +def isMaskedArray(x): + """ + Test whether input is an instance of MaskedArray. + + This function returns True if `x` is an instance of MaskedArray + and returns False otherwise. Any object is accepted as input. + + Parameters + ---------- + x : object + Object to test. + + Returns + ------- + result : bool + True if `x` is a MaskedArray. + + See Also + -------- + isMA : Alias to isMaskedArray. + isarray : Alias to isMaskedArray. + + Examples + -------- + >>> import numpy as np + >>> import numpy.ma as ma + >>> a = np.eye(3, 3) + >>> a + array([[ 1., 0., 0.], + [ 0., 1., 0.], + [ 0., 0., 1.]]) + >>> m = ma.masked_values(a, 0) + >>> m + masked_array( + data=[[1.0, --, --], + [--, 1.0, --], + [--, --, 1.0]], + mask=[[False, True, True], + [ True, False, True], + [ True, True, False]], + fill_value=0.0) + >>> ma.isMaskedArray(a) + False + >>> ma.isMaskedArray(m) + True + >>> ma.isMaskedArray([0, 1, 2]) + False + + """ + return isinstance(x, MaskedArray) + + +isarray = isMaskedArray +isMA = isMaskedArray # backward compatibility + + +class MaskedConstant(MaskedArray): + # the lone np.ma.masked instance + __singleton = None + + @classmethod + def __has_singleton(cls): + # second case ensures `cls.__singleton` is not just a view on the + # superclass singleton + return cls.__singleton is not None and type(cls.__singleton) is cls + + def __new__(cls): + if not cls.__has_singleton(): + # We define the masked singleton as a float for higher precedence. + # Note that it can be tricky sometimes w/ type comparison + data = np.array(0.) + mask = np.array(True) + + # prevent any modifications + data.flags.writeable = False + mask.flags.writeable = False + + # don't fall back on MaskedArray.__new__(MaskedConstant), since + # that might confuse it - this way, the construction is entirely + # within our control + cls.__singleton = MaskedArray(data, mask=mask).view(cls) + + return cls.__singleton + + def __array_finalize__(self, obj): + if not self.__has_singleton(): + # this handles the `.view` in __new__, which we want to copy across + # properties normally + return super().__array_finalize__(obj) + elif self is self.__singleton: + # not clear how this can happen, play it safe + pass + else: + # everywhere else, we want to downcast to MaskedArray, to prevent a + # duplicate maskedconstant. + self.__class__ = MaskedArray + MaskedArray.__array_finalize__(self, obj) + + def __array_wrap__(self, obj, context=None, return_scalar=False): + return self.view(MaskedArray).__array_wrap__(obj, context) + + def __str__(self): + return str(masked_print_option._display) + + def __repr__(self): + if self is MaskedConstant.__singleton: + return 'masked' + else: + # it's a subclass, or something is wrong, make it obvious + return object.__repr__(self) + + def __format__(self, format_spec): + # Replace ndarray.__format__ with the default, which supports no + # format characters. + # Supporting format characters is unwise here, because we do not know + # what type the user was expecting - better to not guess. + try: + return object.__format__(self, format_spec) + except TypeError: + # 2020-03-23, NumPy 1.19.0 + warnings.warn( + "Format strings passed to MaskedConstant are ignored," + " but in future may error or produce different behavior", + FutureWarning, stacklevel=2 + ) + return object.__format__(self, "") + + def __reduce__(self): + """Override of MaskedArray's __reduce__. + """ + return (self.__class__, ()) + + # inplace operations have no effect. We have to override them to avoid + # trying to modify the readonly data and mask arrays + def __iop__(self, other): + return self + __iadd__ = \ + __isub__ = \ + __imul__ = \ + __ifloordiv__ = \ + __itruediv__ = \ + __ipow__ = \ + __iop__ + del __iop__ # don't leave this around + + def copy(self, *args, **kwargs): + """ Copy is a no-op on the maskedconstant, as it is a scalar """ + # maskedconstant is a scalar, so copy doesn't need to copy. There's + # precedent for this with `np.bool` scalars. + return self + + def __copy__(self): + return self + + def __deepcopy__(self, memo): + return self + + def __setattr__(self, attr, value): + if not self.__has_singleton(): + # allow the singleton to be initialized + return super().__setattr__(attr, value) + elif self is self.__singleton: + raise AttributeError( + f"attributes of {self!r} are not writeable") + else: + # duplicate instance - we can end up here from __array_finalize__, + # where we set the __class__ attribute + return super().__setattr__(attr, value) + + +masked = masked_singleton = MaskedConstant() +masked_array = MaskedArray + + +def array(data, dtype=None, copy=False, order=None, + mask=nomask, fill_value=None, keep_mask=True, + hard_mask=False, shrink=True, subok=True, ndmin=0): + """ + Shortcut to MaskedArray. + + The options are in a different order for convenience and backwards + compatibility. + + """ + return MaskedArray(data, mask=mask, dtype=dtype, copy=copy, + subok=subok, keep_mask=keep_mask, + hard_mask=hard_mask, fill_value=fill_value, + ndmin=ndmin, shrink=shrink, order=order) + + +array.__doc__ = masked_array.__doc__ + + +def is_masked(x): + """ + Determine whether input has masked values. + + Accepts any object as input, but always returns False unless the + input is a MaskedArray containing masked values. + + Parameters + ---------- + x : array_like + Array to check for masked values. + + Returns + ------- + result : bool + True if `x` is a MaskedArray with masked values, False otherwise. + + Examples + -------- + >>> import numpy as np + >>> import numpy.ma as ma + >>> x = ma.masked_equal([0, 1, 0, 2, 3], 0) + >>> x + masked_array(data=[--, 1, --, 2, 3], + mask=[ True, False, True, False, False], + fill_value=0) + >>> ma.is_masked(x) + True + >>> x = ma.masked_equal([0, 1, 0, 2, 3], 42) + >>> x + masked_array(data=[0, 1, 0, 2, 3], + mask=False, + fill_value=42) + >>> ma.is_masked(x) + False + + Always returns False if `x` isn't a MaskedArray. + + >>> x = [False, True, False] + >>> ma.is_masked(x) + False + >>> x = 'a string' + >>> ma.is_masked(x) + False + + """ + m = getmask(x) + if m is nomask: + return False + elif m.any(): + return True + return False + + +############################################################################## +# Extrema functions # +############################################################################## + + +class _extrema_operation(_MaskedUFunc): + """ + Generic class for maximum/minimum functions. + + .. note:: + This is the base class for `_maximum_operation` and + `_minimum_operation`. + + """ + def __init__(self, ufunc, compare, fill_value): + super().__init__(ufunc) + self.compare = compare + self.fill_value_func = fill_value + + def __call__(self, a, b): + "Executes the call behavior." + + return where(self.compare(a, b), a, b) + + def reduce(self, target, axis=np._NoValue): + "Reduce target along the given axis." + target = narray(target, copy=None, subok=True) + m = getmask(target) + + if axis is np._NoValue and target.ndim > 1: + name = self.__name__ + # 2017-05-06, Numpy 1.13.0: warn on axis default + warnings.warn( + f"In the future the default for ma.{name}.reduce will be axis=0, " + f"not the current None, to match np.{name}.reduce. " + "Explicitly pass 0 or None to silence this warning.", + MaskedArrayFutureWarning, stacklevel=2) + axis = None + + if axis is not np._NoValue: + kwargs = {'axis': axis} + else: + kwargs = {} + + if m is nomask: + t = self.f.reduce(target, **kwargs) + else: + target = target.filled( + self.fill_value_func(target)).view(type(target)) + t = self.f.reduce(target, **kwargs) + m = umath.logical_and.reduce(m, **kwargs) + if hasattr(t, '_mask'): + t._mask = m + elif m: + t = masked + return t + + def outer(self, a, b): + "Return the function applied to the outer product of a and b." + ma = getmask(a) + mb = getmask(b) + if ma is nomask and mb is nomask: + m = nomask + else: + ma = getmaskarray(a) + mb = getmaskarray(b) + m = logical_or.outer(ma, mb) + result = self.f.outer(filled(a), filled(b)) + if not isinstance(result, MaskedArray): + result = result.view(MaskedArray) + result._mask = m + return result + +def min(obj, axis=None, out=None, fill_value=None, keepdims=np._NoValue): + kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims} + + try: + return obj.min(axis=axis, fill_value=fill_value, out=out, **kwargs) + except (AttributeError, TypeError): + # If obj doesn't have a min method, or if the method doesn't accept a + # fill_value argument + return asanyarray(obj).min(axis=axis, fill_value=fill_value, + out=out, **kwargs) + + +min.__doc__ = MaskedArray.min.__doc__ + +def max(obj, axis=None, out=None, fill_value=None, keepdims=np._NoValue): + kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims} + + try: + return obj.max(axis=axis, fill_value=fill_value, out=out, **kwargs) + except (AttributeError, TypeError): + # If obj doesn't have a max method, or if the method doesn't accept a + # fill_value argument + return asanyarray(obj).max(axis=axis, fill_value=fill_value, + out=out, **kwargs) + + +max.__doc__ = MaskedArray.max.__doc__ + + +def ptp(obj, axis=None, out=None, fill_value=None, keepdims=np._NoValue): + kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims} + try: + return obj.ptp(axis, out=out, fill_value=fill_value, **kwargs) + except (AttributeError, TypeError): + # If obj doesn't have a ptp method or if the method doesn't accept + # a fill_value argument + return asanyarray(obj).ptp(axis=axis, fill_value=fill_value, + out=out, **kwargs) + + +ptp.__doc__ = MaskedArray.ptp.__doc__ + + +############################################################################## +# Definition of functions from the corresponding methods # +############################################################################## + + +def _frommethod(methodname: str, reversed: bool = False): + """ + Define functions from existing MaskedArray methods. + + Parameters + ---------- + methodname : str + Name of the method to transform. + reversed : bool, optional + Whether to reverse the first two arguments of the method. Default is False. + """ + method = getattr(MaskedArray, methodname) + assert callable(method) + + signature = inspect.signature(method) + params = list(signature.parameters.values()) + params[0] = params[0].replace(name="a") # rename 'self' to 'a' + + if reversed: + assert len(params) >= 2 + params[0], params[1] = params[1], params[0] + + def wrapper(a, b, *args, **params): + return getattr(asanyarray(b), methodname)(a, *args, **params) + + else: + def wrapper(a, *args, **params): + return getattr(asanyarray(a), methodname)(*args, **params) + + wrapper.__signature__ = signature.replace(parameters=params) + wrapper.__name__ = wrapper.__qualname__ = methodname + + # __doc__ is None when using `python -OO ...` + if method.__doc__ is not None: + str_signature = f"{methodname}{signature}" + # TODO: For methods with a docstring "Parameters" section, that do not already + # mention `a` (see e.g. `MaskedArray.var.__doc__`), it should be inserted there. + wrapper.__doc__ = f" {str_signature}\n{method.__doc__}" + + return wrapper + + +all = _frommethod('all') +anomalies = anom = _frommethod('anom') +any = _frommethod('any') +argmax = _frommethod('argmax') +argmin = _frommethod('argmin') +compress = _frommethod('compress', reversed=True) +count = _frommethod('count') +cumprod = _frommethod('cumprod') +cumsum = _frommethod('cumsum') +copy = _frommethod('copy') +diagonal = _frommethod('diagonal') +harden_mask = _frommethod('harden_mask') +ids = _frommethod('ids') +maximum = _extrema_operation(umath.maximum, greater, maximum_fill_value) +mean = _frommethod('mean') +minimum = _extrema_operation(umath.minimum, less, minimum_fill_value) +nonzero = _frommethod('nonzero') +prod = _frommethod('prod') +product = _frommethod('product') +ravel = _frommethod('ravel') +repeat = _frommethod('repeat') +shrink_mask = _frommethod('shrink_mask') +soften_mask = _frommethod('soften_mask') +std = _frommethod('std') +sum = _frommethod('sum') +swapaxes = _frommethod('swapaxes') +#take = _frommethod('take') +trace = _frommethod('trace') +var = _frommethod('var') + + +def take(a, indices, axis=None, out=None, mode='raise'): + """ + + """ + a = masked_array(a) + return a.take(indices, axis=axis, out=out, mode=mode) + + +def power(a, b, third=None): + """ + Returns element-wise base array raised to power from second array. + + This is the masked array version of `numpy.power`. For details see + `numpy.power`. + + See Also + -------- + numpy.power + + Notes + ----- + The *out* argument to `numpy.power` is not supported, `third` has to be + None. + + Examples + -------- + >>> import numpy as np + >>> import numpy.ma as ma + >>> x = [11.2, -3.973, 0.801, -1.41] + >>> mask = [0, 0, 0, 1] + >>> masked_x = ma.masked_array(x, mask) + >>> masked_x + masked_array(data=[11.2, -3.973, 0.801, --], + mask=[False, False, False, True], + fill_value=1e+20) + >>> ma.power(masked_x, 2) + masked_array(data=[125.43999999999998, 15.784728999999999, + 0.6416010000000001, --], + mask=[False, False, False, True], + fill_value=1e+20) + >>> y = [-0.5, 2, 0, 17] + >>> masked_y = ma.masked_array(y, mask) + >>> masked_y + masked_array(data=[-0.5, 2.0, 0.0, --], + mask=[False, False, False, True], + fill_value=1e+20) + >>> ma.power(masked_x, masked_y) + masked_array(data=[0.2988071523335984, 15.784728999999999, 1.0, --], + mask=[False, False, False, True], + fill_value=1e+20) + + """ + if third is not None: + raise MaskError("3-argument power not supported.") + # Get the masks + ma = getmask(a) + mb = getmask(b) + m = mask_or(ma, mb) + # Get the rawdata + fa = getdata(a) + fb = getdata(b) + # Get the type of the result (so that we preserve subclasses) + if isinstance(a, MaskedArray): + basetype = type(a) + else: + basetype = MaskedArray + # Get the result and view it as a (subclass of) MaskedArray + with np.errstate(divide='ignore', invalid='ignore'): + result = np.where(m, fa, umath.power(fa, fb)).view(basetype) + result._update_from(a) + # Find where we're in trouble w/ NaNs and Infs + invalid = np.logical_not(np.isfinite(result.view(ndarray))) + # Add the initial mask + if m is not nomask: + if not result.ndim: + return masked + result._mask = np.logical_or(m, invalid) + # Fix the invalid parts + if invalid.any(): + if not result.ndim: + return masked + elif result._mask is nomask: + result._mask = invalid + result._data[invalid] = result.fill_value + return result + + +def argsort(a, axis=np._NoValue, kind=None, order=None, endwith=True, + fill_value=None, *, stable=None): + "Function version of the eponymous method." + a = np.asanyarray(a) + + # 2017-04-11, Numpy 1.13.0, gh-8701: warn on axis default + if axis is np._NoValue: + axis = _deprecate_argsort_axis(a) + + if isinstance(a, MaskedArray): + return a.argsort(axis=axis, kind=kind, order=order, endwith=endwith, + fill_value=fill_value, stable=None) + else: + return a.argsort(axis=axis, kind=kind, order=order, stable=None) + + +argsort.__doc__ = MaskedArray.argsort.__doc__ + +def sort(a, axis=-1, kind=None, order=None, endwith=True, fill_value=None, *, + stable=None): + """ + Return a sorted copy of the masked array. + + Equivalent to creating a copy of the array + and applying the MaskedArray ``sort()`` method. + + Refer to ``MaskedArray.sort`` for the full documentation + + See Also + -------- + MaskedArray.sort : equivalent method + + Examples + -------- + >>> import numpy as np + >>> import numpy.ma as ma + >>> x = [11.2, -3.973, 0.801, -1.41] + >>> mask = [0, 0, 0, 1] + >>> masked_x = ma.masked_array(x, mask) + >>> masked_x + masked_array(data=[11.2, -3.973, 0.801, --], + mask=[False, False, False, True], + fill_value=1e+20) + >>> ma.sort(masked_x) + masked_array(data=[-3.973, 0.801, 11.2, --], + mask=[False, False, False, True], + fill_value=1e+20) + """ + a = np.array(a, copy=True, subok=True) + if axis is None: + a = a.flatten() + axis = 0 + + if isinstance(a, MaskedArray): + a.sort(axis=axis, kind=kind, order=order, endwith=endwith, + fill_value=fill_value, stable=stable) + else: + a.sort(axis=axis, kind=kind, order=order, stable=stable) + return a + + +def compressed(x): + """ + Return all the non-masked data as a 1-D array. + + This function is equivalent to calling the "compressed" method of a + `ma.MaskedArray`, see `ma.MaskedArray.compressed` for details. + + See Also + -------- + ma.MaskedArray.compressed : Equivalent method. + + Examples + -------- + >>> import numpy as np + + Create an array with negative values masked: + + >>> import numpy as np + >>> x = np.array([[1, -1, 0], [2, -1, 3], [7, 4, -1]]) + >>> masked_x = np.ma.masked_array(x, mask=x < 0) + >>> masked_x + masked_array( + data=[[1, --, 0], + [2, --, 3], + [7, 4, --]], + mask=[[False, True, False], + [False, True, False], + [False, False, True]], + fill_value=999999) + + Compress the masked array into a 1-D array of non-masked values: + + >>> np.ma.compressed(masked_x) + array([1, 0, 2, 3, 7, 4]) + + """ + return asanyarray(x).compressed() + + +def concatenate(arrays, axis=0): + """ + Concatenate a sequence of arrays along the given axis. + + Parameters + ---------- + arrays : sequence of array_like + The arrays must have the same shape, except in the dimension + corresponding to `axis` (the first, by default). + axis : int, optional + The axis along which the arrays will be joined. Default is 0. + + Returns + ------- + result : MaskedArray + The concatenated array with any masked entries preserved. + + See Also + -------- + numpy.concatenate : Equivalent function in the top-level NumPy module. + + Examples + -------- + >>> import numpy as np + >>> import numpy.ma as ma + >>> a = ma.arange(3) + >>> a[1] = ma.masked + >>> b = ma.arange(2, 5) + >>> a + masked_array(data=[0, --, 2], + mask=[False, True, False], + fill_value=999999) + >>> b + masked_array(data=[2, 3, 4], + mask=False, + fill_value=999999) + >>> ma.concatenate([a, b]) + masked_array(data=[0, --, 2, 2, 3, 4], + mask=[False, True, False, False, False, False], + fill_value=999999) + + """ + d = np.concatenate([getdata(a) for a in arrays], axis) + rcls = get_masked_subclass(*arrays) + data = d.view(rcls) + # Check whether one of the arrays has a non-empty mask. + for x in arrays: + if getmask(x) is not nomask: + break + else: + return data + # OK, so we have to concatenate the masks + dm = np.concatenate([getmaskarray(a) for a in arrays], axis) + dm = dm.reshape(d.shape) + + # If we decide to keep a '_shrinkmask' option, we want to check that + # all of them are True, and then check for dm.any() + data._mask = _shrink_mask(dm) + return data + + +def diag(v, k=0): + """ + Extract a diagonal or construct a diagonal array. + + This function is the equivalent of `numpy.diag` that takes masked + values into account, see `numpy.diag` for details. + + See Also + -------- + numpy.diag : Equivalent function for ndarrays. + + Examples + -------- + >>> import numpy as np + + Create an array with negative values masked: + + >>> import numpy as np + >>> x = np.array([[11.2, -3.973, 18], [0.801, -1.41, 12], [7, 33, -12]]) + >>> masked_x = np.ma.masked_array(x, mask=x < 0) + >>> masked_x + masked_array( + data=[[11.2, --, 18.0], + [0.801, --, 12.0], + [7.0, 33.0, --]], + mask=[[False, True, False], + [False, True, False], + [False, False, True]], + fill_value=1e+20) + + Isolate the main diagonal from the masked array: + + >>> np.ma.diag(masked_x) + masked_array(data=[11.2, --, --], + mask=[False, True, True], + fill_value=1e+20) + + Isolate the first diagonal below the main diagonal: + + >>> np.ma.diag(masked_x, -1) + masked_array(data=[0.801, 33.0], + mask=[False, False], + fill_value=1e+20) + + """ + output = np.diag(v, k).view(MaskedArray) + if getmask(v) is not nomask: + output._mask = np.diag(v._mask, k) + return output + + +def left_shift(a, n): + """ + Shift the bits of an integer to the left. + + This is the masked array version of `numpy.left_shift`, for details + see that function. + + See Also + -------- + numpy.left_shift + + Examples + -------- + Shift with a masked array: + + >>> arr = np.ma.array([10, 20, 30], mask=[False, True, False]) + >>> np.ma.left_shift(arr, 1) + masked_array(data=[20, --, 60], + mask=[False, True, False], + fill_value=999999) + + Large shift: + + >>> np.ma.left_shift(10, 10) + masked_array(data=10240, + mask=False, + fill_value=999999) + + Shift with a scalar and an array: + + >>> scalar = 10 + >>> arr = np.ma.array([1, 2, 3], mask=[False, True, False]) + >>> np.ma.left_shift(scalar, arr) + masked_array(data=[20, --, 80], + mask=[False, True, False], + fill_value=999999) + + + """ + m = getmask(a) + if m is nomask: + d = umath.left_shift(filled(a), n) + return masked_array(d) + else: + d = umath.left_shift(filled(a, 0), n) + return masked_array(d, mask=m) + + +def right_shift(a, n): + """ + Shift the bits of an integer to the right. + + This is the masked array version of `numpy.right_shift`, for details + see that function. + + See Also + -------- + numpy.right_shift + + Examples + -------- + >>> import numpy as np + >>> import numpy.ma as ma + >>> x = [11, 3, 8, 1] + >>> mask = [0, 0, 0, 1] + >>> masked_x = ma.masked_array(x, mask) + >>> masked_x + masked_array(data=[11, 3, 8, --], + mask=[False, False, False, True], + fill_value=999999) + >>> ma.right_shift(masked_x,1) + masked_array(data=[5, 1, 4, --], + mask=[False, False, False, True], + fill_value=999999) + + """ + m = getmask(a) + if m is nomask: + d = umath.right_shift(filled(a), n) + return masked_array(d) + else: + d = umath.right_shift(filled(a, 0), n) + return masked_array(d, mask=m) + + +def put(a, indices, values, mode='raise'): + """ + Set storage-indexed locations to corresponding values. + + This function is equivalent to `MaskedArray.put`, see that method + for details. + + See Also + -------- + MaskedArray.put + + Examples + -------- + Putting values in a masked array: + + >>> a = np.ma.array([1, 2, 3, 4], mask=[False, True, False, False]) + >>> np.ma.put(a, [1, 3], [10, 30]) + >>> a + masked_array(data=[ 1, 10, 3, 30], + mask=False, + fill_value=999999) + + Using put with a 2D array: + + >>> b = np.ma.array([[1, 2], [3, 4]], mask=[[False, True], [False, False]]) + >>> np.ma.put(b, [[0, 1], [1, 0]], [[10, 20], [30, 40]]) + >>> b + masked_array( + data=[[40, 30], + [ 3, 4]], + mask=False, + fill_value=999999) + + """ + # We can't use 'frommethod', the order of arguments is different + try: + return a.put(indices, values, mode=mode) + except AttributeError: + return np.asarray(a).put(indices, values, mode=mode) + + +def putmask(a, mask, values): # , mode='raise'): + """ + Changes elements of an array based on conditional and input values. + + This is the masked array version of `numpy.putmask`, for details see + `numpy.putmask`. + + See Also + -------- + numpy.putmask + + Notes + ----- + Using a masked array as `values` will **not** transform a `ndarray` into + a `MaskedArray`. + + Examples + -------- + >>> import numpy as np + >>> arr = [[1, 2], [3, 4]] + >>> mask = [[1, 0], [0, 0]] + >>> x = np.ma.array(arr, mask=mask) + >>> np.ma.putmask(x, x < 4, 10*x) + >>> x + masked_array( + data=[[--, 20], + [30, 4]], + mask=[[ True, False], + [False, False]], + fill_value=999999) + >>> x.data + array([[10, 20], + [30, 4]]) + + """ + # We can't use 'frommethod', the order of arguments is different + if not isinstance(a, MaskedArray): + a = a.view(MaskedArray) + (valdata, valmask) = (getdata(values), getmask(values)) + if getmask(a) is nomask: + if valmask is not nomask: + a._sharedmask = True + a._mask = make_mask_none(a.shape, a.dtype) + np.copyto(a._mask, valmask, where=mask) + elif a._hardmask: + if valmask is not nomask: + m = a._mask.copy() + np.copyto(m, valmask, where=mask) + a.mask |= m + else: + if valmask is nomask: + valmask = getmaskarray(values) + np.copyto(a._mask, valmask, where=mask) + np.copyto(a._data, valdata, where=mask) + + +def transpose(a, axes=None): + """ + Permute the dimensions of an array. + + This function is exactly equivalent to `numpy.transpose`. + + See Also + -------- + numpy.transpose : Equivalent function in top-level NumPy module. + + Examples + -------- + >>> import numpy as np + >>> import numpy.ma as ma + >>> x = ma.arange(4).reshape((2,2)) + >>> x[1, 1] = ma.masked + >>> x + masked_array( + data=[[0, 1], + [2, --]], + mask=[[False, False], + [False, True]], + fill_value=999999) + + >>> ma.transpose(x) + masked_array( + data=[[0, 2], + [1, --]], + mask=[[False, False], + [False, True]], + fill_value=999999) + """ + # We can't use 'frommethod', as 'transpose' doesn't take keywords + try: + return a.transpose(axes) + except AttributeError: + return np.asarray(a).transpose(axes).view(MaskedArray) + + +def reshape(a, new_shape, order='C'): + """ + Returns an array containing the same data with a new shape. + + Refer to `MaskedArray.reshape` for full documentation. + + See Also + -------- + MaskedArray.reshape : equivalent function + + Examples + -------- + Reshaping a 1-D array: + + >>> a = np.ma.array([1, 2, 3, 4]) + >>> np.ma.reshape(a, (2, 2)) + masked_array( + data=[[1, 2], + [3, 4]], + mask=False, + fill_value=999999) + + Reshaping a 2-D array: + + >>> b = np.ma.array([[1, 2], [3, 4]]) + >>> np.ma.reshape(b, (1, 4)) + masked_array(data=[[1, 2, 3, 4]], + mask=False, + fill_value=999999) + + Reshaping a 1-D array with a mask: + + >>> c = np.ma.array([1, 2, 3, 4], mask=[False, True, False, False]) + >>> np.ma.reshape(c, (2, 2)) + masked_array( + data=[[1, --], + [3, 4]], + mask=[[False, True], + [False, False]], + fill_value=999999) + + """ + # We can't use 'frommethod', it whine about some parameters. Dmmit. + try: + return a.reshape(new_shape, order=order) + except AttributeError: + _tmp = np.asarray(a).reshape(new_shape, order=order) + return _tmp.view(MaskedArray) + + +def resize(x, new_shape): + """ + Return a new masked array with the specified size and shape. + + This is the masked equivalent of the `numpy.resize` function. The new + array is filled with repeated copies of `x` (in the order that the + data are stored in memory). If `x` is masked, the new array will be + masked, and the new mask will be a repetition of the old one. + + See Also + -------- + numpy.resize : Equivalent function in the top level NumPy module. + + Examples + -------- + >>> import numpy as np + >>> import numpy.ma as ma + >>> a = ma.array([[1, 2] ,[3, 4]]) + >>> a[0, 1] = ma.masked + >>> a + masked_array( + data=[[1, --], + [3, 4]], + mask=[[False, True], + [False, False]], + fill_value=999999) + >>> np.resize(a, (3, 3)) + masked_array( + data=[[1, 2, 3], + [4, 1, 2], + [3, 4, 1]], + mask=False, + fill_value=999999) + >>> ma.resize(a, (3, 3)) + masked_array( + data=[[1, --, 3], + [4, 1, --], + [3, 4, 1]], + mask=[[False, True, False], + [False, False, True], + [False, False, False]], + fill_value=999999) + + A MaskedArray is always returned, regardless of the input type. + + >>> a = np.array([[1, 2] ,[3, 4]]) + >>> ma.resize(a, (3, 3)) + masked_array( + data=[[1, 2, 3], + [4, 1, 2], + [3, 4, 1]], + mask=False, + fill_value=999999) + + """ + # We can't use _frommethods here, as N.resize is notoriously whiny. + m = getmask(x) + if m is not nomask: + m = np.resize(m, new_shape) + result = np.resize(x, new_shape).view(get_masked_subclass(x)) + if result.ndim: + result._mask = m + return result + + +def ndim(obj): + """ + maskedarray version of the numpy function. + + """ + return np.ndim(getdata(obj)) + + +ndim.__doc__ = np.ndim.__doc__ + + +def shape(obj): + "maskedarray version of the numpy function." + return np.shape(getdata(obj)) + + +shape.__doc__ = np.shape.__doc__ + + +def size(obj, axis=None): + "maskedarray version of the numpy function." + return np.size(getdata(obj), axis) + + +size.__doc__ = np.size.__doc__ + + +def diff(a, /, n=1, axis=-1, prepend=np._NoValue, append=np._NoValue): + """ + Calculate the n-th discrete difference along the given axis. + The first difference is given by ``out[i] = a[i+1] - a[i]`` along + the given axis, higher differences are calculated by using `diff` + recursively. + Preserves the input mask. + + Parameters + ---------- + a : array_like + Input array + n : int, optional + The number of times values are differenced. If zero, the input + is returned as-is. + axis : int, optional + The axis along which the difference is taken, default is the + last axis. + prepend, append : array_like, optional + Values to prepend or append to `a` along axis prior to + performing the difference. Scalar values are expanded to + arrays with length 1 in the direction of axis and the shape + of the input array in along all other axes. Otherwise the + dimension and shape must match `a` except along axis. + + Returns + ------- + diff : MaskedArray + The n-th differences. The shape of the output is the same as `a` + except along `axis` where the dimension is smaller by `n`. The + type of the output is the same as the type of the difference + between any two elements of `a`. This is the same as the type of + `a` in most cases. A notable exception is `datetime64`, which + results in a `timedelta64` output array. + + See Also + -------- + numpy.diff : Equivalent function in the top-level NumPy module. + + Notes + ----- + Type is preserved for boolean arrays, so the result will contain + `False` when consecutive elements are the same and `True` when they + differ. + + For unsigned integer arrays, the results will also be unsigned. This + should not be surprising, as the result is consistent with + calculating the difference directly: + + >>> u8_arr = np.array([1, 0], dtype=np.uint8) + >>> np.ma.diff(u8_arr) + masked_array(data=[255], + mask=False, + fill_value=np.uint64(999999), + dtype=uint8) + >>> u8_arr[1,...] - u8_arr[0,...] + np.uint8(255) + + If this is not desirable, then the array should be cast to a larger + integer type first: + + >>> i16_arr = u8_arr.astype(np.int16) + >>> np.ma.diff(i16_arr) + masked_array(data=[-1], + mask=False, + fill_value=np.int64(999999), + dtype=int16) + + Examples + -------- + >>> import numpy as np + >>> a = np.array([1, 2, 3, 4, 7, 0, 2, 3]) + >>> x = np.ma.masked_where(a < 2, a) + >>> np.ma.diff(x) + masked_array(data=[--, 1, 1, 3, --, --, 1], + mask=[ True, False, False, False, True, True, False], + fill_value=999999) + + >>> np.ma.diff(x, n=2) + masked_array(data=[--, 0, 2, --, --, --], + mask=[ True, False, False, True, True, True], + fill_value=999999) + + >>> a = np.array([[1, 3, 1, 5, 10], [0, 1, 5, 6, 8]]) + >>> x = np.ma.masked_equal(a, value=1) + >>> np.ma.diff(x) + masked_array( + data=[[--, --, --, 5], + [--, --, 1, 2]], + mask=[[ True, True, True, False], + [ True, True, False, False]], + fill_value=1) + + >>> np.ma.diff(x, axis=0) + masked_array(data=[[--, --, --, 1, -2]], + mask=[[ True, True, True, False, False]], + fill_value=1) + + """ + if n == 0: + return a + if n < 0: + raise ValueError("order must be non-negative but got " + repr(n)) + + a = np.ma.asanyarray(a) + if a.ndim == 0: + raise ValueError( + "diff requires input that is at least one dimensional" + ) + + combined = [] + if prepend is not np._NoValue: + prepend = np.ma.asanyarray(prepend) + if prepend.ndim == 0: + shape = list(a.shape) + shape[axis] = 1 + prepend = np.broadcast_to(prepend, tuple(shape)) + combined.append(prepend) + + combined.append(a) + + if append is not np._NoValue: + append = np.ma.asanyarray(append) + if append.ndim == 0: + shape = list(a.shape) + shape[axis] = 1 + append = np.broadcast_to(append, tuple(shape)) + combined.append(append) + + if len(combined) > 1: + a = np.ma.concatenate(combined, axis) + + # GH 22465 np.diff without prepend/append preserves the mask + return np.diff(a, n, axis) + + +############################################################################## +# Extra functions # +############################################################################## + + +def where(condition, x=_NoValue, y=_NoValue): + """ + Return a masked array with elements from `x` or `y`, depending on condition. + + .. note:: + When only `condition` is provided, this function is identical to + `nonzero`. The rest of this documentation covers only the case where + all three arguments are provided. + + Parameters + ---------- + condition : array_like, bool + Where True, yield `x`, otherwise yield `y`. + x, y : array_like, optional + Values from which to choose. `x`, `y` and `condition` need to be + broadcastable to some shape. + + Returns + ------- + out : MaskedArray + An masked array with `masked` elements where the condition is masked, + elements from `x` where `condition` is True, and elements from `y` + elsewhere. + + See Also + -------- + numpy.where : Equivalent function in the top-level NumPy module. + nonzero : The function that is called when x and y are omitted + + Examples + -------- + >>> import numpy as np + >>> x = np.ma.array(np.arange(9.).reshape(3, 3), mask=[[0, 1, 0], + ... [1, 0, 1], + ... [0, 1, 0]]) + >>> x + masked_array( + data=[[0.0, --, 2.0], + [--, 4.0, --], + [6.0, --, 8.0]], + mask=[[False, True, False], + [ True, False, True], + [False, True, False]], + fill_value=1e+20) + >>> np.ma.where(x > 5, x, -3.1416) + masked_array( + data=[[-3.1416, --, -3.1416], + [--, -3.1416, --], + [6.0, --, 8.0]], + mask=[[False, True, False], + [ True, False, True], + [False, True, False]], + fill_value=1e+20) + + """ + + # handle the single-argument case + missing = (x is _NoValue, y is _NoValue).count(True) + if missing == 1: + raise ValueError("Must provide both 'x' and 'y' or neither.") + if missing == 2: + return nonzero(condition) + + # we only care if the condition is true - false or masked pick y + cf = filled(condition, False) + xd = getdata(x) + yd = getdata(y) + + # we need the full arrays here for correct final dimensions + cm = getmaskarray(condition) + xm = getmaskarray(x) + ym = getmaskarray(y) + + # deal with the fact that masked.dtype == float64, but we don't actually + # want to treat it as that. + if x is masked and y is not masked: + xd = np.zeros((), dtype=yd.dtype) + xm = np.ones((), dtype=ym.dtype) + elif y is masked and x is not masked: + yd = np.zeros((), dtype=xd.dtype) + ym = np.ones((), dtype=xm.dtype) + + data = np.where(cf, xd, yd) + mask = np.where(cf, xm, ym) + mask = np.where(cm, np.ones((), dtype=mask.dtype), mask) + + # collapse the mask, for backwards compatibility + mask = _shrink_mask(mask) + + return masked_array(data, mask=mask) + + +def choose(indices, choices, out=None, mode='raise'): + """ + Use an index array to construct a new array from a list of choices. + + Given an array of integers and a list of n choice arrays, this method + will create a new array that merges each of the choice arrays. Where a + value in `index` is i, the new array will have the value that choices[i] + contains in the same place. + + Parameters + ---------- + indices : ndarray of ints + This array must contain integers in ``[0, n-1]``, where n is the + number of choices. + choices : sequence of arrays + Choice arrays. The index array and all of the choices should be + broadcastable to the same shape. + out : array, optional + If provided, the result will be inserted into this array. It should + be of the appropriate shape and `dtype`. + mode : {'raise', 'wrap', 'clip'}, optional + Specifies how out-of-bounds indices will behave. + + * 'raise' : raise an error + * 'wrap' : wrap around + * 'clip' : clip to the range + + Returns + ------- + merged_array : array + + See Also + -------- + choose : equivalent function + + Examples + -------- + >>> import numpy as np + >>> choice = np.array([[1,1,1], [2,2,2], [3,3,3]]) + >>> a = np.array([2, 1, 0]) + >>> np.ma.choose(a, choice) + masked_array(data=[3, 2, 1], + mask=False, + fill_value=999999) + + """ + def fmask(x): + "Returns the filled array, or True if masked." + if x is masked: + return True + return filled(x) + + def nmask(x): + "Returns the mask, True if ``masked``, False if ``nomask``." + if x is masked: + return True + return getmask(x) + # Get the indices. + c = filled(indices, 0) + # Get the masks. + masks = [nmask(x) for x in choices] + data = [fmask(x) for x in choices] + # Construct the mask + outputmask = np.choose(c, masks, mode=mode) + outputmask = make_mask(mask_or(outputmask, getmask(indices)), + copy=False, shrink=True) + # Get the choices. + d = np.choose(c, data, mode=mode, out=out).view(MaskedArray) + if out is not None: + if isinstance(out, MaskedArray): + out.__setmask__(outputmask) + return out + d.__setmask__(outputmask) + return d + + +def round_(a, decimals=0, out=None): + """ + Return a copy of a, rounded to 'decimals' places. + + When 'decimals' is negative, it specifies the number of positions + to the left of the decimal point. The real and imaginary parts of + complex numbers are rounded separately. Nothing is done if the + array is not of float type and 'decimals' is greater than or equal + to 0. + + Parameters + ---------- + decimals : int + Number of decimals to round to. May be negative. + out : array_like + Existing array to use for output. + If not given, returns a default copy of a. + + Notes + ----- + If out is given and does not have a mask attribute, the mask of a + is lost! + + Examples + -------- + >>> import numpy as np + >>> import numpy.ma as ma + >>> x = [11.2, -3.973, 0.801, -1.41] + >>> mask = [0, 0, 0, 1] + >>> masked_x = ma.masked_array(x, mask) + >>> masked_x + masked_array(data=[11.2, -3.973, 0.801, --], + mask=[False, False, False, True], + fill_value=1e+20) + >>> ma.round_(masked_x) + masked_array(data=[11.0, -4.0, 1.0, --], + mask=[False, False, False, True], + fill_value=1e+20) + >>> ma.round(masked_x, decimals=1) + masked_array(data=[11.2, -4.0, 0.8, --], + mask=[False, False, False, True], + fill_value=1e+20) + >>> ma.round_(masked_x, decimals=-1) + masked_array(data=[10.0, -0.0, 0.0, --], + mask=[False, False, False, True], + fill_value=1e+20) + """ + if out is None: + return np.round(a, decimals, out) + else: + np.round(getdata(a), decimals, out) + if hasattr(out, '_mask'): + out._mask = getmask(a) + return out + + +round = round_ + + +def _mask_propagate(a, axis): + """ + Mask whole 1-d vectors of an array that contain masked values. + """ + a = array(a, subok=False) + m = getmask(a) + if m is nomask or not m.any() or axis is None: + return a + a._mask = a._mask.copy() + axes = normalize_axis_tuple(axis, a.ndim) + for ax in axes: + a._mask |= m.any(axis=ax, keepdims=True) + return a + + +# Include masked dot here to avoid import problems in getting it from +# extras.py. Note that it is not included in __all__, but rather exported +# from extras in order to avoid backward compatibility problems. +def dot(a, b, strict=False, out=None): + """ + Return the dot product of two arrays. + + This function is the equivalent of `numpy.dot` that takes masked values + into account. Note that `strict` and `out` are in different position + than in the method version. In order to maintain compatibility with the + corresponding method, it is recommended that the optional arguments be + treated as keyword only. At some point that may be mandatory. + + Parameters + ---------- + a, b : masked_array_like + Inputs arrays. + strict : bool, optional + Whether masked data are propagated (True) or set to 0 (False) for + the computation. Default is False. Propagating the mask means that + if a masked value appears in a row or column, the whole row or + column is considered masked. + out : masked_array, optional + Output argument. This must have the exact kind that would be returned + if it was not used. In particular, it must have the right type, must be + C-contiguous, and its dtype must be the dtype that would be returned + for `dot(a,b)`. This is a performance feature. Therefore, if these + conditions are not met, an exception is raised, instead of attempting + to be flexible. + + See Also + -------- + numpy.dot : Equivalent function for ndarrays. + + Examples + -------- + >>> import numpy as np + >>> a = np.ma.array([[1, 2, 3], [4, 5, 6]], mask=[[1, 0, 0], [0, 0, 0]]) + >>> b = np.ma.array([[1, 2], [3, 4], [5, 6]], mask=[[1, 0], [0, 0], [0, 0]]) + >>> np.ma.dot(a, b) + masked_array( + data=[[21, 26], + [45, 64]], + mask=[[False, False], + [False, False]], + fill_value=999999) + >>> np.ma.dot(a, b, strict=True) + masked_array( + data=[[--, --], + [--, 64]], + mask=[[ True, True], + [ True, False]], + fill_value=999999) + + """ + if strict is True: + if np.ndim(a) == 0 or np.ndim(b) == 0: + pass + elif b.ndim == 1: + a = _mask_propagate(a, a.ndim - 1) + b = _mask_propagate(b, b.ndim - 1) + else: + a = _mask_propagate(a, a.ndim - 1) + b = _mask_propagate(b, b.ndim - 2) + am = ~getmaskarray(a) + bm = ~getmaskarray(b) + + if out is None: + d = np.dot(filled(a, 0), filled(b, 0)) + m = ~np.dot(am, bm) + if np.ndim(d) == 0: + d = np.asarray(d) + r = d.view(get_masked_subclass(a, b)) + r.__setmask__(m) + return r + else: + d = np.dot(filled(a, 0), filled(b, 0), out._data) + if out.mask.shape != d.shape: + out._mask = np.empty(d.shape, MaskType) + np.dot(am, bm, out._mask) + np.logical_not(out._mask, out._mask) + return out + + +def inner(a, b): + """ + Returns the inner product of a and b for arrays of floating point types. + + Like the generic NumPy equivalent the product sum is over the last dimension + of a and b. The first argument is not conjugated. + + """ + fa = filled(a, 0) + fb = filled(b, 0) + if fa.ndim == 0: + fa.shape = (1,) + if fb.ndim == 0: + fb.shape = (1,) + return np.inner(fa, fb).view(MaskedArray) + + +inner.__doc__ = doc_note(np.inner.__doc__, + "Masked values are replaced by 0.") +innerproduct = inner + + +def outer(a, b): + "maskedarray version of the numpy function." + fa = filled(a, 0).ravel() + fb = filled(b, 0).ravel() + d = np.outer(fa, fb) + ma = getmask(a) + mb = getmask(b) + if ma is nomask and mb is nomask: + return masked_array(d) + ma = getmaskarray(a) + mb = getmaskarray(b) + m = make_mask(1 - np.outer(1 - ma, 1 - mb), copy=False) + return masked_array(d, mask=m) + + +outer.__doc__ = doc_note(np.outer.__doc__, + "Masked values are replaced by 0.") +outerproduct = outer + + +def _convolve_or_correlate(f, a, v, mode, propagate_mask): + """ + Helper function for ma.correlate and ma.convolve + """ + if propagate_mask: + # results which are contributed to by either item in any pair being invalid + mask = ( + f(getmaskarray(a), np.ones(np.shape(v), dtype=bool), mode=mode) + | f(np.ones(np.shape(a), dtype=bool), getmaskarray(v), mode=mode) + ) + data = f(getdata(a), getdata(v), mode=mode) + else: + # results which are not contributed to by any pair of valid elements + mask = ~f(~getmaskarray(a), ~getmaskarray(v), mode=mode) + data = f(filled(a, 0), filled(v, 0), mode=mode) + + return masked_array(data, mask=mask) + + +def correlate(a, v, mode='valid', propagate_mask=True): + """ + Cross-correlation of two 1-dimensional sequences. + + Parameters + ---------- + a, v : array_like + Input sequences. + mode : {'valid', 'same', 'full'}, optional + Refer to the `np.convolve` docstring. Note that the default + is 'valid', unlike `convolve`, which uses 'full'. + propagate_mask : bool + If True, then a result element is masked if any masked element contributes + towards it. If False, then a result element is only masked if no non-masked + element contribute towards it + + Returns + ------- + out : MaskedArray + Discrete cross-correlation of `a` and `v`. + + See Also + -------- + numpy.correlate : Equivalent function in the top-level NumPy module. + + Examples + -------- + Basic correlation: + + >>> a = np.ma.array([1, 2, 3]) + >>> v = np.ma.array([0, 1, 0]) + >>> np.ma.correlate(a, v, mode='valid') + masked_array(data=[2], + mask=[False], + fill_value=999999) + + Correlation with masked elements: + + >>> a = np.ma.array([1, 2, 3], mask=[False, True, False]) + >>> v = np.ma.array([0, 1, 0]) + >>> np.ma.correlate(a, v, mode='valid', propagate_mask=True) + masked_array(data=[--], + mask=[ True], + fill_value=999999, + dtype=int64) + + Correlation with different modes and mixed array types: + + >>> a = np.ma.array([1, 2, 3]) + >>> v = np.ma.array([0, 1, 0]) + >>> np.ma.correlate(a, v, mode='full') + masked_array(data=[0, 1, 2, 3, 0], + mask=[False, False, False, False, False], + fill_value=999999) + + """ + return _convolve_or_correlate(np.correlate, a, v, mode, propagate_mask) + + +def convolve(a, v, mode='full', propagate_mask=True): + """ + Returns the discrete, linear convolution of two one-dimensional sequences. + + Parameters + ---------- + a, v : array_like + Input sequences. + mode : {'valid', 'same', 'full'}, optional + Refer to the `np.convolve` docstring. + propagate_mask : bool + If True, then if any masked element is included in the sum for a result + element, then the result is masked. + If False, then the result element is only masked if no non-masked cells + contribute towards it + + Returns + ------- + out : MaskedArray + Discrete, linear convolution of `a` and `v`. + + See Also + -------- + numpy.convolve : Equivalent function in the top-level NumPy module. + """ + return _convolve_or_correlate(np.convolve, a, v, mode, propagate_mask) + + +def allequal(a, b, fill_value=True): + """ + Return True if all entries of a and b are equal, using + fill_value as a truth value where either or both are masked. + + Parameters + ---------- + a, b : array_like + Input arrays to compare. + fill_value : bool, optional + Whether masked values in a or b are considered equal (True) or not + (False). + + Returns + ------- + y : bool + Returns True if the two arrays are equal within the given + tolerance, False otherwise. If either array contains NaN, + then False is returned. + + See Also + -------- + all, any + numpy.ma.allclose + + Examples + -------- + >>> import numpy as np + >>> a = np.ma.array([1e10, 1e-7, 42.0], mask=[0, 0, 1]) + >>> a + masked_array(data=[10000000000.0, 1e-07, --], + mask=[False, False, True], + fill_value=1e+20) + + >>> b = np.array([1e10, 1e-7, -42.0]) + >>> b + array([ 1.00000000e+10, 1.00000000e-07, -4.20000000e+01]) + >>> np.ma.allequal(a, b, fill_value=False) + False + >>> np.ma.allequal(a, b) + True + + """ + m = mask_or(getmask(a), getmask(b)) + if m is nomask: + x = getdata(a) + y = getdata(b) + d = umath.equal(x, y) + return d.all() + elif fill_value: + x = getdata(a) + y = getdata(b) + d = umath.equal(x, y) + dm = array(d, mask=m, copy=False) + return dm.filled(True).all(None) + else: + return False + + +def allclose(a, b, masked_equal=True, rtol=1e-5, atol=1e-8): + """ + Returns True if two arrays are element-wise equal within a tolerance. + + This function is equivalent to `allclose` except that masked values + are treated as equal (default) or unequal, depending on the `masked_equal` + argument. + + Parameters + ---------- + a, b : array_like + Input arrays to compare. + masked_equal : bool, optional + Whether masked values in `a` and `b` are considered equal (True) or not + (False). They are considered equal by default. + rtol : float, optional + Relative tolerance. The relative difference is equal to ``rtol * b``. + Default is 1e-5. + atol : float, optional + Absolute tolerance. The absolute difference is equal to `atol`. + Default is 1e-8. + + Returns + ------- + y : bool + Returns True if the two arrays are equal within the given + tolerance, False otherwise. If either array contains NaN, then + False is returned. + + See Also + -------- + all, any + numpy.allclose : the non-masked `allclose`. + + Notes + ----- + If the following equation is element-wise True, then `allclose` returns + True:: + + absolute(`a` - `b`) <= (`atol` + `rtol` * absolute(`b`)) + + Return True if all elements of `a` and `b` are equal subject to + given tolerances. + + Examples + -------- + >>> import numpy as np + >>> a = np.ma.array([1e10, 1e-7, 42.0], mask=[0, 0, 1]) + >>> a + masked_array(data=[10000000000.0, 1e-07, --], + mask=[False, False, True], + fill_value=1e+20) + >>> b = np.ma.array([1e10, 1e-8, -42.0], mask=[0, 0, 1]) + >>> np.ma.allclose(a, b) + False + + >>> a = np.ma.array([1e10, 1e-8, 42.0], mask=[0, 0, 1]) + >>> b = np.ma.array([1.00001e10, 1e-9, -42.0], mask=[0, 0, 1]) + >>> np.ma.allclose(a, b) + True + >>> np.ma.allclose(a, b, masked_equal=False) + False + + Masked values are not compared directly. + + >>> a = np.ma.array([1e10, 1e-8, 42.0], mask=[0, 0, 1]) + >>> b = np.ma.array([1.00001e10, 1e-9, 42.0], mask=[0, 0, 1]) + >>> np.ma.allclose(a, b) + True + >>> np.ma.allclose(a, b, masked_equal=False) + False + + """ + x = masked_array(a, copy=False) + y = masked_array(b, copy=False) + + # make sure y is an inexact type to avoid abs(MIN_INT); will cause + # casting of x later. + # NOTE: We explicitly allow timedelta, which used to work. This could + # possibly be deprecated. See also gh-18286. + # timedelta works if `atol` is an integer or also a timedelta. + # Although, the default tolerances are unlikely to be useful + if y.dtype.kind != "m": + dtype = np.result_type(y, 1.) + if y.dtype != dtype: + y = masked_array(y, dtype=dtype, copy=False) + + m = mask_or(getmask(x), getmask(y)) + xinf = np.isinf(masked_array(x, copy=False, mask=m)).filled(False) + # If we have some infs, they should fall at the same place. + if not np.all(xinf == filled(np.isinf(y), False)): + return False + # No infs at all + if not np.any(xinf): + d = filled(less_equal(absolute(x - y), atol + rtol * absolute(y)), + masked_equal) + return np.all(d) + + if not np.all(filled(x[xinf] == y[xinf], masked_equal)): + return False + x = x[~xinf] + y = y[~xinf] + + d = filled(less_equal(absolute(x - y), atol + rtol * absolute(y)), + masked_equal) + + return np.all(d) + + +def asarray(a, dtype=None, order=None): + """ + Convert the input to a masked array of the given data-type. + + No copy is performed if the input is already an `ndarray`. If `a` is + a subclass of `MaskedArray`, a base class `MaskedArray` is returned. + + Parameters + ---------- + a : array_like + Input data, in any form that can be converted to a masked array. This + includes lists, lists of tuples, tuples, tuples of tuples, tuples + of lists, ndarrays and masked arrays. + dtype : dtype, optional + By default, the data-type is inferred from the input data. + order : {'C', 'F'}, optional + Whether to use row-major ('C') or column-major ('FORTRAN') memory + representation. Default is 'C'. + + Returns + ------- + out : MaskedArray + Masked array interpretation of `a`. + + See Also + -------- + asanyarray : Similar to `asarray`, but conserves subclasses. + + Examples + -------- + >>> import numpy as np + >>> x = np.arange(10.).reshape(2, 5) + >>> x + array([[0., 1., 2., 3., 4.], + [5., 6., 7., 8., 9.]]) + >>> np.ma.asarray(x) + masked_array( + data=[[0., 1., 2., 3., 4.], + [5., 6., 7., 8., 9.]], + mask=False, + fill_value=1e+20) + >>> type(np.ma.asarray(x)) + + + """ + order = order or 'C' + return masked_array(a, dtype=dtype, copy=False, keep_mask=True, + subok=False, order=order) + + +def asanyarray(a, dtype=None, order=None): + """ + Convert the input to a masked array, conserving subclasses. + + If `a` is a subclass of `MaskedArray`, its class is conserved. + No copy is performed if the input is already an `ndarray`. + + Parameters + ---------- + a : array_like + Input data, in any form that can be converted to an array. + dtype : dtype, optional + By default, the data-type is inferred from the input data. + order : {'C', 'F', 'A', 'K'}, optional + Memory layout. 'A' and 'K' depend on the order of input array ``a``. + 'C' row-major (C-style), + 'F' column-major (Fortran-style) memory representation. + 'A' (any) means 'F' if ``a`` is Fortran contiguous, 'C' otherwise + 'K' (keep) preserve input order + Defaults to 'K'. + + Returns + ------- + out : MaskedArray + MaskedArray interpretation of `a`. + + See Also + -------- + asarray : Similar to `asanyarray`, but does not conserve subclass. + + Examples + -------- + >>> import numpy as np + >>> x = np.arange(10.).reshape(2, 5) + >>> x + array([[0., 1., 2., 3., 4.], + [5., 6., 7., 8., 9.]]) + >>> np.ma.asanyarray(x) + masked_array( + data=[[0., 1., 2., 3., 4.], + [5., 6., 7., 8., 9.]], + mask=False, + fill_value=1e+20) + >>> type(np.ma.asanyarray(x)) + + + """ + # workaround for #8666, to preserve identity. Ideally the bottom line + # would handle this for us. + if ( + isinstance(a, MaskedArray) + and (dtype is None or dtype == a.dtype) + and ( + order in {None, 'A', 'K'} + or order == 'C' and a.flags.carray + or order == 'F' and a.flags.f_contiguous + ) + ): + return a + return masked_array(a, dtype=dtype, copy=False, keep_mask=True, subok=True, + order=order) + + +############################################################################## +# Pickling # +############################################################################## + + +def fromfile(file, dtype=float, count=-1, sep=''): + raise NotImplementedError( + "fromfile() not yet implemented for a MaskedArray.") + + +def fromflex(fxarray): + """ + Build a masked array from a suitable flexible-type array. + + The input array has to have a data-type with ``_data`` and ``_mask`` + fields. This type of array is output by `MaskedArray.toflex`. + + Parameters + ---------- + fxarray : ndarray + The structured input array, containing ``_data`` and ``_mask`` + fields. If present, other fields are discarded. + + Returns + ------- + result : MaskedArray + The constructed masked array. + + See Also + -------- + MaskedArray.toflex : Build a flexible-type array from a masked array. + + Examples + -------- + >>> import numpy as np + >>> x = np.ma.array(np.arange(9).reshape(3, 3), mask=[0] + [1, 0] * 4) + >>> rec = x.toflex() + >>> rec + array([[(0, False), (1, True), (2, False)], + [(3, True), (4, False), (5, True)], + [(6, False), (7, True), (8, False)]], + dtype=[('_data', '>> x2 = np.ma.fromflex(rec) + >>> x2 + masked_array( + data=[[0, --, 2], + [--, 4, --], + [6, --, 8]], + mask=[[False, True, False], + [ True, False, True], + [False, True, False]], + fill_value=999999) + + Extra fields can be present in the structured array but are discarded: + + >>> dt = [('_data', '>> rec2 = np.zeros((2, 2), dtype=dt) + >>> rec2 + array([[(0, False, 0.), (0, False, 0.)], + [(0, False, 0.), (0, False, 0.)]], + dtype=[('_data', '>> y = np.ma.fromflex(rec2) + >>> y + masked_array( + data=[[0, 0], + [0, 0]], + mask=[[False, False], + [False, False]], + fill_value=np.int64(999999), + dtype=int32) + + """ + return masked_array(fxarray['_data'], mask=fxarray['_mask']) + + +def _convert2ma(funcname: str, np_ret: str, np_ma_ret: str, + params: dict[str, str] | None = None): + """Convert function from numpy to numpy.ma.""" + func = getattr(np, funcname) + params = params or {} + + @functools.wraps(func, assigned=set(functools.WRAPPER_ASSIGNMENTS) - {"__module__"}) + def wrapper(*args, **kwargs): + common_params = kwargs.keys() & params.keys() + extras = params | {p: kwargs.pop(p) for p in common_params} + + result = func.__call__(*args, **kwargs).view(MaskedArray) + + if "fill_value" in common_params: + result.fill_value = extras["fill_value"] + if "hardmask" in common_params: + result._hardmask = bool(extras["hardmask"]) + + return result + + # workaround for a doctest bug in Python 3.11 that incorrectly assumes `__code__` + # exists on wrapped functions + del wrapper.__wrapped__ + + # `arange`, `empty`, `empty_like`, `frombuffer`, and `zeros` have no signature + try: + signature = inspect.signature(func) + except ValueError: + signature = inspect.Signature([ + inspect.Parameter('args', inspect.Parameter.VAR_POSITIONAL), + inspect.Parameter('kwargs', inspect.Parameter.VAR_KEYWORD), + ]) + + if params: + sig_params = list(signature.parameters.values()) + + # pop `**kwargs` if present + sig_kwargs = None + if sig_params[-1].kind is inspect.Parameter.VAR_KEYWORD: + sig_kwargs = sig_params.pop() + + # add new keyword-only parameters + for param_name, default in params.items(): + new_param = inspect.Parameter( + param_name, + inspect.Parameter.KEYWORD_ONLY, + default=default, + ) + sig_params.append(new_param) + + # re-append `**kwargs` if it was present + if sig_kwargs: + sig_params.append(sig_kwargs) + + signature = signature.replace(parameters=sig_params) + + wrapper.__signature__ = signature + + # __doc__ is None when using `python -OO ...` + if func.__doc__ is not None: + assert np_ret in func.__doc__, ( + f"Failed to replace `{np_ret}` with `{np_ma_ret}`. " + f"The documentation string for return type, {np_ret}, is not " + f"found in the docstring for `np.{func.__name__}`. " + f"Fix the docstring for `np.{func.__name__}` or " + "update the expected string for return type." + ) + wrapper.__doc__ = inspect.cleandoc(func.__doc__).replace(np_ret, np_ma_ret) + + return wrapper + + +arange = _convert2ma( + 'arange', + params={'fill_value': None, 'hardmask': False}, + np_ret='arange : ndarray', + np_ma_ret='arange : MaskedArray', +) +clip = _convert2ma( + 'clip', + params={'fill_value': None, 'hardmask': False}, + np_ret='clipped_array : ndarray', + np_ma_ret='clipped_array : MaskedArray', +) +empty = _convert2ma( + 'empty', + params={'fill_value': None, 'hardmask': False}, + np_ret='out : ndarray', + np_ma_ret='out : MaskedArray', +) +empty_like = _convert2ma( + 'empty_like', + np_ret='out : ndarray', + np_ma_ret='out : MaskedArray', +) +frombuffer = _convert2ma( + 'frombuffer', + np_ret='out : ndarray', + np_ma_ret='out: MaskedArray', +) +fromfunction = _convert2ma( + 'fromfunction', + np_ret='fromfunction : any', + np_ma_ret='fromfunction: MaskedArray', +) +identity = _convert2ma( + 'identity', + params={'fill_value': None, 'hardmask': False}, + np_ret='out : ndarray', + np_ma_ret='out : MaskedArray', +) +indices = _convert2ma( + 'indices', + params={'fill_value': None, 'hardmask': False}, + np_ret='grid : one ndarray or tuple of ndarrays', + np_ma_ret='grid : one MaskedArray or tuple of MaskedArrays', +) +ones = _convert2ma( + 'ones', + params={'fill_value': None, 'hardmask': False}, + np_ret='out : ndarray', + np_ma_ret='out : MaskedArray', +) +ones_like = _convert2ma( + 'ones_like', + np_ret='out : ndarray', + np_ma_ret='out : MaskedArray', +) +squeeze = _convert2ma( + 'squeeze', + params={'fill_value': None, 'hardmask': False}, + np_ret='squeezed : ndarray', + np_ma_ret='squeezed : MaskedArray', +) +zeros = _convert2ma( + 'zeros', + params={'fill_value': None, 'hardmask': False}, + np_ret='out : ndarray', + np_ma_ret='out : MaskedArray', +) +zeros_like = _convert2ma( + 'zeros_like', + np_ret='out : ndarray', + np_ma_ret='out : MaskedArray', +) + + +def append(a, b, axis=None): + """Append values to the end of an array. + + Parameters + ---------- + a : array_like + Values are appended to a copy of this array. + b : array_like + These values are appended to a copy of `a`. It must be of the + correct shape (the same shape as `a`, excluding `axis`). If `axis` + is not specified, `b` can be any shape and will be flattened + before use. + axis : int, optional + The axis along which `v` are appended. If `axis` is not given, + both `a` and `b` are flattened before use. + + Returns + ------- + append : MaskedArray + A copy of `a` with `b` appended to `axis`. Note that `append` + does not occur in-place: a new array is allocated and filled. If + `axis` is None, the result is a flattened array. + + See Also + -------- + numpy.append : Equivalent function in the top-level NumPy module. + + Examples + -------- + >>> import numpy as np + >>> import numpy.ma as ma + >>> a = ma.masked_values([1, 2, 3], 2) + >>> b = ma.masked_values([[4, 5, 6], [7, 8, 9]], 7) + >>> ma.append(a, b) + masked_array(data=[1, --, 3, 4, 5, 6, --, 8, 9], + mask=[False, True, False, False, False, False, True, False, + False], + fill_value=999999) + """ + return concatenate([a, b], axis) diff --git a/python/user_packages/Python313/site-packages/numpy/ma/core.pyi b/python/user_packages/Python313/site-packages/numpy/ma/core.pyi new file mode 100644 index 0000000000000000000000000000000000000000..5e144e5fa54a537c1da498f57fe565d2620a12a5 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/ma/core.pyi @@ -0,0 +1,3733 @@ +# pyright: reportIncompatibleMethodOverride=false + +import datetime as dt +import types +from _typeshed import Incomplete +from collections.abc import Callable, Sequence +from typing import ( + Any, + Concatenate, + Final, + Generic, + Literal, + Never, + NoReturn, + Self, + SupportsComplex, + SupportsFloat, + SupportsIndex, + SupportsInt, + TypeAlias, + Unpack, + final, + overload, +) +from typing_extensions import Buffer, ParamSpec, TypeIs, TypeVar, override + +import numpy as np +from numpy import ( + _AnyShapeT, + _HasDType, + _HasDTypeWithRealAndImag, + _ModeKind, + _OrderACF, + _OrderCF, + _OrderKACF, + _PartitionKind, + _SortKind, + _ToIndices, + amax, + amin, + bool_, + bytes_, + character, + complex128, + complexfloating, + datetime64, + dtype, + dtypes, + expand_dims, + flexible, + float16, + float32, + float64, + floating, + generic, + inexact, + int8, + int64, + int_, + integer, + intp, + ndarray, + number, + object_, + signedinteger, + str_, + timedelta64, + ufunc, + unsignedinteger, + void, +) +from numpy._core.fromnumeric import _UFuncKwargs # type-check only +from numpy._globals import _NoValueType +from numpy._typing import ( + ArrayLike, + DTypeLike, + NDArray, + _32Bit, + _64Bit, + _AnyShape, + _ArrayLike, + _ArrayLikeBool_co, + _ArrayLikeBytes_co, + _ArrayLikeComplex128_co, + _ArrayLikeComplex_co, + _ArrayLikeDT64_co, + _ArrayLikeFloat64_co, + _ArrayLikeFloat_co, + _ArrayLikeInt, + _ArrayLikeInt_co, + _ArrayLikeNumber_co, + _ArrayLikeObject_co, + _ArrayLikeStr_co, + _ArrayLikeString_co, + _ArrayLikeTD64_co, + _ArrayLikeUInt_co, + _CharLike_co, + _DT64Codes, + _DTypeLike, + _DTypeLikeBool, + _DTypeLikeVoid, + _FloatLike_co, + _IntLike_co, + _NestedSequence, + _ScalarLike_co, + _Shape, + _ShapeLike, + _SupportsArrayFunc, + _SupportsDType, + _TD64Like_co, +) +from numpy._typing._dtype_like import _VoidDTypeLike + +__all__ = [ + "MAError", + "MaskError", + "MaskType", + "MaskedArray", + "abs", + "absolute", + "add", + "all", + "allclose", + "allequal", + "alltrue", + "amax", + "amin", + "angle", + "anom", + "anomalies", + "any", + "append", + "arange", + "arccos", + "arccosh", + "arcsin", + "arcsinh", + "arctan", + "arctan2", + "arctanh", + "argmax", + "argmin", + "argsort", + "around", + "array", + "asanyarray", + "asarray", + "bitwise_and", + "bitwise_or", + "bitwise_xor", + "bool_", + "ceil", + "choose", + "clip", + "common_fill_value", + "compress", + "compressed", + "concatenate", + "conjugate", + "convolve", + "copy", + "correlate", + "cos", + "cosh", + "count", + "cumprod", + "cumsum", + "default_fill_value", + "diag", + "diagonal", + "diff", + "divide", + "empty", + "empty_like", + "equal", + "exp", + "expand_dims", + "fabs", + "filled", + "fix_invalid", + "flatten_mask", + "flatten_structured_array", + "floor", + "floor_divide", + "fmod", + "frombuffer", + "fromflex", + "fromfunction", + "getdata", + "getmask", + "getmaskarray", + "greater", + "greater_equal", + "harden_mask", + "hypot", + "identity", + "ids", + "indices", + "inner", + "innerproduct", + "isMA", + "isMaskedArray", + "is_mask", + "is_masked", + "isarray", + "left_shift", + "less", + "less_equal", + "log", + "log2", + "log10", + "logical_and", + "logical_not", + "logical_or", + "logical_xor", + "make_mask", + "make_mask_descr", + "make_mask_none", + "mask_or", + "masked", + "masked_array", + "masked_equal", + "masked_greater", + "masked_greater_equal", + "masked_inside", + "masked_invalid", + "masked_less", + "masked_less_equal", + "masked_not_equal", + "masked_object", + "masked_outside", + "masked_print_option", + "masked_singleton", + "masked_values", + "masked_where", + "max", + "maximum", + "maximum_fill_value", + "mean", + "min", + "minimum", + "minimum_fill_value", + "mod", + "multiply", + "mvoid", + "ndim", + "negative", + "nomask", + "nonzero", + "not_equal", + "ones", + "ones_like", + "outer", + "outerproduct", + "power", + "prod", + "product", + "ptp", + "put", + "putmask", + "ravel", + "remainder", + "repeat", + "reshape", + "resize", + "right_shift", + "round", + "round_", + "set_fill_value", + "shape", + "sin", + "sinh", + "size", + "soften_mask", + "sometrue", + "sort", + "sqrt", + "squeeze", + "std", + "subtract", + "sum", + "swapaxes", + "take", + "tan", + "tanh", + "trace", + "transpose", + "true_divide", + "var", + "where", + "zeros", + "zeros_like", +] + +_ShapeT = TypeVar("_ShapeT", bound=_Shape) +_ShapeOrAnyT = TypeVar("_ShapeOrAnyT", bound=_Shape, default=_AnyShape) +_ShapeT_co = TypeVar("_ShapeT_co", bound=_Shape, default=_AnyShape, covariant=True) +_DTypeT = TypeVar("_DTypeT", bound=dtype) +_DTypeT_co = TypeVar("_DTypeT_co", bound=dtype, default=dtype, covariant=True) +_ArrayT = TypeVar("_ArrayT", bound=ndarray[Any, Any]) +_MArrayT = TypeVar("_MArrayT", bound=MaskedArray[Any, Any]) +_ScalarT = TypeVar("_ScalarT", bound=generic) +_ScalarT_co = TypeVar("_ScalarT_co", bound=generic, covariant=True) +_NumberT = TypeVar("_NumberT", bound=number) +_RealNumberT = TypeVar("_RealNumberT", bound=floating | integer) +_ArangeScalarT = TypeVar("_ArangeScalarT", bound=_ArangeScalar) +_UFuncT_co = TypeVar( + "_UFuncT_co", + # the `| Callable` simplifies self-binding to the ufunc's callable signature + bound=np.ufunc | Callable[..., object], + default=np.ufunc, + covariant=True, +) +_Pss = ParamSpec("_Pss") +_T = TypeVar("_T") + +_Ignored: TypeAlias = object + +# A subset of `MaskedArray` that can be parametrized w.r.t. `np.generic` +_MaskedArray: TypeAlias = MaskedArray[_AnyShape, dtype[_ScalarT]] +_Masked1D: TypeAlias = MaskedArray[tuple[int], dtype[_ScalarT]] + +_MaskedArrayUInt_co: TypeAlias = _MaskedArray[unsignedinteger | np.bool] +_MaskedArrayInt_co: TypeAlias = _MaskedArray[integer | np.bool] +_MaskedArrayFloat64_co: TypeAlias = _MaskedArray[floating[_64Bit] | float32 | float16 | integer | np.bool] +_MaskedArrayFloat_co: TypeAlias = _MaskedArray[floating | integer | np.bool] +_MaskedArrayComplex128_co: TypeAlias = _MaskedArray[number[_64Bit] | number[_32Bit] | float16 | integer | np.bool] +_MaskedArrayComplex_co: TypeAlias = _MaskedArray[inexact | integer | np.bool] +_MaskedArrayNumber_co: TypeAlias = _MaskedArray[number | np.bool] +_MaskedArrayTD64_co: TypeAlias = _MaskedArray[timedelta64 | integer | np.bool] + +_ArrayInt_co: TypeAlias = NDArray[integer | bool_] +_Array1D: TypeAlias = np.ndarray[tuple[int], np.dtype[_ScalarT]] + +_ConvertibleToInt: TypeAlias = SupportsInt | SupportsIndex | _CharLike_co +_ConvertibleToFloat: TypeAlias = SupportsFloat | SupportsIndex | _CharLike_co +_ConvertibleToComplex: TypeAlias = SupportsComplex | SupportsFloat | SupportsIndex | _CharLike_co +_ConvertibleToTD64: TypeAlias = dt.timedelta | int | _CharLike_co | character | number | timedelta64 | np.bool | None +_ConvertibleToDT64: TypeAlias = dt.date | int | _CharLike_co | character | number | datetime64 | np.bool | None +_ArangeScalar: TypeAlias = floating | integer | datetime64 | timedelta64 + +_NoMaskType: TypeAlias = np.bool_[Literal[False]] # type of `np.False_` +_MaskArray: TypeAlias = np.ndarray[_ShapeOrAnyT, np.dtype[np.bool_]] + +_FillValue: TypeAlias = complex | None # int | float | complex | None +_FillValueCallable: TypeAlias = Callable[[np.dtype | ArrayLike], _FillValue] +_DomainCallable: TypeAlias = Callable[..., NDArray[np.bool_]] + +### + +MaskType = np.bool_ + +nomask: Final[_NoMaskType] = ... + +class MaskedArrayFutureWarning(FutureWarning): ... +class MAError(Exception): ... +class MaskError(MAError): ... + +# not generic at runtime +class _MaskedUFunc(Generic[_UFuncT_co]): + f: _UFuncT_co # readonly + def __init__(self, /, ufunc: _UFuncT_co) -> None: ... + +# not generic at runtime +class _MaskedUnaryOperation(_MaskedUFunc[_UFuncT_co], Generic[_UFuncT_co]): + fill: Final[_FillValue] + domain: Final[_DomainCallable | None] + + def __init__(self, /, mufunc: _UFuncT_co, fill: _FillValue = 0, domain: _DomainCallable | None = None) -> None: ... + + # NOTE: This might not work with overloaded callable signatures might not work on + # pyright, which is a long-standing issue, and is unique to pyright: + # https://github.com/microsoft/pyright/issues/9663 + # https://github.com/microsoft/pyright/issues/10849 + # https://github.com/microsoft/pyright/issues/10899 + # https://github.com/microsoft/pyright/issues/11049 + def __call__( + self: _MaskedUnaryOperation[Callable[Concatenate[Any, _Pss], _T]], + /, + a: ArrayLike, + *args: _Pss.args, + **kwargs: _Pss.kwargs, + ) -> _T: ... + +# not generic at runtime +class _MaskedBinaryOperation(_MaskedUFunc[_UFuncT_co], Generic[_UFuncT_co]): + fillx: Final[_FillValue] + filly: Final[_FillValue] + + def __init__(self, /, mbfunc: _UFuncT_co, fillx: _FillValue = 0, filly: _FillValue = 0) -> None: ... + + # NOTE: See the comment in `_MaskedUnaryOperation.__call__` + def __call__( + self: _MaskedBinaryOperation[Callable[Concatenate[Any, Any, _Pss], _T]], + /, + a: ArrayLike, + b: ArrayLike, + *args: _Pss.args, + **kwargs: _Pss.kwargs, + ) -> _T: ... + + # NOTE: We cannot meaningfully annotate the return (d)types of these methods until + # the signatures of the corresponding `numpy.ufunc` methods are specified. + def reduce(self, /, target: ArrayLike, axis: SupportsIndex = 0, dtype: DTypeLike | None = None) -> Incomplete: ... + def outer(self, /, a: ArrayLike, b: ArrayLike) -> _MaskedArray[Incomplete]: ... + def accumulate(self, /, target: ArrayLike, axis: SupportsIndex = 0) -> _MaskedArray[Incomplete]: ... + +# not generic at runtime +class _DomainedBinaryOperation(_MaskedUFunc[_UFuncT_co], Generic[_UFuncT_co]): + domain: Final[_DomainCallable] + fillx: Final[_FillValue] + filly: Final[_FillValue] + + def __init__( + self, + /, + dbfunc: _UFuncT_co, + domain: _DomainCallable, + fillx: _FillValue = 0, + filly: _FillValue = 0, + ) -> None: ... + + # NOTE: See the comment in `_MaskedUnaryOperation.__call__` + def __call__( + self: _DomainedBinaryOperation[Callable[Concatenate[Any, Any, _Pss], _T]], + /, + a: ArrayLike, + b: ArrayLike, + *args: _Pss.args, + **kwargs: _Pss.kwargs, + ) -> _T: ... + +# not generic at runtime +class _extrema_operation(_MaskedUFunc[_UFuncT_co], Generic[_UFuncT_co]): + compare: Final[_MaskedBinaryOperation] + fill_value_func: Final[_FillValueCallable] + + def __init__( + self, + /, + ufunc: _UFuncT_co, + compare: _MaskedBinaryOperation, + fill_value: _FillValueCallable, + ) -> None: ... + + # NOTE: This class is only used internally for `maximum` and `minimum`, so we are + # able to annotate the `__call__` method specifically for those two functions. + @overload + def __call__(self, /, a: _ArrayLike[_ScalarT], b: _ArrayLike[_ScalarT]) -> _MaskedArray[_ScalarT]: ... + @overload + def __call__(self, /, a: ArrayLike, b: ArrayLike) -> _MaskedArray[Incomplete]: ... + + # NOTE: We cannot meaningfully annotate the return (d)types of these methods until + # the signatures of the corresponding `numpy.ufunc` methods are specified. + def reduce(self, /, target: ArrayLike, axis: SupportsIndex | _NoValueType = ...) -> Incomplete: ... + def outer(self, /, a: ArrayLike, b: ArrayLike) -> _MaskedArray[Incomplete]: ... + +@final +class _MaskedPrintOption: + _display: str + _enabled: bool | Literal[0, 1] + def __init__(self, /, display: str) -> None: ... + def display(self, /) -> str: ... + def set_display(self, /, s: str) -> None: ... + def enabled(self, /) -> bool: ... + def enable(self, /, shrink: bool | Literal[0, 1] = 1) -> None: ... + +masked_print_option: Final[_MaskedPrintOption] = ... + +exp: _MaskedUnaryOperation = ... +conjugate: _MaskedUnaryOperation = ... +sin: _MaskedUnaryOperation = ... +cos: _MaskedUnaryOperation = ... +arctan: _MaskedUnaryOperation = ... +arcsinh: _MaskedUnaryOperation = ... +sinh: _MaskedUnaryOperation = ... +cosh: _MaskedUnaryOperation = ... +tanh: _MaskedUnaryOperation = ... +abs: _MaskedUnaryOperation = ... +absolute: _MaskedUnaryOperation = ... +angle: _MaskedUnaryOperation = ... +fabs: _MaskedUnaryOperation = ... +negative: _MaskedUnaryOperation = ... +floor: _MaskedUnaryOperation = ... +ceil: _MaskedUnaryOperation = ... +around: _MaskedUnaryOperation = ... +logical_not: _MaskedUnaryOperation = ... +sqrt: _MaskedUnaryOperation = ... +log: _MaskedUnaryOperation = ... +log2: _MaskedUnaryOperation = ... +log10: _MaskedUnaryOperation = ... +tan: _MaskedUnaryOperation = ... +arcsin: _MaskedUnaryOperation = ... +arccos: _MaskedUnaryOperation = ... +arccosh: _MaskedUnaryOperation = ... +arctanh: _MaskedUnaryOperation = ... + +add: _MaskedBinaryOperation = ... +subtract: _MaskedBinaryOperation = ... +multiply: _MaskedBinaryOperation = ... +arctan2: _MaskedBinaryOperation = ... +equal: _MaskedBinaryOperation = ... +not_equal: _MaskedBinaryOperation = ... +less_equal: _MaskedBinaryOperation = ... +greater_equal: _MaskedBinaryOperation = ... +less: _MaskedBinaryOperation = ... +greater: _MaskedBinaryOperation = ... +logical_and: _MaskedBinaryOperation = ... +def alltrue(target: ArrayLike, axis: SupportsIndex | None = 0, dtype: _DTypeLikeBool | None = None) -> Incomplete: ... +logical_or: _MaskedBinaryOperation = ... +def sometrue(target: ArrayLike, axis: SupportsIndex | None = 0, dtype: _DTypeLikeBool | None = None) -> Incomplete: ... +logical_xor: _MaskedBinaryOperation = ... +bitwise_and: _MaskedBinaryOperation = ... +bitwise_or: _MaskedBinaryOperation = ... +bitwise_xor: _MaskedBinaryOperation = ... +hypot: _MaskedBinaryOperation = ... + +divide: _DomainedBinaryOperation = ... +true_divide: _DomainedBinaryOperation = ... +floor_divide: _DomainedBinaryOperation = ... +remainder: _DomainedBinaryOperation = ... +fmod: _DomainedBinaryOperation = ... +mod: _DomainedBinaryOperation = ... + +# `obj` can be anything (even `object()`), and is too "flexible", so we can't +# meaningfully annotate it, or its return type. +def default_fill_value(obj: object) -> Any: ... +def minimum_fill_value(obj: object) -> Any: ... +def maximum_fill_value(obj: object) -> Any: ... + +# +@overload # returns `a.fill_value` if `a` is a `MaskedArray` +def get_fill_value(a: _MaskedArray[_ScalarT]) -> _ScalarT: ... +@overload # otherwise returns `default_fill_value(a)` +def get_fill_value(a: object) -> Any: ... + +# this is a noop if `a` isn't a `MaskedArray`, so we only accept `MaskedArray` input +def set_fill_value(a: MaskedArray, fill_value: _ScalarLike_co) -> None: ... + +# the return type depends on the *values* of `a` and `b` (which cannot be known +# statically), which is why we need to return an awkward `_ | None` +@overload +def common_fill_value(a: _MaskedArray[_ScalarT], b: MaskedArray) -> _ScalarT | None: ... +@overload +def common_fill_value(a: object, b: object) -> Any: ... + +# keep in sync with `fix_invalid`, but return `ndarray` instead of `MaskedArray` +@overload +def filled(a: ndarray[_ShapeT, _DTypeT], fill_value: _ScalarLike_co | None = None) -> ndarray[_ShapeT, _DTypeT]: ... +@overload +def filled(a: _ArrayLike[_ScalarT], fill_value: _ScalarLike_co | None = None) -> NDArray[_ScalarT]: ... +@overload +def filled(a: ArrayLike, fill_value: _ScalarLike_co | None = None) -> NDArray[Incomplete]: ... + +# keep in sync with `filled`, but return `MaskedArray` instead of `ndarray` +@overload +def fix_invalid( + a: np.ndarray[_ShapeT, _DTypeT], + mask: _ArrayLikeBool_co = nomask, + copy: bool = True, + fill_value: _ScalarLike_co | None = None, +) -> MaskedArray[_ShapeT, _DTypeT]: ... +@overload +def fix_invalid( + a: _ArrayLike[_ScalarT], + mask: _ArrayLikeBool_co = nomask, + copy: bool = True, + fill_value: _ScalarLike_co | None = None, +) -> _MaskedArray[_ScalarT]: ... +@overload +def fix_invalid( + a: ArrayLike, + mask: _ArrayLikeBool_co = nomask, + copy: bool = True, + fill_value: _ScalarLike_co | None = None, +) -> _MaskedArray[Incomplete]: ... + +# +def get_masked_subclass(*arrays: object) -> type[MaskedArray]: ... + +# +@overload +def getdata(a: np.ndarray[_ShapeT, _DTypeT], subok: bool = True) -> np.ndarray[_ShapeT, _DTypeT]: ... +@overload +def getdata(a: _ArrayLike[_ScalarT], subok: bool = True) -> NDArray[_ScalarT]: ... +@overload +def getdata(a: ArrayLike, subok: bool = True) -> NDArray[Incomplete]: ... + +get_data = getdata + +# +@overload +def getmask(a: _ScalarLike_co) -> _NoMaskType: ... +@overload +def getmask(a: MaskedArray[_ShapeT, Any]) -> _MaskArray[_ShapeT] | _NoMaskType: ... +@overload +def getmask(a: ArrayLike) -> _MaskArray | _NoMaskType: ... + +get_mask = getmask + +# like `getmask`, but instead of `nomask` returns `make_mask_none(arr, arr.dtype?)` +@overload +def getmaskarray(arr: _ScalarLike_co) -> _MaskArray[tuple[()]]: ... +@overload +def getmaskarray(arr: np.ndarray[_ShapeT, Any]) -> _MaskArray[_ShapeT]: ... + +# It's sufficient for `m` to have dtype with type: `type[np.bool_]`, +# which isn't necessarily a ndarray. Please open an issue if this causes issues. +def is_mask(m: object) -> TypeIs[NDArray[bool_]]: ... + +# +@overload +def make_mask_descr(ndtype: _VoidDTypeLike) -> np.dtype[np.void]: ... +@overload +def make_mask_descr(ndtype: _DTypeLike[np.generic] | str | type) -> np.dtype[np.bool_]: ... + +# +@overload # m is nomask +def make_mask( + m: _NoMaskType, + copy: bool = False, + shrink: bool = True, + dtype: _DTypeLikeBool = ..., +) -> _NoMaskType: ... +@overload # m: ndarray, shrink=True (default), dtype: bool-like (default) +def make_mask( + m: np.ndarray[_ShapeT], + copy: bool = False, + shrink: Literal[True] = True, + dtype: _DTypeLikeBool = ..., +) -> _MaskArray[_ShapeT] | _NoMaskType: ... +@overload # m: ndarray, shrink=False (kwarg), dtype: bool-like (default) +def make_mask( + m: np.ndarray[_ShapeT], + copy: bool = False, + *, + shrink: Literal[False], + dtype: _DTypeLikeBool = ..., +) -> _MaskArray[_ShapeT]: ... +@overload # m: ndarray, dtype: void-like +def make_mask( + m: np.ndarray[_ShapeT], + copy: bool = False, + shrink: bool = True, + *, + dtype: _DTypeLikeVoid, +) -> np.ndarray[_ShapeT, np.dtype[np.void]]: ... +@overload # m: array-like, shrink=True (default), dtype: bool-like (default) +def make_mask( + m: ArrayLike, + copy: bool = False, + shrink: Literal[True] = True, + dtype: _DTypeLikeBool = ..., +) -> _MaskArray | _NoMaskType: ... +@overload # m: array-like, shrink=False (kwarg), dtype: bool-like (default) +def make_mask( + m: ArrayLike, + copy: bool = False, + *, + shrink: Literal[False], + dtype: _DTypeLikeBool = ..., +) -> _MaskArray: ... +@overload # m: array-like, dtype: void-like +def make_mask( + m: ArrayLike, + copy: bool = False, + shrink: bool = True, + *, + dtype: _DTypeLikeVoid, +) -> NDArray[np.void]: ... +@overload # fallback +def make_mask( + m: ArrayLike, + copy: bool = False, + shrink: bool = True, + *, + dtype: DTypeLike = ..., +) -> NDArray[Incomplete] | _NoMaskType: ... + +# +@overload # known shape, dtype: unstructured (default) +def make_mask_none(newshape: _ShapeT, dtype: np.dtype | type | str | None = None) -> _MaskArray[_ShapeT]: ... +@overload # known shape, dtype: structured +def make_mask_none(newshape: _ShapeT, dtype: _VoidDTypeLike) -> np.ndarray[_ShapeT, dtype[np.void]]: ... +@overload # unknown shape, dtype: unstructured (default) +def make_mask_none(newshape: _ShapeLike, dtype: np.dtype | type | str | None = None) -> _MaskArray: ... +@overload # unknown shape, dtype: structured +def make_mask_none(newshape: _ShapeLike, dtype: _VoidDTypeLike) -> NDArray[np.void]: ... + +# +@overload # nomask, scalar-like, shrink=True (default) +def mask_or( + m1: _NoMaskType | Literal[False], + m2: _ScalarLike_co, + copy: bool = False, + shrink: Literal[True] = True, +) -> _NoMaskType: ... +@overload # nomask, scalar-like, shrink=False (kwarg) +def mask_or( + m1: _NoMaskType | Literal[False], + m2: _ScalarLike_co, + copy: bool = False, + *, + shrink: Literal[False], +) -> _MaskArray[tuple[()]]: ... +@overload # scalar-like, nomask, shrink=True (default) +def mask_or( + m1: _ScalarLike_co, + m2: _NoMaskType | Literal[False], + copy: bool = False, + shrink: Literal[True] = True, +) -> _NoMaskType: ... +@overload # scalar-like, nomask, shrink=False (kwarg) +def mask_or( + m1: _ScalarLike_co, + m2: _NoMaskType | Literal[False], + copy: bool = False, + *, + shrink: Literal[False], +) -> _MaskArray[tuple[()]]: ... +@overload # ndarray, ndarray | nomask, shrink=True (default) +def mask_or( + m1: np.ndarray[_ShapeT, np.dtype[_ScalarT]], + m2: np.ndarray[_ShapeT, np.dtype[_ScalarT]] | _NoMaskType | Literal[False], + copy: bool = False, + shrink: Literal[True] = True, +) -> _MaskArray[_ShapeT] | _NoMaskType: ... +@overload # ndarray, ndarray | nomask, shrink=False (kwarg) +def mask_or( + m1: np.ndarray[_ShapeT, np.dtype[_ScalarT]], + m2: np.ndarray[_ShapeT, np.dtype[_ScalarT]] | _NoMaskType | Literal[False], + copy: bool = False, + *, + shrink: Literal[False], +) -> _MaskArray[_ShapeT]: ... +@overload # ndarray | nomask, ndarray, shrink=True (default) +def mask_or( + m1: np.ndarray[_ShapeT, np.dtype[_ScalarT]] | _NoMaskType | Literal[False], + m2: np.ndarray[_ShapeT, np.dtype[_ScalarT]], + copy: bool = False, + shrink: Literal[True] = True, +) -> _MaskArray[_ShapeT] | _NoMaskType: ... +@overload # ndarray | nomask, ndarray, shrink=False (kwarg) +def mask_or( + m1: np.ndarray[_ShapeT, np.dtype[_ScalarT]] | _NoMaskType | Literal[False], + m2: np.ndarray[_ShapeT, np.dtype[_ScalarT]], + copy: bool = False, + *, + shrink: Literal[False], +) -> _MaskArray[_ShapeT]: ... + +# +@overload +def flatten_mask(mask: np.ndarray[_ShapeT]) -> _MaskArray[_ShapeT]: ... +@overload +def flatten_mask(mask: ArrayLike) -> _MaskArray: ... + +# NOTE: we currently don't know the field types of `void` dtypes, so it's not possible +# to know the output dtype of the returned array. +@overload +def flatten_structured_array(a: MaskedArray[_ShapeT, np.dtype[np.void]]) -> MaskedArray[_ShapeT]: ... +@overload +def flatten_structured_array(a: np.ndarray[_ShapeT, np.dtype[np.void]]) -> np.ndarray[_ShapeT]: ... +@overload # for some reason this accepts unstructured array-likes, hence this fallback overload +def flatten_structured_array(a: ArrayLike) -> np.ndarray: ... + +# keep in sync with other the `masked_*` functions +@overload # known array with known shape and dtype +def masked_invalid(a: ndarray[_ShapeT, _DTypeT], copy: bool = True) -> MaskedArray[_ShapeT, _DTypeT]: ... +@overload # array-like of known scalar-type +def masked_invalid(a: _ArrayLike[_ScalarT], copy: bool = True) -> _MaskedArray[_ScalarT]: ... +@overload # unknown array-like +def masked_invalid(a: ArrayLike, copy: bool = True) -> _MaskedArray[Incomplete]: ... + +# keep in sync with other the `masked_*` functions +@overload # array-like of known scalar-type +def masked_where( + condition: _ArrayLikeBool_co, a: ndarray[_ShapeT, _DTypeT], copy: bool = True +) -> MaskedArray[_ShapeT, _DTypeT]: ... +@overload # array-like of known scalar-type +def masked_where(condition: _ArrayLikeBool_co, a: _ArrayLike[_ScalarT], copy: bool = True) -> _MaskedArray[_ScalarT]: ... +@overload # unknown array-like +def masked_where(condition: _ArrayLikeBool_co, a: ArrayLike, copy: bool = True) -> _MaskedArray[Incomplete]: ... + +# keep in sync with other the `masked_*` functions +@overload # known array with known shape and dtype +def masked_greater(x: ndarray[_ShapeT, _DTypeT], value: ArrayLike, copy: bool = True) -> MaskedArray[_ShapeT, _DTypeT]: ... +@overload # array-like of known scalar-type +def masked_greater(x: _ArrayLike[_ScalarT], value: ArrayLike, copy: bool = True) -> _MaskedArray[_ScalarT]: ... +@overload # unknown array-like +def masked_greater(x: ArrayLike, value: ArrayLike, copy: bool = True) -> _MaskedArray[Incomplete]: ... + +# keep in sync with other the `masked_*` functions +@overload # known array with known shape and dtype +def masked_greater_equal(x: ndarray[_ShapeT, _DTypeT], value: ArrayLike, copy: bool = True) -> MaskedArray[_ShapeT, _DTypeT]: ... +@overload # array-like of known scalar-type +def masked_greater_equal(x: _ArrayLike[_ScalarT], value: ArrayLike, copy: bool = True) -> _MaskedArray[_ScalarT]: ... +@overload # unknown array-like +def masked_greater_equal(x: ArrayLike, value: ArrayLike, copy: bool = True) -> _MaskedArray[Incomplete]: ... + +# keep in sync with other the `masked_*` functions +@overload # known array with known shape and dtype +def masked_less(x: ndarray[_ShapeT, _DTypeT], value: ArrayLike, copy: bool = True) -> MaskedArray[_ShapeT, _DTypeT]: ... +@overload # array-like of known scalar-type +def masked_less(x: _ArrayLike[_ScalarT], value: ArrayLike, copy: bool = True) -> _MaskedArray[_ScalarT]: ... +@overload # unknown array-like +def masked_less(x: ArrayLike, value: ArrayLike, copy: bool = True) -> _MaskedArray[Incomplete]: ... + +# keep in sync with other the `masked_*` functions +@overload # known array with known shape and dtype +def masked_less_equal(x: ndarray[_ShapeT, _DTypeT], value: ArrayLike, copy: bool = True) -> MaskedArray[_ShapeT, _DTypeT]: ... +@overload # array-like of known scalar-type +def masked_less_equal(x: _ArrayLike[_ScalarT], value: ArrayLike, copy: bool = True) -> _MaskedArray[_ScalarT]: ... +@overload # unknown array-like +def masked_less_equal(x: ArrayLike, value: ArrayLike, copy: bool = True) -> _MaskedArray[Incomplete]: ... + +# keep in sync with other the `masked_*` functions +@overload # known array with known shape and dtype +def masked_not_equal(x: ndarray[_ShapeT, _DTypeT], value: ArrayLike, copy: bool = True) -> MaskedArray[_ShapeT, _DTypeT]: ... +@overload # array-like of known scalar-type +def masked_not_equal(x: _ArrayLike[_ScalarT], value: ArrayLike, copy: bool = True) -> _MaskedArray[_ScalarT]: ... +@overload # unknown array-like +def masked_not_equal(x: ArrayLike, value: ArrayLike, copy: bool = True) -> _MaskedArray[Incomplete]: ... + +# keep in sync with other the `masked_*` functions +@overload # known array with known shape and dtype +def masked_equal(x: ndarray[_ShapeT, _DTypeT], value: ArrayLike, copy: bool = True) -> MaskedArray[_ShapeT, _DTypeT]: ... +@overload # array-like of known scalar-type +def masked_equal(x: _ArrayLike[_ScalarT], value: ArrayLike, copy: bool = True) -> _MaskedArray[_ScalarT]: ... +@overload # unknown array-like +def masked_equal(x: ArrayLike, value: ArrayLike, copy: bool = True) -> _MaskedArray[Incomplete]: ... + +# keep in sync with other the `masked_*` functions +@overload # known array with known shape and dtype +def masked_inside(x: ndarray[_ShapeT, _DTypeT], v1: ArrayLike, v2: ArrayLike, copy: bool = True) -> MaskedArray[_ShapeT, _DTypeT]: ... +@overload # array-like of known scalar-type +def masked_inside(x: _ArrayLike[_ScalarT], v1: ArrayLike, v2: ArrayLike, copy: bool = True) -> _MaskedArray[_ScalarT]: ... +@overload # unknown array-like +def masked_inside(x: ArrayLike, v1: ArrayLike, v2: ArrayLike, copy: bool = True) -> _MaskedArray[Incomplete]: ... + +# keep in sync with other the `masked_*` functions +@overload # known array with known shape and dtype +def masked_outside(x: ndarray[_ShapeT, _DTypeT], v1: ArrayLike, v2: ArrayLike, copy: bool = True) -> MaskedArray[_ShapeT, _DTypeT]: ... +@overload # array-like of known scalar-type +def masked_outside(x: _ArrayLike[_ScalarT], v1: ArrayLike, v2: ArrayLike, copy: bool = True) -> _MaskedArray[_ScalarT]: ... +@overload # unknown array-like +def masked_outside(x: ArrayLike, v1: ArrayLike, v2: ArrayLike, copy: bool = True) -> _MaskedArray[Incomplete]: ... + +# only intended for object arrays, so we assume that's how it's always used in practice +@overload +def masked_object( + x: np.ndarray[_ShapeT, np.dtype[np.object_]], + value: object, + copy: bool = True, + shrink: bool = True, +) -> MaskedArray[_ShapeT, np.dtype[np.object_]]: ... +@overload +def masked_object( + x: _ArrayLikeObject_co, + value: object, + copy: bool = True, + shrink: bool = True, +) -> _MaskedArray[np.object_]: ... + +# keep roughly in sync with `filled` +@overload +def masked_values( + x: np.ndarray[_ShapeT, _DTypeT], + value: _ScalarLike_co, + rtol: float = 1e-5, + atol: float = 1e-8, + copy: bool = True, + shrink: bool = True +) -> MaskedArray[_ShapeT, _DTypeT]: ... +@overload +def masked_values( + x: _ArrayLike[_ScalarT], + value: _ScalarLike_co, + rtol: float = 1e-5, + atol: float = 1e-8, + copy: bool = True, + shrink: bool = True +) -> _MaskedArray[_ScalarT]: ... +@overload +def masked_values( + x: ArrayLike, + value: _ScalarLike_co, + rtol: float = 1e-5, + atol: float = 1e-8, + copy: bool = True, + shrink: bool = True +) -> _MaskedArray[Incomplete]: ... + +# TODO: Support non-boolean mask dtypes, such as `np.void`. This will require adding an +# additional generic type parameter to (at least) `MaskedArray` and `MaskedIterator` to +# hold the dtype of the mask. + +class MaskedIterator(Generic[_ShapeT_co, _DTypeT_co]): + ma: MaskedArray[_ShapeT_co, _DTypeT_co] # readonly + dataiter: np.flatiter[ndarray[_ShapeT_co, _DTypeT_co]] # readonly + maskiter: Final[np.flatiter[NDArray[np.bool]]] + + def __init__(self, ma: MaskedArray[_ShapeT_co, _DTypeT_co]) -> None: ... + def __iter__(self) -> Self: ... + + # Similar to `MaskedArray.__getitem__` but without the `void` case. + @overload + def __getitem__(self, indx: _ArrayInt_co | tuple[_ArrayInt_co, ...], /) -> MaskedArray[_AnyShape, _DTypeT_co]: ... + @overload + def __getitem__(self, indx: SupportsIndex | tuple[SupportsIndex, ...], /) -> Incomplete: ... + @overload + def __getitem__(self, indx: _ToIndices, /) -> MaskedArray[_AnyShape, _DTypeT_co]: ... + + # Similar to `ndarray.__setitem__` but without the `void` case. + @overload # flexible | object_ | bool + def __setitem__( + self: MaskedIterator[Any, dtype[flexible | object_ | np.bool] | dtypes.StringDType], + index: _ToIndices, + value: object, + /, + ) -> None: ... + @overload # integer + def __setitem__( + self: MaskedIterator[Any, dtype[integer]], + index: _ToIndices, + value: _ConvertibleToInt | _NestedSequence[_ConvertibleToInt] | _ArrayLikeInt_co, + /, + ) -> None: ... + @overload # floating + def __setitem__( + self: MaskedIterator[Any, dtype[floating]], + index: _ToIndices, + value: _ConvertibleToFloat | _NestedSequence[_ConvertibleToFloat | None] | _ArrayLikeFloat_co | None, + /, + ) -> None: ... + @overload # complexfloating + def __setitem__( + self: MaskedIterator[Any, dtype[complexfloating]], + index: _ToIndices, + value: _ConvertibleToComplex | _NestedSequence[_ConvertibleToComplex | None] | _ArrayLikeNumber_co | None, + /, + ) -> None: ... + @overload # timedelta64 + def __setitem__( + self: MaskedIterator[Any, dtype[timedelta64]], + index: _ToIndices, + value: _ConvertibleToTD64 | _NestedSequence[_ConvertibleToTD64], + /, + ) -> None: ... + @overload # datetime64 + def __setitem__( + self: MaskedIterator[Any, dtype[datetime64]], + index: _ToIndices, + value: _ConvertibleToDT64 | _NestedSequence[_ConvertibleToDT64], + /, + ) -> None: ... + @overload # catch-all + def __setitem__(self, index: _ToIndices, value: ArrayLike, /) -> None: ... + + # TODO: Returns `mvoid[(), _DTypeT_co]` for masks with `np.void` dtype. + def __next__(self: MaskedIterator[Any, np.dtype[_ScalarT]]) -> _ScalarT: ... + +class MaskedArray(ndarray[_ShapeT_co, _DTypeT_co]): + __array_priority__: Final[Literal[15]] = 15 + + @overload + def __new__( + cls, + data: _ArrayLike[_ScalarT], + mask: _ArrayLikeBool_co = nomask, + dtype: None = None, + copy: bool = False, + subok: bool = True, + ndmin: int = 0, + fill_value: _ScalarLike_co | None = None, + keep_mask: bool = True, + hard_mask: bool | None = None, + shrink: bool = True, + order: _OrderKACF | None = None, + ) -> _MaskedArray[_ScalarT]: ... + @overload + def __new__( + cls, + data: object, + mask: _ArrayLikeBool_co, + dtype: _DTypeLike[_ScalarT], + copy: bool = False, + subok: bool = True, + ndmin: int = 0, + fill_value: _ScalarLike_co | None = None, + keep_mask: bool = True, + hard_mask: bool | None = None, + shrink: bool = True, + order: _OrderKACF | None = None, + ) -> _MaskedArray[_ScalarT]: ... + @overload + def __new__( + cls, + data: object, + mask: _ArrayLikeBool_co = nomask, + *, + dtype: _DTypeLike[_ScalarT], + copy: bool = False, + subok: bool = True, + ndmin: int = 0, + fill_value: _ScalarLike_co | None = None, + keep_mask: bool = True, + hard_mask: bool | None = None, + shrink: bool = True, + order: _OrderKACF | None = None, + ) -> _MaskedArray[_ScalarT]: ... + @overload + def __new__( + cls, + data: object = None, + mask: _ArrayLikeBool_co = nomask, + dtype: DTypeLike | None = None, + copy: bool = False, + subok: bool = True, + ndmin: int = 0, + fill_value: _ScalarLike_co | None = None, + keep_mask: bool = True, + hard_mask: bool | None = None, + shrink: bool = True, + order: _OrderKACF | None = None, + ) -> _MaskedArray[Any]: ... + + def __array_wrap__( + self, + obj: ndarray[_ShapeT, _DTypeT], + context: tuple[ufunc, tuple[Any, ...], int] | None = None, + return_scalar: bool = False, + ) -> MaskedArray[_ShapeT, _DTypeT]: ... + + @overload # type: ignore[override] # () + def view(self, /, dtype: None = None, type: None = None, fill_value: _ScalarLike_co | None = None) -> Self: ... + @overload # (dtype: DTypeT) + def view( + self, + /, + dtype: _DTypeT | _HasDType[_DTypeT], + type: None = None, + fill_value: _ScalarLike_co | None = None + ) -> MaskedArray[_ShapeT_co, _DTypeT]: ... + @overload # (dtype: dtype[ScalarT]) + def view( + self, + /, + dtype: _DTypeLike[_ScalarT], + type: None = None, + fill_value: _ScalarLike_co | None = None + ) -> MaskedArray[_ShapeT_co, dtype[_ScalarT]]: ... + @overload # ([dtype: _, ]*, type: ArrayT) + def view( + self, + /, + dtype: DTypeLike | None = None, + *, + type: type[_ArrayT], + fill_value: _ScalarLike_co | None = None + ) -> _ArrayT: ... + @overload # (dtype: _, type: ArrayT) + def view(self, /, dtype: DTypeLike | None, type: type[_ArrayT], fill_value: _ScalarLike_co | None = None) -> _ArrayT: ... + @overload # (dtype: ArrayT, /) + def view(self, /, dtype: type[_ArrayT], type: None = None, fill_value: _ScalarLike_co | None = None) -> _ArrayT: ... + @overload # (dtype: ?) + def view( + self, + /, + # `_VoidDTypeLike | str | None` is like `DTypeLike` but without `_DTypeLike[Any]` to avoid + # overlaps with previous overloads. + dtype: _VoidDTypeLike | str | None, + type: None = None, + fill_value: _ScalarLike_co | None = None + ) -> MaskedArray[_ShapeT_co, dtype]: ... + + # Keep in sync with `ndarray.__getitem__` + @overload + def __getitem__(self, key: _ArrayInt_co | tuple[_ArrayInt_co, ...], /) -> MaskedArray[_AnyShape, _DTypeT_co]: ... + @overload + def __getitem__(self, key: SupportsIndex | tuple[SupportsIndex, ...], /) -> Any: ... + @overload + def __getitem__(self, key: _ToIndices, /) -> MaskedArray[_AnyShape, _DTypeT_co]: ... + @overload + def __getitem__(self: _MaskedArray[void], indx: str, /) -> MaskedArray[_ShapeT_co, dtype]: ... + @overload + def __getitem__(self: _MaskedArray[void], indx: list[str], /) -> MaskedArray[_ShapeT_co, dtype[void]]: ... + + @property + def shape(self) -> _ShapeT_co: ... + @shape.setter # type: ignore[override] + def shape(self: MaskedArray[_ShapeT, Any], shape: _ShapeT, /) -> None: ... + + def __setmask__(self, mask: _ArrayLikeBool_co, copy: bool = False) -> None: ... + @property + def mask(self) -> np.ndarray[_ShapeT_co, dtype[MaskType]] | MaskType: ... + @mask.setter + def mask(self, value: _ArrayLikeBool_co, /) -> None: ... + @property + def recordmask(self) -> np.ndarray[_ShapeT_co, dtype[MaskType]] | MaskType: ... + @recordmask.setter + def recordmask(self, mask: Never, /) -> NoReturn: ... + def harden_mask(self) -> Self: ... + def soften_mask(self) -> Self: ... + @property + def hardmask(self) -> bool: ... + def unshare_mask(self) -> Self: ... + @property + def sharedmask(self) -> bool: ... + def shrink_mask(self) -> Self: ... + + @property + def baseclass(self) -> type[ndarray]: ... + + @property + def _data(self) -> ndarray[_ShapeT_co, _DTypeT_co]: ... + @property + def data(self) -> ndarray[_ShapeT_co, _DTypeT_co]: ... # type: ignore[override] + + @property # type: ignore[override] + def flat(self) -> MaskedIterator[_ShapeT_co, _DTypeT_co]: ... + @flat.setter + def flat(self, value: ArrayLike, /) -> None: ... + + @property + def fill_value(self: _MaskedArray[_ScalarT]) -> _ScalarT: ... + @fill_value.setter + def fill_value(self, value: _ScalarLike_co | None = None, /) -> None: ... + + def get_fill_value(self: _MaskedArray[_ScalarT]) -> _ScalarT: ... + def set_fill_value(self, /, value: _ScalarLike_co | None = None) -> None: ... + + def filled(self, /, fill_value: _ScalarLike_co | None = None) -> ndarray[_ShapeT_co, _DTypeT_co]: ... + def compressed(self) -> ndarray[tuple[int], _DTypeT_co]: ... + + # keep roughly in sync with `ma.core.compress`, but swap the first two arguments + @overload # type: ignore[override] + def compress( + self, + condition: _ArrayLikeBool_co, + axis: _ShapeLike | None, + out: _ArrayT + ) -> _ArrayT: ... + @overload + def compress( + self, + condition: _ArrayLikeBool_co, + axis: _ShapeLike | None = None, + *, + out: _ArrayT + ) -> _ArrayT: ... + @overload + def compress( + self, + condition: _ArrayLikeBool_co, + axis: None = None, + out: None = None + ) -> MaskedArray[tuple[int], _DTypeT_co]: ... + @overload + def compress( + self, + condition: _ArrayLikeBool_co, + axis: _ShapeLike | None = None, + out: None = None + ) -> MaskedArray[_AnyShape, _DTypeT_co]: ... + + # TODO: How to deal with the non-commutative nature of `==` and `!=`? + # xref numpy/numpy#17368 + def __eq__(self, other: Incomplete, /) -> Incomplete: ... + def __ne__(self, other: Incomplete, /) -> Incomplete: ... + + def __ge__(self, other: ArrayLike, /) -> _MaskedArray[bool_]: ... # type: ignore[override] + def __gt__(self, other: ArrayLike, /) -> _MaskedArray[bool_]: ... # type: ignore[override] + def __le__(self, other: ArrayLike, /) -> _MaskedArray[bool_]: ... # type: ignore[override] + def __lt__(self, other: ArrayLike, /) -> _MaskedArray[bool_]: ... # type: ignore[override] + + # Keep in sync with `ndarray.__add__` + @overload # type: ignore[override] + def __add__(self: _MaskedArray[_NumberT], other: int | np.bool, /) -> MaskedArray[_ShapeT_co, dtype[_NumberT]]: ... + @overload + def __add__(self: _MaskedArray[_NumberT], other: _ArrayLikeBool_co, /) -> _MaskedArray[_NumberT]: ... # type: ignore[overload-overlap] + @overload + def __add__(self: _MaskedArray[np.bool], other: _ArrayLikeBool_co, /) -> _MaskedArray[np.bool]: ... # type: ignore[overload-overlap] + @overload + def __add__(self: _MaskedArray[np.bool], other: _ArrayLike[_NumberT], /) -> _MaskedArray[_NumberT]: ... # type: ignore[overload-overlap] + @overload + def __add__(self: _MaskedArray[float64], other: _ArrayLikeFloat64_co, /) -> _MaskedArray[float64]: ... + @overload + def __add__(self: _MaskedArrayFloat64_co, other: _ArrayLike[floating[_64Bit]], /) -> _MaskedArray[float64]: ... + @overload + def __add__(self: _MaskedArray[complex128], other: _ArrayLikeComplex128_co, /) -> _MaskedArray[complex128]: ... + @overload + def __add__(self: _MaskedArrayComplex128_co, other: _ArrayLike[complexfloating[_64Bit]], /) -> _MaskedArray[complex128]: ... + @overload + def __add__(self: _MaskedArrayUInt_co, other: _ArrayLikeUInt_co, /) -> _MaskedArray[unsignedinteger]: ... # type: ignore[overload-overlap] + @overload + def __add__(self: _MaskedArrayInt_co, other: _ArrayLikeInt_co, /) -> _MaskedArray[signedinteger]: ... # type: ignore[overload-overlap] + @overload + def __add__(self: _MaskedArrayFloat_co, other: _ArrayLikeFloat_co, /) -> _MaskedArray[floating]: ... # type: ignore[overload-overlap] + @overload + def __add__(self: _MaskedArrayComplex_co, other: _ArrayLikeComplex_co, /) -> _MaskedArray[complexfloating]: ... # type: ignore[overload-overlap] + @overload + def __add__(self: _MaskedArray[number], other: _ArrayLikeNumber_co, /) -> _MaskedArray[number]: ... # type: ignore[overload-overlap] + @overload + def __add__(self: _MaskedArrayTD64_co, other: _ArrayLikeTD64_co, /) -> _MaskedArray[timedelta64]: ... + @overload + def __add__(self: _MaskedArrayTD64_co, other: _ArrayLikeDT64_co, /) -> _MaskedArray[datetime64]: ... + @overload + def __add__(self: _MaskedArray[datetime64], other: _ArrayLikeTD64_co, /) -> _MaskedArray[datetime64]: ... + @overload + def __add__(self: _MaskedArray[bytes_], other: _ArrayLikeBytes_co, /) -> _MaskedArray[bytes_]: ... + @overload + def __add__(self: _MaskedArray[str_], other: _ArrayLikeStr_co, /) -> _MaskedArray[str_]: ... + @overload + def __add__( + self: MaskedArray[Any, dtypes.StringDType], + other: _ArrayLikeStr_co | _ArrayLikeString_co, + /, + ) -> MaskedArray[_AnyShape, dtypes.StringDType]: ... + @overload + def __add__(self: _MaskedArray[object_], other: Any, /) -> Any: ... + @overload + def __add__(self: _MaskedArray[Any], other: _ArrayLikeObject_co, /) -> Any: ... + + # Keep in sync with `ndarray.__radd__` + @overload # type: ignore[override] # signature equivalent to __add__ + def __radd__(self: _MaskedArray[_NumberT], other: int | np.bool, /) -> MaskedArray[_ShapeT_co, dtype[_NumberT]]: ... + @overload + def __radd__(self: _MaskedArray[_NumberT], other: _ArrayLikeBool_co, /) -> _MaskedArray[_NumberT]: ... # type: ignore[overload-overlap] + @overload + def __radd__(self: _MaskedArray[np.bool], other: _ArrayLikeBool_co, /) -> _MaskedArray[np.bool]: ... # type: ignore[overload-overlap] + @overload + def __radd__(self: _MaskedArray[np.bool], other: _ArrayLike[_NumberT], /) -> _MaskedArray[_NumberT]: ... # type: ignore[overload-overlap] + @overload + def __radd__(self: _MaskedArray[float64], other: _ArrayLikeFloat64_co, /) -> _MaskedArray[float64]: ... + @overload + def __radd__(self: _MaskedArrayFloat64_co, other: _ArrayLike[floating[_64Bit]], /) -> _MaskedArray[float64]: ... + @overload + def __radd__(self: _MaskedArray[complex128], other: _ArrayLikeComplex128_co, /) -> _MaskedArray[complex128]: ... + @overload + def __radd__(self: _MaskedArrayComplex128_co, other: _ArrayLike[complexfloating[_64Bit]], /) -> _MaskedArray[complex128]: ... + @overload + def __radd__(self: _MaskedArrayUInt_co, other: _ArrayLikeUInt_co, /) -> _MaskedArray[unsignedinteger]: ... # type: ignore[overload-overlap] + @overload + def __radd__(self: _MaskedArrayInt_co, other: _ArrayLikeInt_co, /) -> _MaskedArray[signedinteger]: ... # type: ignore[overload-overlap] + @overload + def __radd__(self: _MaskedArrayFloat_co, other: _ArrayLikeFloat_co, /) -> _MaskedArray[floating]: ... # type: ignore[overload-overlap] + @overload + def __radd__(self: _MaskedArrayComplex_co, other: _ArrayLikeComplex_co, /) -> _MaskedArray[complexfloating]: ... # type: ignore[overload-overlap] + @overload + def __radd__(self: _MaskedArray[number], other: _ArrayLikeNumber_co, /) -> _MaskedArray[number]: ... # type: ignore[overload-overlap] + @overload + def __radd__(self: _MaskedArrayTD64_co, other: _ArrayLikeTD64_co, /) -> _MaskedArray[timedelta64]: ... + @overload + def __radd__(self: _MaskedArrayTD64_co, other: _ArrayLikeDT64_co, /) -> _MaskedArray[datetime64]: ... + @overload + def __radd__(self: _MaskedArray[datetime64], other: _ArrayLikeTD64_co, /) -> _MaskedArray[datetime64]: ... + @overload + def __radd__(self: _MaskedArray[bytes_], other: _ArrayLikeBytes_co, /) -> _MaskedArray[bytes_]: ... + @overload + def __radd__(self: _MaskedArray[str_], other: _ArrayLikeStr_co, /) -> _MaskedArray[str_]: ... + @overload + def __radd__( + self: MaskedArray[Any, dtypes.StringDType], + other: _ArrayLikeStr_co | _ArrayLikeString_co, + /, + ) -> MaskedArray[_AnyShape, dtypes.StringDType]: ... + @overload + def __radd__(self: _MaskedArray[object_], other: Any, /) -> Any: ... + @overload + def __radd__(self: _MaskedArray[Any], other: _ArrayLikeObject_co, /) -> Any: ... + + # Keep in sync with `ndarray.__sub__` + @overload # type: ignore[override] + def __sub__(self: _MaskedArray[_NumberT], other: int | np.bool, /) -> MaskedArray[_ShapeT_co, dtype[_NumberT]]: ... + @overload + def __sub__(self: _MaskedArray[_NumberT], other: _ArrayLikeBool_co, /) -> _MaskedArray[_NumberT]: ... # type: ignore[overload-overlap] + @overload + def __sub__(self: _MaskedArray[np.bool], other: _ArrayLikeBool_co, /) -> NoReturn: ... + @overload + def __sub__(self: _MaskedArray[np.bool], other: _ArrayLike[_NumberT], /) -> _MaskedArray[_NumberT]: ... # type: ignore[overload-overlap] + @overload + def __sub__(self: _MaskedArray[float64], other: _ArrayLikeFloat64_co, /) -> _MaskedArray[float64]: ... + @overload + def __sub__(self: _MaskedArrayFloat64_co, other: _ArrayLike[floating[_64Bit]], /) -> _MaskedArray[float64]: ... + @overload + def __sub__(self: _MaskedArray[complex128], other: _ArrayLikeComplex128_co, /) -> _MaskedArray[complex128]: ... + @overload + def __sub__(self: _MaskedArrayComplex128_co, other: _ArrayLike[complexfloating[_64Bit]], /) -> _MaskedArray[complex128]: ... + @overload + def __sub__(self: _MaskedArrayUInt_co, other: _ArrayLikeUInt_co, /) -> _MaskedArray[unsignedinteger]: ... # type: ignore[overload-overlap] + @overload + def __sub__(self: _MaskedArrayInt_co, other: _ArrayLikeInt_co, /) -> _MaskedArray[signedinteger]: ... # type: ignore[overload-overlap] + @overload + def __sub__(self: _MaskedArrayFloat_co, other: _ArrayLikeFloat_co, /) -> _MaskedArray[floating]: ... # type: ignore[overload-overlap] + @overload + def __sub__(self: _MaskedArrayComplex_co, other: _ArrayLikeComplex_co, /) -> _MaskedArray[complexfloating]: ... # type: ignore[overload-overlap] + @overload + def __sub__(self: _MaskedArray[number], other: _ArrayLikeNumber_co, /) -> _MaskedArray[number]: ... # type: ignore[overload-overlap] + @overload + def __sub__(self: _MaskedArrayTD64_co, other: _ArrayLikeTD64_co, /) -> _MaskedArray[timedelta64]: ... + @overload + def __sub__(self: _MaskedArray[datetime64], other: _ArrayLikeTD64_co, /) -> _MaskedArray[datetime64]: ... + @overload + def __sub__(self: _MaskedArray[datetime64], other: _ArrayLikeDT64_co, /) -> _MaskedArray[timedelta64]: ... + @overload + def __sub__(self: _MaskedArray[object_], other: Any, /) -> Any: ... + @overload + def __sub__(self: _MaskedArray[Any], other: _ArrayLikeObject_co, /) -> Any: ... + + # Keep in sync with `ndarray.__rsub__` + @overload # type: ignore[override] + def __rsub__(self: _MaskedArray[_NumberT], other: int | np.bool, /) -> MaskedArray[_ShapeT_co, dtype[_NumberT]]: ... + @overload + def __rsub__(self: _MaskedArray[_NumberT], other: _ArrayLikeBool_co, /) -> _MaskedArray[_NumberT]: ... # type: ignore[overload-overlap] + @overload + def __rsub__(self: _MaskedArray[np.bool], other: _ArrayLikeBool_co, /) -> NoReturn: ... + @overload + def __rsub__(self: _MaskedArray[np.bool], other: _ArrayLike[_NumberT], /) -> _MaskedArray[_NumberT]: ... # type: ignore[overload-overlap] + @overload + def __rsub__(self: _MaskedArray[float64], other: _ArrayLikeFloat64_co, /) -> _MaskedArray[float64]: ... + @overload + def __rsub__(self: _MaskedArrayFloat64_co, other: _ArrayLike[floating[_64Bit]], /) -> _MaskedArray[float64]: ... + @overload + def __rsub__(self: _MaskedArray[complex128], other: _ArrayLikeComplex128_co, /) -> _MaskedArray[complex128]: ... + @overload + def __rsub__(self: _MaskedArrayComplex128_co, other: _ArrayLike[complexfloating[_64Bit]], /) -> _MaskedArray[complex128]: ... + @overload + def __rsub__(self: _MaskedArrayUInt_co, other: _ArrayLikeUInt_co, /) -> _MaskedArray[unsignedinteger]: ... # type: ignore[overload-overlap] + @overload + def __rsub__(self: _MaskedArrayInt_co, other: _ArrayLikeInt_co, /) -> _MaskedArray[signedinteger]: ... # type: ignore[overload-overlap] + @overload + def __rsub__(self: _MaskedArrayFloat_co, other: _ArrayLikeFloat_co, /) -> _MaskedArray[floating]: ... # type: ignore[overload-overlap] + @overload + def __rsub__(self: _MaskedArrayComplex_co, other: _ArrayLikeComplex_co, /) -> _MaskedArray[complexfloating]: ... # type: ignore[overload-overlap] + @overload + def __rsub__(self: _MaskedArray[number], other: _ArrayLikeNumber_co, /) -> _MaskedArray[number]: ... # type: ignore[overload-overlap] + @overload + def __rsub__(self: _MaskedArrayTD64_co, other: _ArrayLikeTD64_co, /) -> _MaskedArray[timedelta64]: ... + @overload + def __rsub__(self: _MaskedArrayTD64_co, other: _ArrayLikeDT64_co, /) -> _MaskedArray[datetime64]: ... + @overload + def __rsub__(self: _MaskedArray[datetime64], other: _ArrayLikeDT64_co, /) -> _MaskedArray[timedelta64]: ... + @overload + def __rsub__(self: _MaskedArray[object_], other: Any, /) -> Any: ... + @overload + def __rsub__(self: _MaskedArray[Any], other: _ArrayLikeObject_co, /) -> Any: ... + + # Keep in sync with `ndarray.__mul__` + @overload # type: ignore[override] + def __mul__(self: _MaskedArray[_NumberT], other: int | np.bool, /) -> MaskedArray[_ShapeT_co, dtype[_NumberT]]: ... + @overload + def __mul__(self: _MaskedArray[_NumberT], other: _ArrayLikeBool_co, /) -> _MaskedArray[_NumberT]: ... # type: ignore[overload-overlap] + @overload + def __mul__(self: _MaskedArray[np.bool], other: _ArrayLikeBool_co, /) -> _MaskedArray[np.bool]: ... # type: ignore[overload-overlap] + @overload + def __mul__(self: _MaskedArray[np.bool], other: _ArrayLike[_NumberT], /) -> _MaskedArray[_NumberT]: ... # type: ignore[overload-overlap] + @overload + def __mul__(self: _MaskedArray[float64], other: _ArrayLikeFloat64_co, /) -> _MaskedArray[float64]: ... + @overload + def __mul__(self: _MaskedArrayFloat64_co, other: _ArrayLike[floating[_64Bit]], /) -> _MaskedArray[float64]: ... + @overload + def __mul__(self: _MaskedArray[complex128], other: _ArrayLikeComplex128_co, /) -> _MaskedArray[complex128]: ... + @overload + def __mul__(self: _MaskedArrayComplex128_co, other: _ArrayLike[complexfloating[_64Bit]], /) -> _MaskedArray[complex128]: ... + @overload + def __mul__(self: _MaskedArrayUInt_co, other: _ArrayLikeUInt_co, /) -> _MaskedArray[unsignedinteger]: ... # type: ignore[overload-overlap] + @overload + def __mul__(self: _MaskedArrayInt_co, other: _ArrayLikeInt_co, /) -> _MaskedArray[signedinteger]: ... # type: ignore[overload-overlap] + @overload + def __mul__(self: _MaskedArrayFloat_co, other: _ArrayLikeFloat_co, /) -> _MaskedArray[floating]: ... # type: ignore[overload-overlap] + @overload + def __mul__(self: _MaskedArrayComplex_co, other: _ArrayLikeComplex_co, /) -> _MaskedArray[complexfloating]: ... # type: ignore[overload-overlap] + @overload + def __mul__(self: _MaskedArray[number], other: _ArrayLikeNumber_co, /) -> _MaskedArray[number]: ... + @overload + def __mul__(self: _MaskedArray[timedelta64], other: _ArrayLikeFloat_co, /) -> _MaskedArray[timedelta64]: ... + @overload + def __mul__(self: _MaskedArrayFloat_co, other: _ArrayLike[timedelta64], /) -> _MaskedArray[timedelta64]: ... + @overload + def __mul__( + self: MaskedArray[Any, dtype[character] | dtypes.StringDType], + other: _ArrayLikeInt, + /, + ) -> MaskedArray[tuple[Any, ...], _DTypeT_co]: ... + @overload + def __mul__(self: _MaskedArray[object_], other: Any, /) -> Any: ... + @overload + def __mul__(self: _MaskedArray[Any], other: _ArrayLikeObject_co, /) -> Any: ... + + # Keep in sync with `ndarray.__rmul__` + @overload # type: ignore[override] # signature equivalent to __mul__ + def __rmul__(self: _MaskedArray[_NumberT], other: int | np.bool, /) -> MaskedArray[_ShapeT_co, dtype[_NumberT]]: ... + @overload + def __rmul__(self: _MaskedArray[_NumberT], other: _ArrayLikeBool_co, /) -> _MaskedArray[_NumberT]: ... # type: ignore[overload-overlap] + @overload + def __rmul__(self: _MaskedArray[np.bool], other: _ArrayLikeBool_co, /) -> _MaskedArray[np.bool]: ... # type: ignore[overload-overlap] + @overload + def __rmul__(self: _MaskedArray[np.bool], other: _ArrayLike[_NumberT], /) -> _MaskedArray[_NumberT]: ... # type: ignore[overload-overlap] + @overload + def __rmul__(self: _MaskedArray[float64], other: _ArrayLikeFloat64_co, /) -> _MaskedArray[float64]: ... + @overload + def __rmul__(self: _MaskedArrayFloat64_co, other: _ArrayLike[floating[_64Bit]], /) -> _MaskedArray[float64]: ... + @overload + def __rmul__(self: _MaskedArray[complex128], other: _ArrayLikeComplex128_co, /) -> _MaskedArray[complex128]: ... + @overload + def __rmul__(self: _MaskedArrayComplex128_co, other: _ArrayLike[complexfloating[_64Bit]], /) -> _MaskedArray[complex128]: ... + @overload + def __rmul__(self: _MaskedArrayUInt_co, other: _ArrayLikeUInt_co, /) -> _MaskedArray[unsignedinteger]: ... # type: ignore[overload-overlap] + @overload + def __rmul__(self: _MaskedArrayInt_co, other: _ArrayLikeInt_co, /) -> _MaskedArray[signedinteger]: ... # type: ignore[overload-overlap] + @overload + def __rmul__(self: _MaskedArrayFloat_co, other: _ArrayLikeFloat_co, /) -> _MaskedArray[floating]: ... # type: ignore[overload-overlap] + @overload + def __rmul__(self: _MaskedArrayComplex_co, other: _ArrayLikeComplex_co, /) -> _MaskedArray[complexfloating]: ... # type: ignore[overload-overlap] + @overload + def __rmul__(self: _MaskedArray[number], other: _ArrayLikeNumber_co, /) -> _MaskedArray[number]: ... + @overload + def __rmul__(self: _MaskedArray[timedelta64], other: _ArrayLikeFloat_co, /) -> _MaskedArray[timedelta64]: ... + @overload + def __rmul__(self: _MaskedArrayFloat_co, other: _ArrayLike[timedelta64], /) -> _MaskedArray[timedelta64]: ... + @overload + def __rmul__( + self: MaskedArray[Any, dtype[character] | dtypes.StringDType], + other: _ArrayLikeInt, + /, + ) -> MaskedArray[tuple[Any, ...], _DTypeT_co]: ... + @overload + def __rmul__(self: _MaskedArray[object_], other: Any, /) -> Any: ... + @overload + def __rmul__(self: _MaskedArray[Any], other: _ArrayLikeObject_co, /) -> Any: ... + + # Keep in sync with `ndarray.__truediv__` + @overload # type: ignore[override] + def __truediv__(self: _MaskedArrayInt_co | _MaskedArray[float64], other: _ArrayLikeFloat64_co, /) -> _MaskedArray[float64]: ... + @overload + def __truediv__(self: _MaskedArrayFloat64_co, other: _ArrayLikeInt_co | _ArrayLike[floating[_64Bit]], /) -> _MaskedArray[float64]: ... + @overload + def __truediv__(self: _MaskedArray[complex128], other: _ArrayLikeComplex128_co, /) -> _MaskedArray[complex128]: ... + @overload + def __truediv__(self: _MaskedArrayComplex128_co, other: _ArrayLike[complexfloating[_64Bit]], /) -> _MaskedArray[complex128]: ... + @overload + def __truediv__(self: _MaskedArray[floating], other: _ArrayLikeFloat_co, /) -> _MaskedArray[floating]: ... + @overload + def __truediv__(self: _MaskedArrayFloat_co, other: _ArrayLike[floating], /) -> _MaskedArray[floating]: ... + @overload + def __truediv__(self: _MaskedArray[complexfloating], other: _ArrayLikeNumber_co, /) -> _MaskedArray[complexfloating]: ... + @overload + def __truediv__(self: _MaskedArrayNumber_co, other: _ArrayLike[complexfloating], /) -> _MaskedArray[complexfloating]: ... + @overload + def __truediv__(self: _MaskedArray[inexact], other: _ArrayLikeNumber_co, /) -> _MaskedArray[inexact]: ... + @overload + def __truediv__(self: _MaskedArray[number], other: _ArrayLikeNumber_co, /) -> _MaskedArray[number]: ... + @overload + def __truediv__(self: _MaskedArray[timedelta64], other: _ArrayLike[timedelta64], /) -> _MaskedArray[float64]: ... + @overload + def __truediv__(self: _MaskedArray[timedelta64], other: _ArrayLikeBool_co, /) -> NoReturn: ... + @overload + def __truediv__(self: _MaskedArray[timedelta64], other: _ArrayLikeFloat_co, /) -> _MaskedArray[timedelta64]: ... + @overload + def __truediv__(self: _MaskedArray[object_], other: Any, /) -> Any: ... + @overload + def __truediv__(self: _MaskedArray[Any], other: _ArrayLikeObject_co, /) -> Any: ... + + # Keep in sync with `ndarray.__rtruediv__` + @overload # type: ignore[override] + def __rtruediv__(self: _MaskedArrayInt_co | _MaskedArray[float64], other: _ArrayLikeFloat64_co, /) -> _MaskedArray[float64]: ... + @overload + def __rtruediv__(self: _MaskedArrayFloat64_co, other: _ArrayLikeInt_co | _ArrayLike[floating[_64Bit]], /) -> _MaskedArray[float64]: ... + @overload + def __rtruediv__(self: _MaskedArray[complex128], other: _ArrayLikeComplex128_co, /) -> _MaskedArray[complex128]: ... + @overload + def __rtruediv__(self: _MaskedArrayComplex128_co, other: _ArrayLike[complexfloating[_64Bit]], /) -> _MaskedArray[complex128]: ... + @overload + def __rtruediv__(self: _MaskedArray[floating], other: _ArrayLikeFloat_co, /) -> _MaskedArray[floating]: ... + @overload + def __rtruediv__(self: _MaskedArrayFloat_co, other: _ArrayLike[floating], /) -> _MaskedArray[floating]: ... + @overload + def __rtruediv__(self: _MaskedArray[complexfloating], other: _ArrayLikeNumber_co, /) -> _MaskedArray[complexfloating]: ... + @overload + def __rtruediv__(self: _MaskedArrayNumber_co, other: _ArrayLike[complexfloating], /) -> _MaskedArray[complexfloating]: ... + @overload + def __rtruediv__(self: _MaskedArray[inexact], other: _ArrayLikeNumber_co, /) -> _MaskedArray[inexact]: ... + @overload + def __rtruediv__(self: _MaskedArray[number], other: _ArrayLikeNumber_co, /) -> _MaskedArray[number]: ... + @overload + def __rtruediv__(self: _MaskedArray[timedelta64], other: _ArrayLike[timedelta64], /) -> _MaskedArray[float64]: ... + @overload + def __rtruediv__(self: _MaskedArray[integer | floating], other: _ArrayLike[timedelta64], /) -> _MaskedArray[timedelta64]: ... + @overload + def __rtruediv__(self: _MaskedArray[object_], other: Any, /) -> Any: ... + @overload + def __rtruediv__(self: _MaskedArray[Any], other: _ArrayLikeObject_co, /) -> Any: ... + + # Keep in sync with `ndarray.__floordiv__` + @overload # type: ignore[override] + def __floordiv__(self: _MaskedArray[_RealNumberT], other: int | np.bool, /) -> MaskedArray[_ShapeT_co, dtype[_RealNumberT]]: ... + @overload + def __floordiv__(self: _MaskedArray[_RealNumberT], other: _ArrayLikeBool_co, /) -> _MaskedArray[_RealNumberT]: ... # type: ignore[overload-overlap] + @overload + def __floordiv__(self: _MaskedArray[np.bool], other: _ArrayLikeBool_co, /) -> _MaskedArray[int8]: ... # type: ignore[overload-overlap] + @overload + def __floordiv__(self: _MaskedArray[np.bool], other: _ArrayLike[_RealNumberT], /) -> _MaskedArray[_RealNumberT]: ... # type: ignore[overload-overlap] + @overload + def __floordiv__(self: _MaskedArray[float64], other: _ArrayLikeFloat64_co, /) -> _MaskedArray[float64]: ... + @overload + def __floordiv__(self: _MaskedArrayFloat64_co, other: _ArrayLike[floating[_64Bit]], /) -> _MaskedArray[float64]: ... + @overload + def __floordiv__(self: _MaskedArrayUInt_co, other: _ArrayLikeUInt_co, /) -> _MaskedArray[unsignedinteger]: ... # type: ignore[overload-overlap] + @overload + def __floordiv__(self: _MaskedArrayInt_co, other: _ArrayLikeInt_co, /) -> _MaskedArray[signedinteger]: ... # type: ignore[overload-overlap] + @overload + def __floordiv__(self: _MaskedArrayFloat_co, other: _ArrayLikeFloat_co, /) -> _MaskedArray[floating]: ... + @overload + def __floordiv__(self: _MaskedArray[timedelta64], other: _ArrayLike[timedelta64], /) -> _MaskedArray[int64]: ... + @overload + def __floordiv__(self: _MaskedArray[timedelta64], other: _ArrayLikeBool_co, /) -> NoReturn: ... + @overload + def __floordiv__(self: _MaskedArray[timedelta64], other: _ArrayLikeFloat_co, /) -> _MaskedArray[timedelta64]: ... + @overload + def __floordiv__(self: _MaskedArray[object_], other: Any, /) -> Any: ... + @overload + def __floordiv__(self: _MaskedArray[Any], other: _ArrayLikeObject_co, /) -> Any: ... + + # Keep in sync with `ndarray.__rfloordiv__` + @overload # type: ignore[override] + def __rfloordiv__(self: _MaskedArray[_RealNumberT], other: int | np.bool, /) -> MaskedArray[_ShapeT_co, dtype[_RealNumberT]]: ... + @overload + def __rfloordiv__(self: _MaskedArray[_RealNumberT], other: _ArrayLikeBool_co, /) -> _MaskedArray[_RealNumberT]: ... # type: ignore[overload-overlap] + @overload + def __rfloordiv__(self: _MaskedArray[np.bool], other: _ArrayLikeBool_co, /) -> _MaskedArray[int8]: ... # type: ignore[overload-overlap] + @overload + def __rfloordiv__(self: _MaskedArray[np.bool], other: _ArrayLike[_RealNumberT], /) -> _MaskedArray[_RealNumberT]: ... # type: ignore[overload-overlap] + @overload + def __rfloordiv__(self: _MaskedArray[float64], other: _ArrayLikeFloat64_co, /) -> _MaskedArray[float64]: ... + @overload + def __rfloordiv__(self: _MaskedArrayFloat64_co, other: _ArrayLike[floating[_64Bit]], /) -> _MaskedArray[float64]: ... + @overload + def __rfloordiv__(self: _MaskedArrayUInt_co, other: _ArrayLikeUInt_co, /) -> _MaskedArray[unsignedinteger]: ... # type: ignore[overload-overlap] + @overload + def __rfloordiv__(self: _MaskedArrayInt_co, other: _ArrayLikeInt_co, /) -> _MaskedArray[signedinteger]: ... # type: ignore[overload-overlap] + @overload + def __rfloordiv__(self: _MaskedArrayFloat_co, other: _ArrayLikeFloat_co, /) -> _MaskedArray[floating]: ... # type: ignore[overload-overlap] + @overload + def __rfloordiv__(self: _MaskedArray[timedelta64], other: _ArrayLike[timedelta64], /) -> _MaskedArray[int64]: ... + @overload + def __rfloordiv__(self: _MaskedArray[floating | integer], other: _ArrayLike[timedelta64], /) -> _MaskedArray[timedelta64]: ... + @overload + def __rfloordiv__(self: _MaskedArray[object_], other: Any, /) -> Any: ... + @overload + def __rfloordiv__(self: _MaskedArray[Any], other: _ArrayLikeObject_co, /) -> Any: ... + + # Keep in sync with `ndarray.__pow__` (minus the `mod` parameter) + @overload # type: ignore[override] + def __pow__(self: _MaskedArray[_NumberT], other: int | np.bool, /) -> MaskedArray[_ShapeT_co, dtype[_NumberT]]: ... + @overload + def __pow__(self: _MaskedArray[_NumberT], other: _ArrayLikeBool_co, /) -> _MaskedArray[_NumberT]: ... # type: ignore[overload-overlap] + @overload + def __pow__(self: _MaskedArray[np.bool], other: _ArrayLikeBool_co, /) -> _MaskedArray[int8]: ... # type: ignore[overload-overlap] + @overload + def __pow__(self: _MaskedArray[np.bool], other: _ArrayLike[_NumberT], /) -> _MaskedArray[_NumberT]: ... # type: ignore[overload-overlap] + @overload + def __pow__(self: _MaskedArray[float64], other: _ArrayLikeFloat64_co, /) -> _MaskedArray[float64]: ... + @overload + def __pow__(self: _MaskedArrayFloat64_co, other: _ArrayLike[floating[_64Bit]], /) -> _MaskedArray[float64]: ... + @overload + def __pow__(self: _MaskedArray[complex128], other: _ArrayLikeComplex128_co, /) -> _MaskedArray[complex128]: ... + @overload + def __pow__(self: _MaskedArrayComplex128_co, other: _ArrayLike[complexfloating[_64Bit]], /) -> _MaskedArray[complex128]: ... + @overload + def __pow__(self: _MaskedArrayUInt_co, other: _ArrayLikeUInt_co, /) -> _MaskedArray[unsignedinteger]: ... # type: ignore[overload-overlap] + @overload + def __pow__(self: _MaskedArrayInt_co, other: _ArrayLikeInt_co, /) -> _MaskedArray[signedinteger]: ... # type: ignore[overload-overlap] + @overload + def __pow__(self: _MaskedArrayFloat_co, other: _ArrayLikeFloat_co, /) -> _MaskedArray[floating]: ... # type: ignore[overload-overlap] + @overload + def __pow__(self: _MaskedArrayComplex_co, other: _ArrayLikeComplex_co, /) -> _MaskedArray[complexfloating]: ... + @overload + def __pow__(self: _MaskedArray[number], other: _ArrayLikeNumber_co, /) -> _MaskedArray[number]: ... + @overload + def __pow__(self: _MaskedArray[object_], other: Any, /) -> Any: ... + @overload + def __pow__(self: _MaskedArray[Any], other: _ArrayLikeObject_co, /) -> Any: ... + + # Keep in sync with `ndarray.__rpow__` (minus the `mod` parameter) + @overload # type: ignore[override] + def __rpow__(self: _MaskedArray[_NumberT], other: int | np.bool, /) -> MaskedArray[_ShapeT_co, dtype[_NumberT]]: ... + @overload + def __rpow__(self: _MaskedArray[_NumberT], other: _ArrayLikeBool_co, /) -> _MaskedArray[_NumberT]: ... # type: ignore[overload-overlap] + @overload + def __rpow__(self: _MaskedArray[np.bool], other: _ArrayLikeBool_co, /) -> _MaskedArray[int8]: ... # type: ignore[overload-overlap] + @overload + def __rpow__(self: _MaskedArray[np.bool], other: _ArrayLike[_NumberT], /) -> _MaskedArray[_NumberT]: ... # type: ignore[overload-overlap] + @overload + def __rpow__(self: _MaskedArray[float64], other: _ArrayLikeFloat64_co, /) -> _MaskedArray[float64]: ... + @overload + def __rpow__(self: _MaskedArrayFloat64_co, other: _ArrayLike[floating[_64Bit]], /) -> _MaskedArray[float64]: ... + @overload + def __rpow__(self: _MaskedArray[complex128], other: _ArrayLikeComplex128_co, /) -> _MaskedArray[complex128]: ... + @overload + def __rpow__(self: _MaskedArrayComplex128_co, other: _ArrayLike[complexfloating[_64Bit]], /) -> _MaskedArray[complex128]: ... + @overload + def __rpow__(self: _MaskedArrayUInt_co, other: _ArrayLikeUInt_co, /) -> _MaskedArray[unsignedinteger]: ... # type: ignore[overload-overlap] + @overload + def __rpow__(self: _MaskedArrayInt_co, other: _ArrayLikeInt_co, /) -> _MaskedArray[signedinteger]: ... # type: ignore[overload-overlap] + @overload + def __rpow__(self: _MaskedArrayFloat_co, other: _ArrayLikeFloat_co, /) -> _MaskedArray[floating]: ... # type: ignore[overload-overlap] + @overload + def __rpow__(self: _MaskedArrayComplex_co, other: _ArrayLikeComplex_co, /) -> _MaskedArray[complexfloating]: ... + @overload + def __rpow__(self: _MaskedArray[number], other: _ArrayLikeNumber_co, /) -> _MaskedArray[number]: ... + @overload + def __rpow__(self: _MaskedArray[object_], other: Any, /) -> Any: ... + @overload + def __rpow__(self: _MaskedArray[Any], other: _ArrayLikeObject_co, /) -> Any: ... + + # + @property # type: ignore[misc] + def imag(self: _HasDTypeWithRealAndImag[object, _ScalarT], /) -> MaskedArray[_ShapeT_co, dtype[_ScalarT]]: ... # type: ignore[override] + def get_imag(self: _HasDTypeWithRealAndImag[object, _ScalarT], /) -> MaskedArray[_ShapeT_co, dtype[_ScalarT]]: ... + + # + @property # type: ignore[misc] + def real(self: _HasDTypeWithRealAndImag[_ScalarT, object], /) -> MaskedArray[_ShapeT_co, dtype[_ScalarT]]: ... # type: ignore[override] + def get_real(self: _HasDTypeWithRealAndImag[_ScalarT, object], /) -> MaskedArray[_ShapeT_co, dtype[_ScalarT]]: ... + + # keep in sync with `np.ma.count` + @overload + def count(self, axis: None = None, keepdims: Literal[False] | _NoValueType = ...) -> int: ... + @overload + def count(self, axis: _ShapeLike, keepdims: bool | _NoValueType = ...) -> NDArray[int_]: ... + @overload + def count(self, axis: _ShapeLike | None = None, *, keepdims: Literal[True]) -> NDArray[int_]: ... + @overload + def count(self, axis: _ShapeLike | None, keepdims: Literal[True]) -> NDArray[int_]: ... + + # Keep in sync with `ndarray.reshape` + # NOTE: reshape also accepts negative integers, so we can't use integer literals + @overload # (None) + def reshape(self, shape: None, /, *, order: _OrderACF = "C", copy: bool | None = None) -> Self: ... + @overload # (empty_sequence) + def reshape( # type: ignore[overload-overlap] # mypy false positive + self, + shape: Sequence[Never], + /, + *, + order: _OrderACF = "C", + copy: bool | None = None, + ) -> MaskedArray[tuple[()], _DTypeT_co]: ... + @overload # (() | (int) | (int, int) | ....) # up to 8-d + def reshape( + self, + shape: _AnyShapeT, + /, + *, + order: _OrderACF = "C", + copy: bool | None = None, + ) -> MaskedArray[_AnyShapeT, _DTypeT_co]: ... + @overload # (index) + def reshape( + self, + size1: SupportsIndex, + /, + *, + order: _OrderACF = "C", + copy: bool | None = None, + ) -> MaskedArray[tuple[int], _DTypeT_co]: ... + @overload # (index, index) + def reshape( + self, + size1: SupportsIndex, + size2: SupportsIndex, + /, + *, + order: _OrderACF = "C", + copy: bool | None = None, + ) -> MaskedArray[tuple[int, int], _DTypeT_co]: ... + @overload # (index, index, index) + def reshape( + self, + size1: SupportsIndex, + size2: SupportsIndex, + size3: SupportsIndex, + /, + *, + order: _OrderACF = "C", + copy: bool | None = None, + ) -> MaskedArray[tuple[int, int, int], _DTypeT_co]: ... + @overload # (index, index, index, index) + def reshape( + self, + size1: SupportsIndex, + size2: SupportsIndex, + size3: SupportsIndex, + size4: SupportsIndex, + /, + *, + order: _OrderACF = "C", + copy: bool | None = None, + ) -> MaskedArray[tuple[int, int, int, int], _DTypeT_co]: ... + @overload # (int, *(index, ...)) + def reshape( + self, + size0: SupportsIndex, + /, + *shape: SupportsIndex, + order: _OrderACF = "C", + copy: bool | None = None, + ) -> MaskedArray[_AnyShape, _DTypeT_co]: ... + @overload # (sequence[index]) + def reshape( + self, + shape: Sequence[SupportsIndex], + /, + *, + order: _OrderACF = "C", + copy: bool | None = None, + ) -> MaskedArray[_AnyShape, _DTypeT_co]: ... + + def resize(self, newshape: Never, refcheck: bool = True, order: bool = False) -> NoReturn: ... # type: ignore[override] + def put(self, indices: _ArrayLikeInt_co, values: ArrayLike, mode: _ModeKind = "raise") -> None: ... + def ids(self) -> tuple[int, int]: ... + def iscontiguous(self) -> bool: ... + + # Keep in sync with `ma.core.all` + @overload # type: ignore[override] + def all( + self, + axis: None = None, + out: None = None, + keepdims: Literal[False] | _NoValueType = ..., + ) -> bool_: ... + @overload + def all( + self, + axis: _ShapeLike | None = None, + out: None = None, + *, + keepdims: Literal[True], + ) -> _MaskedArray[bool_]: ... + @overload + def all( + self, + axis: _ShapeLike | None, + out: None, + keepdims: Literal[True], + ) -> _MaskedArray[bool_]: ... + @overload + def all( + self, + axis: _ShapeLike | None = None, + out: None = None, + keepdims: bool | _NoValueType = ..., + ) -> bool_ | _MaskedArray[bool_]: ... + @overload + def all( + self, + axis: _ShapeLike | None = None, + *, + out: _ArrayT, + keepdims: bool | _NoValueType = ..., + ) -> _ArrayT: ... + @overload + def all( + self, + axis: _ShapeLike | None, + out: _ArrayT, + keepdims: bool | _NoValueType = ..., + ) -> _ArrayT: ... + + # Keep in sync with `ma.core.any` + @overload # type: ignore[override] + def any( + self, + axis: None = None, + out: None = None, + keepdims: Literal[False] | _NoValueType = ..., + ) -> bool_: ... + @overload + def any( + self, + axis: _ShapeLike | None = None, + out: None = None, + *, + keepdims: Literal[True], + ) -> _MaskedArray[bool_]: ... + @overload + def any( + self, + axis: _ShapeLike | None, + out: None, + keepdims: Literal[True], + ) -> _MaskedArray[bool_]: ... + @overload + def any( + self, + axis: _ShapeLike | None = None, + out: None = None, + keepdims: bool | _NoValueType = ..., + ) -> bool_ | _MaskedArray[bool_]: ... + @overload + def any( + self, + axis: _ShapeLike | None = None, + *, + out: _ArrayT, + keepdims: bool | _NoValueType = ..., + ) -> _ArrayT: ... + @overload + def any( + self, + axis: _ShapeLike | None, + out: _ArrayT, + keepdims: bool | _NoValueType = ..., + ) -> _ArrayT: ... + + # Keep in sync with `ndarray.trace` and `ma.core.trace` + @overload + def trace( + self, # >= 2D MaskedArray + offset: SupportsIndex = 0, + axis1: SupportsIndex = 0, + axis2: SupportsIndex = 1, + dtype: DTypeLike | None = None, + out: None = None, + ) -> Any: ... + @overload + def trace( + self, # >= 2D MaskedArray + offset: SupportsIndex = 0, + axis1: SupportsIndex = 0, + axis2: SupportsIndex = 1, + dtype: DTypeLike | None = None, + *, + out: _ArrayT, + ) -> _ArrayT: ... + @overload + def trace( + self, # >= 2D MaskedArray + offset: SupportsIndex, + axis1: SupportsIndex, + axis2: SupportsIndex, + dtype: DTypeLike | None, + out: _ArrayT, + ) -> _ArrayT: ... + + # This differs from `ndarray.dot`, in that 1D dot 1D returns a 0D array. + @overload + def dot(self, b: ArrayLike, out: None = None, strict: bool = False) -> _MaskedArray[Any]: ... + @overload + def dot(self, b: ArrayLike, out: _ArrayT, strict: bool = False) -> _ArrayT: ... + + # Keep in sync with `ma.core.sum` + @overload # type: ignore[override] + def sum( + self, + /, + axis: _ShapeLike | None = None, + dtype: DTypeLike | None = None, + out: None = None, + keepdims: bool | _NoValueType = ..., + ) -> Any: ... + @overload + def sum( + self, + /, + axis: _ShapeLike | None, + dtype: DTypeLike | None, + out: _ArrayT, + keepdims: bool | _NoValueType = ..., + ) -> _ArrayT: ... + @overload + def sum( + self, + /, + axis: _ShapeLike | None = None, + dtype: DTypeLike | None = None, + *, + out: _ArrayT, + keepdims: bool | _NoValueType = ..., + ) -> _ArrayT: ... + + # Keep in sync with `ndarray.cumsum` and `ma.core.cumsum` + @overload # out: None (default) + def cumsum(self, /, axis: SupportsIndex | None = None, dtype: DTypeLike | None = None, out: None = None) -> _MaskedArray[Any]: ... + @overload # out: ndarray + def cumsum(self, /, axis: SupportsIndex | None, dtype: DTypeLike | None, out: _ArrayT) -> _ArrayT: ... + @overload + def cumsum(self, /, axis: SupportsIndex | None = None, dtype: DTypeLike | None = None, *, out: _ArrayT) -> _ArrayT: ... + + # Keep in sync with `ma.core.prod` + @overload # type: ignore[override] + def prod( + self, + /, + axis: _ShapeLike | None = None, + dtype: DTypeLike | None = None, + out: None = None, + keepdims: bool | _NoValueType = ..., + ) -> Any: ... + @overload + def prod( + self, + /, + axis: _ShapeLike | None, + dtype: DTypeLike | None, + out: _ArrayT, + keepdims: bool | _NoValueType = ..., + ) -> _ArrayT: ... + @overload + def prod( + self, + /, + axis: _ShapeLike | None = None, + dtype: DTypeLike | None = None, + *, + out: _ArrayT, + keepdims: bool | _NoValueType = ..., + ) -> _ArrayT: ... + + product = prod + + # Keep in sync with `ndarray.cumprod` and `ma.core.cumprod` + @overload # out: None (default) + def cumprod(self, /, axis: SupportsIndex | None = None, dtype: DTypeLike | None = None, out: None = None) -> _MaskedArray[Any]: ... + @overload # out: ndarray + def cumprod(self, /, axis: SupportsIndex | None, dtype: DTypeLike | None, out: _ArrayT) -> _ArrayT: ... + @overload + def cumprod(self, /, axis: SupportsIndex | None = None, dtype: DTypeLike | None = None, *, out: _ArrayT) -> _ArrayT: ... + + # Keep in sync with `ma.core.mean` + @overload # type: ignore[override] + def mean( + self, + axis: _ShapeLike | None = None, + dtype: DTypeLike | None = None, + out: None = None, + keepdims: bool | _NoValueType = ..., + ) -> Any: ... + @overload + def mean( + self, + /, + axis: _ShapeLike | None, + dtype: DTypeLike | None, + out: _ArrayT, + keepdims: bool | _NoValueType = ..., + ) -> _ArrayT: ... + @overload + def mean( + self, + /, + axis: _ShapeLike | None = None, + dtype: DTypeLike | None = None, + *, + out: _ArrayT, + keepdims: bool | _NoValueType = ..., + ) -> _ArrayT: ... + + # keep roughly in sync with `ma.core.anom` + @overload + def anom(self, axis: SupportsIndex | None = None, dtype: None = None) -> Self: ... + @overload + def anom(self, axis: SupportsIndex | None = None, *, dtype: DTypeLike) -> MaskedArray[_ShapeT_co, dtype]: ... + @overload + def anom(self, axis: SupportsIndex | None, dtype: DTypeLike) -> MaskedArray[_ShapeT_co, dtype]: ... + + # keep in sync with `std` and `ma.core.var` + @overload # type: ignore[override] + def var( + self, + axis: _ShapeLike | None = None, + dtype: DTypeLike | None = None, + out: None = None, + ddof: float = 0, + keepdims: bool | _NoValueType = ..., + mean: _ArrayLikeNumber_co | _NoValueType = ..., + ) -> Any: ... + @overload + def var( + self, + axis: _ShapeLike | None, + dtype: DTypeLike | None, + out: _ArrayT, + ddof: float = 0, + keepdims: bool | _NoValueType = ..., + mean: _ArrayLikeNumber_co | _NoValueType = ..., + ) -> _ArrayT: ... + @overload + def var( + self, + axis: _ShapeLike | None = None, + dtype: DTypeLike | None = None, + *, + out: _ArrayT, + ddof: float = 0, + keepdims: bool | _NoValueType = ..., + mean: _ArrayLikeNumber_co | _NoValueType = ..., + ) -> _ArrayT: ... + + # keep in sync with `var` and `ma.core.std` + @overload # type: ignore[override] + def std( + self, + axis: _ShapeLike | None = None, + dtype: DTypeLike | None = None, + out: None = None, + ddof: float = 0, + keepdims: bool | _NoValueType = ..., + mean: _ArrayLikeNumber_co | _NoValueType = ..., + ) -> Any: ... + @overload + def std( + self, + axis: _ShapeLike | None, + dtype: DTypeLike | None, + out: _ArrayT, + ddof: float = 0, + keepdims: bool | _NoValueType = ..., + mean: _ArrayLikeNumber_co | _NoValueType = ..., + ) -> _ArrayT: ... + @overload + def std( + self, + axis: _ShapeLike | None = None, + dtype: DTypeLike | None = None, + *, + out: _ArrayT, + ddof: float = 0, + keepdims: bool | _NoValueType = ..., + mean: _ArrayLikeNumber_co | _NoValueType = ..., + ) -> _ArrayT: ... + + # Keep in sync with `ndarray.round` + @overload # out=None (default) + def round(self, /, decimals: SupportsIndex = 0, out: None = None) -> Self: ... + @overload # out=ndarray + def round(self, /, decimals: SupportsIndex, out: _ArrayT) -> _ArrayT: ... + @overload + def round(self, /, decimals: SupportsIndex = 0, *, out: _ArrayT) -> _ArrayT: ... + + def argsort( # type: ignore[override] + self, + axis: SupportsIndex | _NoValueType = ..., + kind: _SortKind | None = None, + order: str | Sequence[str] | None = None, + endwith: bool = True, + fill_value: _ScalarLike_co | None = None, + *, + stable: bool = False, + ) -> _MaskedArray[intp]: ... + + # Keep in-sync with np.ma.argmin + @overload # type: ignore[override] + def argmin( + self, + axis: None = None, + fill_value: _ScalarLike_co | None = None, + out: None = None, + *, + keepdims: Literal[False] | _NoValueType = ..., + ) -> intp: ... + @overload + def argmin( + self, + axis: SupportsIndex | None = None, + fill_value: _ScalarLike_co | None = None, + out: None = None, + *, + keepdims: bool | _NoValueType = ..., + ) -> Any: ... + @overload + def argmin( + self, + axis: SupportsIndex | None = None, + fill_value: _ScalarLike_co | None = None, + *, + out: _ArrayT, + keepdims: bool | _NoValueType = ..., + ) -> _ArrayT: ... + @overload + def argmin( + self, + axis: SupportsIndex | None, + fill_value: _ScalarLike_co | None, + out: _ArrayT, + *, + keepdims: bool | _NoValueType = ..., + ) -> _ArrayT: ... + + # Keep in-sync with np.ma.argmax + @overload # type: ignore[override] + def argmax( + self, + axis: None = None, + fill_value: _ScalarLike_co | None = None, + out: None = None, + *, + keepdims: Literal[False] | _NoValueType = ..., + ) -> intp: ... + @overload + def argmax( + self, + axis: SupportsIndex | None = None, + fill_value: _ScalarLike_co | None = None, + out: None = None, + *, + keepdims: bool | _NoValueType = ..., + ) -> Any: ... + @overload + def argmax( + self, + axis: SupportsIndex | None = None, + fill_value: _ScalarLike_co | None = None, + *, + out: _ArrayT, + keepdims: bool | _NoValueType = ..., + ) -> _ArrayT: ... + @overload + def argmax( + self, + axis: SupportsIndex | None, + fill_value: _ScalarLike_co | None, + out: _ArrayT, + *, + keepdims: bool | _NoValueType = ..., + ) -> _ArrayT: ... + + # + def sort( # type: ignore[override] + self, + axis: SupportsIndex = -1, + kind: _SortKind | None = None, + order: str | Sequence[str] | None = None, + endwith: bool | None = True, + fill_value: _ScalarLike_co | None = None, + *, + stable: Literal[False] | None = False, + ) -> None: ... + + # + @overload # type: ignore[override] + def min( + self: _MaskedArray[_ScalarT], + axis: None = None, + out: None = None, + fill_value: _ScalarLike_co | None = None, + keepdims: Literal[False] | _NoValueType = ..., + ) -> _ScalarT: ... + @overload + def min( + self, + axis: _ShapeLike | None = None, + out: None = None, + fill_value: _ScalarLike_co | None = None, + keepdims: bool | _NoValueType = ... + ) -> Any: ... + @overload + def min( + self, + axis: _ShapeLike | None, + out: _ArrayT, + fill_value: _ScalarLike_co | None = None, + keepdims: bool | _NoValueType = ..., + ) -> _ArrayT: ... + @overload + def min( + self, + axis: _ShapeLike | None = None, + *, + out: _ArrayT, + fill_value: _ScalarLike_co | None = None, + keepdims: bool | _NoValueType = ..., + ) -> _ArrayT: ... + + # + @overload # type: ignore[override] + def max( + self: _MaskedArray[_ScalarT], + axis: None = None, + out: None = None, + fill_value: _ScalarLike_co | None = None, + keepdims: Literal[False] | _NoValueType = ..., + ) -> _ScalarT: ... + @overload + def max( + self, + axis: _ShapeLike | None = None, + out: None = None, + fill_value: _ScalarLike_co | None = None, + keepdims: bool | _NoValueType = ... + ) -> Any: ... + @overload + def max( + self, + axis: _ShapeLike | None, + out: _ArrayT, + fill_value: _ScalarLike_co | None = None, + keepdims: bool | _NoValueType = ..., + ) -> _ArrayT: ... + @overload + def max( + self, + axis: _ShapeLike | None = None, + *, + out: _ArrayT, + fill_value: _ScalarLike_co | None = None, + keepdims: bool | _NoValueType = ..., + ) -> _ArrayT: ... + + # + @overload + def ptp( + self: _MaskedArray[_ScalarT], + axis: None = None, + out: None = None, + fill_value: _ScalarLike_co | None = None, + keepdims: Literal[False] = False, + ) -> _ScalarT: ... + @overload + def ptp( + self, + axis: _ShapeLike | None = None, + out: None = None, + fill_value: _ScalarLike_co | None = None, + keepdims: bool = False, + ) -> Any: ... + @overload + def ptp( + self, + axis: _ShapeLike | None, + out: _ArrayT, + fill_value: _ScalarLike_co | None = None, + keepdims: bool = False, + ) -> _ArrayT: ... + @overload + def ptp( + self, + axis: _ShapeLike | None = None, + *, + out: _ArrayT, + fill_value: _ScalarLike_co | None = None, + keepdims: bool = False, + ) -> _ArrayT: ... + + # + @overload + def partition( + self, + /, + kth: _ArrayLikeInt, + axis: SupportsIndex = -1, + kind: _PartitionKind = "introselect", + order: None = None + ) -> None: ... + @overload + def partition( + self: _MaskedArray[np.void], + /, + kth: _ArrayLikeInt, + axis: SupportsIndex = -1, + kind: _PartitionKind = "introselect", + order: str | Sequence[str] | None = None, + ) -> None: ... + + # + @overload + def argpartition( + self, + /, + kth: _ArrayLikeInt, + axis: SupportsIndex | None = -1, + kind: _PartitionKind = "introselect", + order: None = None, + ) -> _MaskedArray[intp]: ... + @overload + def argpartition( + self: _MaskedArray[np.void], + /, + kth: _ArrayLikeInt, + axis: SupportsIndex | None = -1, + kind: _PartitionKind = "introselect", + order: str | Sequence[str] | None = None, + ) -> _MaskedArray[intp]: ... + + # Keep in-sync with np.ma.take + @overload # type: ignore[override] + def take( # type: ignore[overload-overlap] + self: _MaskedArray[_ScalarT], + indices: _IntLike_co, + axis: None = None, + out: None = None, + mode: _ModeKind = "raise" + ) -> _ScalarT: ... + @overload + def take( + self: _MaskedArray[_ScalarT], + indices: _ArrayLikeInt_co, + axis: SupportsIndex | None = None, + out: None = None, + mode: _ModeKind = "raise", + ) -> _MaskedArray[_ScalarT]: ... + @overload + def take( + self, + indices: _ArrayLikeInt_co, + axis: SupportsIndex | None, + out: _ArrayT, + mode: _ModeKind = "raise", + ) -> _ArrayT: ... + @overload + def take( + self, + indices: _ArrayLikeInt_co, + axis: SupportsIndex | None = None, + *, + out: _ArrayT, + mode: _ModeKind = "raise", + ) -> _ArrayT: ... + + # keep in sync with `ndarray.diagonal` + @override + def diagonal( + self, + /, + offset: SupportsIndex = 0, + axis1: SupportsIndex = 0, + axis2: SupportsIndex = 1, + ) -> MaskedArray[_AnyShape, _DTypeT_co]: ... + + # keep in sync with `ndarray.repeat` + @override + @overload + def repeat( + self, + /, + repeats: _ArrayLikeInt_co, + axis: None = None, + ) -> MaskedArray[tuple[int], _DTypeT_co]: ... + @overload + def repeat( + self, + /, + repeats: _ArrayLikeInt_co, + axis: SupportsIndex, + ) -> MaskedArray[_AnyShape, _DTypeT_co]: ... + + # keep in sync with `ndarray.flatten` and `ndarray.ravel` + @override + def flatten(self, /, order: _OrderKACF = "C") -> MaskedArray[tuple[int], _DTypeT_co]: ... + @override + def ravel(self, order: _OrderKACF = "C") -> MaskedArray[tuple[int], _DTypeT_co]: ... + + # keep in sync with `ndarray.squeeze` + @override + def squeeze( + self, + /, + axis: SupportsIndex | tuple[SupportsIndex, ...] | None = None, + ) -> MaskedArray[_AnyShape, _DTypeT_co]: ... + + # + def toflex(self) -> MaskedArray[_ShapeT_co, np.dtype[np.void]]: ... + def torecords(self) -> MaskedArray[_ShapeT_co, np.dtype[np.void]]: ... + + # + @override + def tobytes(self, /, fill_value: Incomplete | None = None, order: _OrderKACF = "C") -> bytes: ... # type: ignore[override] + + # keep in sync with `ndarray.tolist` + @override + @overload + def tolist(self: MaskedArray[tuple[Never], dtype[generic[_T]]], /, fill_value: _ScalarLike_co | None = None) -> Any: ... + @overload + def tolist(self: MaskedArray[tuple[()], dtype[generic[_T]]], /, fill_value: _ScalarLike_co | None = None) -> _T: ... + @overload + def tolist(self: MaskedArray[tuple[int], dtype[generic[_T]]], /, fill_value: _ScalarLike_co | None = None) -> list[_T]: ... + @overload + def tolist( + self: MaskedArray[tuple[int, int], dtype[generic[_T]]], /, fill_value: _ScalarLike_co | None = None + ) -> list[list[_T]]: ... + @overload + def tolist( + self: MaskedArray[tuple[int, int, int], dtype[generic[_T]]], /, fill_value: _ScalarLike_co | None = None + ) -> list[list[list[_T]]]: ... + @overload + def tolist(self, /, fill_value: _ScalarLike_co | None = None) -> Any: ... + + # NOTE: will raise `NotImplementedError` + @override + def tofile(self, /, fid: Never, sep: str = "", format: str = "%s") -> NoReturn: ... # type: ignore[override] + + # + @override + def __deepcopy__(self, memo: dict[int, Any] | None = None) -> Self: ... + + # Keep `dtype` at the bottom to avoid name conflicts with `np.dtype` + @property + def dtype(self) -> _DTypeT_co: ... + @dtype.setter + def dtype(self: MaskedArray[_AnyShape, _DTypeT], dtype: _DTypeT, /) -> None: ... + +class mvoid(MaskedArray[_ShapeT_co, _DTypeT_co]): + def __new__( + self, # pyright: ignore[reportSelfClsParameterName] + data, + mask=..., + dtype=..., + fill_value=..., + hardmask=..., + copy=..., + subok=..., + ): ... + def __getitem__(self, indx): ... + def __setitem__(self, indx, value): ... + def __iter__(self): ... + def __len__(self): ... + def filled(self, fill_value=None): ... + def tolist(self): ... # type: ignore[override] + +def isMaskedArray(x: object) -> TypeIs[MaskedArray]: ... +def isarray(x: object) -> TypeIs[MaskedArray]: ... # alias to isMaskedArray +def isMA(x: object) -> TypeIs[MaskedArray]: ... # alias to isMaskedArray + +# 0D float64 array +class MaskedConstant(MaskedArray[tuple[()], dtype[float64]]): + def __new__(cls) -> Self: ... + + # these overrides are no-ops + @override + def __iadd__(self, other: _Ignored, /) -> Self: ... # type: ignore[override] + @override + def __isub__(self, other: _Ignored, /) -> Self: ... # type: ignore[override] + @override + def __imul__(self, other: _Ignored, /) -> Self: ... # type: ignore[override] + @override + def __ifloordiv__(self, other: _Ignored, /) -> Self: ... + @override + def __itruediv__(self, other: _Ignored, /) -> Self: ... # type: ignore[override] + @override + def __ipow__(self, other: _Ignored, /) -> Self: ... # type: ignore[override] + @override + def __deepcopy__(self, /, memo: _Ignored) -> Self: ... # type: ignore[override] + @override + def copy(self, /, *args: _Ignored, **kwargs: _Ignored) -> Self: ... + +masked: Final[MaskedConstant] = ... +masked_singleton: Final[MaskedConstant] = ... + +masked_array: TypeAlias = MaskedArray + +# keep in sync with `MaskedArray.__new__` +@overload +def array( + data: _ArrayLike[_ScalarT], + dtype: None = None, + copy: bool = False, + order: _OrderKACF | None = None, + mask: _ArrayLikeBool_co = nomask, + fill_value: _ScalarLike_co | None = None, + keep_mask: bool = True, + hard_mask: bool = False, + shrink: bool = True, + subok: bool = True, + ndmin: int = 0, +) -> _MaskedArray[_ScalarT]: ... +@overload +def array( + data: object, + dtype: _DTypeLike[_ScalarT], + copy: bool = False, + order: _OrderKACF | None = None, + mask: _ArrayLikeBool_co = nomask, + fill_value: _ScalarLike_co | None = None, + keep_mask: bool = True, + hard_mask: bool = False, + shrink: bool = True, + subok: bool = True, + ndmin: int = 0, +) -> _MaskedArray[_ScalarT]: ... +@overload +def array( + data: object, + dtype: DTypeLike | None = None, + copy: bool = False, + order: _OrderKACF | None = None, + mask: _ArrayLikeBool_co = nomask, + fill_value: _ScalarLike_co | None = None, + keep_mask: bool = True, + hard_mask: bool = False, + shrink: bool = True, + subok: bool = True, + ndmin: int = 0, +) -> _MaskedArray[_ScalarT]: ... + +# keep in sync with `array` +@overload +def asarray(a: _ArrayLike[_ScalarT], dtype: None = None, order: _OrderKACF | None = None) -> _MaskedArray[_ScalarT]: ... +@overload +def asarray(a: object, dtype: _DTypeLike[_ScalarT], order: _OrderKACF | None = None) -> _MaskedArray[_ScalarT]: ... +@overload +def asarray(a: object, dtype: DTypeLike | None = None, order: _OrderKACF | None = None) -> _MaskedArray[_ScalarT]: ... + +# keep in sync with `asarray` (but note the additional first overload) +@overload +def asanyarray(a: _MArrayT, dtype: None = None, order: _OrderKACF | None = None) -> _MArrayT: ... +@overload +def asanyarray(a: _ArrayLike[_ScalarT], dtype: None = None, order: _OrderKACF | None = None) -> _MaskedArray[_ScalarT]: ... +@overload +def asanyarray(a: object, dtype: _DTypeLike[_ScalarT], order: _OrderKACF | None = None) -> _MaskedArray[_ScalarT]: ... +@overload +def asanyarray(a: object, dtype: DTypeLike | None = None, order: _OrderKACF | None = None) -> _MaskedArray[_ScalarT]: ... + +# +def is_masked(x: object) -> bool: ... + +@overload +def min( + obj: _ArrayLike[_ScalarT], + axis: None = None, + out: None = None, + fill_value: _ScalarLike_co | None = None, + keepdims: Literal[False] | _NoValueType = ..., +) -> _ScalarT: ... +@overload +def min( + obj: ArrayLike, + axis: _ShapeLike | None = None, + out: None = None, + fill_value: _ScalarLike_co | None = None, + keepdims: bool | _NoValueType = ... +) -> Any: ... +@overload +def min( + obj: ArrayLike, + axis: _ShapeLike | None, + out: _ArrayT, + fill_value: _ScalarLike_co | None = None, + keepdims: bool | _NoValueType = ..., +) -> _ArrayT: ... +@overload +def min( + obj: ArrayLike, + axis: _ShapeLike | None = None, + *, + out: _ArrayT, + fill_value: _ScalarLike_co | None = None, + keepdims: bool | _NoValueType = ..., +) -> _ArrayT: ... + +@overload +def max( + obj: _ArrayLike[_ScalarT], + axis: None = None, + out: None = None, + fill_value: _ScalarLike_co | None = None, + keepdims: Literal[False] | _NoValueType = ..., +) -> _ScalarT: ... +@overload +def max( + obj: ArrayLike, + axis: _ShapeLike | None = None, + out: None = None, + fill_value: _ScalarLike_co | None = None, + keepdims: bool | _NoValueType = ... +) -> Any: ... +@overload +def max( + obj: ArrayLike, + axis: _ShapeLike | None, + out: _ArrayT, + fill_value: _ScalarLike_co | None = None, + keepdims: bool | _NoValueType = ..., +) -> _ArrayT: ... +@overload +def max( + obj: ArrayLike, + axis: _ShapeLike | None = None, + *, + out: _ArrayT, + fill_value: _ScalarLike_co | None = None, + keepdims: bool | _NoValueType = ..., +) -> _ArrayT: ... + +@overload +def ptp( + obj: _ArrayLike[_ScalarT], + axis: None = None, + out: None = None, + fill_value: _ScalarLike_co | None = None, + keepdims: Literal[False] | _NoValueType = ..., +) -> _ScalarT: ... +@overload +def ptp( + obj: ArrayLike, + axis: _ShapeLike | None = None, + out: None = None, + fill_value: _ScalarLike_co | None = None, + keepdims: bool | _NoValueType = ... +) -> Any: ... +@overload +def ptp( + obj: ArrayLike, + axis: _ShapeLike | None, + out: _ArrayT, + fill_value: _ScalarLike_co | None = None, + keepdims: bool | _NoValueType = ..., +) -> _ArrayT: ... +@overload +def ptp( + obj: ArrayLike, + axis: _ShapeLike | None = None, + *, + out: _ArrayT, + fill_value: _ScalarLike_co | None = None, + keepdims: bool | _NoValueType = ..., +) -> _ArrayT: ... + +# we cannot meaningfully annotate `frommethod` further, because the callable signature +# of the return type fully depends on the *value* of `methodname` and `reversed` in +# a way that cannot be expressed in the Python type system. +def _frommethod(methodname: str, reversed: bool = False) -> types.FunctionType: ... + +# NOTE: The following `*_mask` functions will accept any array-like input runtime, but +# since their use-cases are specific to masks, they only accept `MaskedArray` inputs. + +# keep in sync with `MaskedArray.harden_mask` +def harden_mask(a: _MArrayT) -> _MArrayT: ... +# keep in sync with `MaskedArray.soften_mask` +def soften_mask(a: _MArrayT) -> _MArrayT: ... +# keep in sync with `MaskedArray.shrink_mask` +def shrink_mask(a: _MArrayT) -> _MArrayT: ... + +# keep in sync with `MaskedArray.ids` +def ids(a: ArrayLike) -> tuple[int, int]: ... + +# keep in sync with `ndarray.nonzero` +def nonzero(a: ArrayLike) -> tuple[ndarray[tuple[int], np.dtype[intp]], ...]: ... + +# keep first overload in sync with `MaskedArray.ravel` +@overload +def ravel(a: np.ndarray[Any, _DTypeT], order: _OrderKACF = "C") -> MaskedArray[tuple[int], _DTypeT]: ... +@overload +def ravel(a: _ArrayLike[_ScalarT], order: _OrderKACF = "C") -> MaskedArray[tuple[int], np.dtype[_ScalarT]]: ... +@overload +def ravel(a: ArrayLike, order: _OrderKACF = "C") -> MaskedArray[tuple[int], _DTypeT_co]: ... + +# keep roughly in sync with `lib._function_base_impl.copy` +@overload +def copy(a: _MArrayT, order: _OrderKACF = "C") -> _MArrayT: ... +@overload +def copy(a: np.ndarray[_ShapeT, _DTypeT], order: _OrderKACF = "C") -> MaskedArray[_ShapeT, _DTypeT]: ... +@overload +def copy(a: _ArrayLike[_ScalarT], order: _OrderKACF = "C") -> _MaskedArray[_ScalarT]: ... +@overload +def copy(a: ArrayLike, order: _OrderKACF = "C") -> _MaskedArray[Incomplete]: ... + +# keep in sync with `_core.fromnumeric.diagonal` +@overload +def diagonal( + a: _ArrayLike[_ScalarT], + offset: SupportsIndex = 0, + axis1: SupportsIndex = 0, + axis2: SupportsIndex = 1, +) -> NDArray[_ScalarT]: ... +@overload +def diagonal( + a: ArrayLike, + offset: SupportsIndex = 0, + axis1: SupportsIndex = 0, + axis2: SupportsIndex = 1, +) -> NDArray[Incomplete]: ... + +# keep in sync with `_core.fromnumeric.repeat` +@overload +def repeat(a: _ArrayLike[_ScalarT], repeats: _ArrayLikeInt_co, axis: None = None) -> MaskedArray[tuple[int], dtype[_ScalarT]]: ... +@overload +def repeat(a: _ArrayLike[_ScalarT], repeats: _ArrayLikeInt_co, axis: SupportsIndex) -> _MaskedArray[_ScalarT]: ... +@overload +def repeat(a: ArrayLike, repeats: _ArrayLikeInt_co, axis: None = None) -> MaskedArray[tuple[int], dtype[Incomplete]]: ... +@overload +def repeat(a: ArrayLike, repeats: _ArrayLikeInt_co, axis: SupportsIndex) -> _MaskedArray[Incomplete]: ... + +# keep in sync with `_core.fromnumeric.swapaxes` +@overload +def swapaxes(a: _MArrayT, axis1: SupportsIndex, axis2: SupportsIndex) -> _MArrayT: ... +@overload +def swapaxes(a: _ArrayLike[_ScalarT], axis1: SupportsIndex, axis2: SupportsIndex) -> _MaskedArray[_ScalarT]: ... +@overload +def swapaxes(a: ArrayLike, axis1: SupportsIndex, axis2: SupportsIndex) -> _MaskedArray[Incomplete]: ... + +# NOTE: The `MaskedArray.anom` definition is specific to `MaskedArray`, so we need +# additional overloads to cover the array-like input here. +@overload # a: MaskedArray, dtype=None +def anom(a: _MArrayT, axis: SupportsIndex | None = None, dtype: None = None) -> _MArrayT: ... +@overload # a: array-like, dtype=None +def anom(a: _ArrayLike[_ScalarT], axis: SupportsIndex | None = None, dtype: None = None) -> _MaskedArray[_ScalarT]: ... +@overload # a: unknown array-like, dtype: dtype-like (positional) +def anom(a: ArrayLike, axis: SupportsIndex | None, dtype: _DTypeLike[_ScalarT]) -> _MaskedArray[_ScalarT]: ... +@overload # a: unknown array-like, dtype: dtype-like (keyword) +def anom(a: ArrayLike, axis: SupportsIndex | None = None, *, dtype: _DTypeLike[_ScalarT]) -> _MaskedArray[_ScalarT]: ... +@overload # a: unknown array-like, dtype: unknown dtype-like (positional) +def anom(a: ArrayLike, axis: SupportsIndex | None, dtype: DTypeLike) -> _MaskedArray[Incomplete]: ... +@overload # a: unknown array-like, dtype: unknown dtype-like (keyword) +def anom(a: ArrayLike, axis: SupportsIndex | None = None, *, dtype: DTypeLike) -> _MaskedArray[Incomplete]: ... + +anomalies = anom + +# Keep in sync with `any` and `MaskedArray.all` +@overload +def all(a: ArrayLike, axis: None = None, out: None = None, keepdims: Literal[False] | _NoValueType = ...) -> np.bool: ... +@overload +def all(a: ArrayLike, axis: _ShapeLike | None, out: None, keepdims: Literal[True]) -> _MaskedArray[np.bool]: ... +@overload +def all(a: ArrayLike, axis: _ShapeLike | None = None, out: None = None, *, keepdims: Literal[True]) -> _MaskedArray[np.bool]: ... +@overload +def all( + a: ArrayLike, axis: _ShapeLike | None = None, out: None = None, keepdims: bool | _NoValueType = ... +) -> np.bool | _MaskedArray[np.bool]: ... +@overload +def all(a: ArrayLike, axis: _ShapeLike | None, out: _ArrayT, keepdims: bool | _NoValueType = ...) -> _ArrayT: ... +@overload +def all(a: ArrayLike, axis: _ShapeLike | None = None, *, out: _ArrayT, keepdims: bool | _NoValueType = ...) -> _ArrayT: ... + +# Keep in sync with `all` and `MaskedArray.any` +@overload +def any(a: ArrayLike, axis: None = None, out: None = None, keepdims: Literal[False] | _NoValueType = ...) -> np.bool: ... +@overload +def any(a: ArrayLike, axis: _ShapeLike | None, out: None, keepdims: Literal[True]) -> _MaskedArray[np.bool]: ... +@overload +def any(a: ArrayLike, axis: _ShapeLike | None = None, out: None = None, *, keepdims: Literal[True]) -> _MaskedArray[np.bool]: ... +@overload +def any( + a: ArrayLike, axis: _ShapeLike | None = None, out: None = None, keepdims: bool | _NoValueType = ... +) -> np.bool | _MaskedArray[np.bool]: ... +@overload +def any(a: ArrayLike, axis: _ShapeLike | None, out: _ArrayT, keepdims: bool | _NoValueType = ...) -> _ArrayT: ... +@overload +def any(a: ArrayLike, axis: _ShapeLike | None = None, *, out: _ArrayT, keepdims: bool | _NoValueType = ...) -> _ArrayT: ... + +# NOTE: The `MaskedArray.compress` definition uses its `DTypeT_co` type parameter, +# which wouldn't work here for array-like inputs, so we need additional overloads. +@overload +def compress( + condition: _ArrayLikeBool_co, a: _ArrayLike[_ScalarT], axis: None = None, out: None = None +) -> MaskedArray[tuple[int], np.dtype[_ScalarT]]: ... +@overload +def compress( + condition: _ArrayLikeBool_co, a: _ArrayLike[_ScalarT], axis: _ShapeLike | None = None, out: None = None +) -> MaskedArray[_AnyShape, np.dtype[_ScalarT]]: ... +@overload +def compress(condition: _ArrayLikeBool_co, a: ArrayLike, axis: None = None, out: None = None) -> MaskedArray[tuple[int]]: ... +@overload +def compress( + condition: _ArrayLikeBool_co, a: ArrayLike, axis: _ShapeLike | None = None, out: None = None +) -> _MaskedArray[Incomplete]: ... +@overload +def compress(condition: _ArrayLikeBool_co, a: ArrayLike, axis: _ShapeLike | None, out: _ArrayT) -> _ArrayT: ... +@overload +def compress(condition: _ArrayLikeBool_co, a: ArrayLike, axis: _ShapeLike | None = None, *, out: _ArrayT) -> _ArrayT: ... + +# Keep in sync with `cumprod` and `MaskedArray.cumsum` +@overload # out: None (default) +def cumsum( + a: ArrayLike, axis: SupportsIndex | None = None, dtype: DTypeLike | None = None, out: None = None +) -> _MaskedArray[Incomplete]: ... +@overload # out: ndarray (positional) +def cumsum(a: ArrayLike, axis: SupportsIndex | None, dtype: DTypeLike | None, out: _ArrayT) -> _ArrayT: ... +@overload # out: ndarray (kwarg) +def cumsum(a: ArrayLike, axis: SupportsIndex | None = None, dtype: DTypeLike | None = None, *, out: _ArrayT) -> _ArrayT: ... + +# Keep in sync with `cumsum` and `MaskedArray.cumsum` +@overload # out: None (default) +def cumprod( + a: ArrayLike, axis: SupportsIndex | None = None, dtype: DTypeLike | None = None, out: None = None +) -> _MaskedArray[Incomplete]: ... +@overload # out: ndarray (positional) +def cumprod(a: ArrayLike, axis: SupportsIndex | None, dtype: DTypeLike | None, out: _ArrayT) -> _ArrayT: ... +@overload # out: ndarray (kwarg) +def cumprod(a: ArrayLike, axis: SupportsIndex | None = None, dtype: DTypeLike | None = None, *, out: _ArrayT) -> _ArrayT: ... + +# Keep in sync with `sum`, `prod`, `product`, and `MaskedArray.mean` +@overload +def mean( + a: ArrayLike, + axis: _ShapeLike | None = None, + dtype: DTypeLike | None = None, + out: None = None, + keepdims: bool | _NoValueType = ..., +) -> Incomplete: ... +@overload +def mean( + a: ArrayLike, + axis: _ShapeLike | None, + dtype: DTypeLike | None, + out: _ArrayT, + keepdims: bool | _NoValueType = ..., +) -> _ArrayT: ... +@overload +def mean( + a: ArrayLike, + axis: _ShapeLike | None = None, + dtype: DTypeLike | None = None, + *, + out: _ArrayT, + keepdims: bool | _NoValueType = ..., +) -> _ArrayT: ... + +# Keep in sync with `mean`, `prod`, `product`, and `MaskedArray.sum` +@overload +def sum( + a: ArrayLike, + axis: _ShapeLike | None = None, + dtype: DTypeLike | None = None, + out: None = None, + keepdims: bool | _NoValueType = ..., +) -> Incomplete: ... +@overload +def sum( + a: ArrayLike, + axis: _ShapeLike | None, + dtype: DTypeLike | None, + out: _ArrayT, + keepdims: bool | _NoValueType = ..., +) -> _ArrayT: ... +@overload +def sum( + a: ArrayLike, + axis: _ShapeLike | None = None, + dtype: DTypeLike | None = None, + *, + out: _ArrayT, + keepdims: bool | _NoValueType = ..., +) -> _ArrayT: ... + +# Keep in sync with `product` and `MaskedArray.prod` +@overload +def prod( + a: ArrayLike, + axis: _ShapeLike | None = None, + dtype: DTypeLike | None = None, + out: None = None, + keepdims: bool | _NoValueType = ..., +) -> Incomplete: ... +@overload +def prod( + a: ArrayLike, + axis: _ShapeLike | None, + dtype: DTypeLike | None, + out: _ArrayT, + keepdims: bool | _NoValueType = ..., +) -> _ArrayT: ... +@overload +def prod( + a: ArrayLike, + axis: _ShapeLike | None = None, + dtype: DTypeLike | None = None, + *, + out: _ArrayT, + keepdims: bool | _NoValueType = ..., +) -> _ArrayT: ... + +# Keep in sync with `prod` and `MaskedArray.prod` +@overload +def product( + a: ArrayLike, + axis: _ShapeLike | None = None, + dtype: DTypeLike | None = None, + out: None = None, + keepdims: bool | _NoValueType = ..., +) -> Incomplete: ... +@overload +def product( + a: ArrayLike, + axis: _ShapeLike | None, + dtype: DTypeLike | None, + out: _ArrayT, + keepdims: bool | _NoValueType = ..., +) -> _ArrayT: ... +@overload +def product( + a: ArrayLike, + axis: _ShapeLike | None = None, + dtype: DTypeLike | None = None, + *, + out: _ArrayT, + keepdims: bool | _NoValueType = ..., +) -> _ArrayT: ... + +# Keep in sync with `MaskedArray.trace` and `_core.fromnumeric.trace` +@overload +def trace( + a: ArrayLike, + offset: SupportsIndex = 0, + axis1: SupportsIndex = 0, + axis2: SupportsIndex = 1, + dtype: DTypeLike | None = None, + out: None = None, +) -> Incomplete: ... +@overload +def trace( + a: ArrayLike, + offset: SupportsIndex, + axis1: SupportsIndex, + axis2: SupportsIndex, + dtype: DTypeLike | None, + out: _ArrayT, +) -> _ArrayT: ... +@overload +def trace( + a: ArrayLike, + offset: SupportsIndex = 0, + axis1: SupportsIndex = 0, + axis2: SupportsIndex = 1, + dtype: DTypeLike | None = None, + *, + out: _ArrayT, +) -> _ArrayT: ... + +# keep in sync with `std` and `MaskedArray.var` +@overload +def std( + a: ArrayLike, + axis: _ShapeLike | None = None, + dtype: DTypeLike | None = None, + out: None = None, + ddof: float = 0, + keepdims: bool | _NoValueType = ..., + mean: _ArrayLikeNumber_co | _NoValueType = ..., +) -> Incomplete: ... +@overload +def std( + a: ArrayLike, + axis: _ShapeLike | None, + dtype: DTypeLike | None, + out: _ArrayT, + ddof: float = 0, + keepdims: bool | _NoValueType = ..., + mean: _ArrayLikeNumber_co | _NoValueType = ..., +) -> _ArrayT: ... +@overload +def std( + a: ArrayLike, + axis: _ShapeLike | None = None, + dtype: DTypeLike | None = None, + *, + out: _ArrayT, + ddof: float = 0, + keepdims: bool | _NoValueType = ..., + mean: _ArrayLikeNumber_co | _NoValueType = ..., +) -> _ArrayT: ... + +# keep in sync with `std` and `MaskedArray.var` +@overload +def var( + a: ArrayLike, + axis: _ShapeLike | None = None, + dtype: DTypeLike | None = None, + out: None = None, + ddof: float = 0, + keepdims: bool | _NoValueType = ..., + mean: _ArrayLikeNumber_co | _NoValueType = ..., +) -> Incomplete: ... +@overload +def var( + a: ArrayLike, + axis: _ShapeLike | None, + dtype: DTypeLike | None, + out: _ArrayT, + ddof: float = 0, + keepdims: bool | _NoValueType = ..., + mean: _ArrayLikeNumber_co | _NoValueType = ..., +) -> _ArrayT: ... +@overload +def var( + a: ArrayLike, + axis: _ShapeLike | None = None, + dtype: DTypeLike | None = None, + *, + out: _ArrayT, + ddof: float = 0, + keepdims: bool | _NoValueType = ..., + mean: _ArrayLikeNumber_co | _NoValueType = ..., +) -> _ArrayT: ... + +# (a, b) +minimum: _extrema_operation = ... +maximum: _extrema_operation = ... + +# NOTE: this is a `_frommethod` instance at runtime +@overload +def count(a: ArrayLike, axis: None = None, keepdims: Literal[False] | _NoValueType = ...) -> int: ... +@overload +def count(a: ArrayLike, axis: _ShapeLike, keepdims: bool | _NoValueType = ...) -> NDArray[int_]: ... +@overload +def count(a: ArrayLike, axis: _ShapeLike | None = None, *, keepdims: Literal[True]) -> NDArray[int_]: ... +@overload +def count(a: ArrayLike, axis: _ShapeLike | None, keepdims: Literal[True]) -> NDArray[int_]: ... + +# NOTE: this is a `_frommethod` instance at runtime +@overload +def argmin( + a: ArrayLike, + axis: None = None, + fill_value: _ScalarLike_co | None = None, + out: None = None, + *, + keepdims: Literal[False] | _NoValueType = ..., +) -> intp: ... +@overload +def argmin( + a: ArrayLike, + axis: SupportsIndex | None = None, + fill_value: _ScalarLike_co | None = None, + out: None = None, + *, + keepdims: bool | _NoValueType = ..., +) -> Any: ... +@overload +def argmin( + a: ArrayLike, + axis: SupportsIndex | None = None, + fill_value: _ScalarLike_co | None = None, + *, + out: _ArrayT, + keepdims: bool | _NoValueType = ..., +) -> _ArrayT: ... +@overload +def argmin( + a: ArrayLike, + axis: SupportsIndex | None, + fill_value: _ScalarLike_co | None, + out: _ArrayT, + *, + keepdims: bool | _NoValueType = ..., +) -> _ArrayT: ... + +# keep in sync with `argmin` +@overload +def argmax( + a: ArrayLike, + axis: None = None, + fill_value: _ScalarLike_co | None = None, + out: None = None, + *, + keepdims: Literal[False] | _NoValueType = ..., +) -> intp: ... +@overload +def argmax( + a: ArrayLike, + axis: SupportsIndex | None = None, + fill_value: _ScalarLike_co | None = None, + out: None = None, + *, + keepdims: bool | _NoValueType = ..., +) -> Any: ... +@overload +def argmax( + a: ArrayLike, + axis: SupportsIndex | None = None, + fill_value: _ScalarLike_co | None = None, + *, + out: _ArrayT, + keepdims: bool | _NoValueType = ..., +) -> _ArrayT: ... +@overload +def argmax( + a: ArrayLike, + axis: SupportsIndex | None, + fill_value: _ScalarLike_co | None, + out: _ArrayT, + *, + keepdims: bool | _NoValueType = ..., +) -> _ArrayT: ... + +@overload +def take( + a: _ArrayLike[_ScalarT], + indices: _IntLike_co, + axis: None = None, + out: None = None, + mode: _ModeKind = "raise" +) -> _ScalarT: ... +@overload +def take( + a: _ArrayLike[_ScalarT], + indices: _ArrayLikeInt_co, + axis: SupportsIndex | None = None, + out: None = None, + mode: _ModeKind = "raise", +) -> _MaskedArray[_ScalarT]: ... +@overload +def take( + a: ArrayLike, + indices: _IntLike_co, + axis: SupportsIndex | None = None, + out: None = None, + mode: _ModeKind = "raise", +) -> Any: ... +@overload +def take( + a: ArrayLike, + indices: _ArrayLikeInt_co, + axis: SupportsIndex | None = None, + out: None = None, + mode: _ModeKind = "raise", +) -> _MaskedArray[Any]: ... +@overload +def take( + a: ArrayLike, + indices: _ArrayLikeInt_co, + axis: SupportsIndex | None, + out: _ArrayT, + mode: _ModeKind = "raise", +) -> _ArrayT: ... +@overload +def take( + a: ArrayLike, + indices: _ArrayLikeInt_co, + axis: SupportsIndex | None = None, + *, + out: _ArrayT, + mode: _ModeKind = "raise", +) -> _ArrayT: ... + +def power(a, b, third=None): ... +def argsort(a, axis=..., kind=None, order=None, endwith=True, fill_value=None, *, stable=None): ... +@overload +def sort( + a: _ArrayT, + axis: SupportsIndex = -1, + kind: _SortKind | None = None, + order: str | Sequence[str] | None = None, + endwith: bool | None = True, + fill_value: _ScalarLike_co | None = None, + *, + stable: Literal[False] | None = None, +) -> _ArrayT: ... +@overload +def sort( + a: ArrayLike, + axis: SupportsIndex = -1, + kind: _SortKind | None = None, + order: str | Sequence[str] | None = None, + endwith: bool | None = True, + fill_value: _ScalarLike_co | None = None, + *, + stable: Literal[False] | None = None, +) -> NDArray[Any]: ... +@overload +def compressed(x: _ArrayLike[_ScalarT_co]) -> _Array1D[_ScalarT_co]: ... +@overload +def compressed(x: ArrayLike) -> _Array1D[Any]: ... +def concatenate(arrays, axis=0): ... +def diag(v, k=0): ... +def left_shift(a, n): ... +def right_shift(a, n): ... +def put(a: NDArray[Any], indices: _ArrayLikeInt_co, values: ArrayLike, mode: _ModeKind = "raise") -> None: ... +def putmask(a: NDArray[Any], mask: _ArrayLikeBool_co, values: ArrayLike) -> None: ... +def transpose(a, axes=None): ... +def reshape(a, new_shape, order="C"): ... +def resize(x, new_shape): ... +def ndim(obj: ArrayLike) -> int: ... +def shape(obj): ... +def size(obj: ArrayLike, axis: SupportsIndex | None = None) -> int: ... +def diff(a, /, n=1, axis=-1, prepend=..., append=...): ... +def where(condition, x=..., y=...): ... +def choose(indices, choices, out=None, mode="raise"): ... +def round_(a, decimals=0, out=None): ... +round = round_ + +def inner(a, b): ... +innerproduct = inner + +def outer(a, b): ... +outerproduct = outer + +def correlate(a, v, mode="valid", propagate_mask=True): ... +def convolve(a, v, mode="full", propagate_mask=True): ... + +def allequal(a: ArrayLike, b: ArrayLike, fill_value: bool = True) -> bool: ... + +def allclose(a: ArrayLike, b: ArrayLike, masked_equal: bool = True, rtol: float = 1e-5, atol: float = 1e-8) -> bool: ... + +def fromflex(fxarray): ... + +def append(a, b, axis=None): ... +def dot(a, b, strict=False, out=None): ... + +# internal wrapper functions for the functions below +def _convert2ma( + funcname: str, + np_ret: str, + np_ma_ret: str, + params: dict[str, Any] | None = None, +) -> Callable[..., Any]: ... + +# keep in sync with `_core.multiarray.arange` +@overload # dtype= +def arange( + start_or_stop: _ArangeScalar | float, + /, + stop: _ArangeScalar | float | None = None, + step: _ArangeScalar | float | None = 1, + *, + dtype: _DTypeLike[_ArangeScalarT], + device: Literal["cpu"] | None = None, + like: _SupportsArrayFunc | None = None, + fill_value: _FillValue | None = None, + hardmask: bool = False, +) -> _Masked1D[_ArangeScalarT]: ... +@overload # (int-like, int-like?, int-like?) +def arange( + start_or_stop: _IntLike_co, + /, + stop: _IntLike_co | None = None, + step: _IntLike_co | None = 1, + *, + dtype: type[int] | _DTypeLike[np.int_] | None = None, + device: Literal["cpu"] | None = None, + like: _SupportsArrayFunc | None = None, + fill_value: _FillValue | None = None, + hardmask: bool = False, +) -> _Masked1D[np.int_]: ... +@overload # (float, float-like?, float-like?) +def arange( + start_or_stop: float | floating, + /, + stop: _FloatLike_co | None = None, + step: _FloatLike_co | None = 1, + *, + dtype: type[float] | _DTypeLike[np.float64] | None = None, + device: Literal["cpu"] | None = None, + like: _SupportsArrayFunc | None = None, + fill_value: _FillValue | None = None, + hardmask: bool = False, +) -> _Masked1D[np.float64 | Any]: ... +@overload # (float-like, float, float-like?) +def arange( + start_or_stop: _FloatLike_co, + /, + stop: float | floating, + step: _FloatLike_co | None = 1, + *, + dtype: type[float] | _DTypeLike[np.float64] | None = None, + device: Literal["cpu"] | None = None, + like: _SupportsArrayFunc | None = None, + fill_value: _FillValue | None = None, + hardmask: bool = False, +) -> _Masked1D[np.float64 | Any]: ... +@overload # (timedelta, timedelta-like?, timedelta-like?) +def arange( + start_or_stop: np.timedelta64, + /, + stop: _TD64Like_co | None = None, + step: _TD64Like_co | None = 1, + *, + dtype: _DTypeLike[np.timedelta64] | None = None, + device: Literal["cpu"] | None = None, + like: _SupportsArrayFunc | None = None, + fill_value: _FillValue | None = None, + hardmask: bool = False, +) -> _Masked1D[np.timedelta64[Incomplete]]: ... +@overload # (timedelta-like, timedelta, timedelta-like?) +def arange( + start_or_stop: _TD64Like_co, + /, + stop: np.timedelta64, + step: _TD64Like_co | None = 1, + *, + dtype: _DTypeLike[np.timedelta64] | None = None, + device: Literal["cpu"] | None = None, + like: _SupportsArrayFunc | None = None, + fill_value: _FillValue | None = None, + hardmask: bool = False, +) -> _Masked1D[np.timedelta64[Incomplete]]: ... +@overload # (datetime, datetime, timedelta-like) (requires both start and stop) +def arange( + start_or_stop: np.datetime64, + /, + stop: np.datetime64, + step: _TD64Like_co | None = 1, + *, + dtype: _DTypeLike[np.datetime64] | None = None, + device: Literal["cpu"] | None = None, + like: _SupportsArrayFunc | None = None, + fill_value: _FillValue | None = None, + hardmask: bool = False, +) -> _Masked1D[np.datetime64[Incomplete]]: ... +@overload # (str, str, timedelta-like, dtype=dt64-like) (requires both start and stop) +def arange( + start_or_stop: str, + /, + stop: str, + step: _TD64Like_co | None = 1, + *, + dtype: _DTypeLike[np.datetime64] | _DT64Codes, + like: _SupportsArrayFunc | None = None, + fill_value: _FillValue | None = None, + hardmask: bool = False, +) -> _Masked1D[np.datetime64[Incomplete]]: ... +@overload # dtype= +def arange( + start_or_stop: _ArangeScalar | float | str, + /, + stop: _ArangeScalar | float | str | None = None, + step: _ArangeScalar | float | None = 1, + *, + dtype: DTypeLike | None = None, + device: Literal["cpu"] | None = None, + like: _SupportsArrayFunc | None = None, + fill_value: _FillValue | None = None, + hardmask: bool = False, +) -> _Masked1D[Incomplete]: ... + +# based on `_core.fromnumeric.clip` +@overload +def clip( + a: _ScalarT, + a_min: ArrayLike | _NoValueType | None = ..., + a_max: ArrayLike | _NoValueType | None = ..., + out: None = None, + *, + min: ArrayLike | _NoValueType | None = ..., + max: ArrayLike | _NoValueType | None = ..., + fill_value: _FillValue | None = None, + hardmask: bool = False, + dtype: None = None, + **kwargs: Unpack[_UFuncKwargs], +) -> _ScalarT: ... +@overload +def clip( + a: NDArray[_ScalarT], + a_min: ArrayLike | _NoValueType | None = ..., + a_max: ArrayLike | _NoValueType | None = ..., + out: None = None, + *, + min: ArrayLike | _NoValueType | None = ..., + max: ArrayLike | _NoValueType | None = ..., + fill_value: _FillValue | None = None, + hardmask: bool = False, + dtype: None = None, + **kwargs: Unpack[_UFuncKwargs], +) -> _MaskedArray[_ScalarT]: ... +@overload +def clip( + a: ArrayLike, + a_min: ArrayLike | None, + a_max: ArrayLike | None, + out: _MArrayT, + *, + min: ArrayLike | _NoValueType | None = ..., + max: ArrayLike | _NoValueType | None = ..., + fill_value: _FillValue | None = None, + hardmask: bool = False, + dtype: DTypeLike | None = None, + **kwargs: Unpack[_UFuncKwargs], +) -> _MArrayT: ... +@overload +def clip( + a: ArrayLike, + a_min: ArrayLike | _NoValueType | None = ..., + a_max: ArrayLike | _NoValueType | None = ..., + *, + out: _MArrayT, + min: ArrayLike | _NoValueType | None = ..., + max: ArrayLike | _NoValueType | None = ..., + fill_value: _FillValue | None = None, + hardmask: bool = False, + dtype: DTypeLike | None = None, + **kwargs: Unpack[_UFuncKwargs], +) -> _MArrayT: ... +@overload +def clip( + a: ArrayLike, + a_min: ArrayLike | _NoValueType | None = ..., + a_max: ArrayLike | _NoValueType | None = ..., + out: None = None, + *, + min: ArrayLike | _NoValueType | None = ..., + max: ArrayLike | _NoValueType | None = ..., + fill_value: _FillValue | None = None, + hardmask: bool = False, + dtype: DTypeLike | None = None, + **kwargs: Unpack[_UFuncKwargs], +) -> Incomplete: ... + +# keep in sync with `_core.multiarray.ones` +@overload +def empty( + shape: SupportsIndex, + dtype: None = None, + order: _OrderCF = "C", + *, + device: Literal["cpu"] | None = None, + like: _SupportsArrayFunc | None = None, + fill_value: _FillValue | None = None, + hardmask: bool = False, +) -> MaskedArray[tuple[int], np.dtype[np.float64]]: ... +@overload +def empty( + shape: SupportsIndex, + dtype: _DTypeT | _SupportsDType[_DTypeT], + order: _OrderCF = "C", + *, + device: Literal["cpu"] | None = None, + like: _SupportsArrayFunc | None = None, + fill_value: _FillValue | None = None, + hardmask: bool = False, +) -> MaskedArray[tuple[int], _DTypeT]: ... +@overload +def empty( + shape: SupportsIndex, + dtype: type[_ScalarT], + order: _OrderCF = "C", + *, + device: Literal["cpu"] | None = None, + like: _SupportsArrayFunc | None = None, + fill_value: _FillValue | None = None, + hardmask: bool = False, +) -> MaskedArray[tuple[int], np.dtype[_ScalarT]]: ... +@overload +def empty( + shape: SupportsIndex, + dtype: DTypeLike | None = None, + order: _OrderCF = "C", + *, + device: Literal["cpu"] | None = None, + like: _SupportsArrayFunc | None = None, + fill_value: _FillValue | None = None, + hardmask: bool = False, +) -> MaskedArray[tuple[int]]: ... +@overload # known shape +def empty( + shape: _AnyShapeT, + dtype: None = None, + order: _OrderCF = "C", + *, + device: Literal["cpu"] | None = None, + like: _SupportsArrayFunc | None = None, + fill_value: _FillValue | None = None, + hardmask: bool = False, +) -> MaskedArray[_AnyShapeT, np.dtype[np.float64]]: ... +@overload +def empty( + shape: _AnyShapeT, + dtype: _DTypeT | _SupportsDType[_DTypeT], + order: _OrderCF = "C", + *, + device: Literal["cpu"] | None = None, + like: _SupportsArrayFunc | None = None, + fill_value: _FillValue | None = None, + hardmask: bool = False, +) -> MaskedArray[_AnyShapeT, _DTypeT]: ... +@overload +def empty( + shape: _AnyShapeT, + dtype: type[_ScalarT], + order: _OrderCF = "C", + *, + device: Literal["cpu"] | None = None, + like: _SupportsArrayFunc | None = None, + fill_value: _FillValue | None = None, + hardmask: bool = False, +) -> MaskedArray[_AnyShapeT, np.dtype[_ScalarT]]: ... +@overload +def empty( + shape: _AnyShapeT, + dtype: DTypeLike | None = None, + order: _OrderCF = "C", + *, + device: Literal["cpu"] | None = None, + like: _SupportsArrayFunc | None = None, + fill_value: _FillValue | None = None, + hardmask: bool = False, +) -> MaskedArray[_AnyShapeT]: ... +@overload # unknown shape +def empty( + shape: _ShapeLike, + dtype: None = None, + order: _OrderCF = "C", + *, + device: Literal["cpu"] | None = None, + like: _SupportsArrayFunc | None = None, + fill_value: _FillValue | None = None, + hardmask: bool = False, +) -> _MaskedArray[np.float64]: ... +@overload +def empty( + shape: _ShapeLike, + dtype: _DTypeT | _SupportsDType[_DTypeT], + order: _OrderCF = "C", + *, + device: Literal["cpu"] | None = None, + like: _SupportsArrayFunc | None = None, + fill_value: _FillValue | None = None, + hardmask: bool = False, +) -> MaskedArray[_AnyShape, _DTypeT]: ... +@overload +def empty( + shape: _ShapeLike, + dtype: type[_ScalarT], + order: _OrderCF = "C", + *, + device: Literal["cpu"] | None = None, + like: _SupportsArrayFunc | None = None, + fill_value: _FillValue | None = None, + hardmask: bool = False, +) -> _MaskedArray[_ScalarT]: ... +@overload +def empty( + shape: _ShapeLike, + dtype: DTypeLike | None = None, + *, + device: Literal["cpu"] | None = None, + like: _SupportsArrayFunc | None = None, + fill_value: _FillValue | None = None, + hardmask: bool = False, +) -> MaskedArray: ... + +# keep in sync with `_core.multiarray.empty_like` +@overload +def empty_like( + a: _MArrayT, + /, + dtype: None = None, + order: _OrderKACF = "K", + subok: bool = True, + shape: _ShapeLike | None = None, + *, + device: Literal["cpu"] | None = None, +) -> _MArrayT: ... +@overload +def empty_like( + a: _ArrayLike[_ScalarT], + /, + dtype: None = None, + order: _OrderKACF = "K", + subok: bool = True, + shape: _ShapeLike | None = None, + *, + device: Literal["cpu"] | None = None, +) -> _MaskedArray[_ScalarT]: ... +@overload +def empty_like( + a: Incomplete, + /, + dtype: _DTypeLike[_ScalarT], + order: _OrderKACF = "K", + subok: bool = True, + shape: _ShapeLike | None = None, + *, + device: Literal["cpu"] | None = None, +) -> _MaskedArray[_ScalarT]: ... +@overload +def empty_like( + a: Incomplete, + /, + dtype: DTypeLike | None = None, + order: _OrderKACF = "K", + subok: bool = True, + shape: _ShapeLike | None = None, + *, + device: Literal["cpu"] | None = None, +) -> _MaskedArray[Incomplete]: ... + +# This is a bit of a hack to avoid having to duplicate all those `empty` overloads for +# `ones` and `zeros`, that relies on the fact that empty/zeros/ones have identical +# type signatures, but may cause some type-checkers to report incorrect names in case +# of user errors. Mypy and Pyright seem to handle this just fine. +ones = empty +ones_like = empty_like +zeros = empty +zeros_like = empty_like + +# keep in sync with `_core.multiarray.frombuffer` +@overload +def frombuffer( + buffer: Buffer, + *, + count: SupportsIndex = -1, + offset: SupportsIndex = 0, + like: _SupportsArrayFunc | None = None, +) -> _MaskedArray[np.float64]: ... +@overload +def frombuffer( + buffer: Buffer, + dtype: _DTypeLike[_ScalarT], + count: SupportsIndex = -1, + offset: SupportsIndex = 0, + *, + like: _SupportsArrayFunc | None = None, +) -> _MaskedArray[_ScalarT]: ... +@overload +def frombuffer( + buffer: Buffer, + dtype: DTypeLike | None = float, + count: SupportsIndex = -1, + offset: SupportsIndex = 0, + *, + like: _SupportsArrayFunc | None = None, +) -> _MaskedArray[Incomplete]: ... + +# keep roughly in sync with `_core.numeric.fromfunction` +def fromfunction( + function: Callable[..., np.ndarray[_ShapeT, _DTypeT]], + shape: Sequence[int], + *, + dtype: DTypeLike | None = float, + like: _SupportsArrayFunc | None = None, + **kwargs: object, +) -> MaskedArray[_ShapeT, _DTypeT]: ... + +# keep roughly in sync with `_core.numeric.identity` +@overload +def identity( + n: int, + dtype: None = None, + *, + like: _SupportsArrayFunc | None = None, + fill_value: _FillValue | None = None, + hardmask: bool = False, +) -> MaskedArray[tuple[int, int], np.dtype[np.float64]]: ... +@overload +def identity( + n: int, + dtype: _DTypeLike[_ScalarT], + *, + like: _SupportsArrayFunc | None = None, + fill_value: _FillValue | None = None, + hardmask: bool = False, +) -> MaskedArray[tuple[int, int], np.dtype[_ScalarT]]: ... +@overload +def identity( + n: int, + dtype: DTypeLike | None = None, + *, + like: _SupportsArrayFunc | None = None, + fill_value: _FillValue | None = None, + hardmask: bool = False, +) -> MaskedArray[tuple[int, int], np.dtype[Incomplete]]: ... + +# keep roughly in sync with `_core.numeric.indices` +@overload +def indices( + dimensions: Sequence[int], + dtype: type[int] = int, + sparse: Literal[False] = False, + *, + fill_value: _FillValue | None = None, + hardmask: bool = False, +) -> _MaskedArray[np.intp]: ... +@overload +def indices( + dimensions: Sequence[int], + dtype: type[int], + sparse: Literal[True], + *, + fill_value: _FillValue | None = None, + hardmask: bool = False, +) -> tuple[_MaskedArray[np.intp], ...]: ... +@overload +def indices( + dimensions: Sequence[int], + dtype: type[int] = int, + *, + sparse: Literal[True], + fill_value: _FillValue | None = None, + hardmask: bool = False, +) -> tuple[_MaskedArray[np.intp], ...]: ... +@overload +def indices( + dimensions: Sequence[int], + dtype: _DTypeLike[_ScalarT], + sparse: Literal[False] = False, + *, + fill_value: _FillValue | None = None, + hardmask: bool = False, +) -> _MaskedArray[_ScalarT]: ... +@overload +def indices( + dimensions: Sequence[int], + dtype: _DTypeLike[_ScalarT], + sparse: Literal[True], + *, + fill_value: _FillValue | None = None, + hardmask: bool = False, +) -> tuple[_MaskedArray[_ScalarT], ...]: ... +@overload +def indices( + dimensions: Sequence[int], + dtype: DTypeLike | None = int, + sparse: Literal[False] = False, + *, + fill_value: _FillValue | None = None, + hardmask: bool = False, +) -> _MaskedArray[Incomplete]: ... +@overload +def indices( + dimensions: Sequence[int], + dtype: DTypeLike | None, + sparse: Literal[True], + *, + fill_value: _FillValue | None = None, + hardmask: bool = False, +) -> tuple[_MaskedArray[Incomplete], ...]: ... +@overload +def indices( + dimensions: Sequence[int], + dtype: DTypeLike | None = int, + *, + sparse: Literal[True], + fill_value: _FillValue | None = None, + hardmask: bool = False, +) -> tuple[_MaskedArray[Incomplete], ...]: ... + +# keep roughly in sync with `_core.fromnumeric.squeeze` +@overload +def squeeze( + a: _ArrayLike[_ScalarT], + axis: _ShapeLike | None = None, + *, + fill_value: _FillValue | None = None, + hardmask: bool = False, +) -> _MaskedArray[_ScalarT]: ... +@overload +def squeeze( + a: ArrayLike, + axis: _ShapeLike | None = None, + *, + fill_value: _FillValue | None = None, + hardmask: bool = False, +) -> _MaskedArray[Incomplete]: ... diff --git a/python/user_packages/Python313/site-packages/numpy/ma/extras.py b/python/user_packages/Python313/site-packages/numpy/ma/extras.py new file mode 100644 index 0000000000000000000000000000000000000000..82f1b6bcac5a3b39f59a9438d862112670560150 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/ma/extras.py @@ -0,0 +1,2266 @@ +""" +Masked arrays add-ons. + +A collection of utilities for `numpy.ma`. + +:author: Pierre Gerard-Marchant +:contact: pierregm_at_uga_dot_edu + +""" +__all__ = [ + 'apply_along_axis', 'apply_over_axes', 'atleast_1d', 'atleast_2d', + 'atleast_3d', 'average', 'clump_masked', 'clump_unmasked', 'column_stack', + 'compress_cols', 'compress_nd', 'compress_rowcols', 'compress_rows', + 'count_masked', 'corrcoef', 'cov', 'diagflat', 'dot', 'dstack', 'ediff1d', + 'flatnotmasked_contiguous', 'flatnotmasked_edges', 'hsplit', 'hstack', + 'isin', 'in1d', 'intersect1d', 'mask_cols', 'mask_rowcols', 'mask_rows', + 'masked_all', 'masked_all_like', 'median', 'mr_', 'ndenumerate', + 'notmasked_contiguous', 'notmasked_edges', 'polyfit', 'row_stack', + 'setdiff1d', 'setxor1d', 'stack', 'unique', 'union1d', 'vander', 'vstack', + ] + +import functools +import itertools +import warnings + +import numpy as np +from numpy import array as nxarray, ndarray +from numpy.lib._function_base_impl import _ureduce +from numpy.lib._index_tricks_impl import AxisConcatenator +from numpy.lib.array_utils import normalize_axis_index, normalize_axis_tuple + +from . import core as ma +from .core import ( # noqa: F401 + MAError, + MaskedArray, + add, + array, + asarray, + concatenate, + count, + dot, + filled, + get_masked_subclass, + getdata, + getmask, + getmaskarray, + make_mask_descr, + mask_or, + masked, + masked_array, + nomask, + ones, + sort, + zeros, +) + + +def issequence(seq): + """ + Is seq a sequence (ndarray, list or tuple)? + + """ + return isinstance(seq, (ndarray, tuple, list)) + + +def count_masked(arr, axis=None): + """ + Count the number of masked elements along the given axis. + + Parameters + ---------- + arr : array_like + An array with (possibly) masked elements. + axis : int, optional + Axis along which to count. If None (default), a flattened + version of the array is used. + + Returns + ------- + count : int, ndarray + The total number of masked elements (axis=None) or the number + of masked elements along each slice of the given axis. + + See Also + -------- + MaskedArray.count : Count non-masked elements. + + Examples + -------- + >>> import numpy as np + >>> a = np.arange(9).reshape((3,3)) + >>> a = np.ma.array(a) + >>> a[1, 0] = np.ma.masked + >>> a[1, 2] = np.ma.masked + >>> a[2, 1] = np.ma.masked + >>> a + masked_array( + data=[[0, 1, 2], + [--, 4, --], + [6, --, 8]], + mask=[[False, False, False], + [ True, False, True], + [False, True, False]], + fill_value=999999) + >>> np.ma.count_masked(a) + 3 + + When the `axis` keyword is used an array is returned. + + >>> np.ma.count_masked(a, axis=0) + array([1, 1, 1]) + >>> np.ma.count_masked(a, axis=1) + array([0, 2, 1]) + + """ + m = getmaskarray(arr) + return m.sum(axis) + + +def masked_all(shape, dtype=float): + """ + Empty masked array with all elements masked. + + Return an empty masked array of the given shape and dtype, where all the + data are masked. + + Parameters + ---------- + shape : int or tuple of ints + Shape of the required MaskedArray, e.g., ``(2, 3)`` or ``2``. + dtype : dtype, optional + Data type of the output. + + Returns + ------- + a : MaskedArray + A masked array with all data masked. + + See Also + -------- + masked_all_like : Empty masked array modelled on an existing array. + + Notes + ----- + Unlike other masked array creation functions (e.g. `numpy.ma.zeros`, + `numpy.ma.ones`, `numpy.ma.full`), `masked_all` does not initialize the + values of the array, and may therefore be marginally faster. However, + the values stored in the newly allocated array are arbitrary. For + reproducible behavior, be sure to set each element of the array before + reading. + + Examples + -------- + >>> import numpy as np + >>> np.ma.masked_all((3, 3)) + masked_array( + data=[[--, --, --], + [--, --, --], + [--, --, --]], + mask=[[ True, True, True], + [ True, True, True], + [ True, True, True]], + fill_value=1e+20, + dtype=float64) + + The `dtype` parameter defines the underlying data type. + + >>> a = np.ma.masked_all((3, 3)) + >>> a.dtype + dtype('float64') + >>> a = np.ma.masked_all((3, 3), dtype=np.int32) + >>> a.dtype + dtype('int32') + + """ + a = masked_array(np.empty(shape, dtype), + mask=np.ones(shape, make_mask_descr(dtype))) + return a + + +def masked_all_like(arr): + """ + Empty masked array with the properties of an existing array. + + Return an empty masked array of the same shape and dtype as + the array `arr`, where all the data are masked. + + Parameters + ---------- + arr : ndarray + An array describing the shape and dtype of the required MaskedArray. + + Returns + ------- + a : MaskedArray + A masked array with all data masked. + + Raises + ------ + AttributeError + If `arr` doesn't have a shape attribute (i.e. not an ndarray) + + See Also + -------- + masked_all : Empty masked array with all elements masked. + + Notes + ----- + Unlike other masked array creation functions (e.g. `numpy.ma.zeros_like`, + `numpy.ma.ones_like`, `numpy.ma.full_like`), `masked_all_like` does not + initialize the values of the array, and may therefore be marginally + faster. However, the values stored in the newly allocated array are + arbitrary. For reproducible behavior, be sure to set each element of the + array before reading. + + Examples + -------- + >>> import numpy as np + >>> arr = np.zeros((2, 3), dtype=np.float32) + >>> arr + array([[0., 0., 0.], + [0., 0., 0.]], dtype=float32) + >>> np.ma.masked_all_like(arr) + masked_array( + data=[[--, --, --], + [--, --, --]], + mask=[[ True, True, True], + [ True, True, True]], + fill_value=np.float64(1e+20), + dtype=float32) + + The dtype of the masked array matches the dtype of `arr`. + + >>> arr.dtype + dtype('float32') + >>> np.ma.masked_all_like(arr).dtype + dtype('float32') + + """ + a = np.empty_like(arr).view(MaskedArray) + a._mask = np.ones(a.shape, dtype=make_mask_descr(a.dtype)) + return a + + +#####-------------------------------------------------------------------------- +#---- --- Standard functions --- +#####-------------------------------------------------------------------------- + +def _fromnxfunction_function(_fromnxfunction): + """ + Decorator to wrap a "_fromnxfunction" function, wrapping a numpy function as a + masked array function, with proper docstring and name. + + Parameters + ---------- + _fromnxfunction : ({params}) -> ndarray, {params}) -> masked_array + Wrapper function that calls the wrapped numpy function + + Returns + ------- + decorator : (f: ({params}) -> ndarray) -> ({params}) -> masked_array + Function that accepts a numpy function and returns a masked array function + + """ + def decorator(npfunc, /): + def wrapper(*args, **kwargs): + return _fromnxfunction(npfunc, *args, **kwargs) + + functools.update_wrapper(wrapper, npfunc, assigned=("__name__", "__qualname__")) + wrapper.__doc__ = ma.doc_note( + npfunc.__doc__, + "The function is applied to both the ``_data`` and the ``_mask``, if any.", + ) + return wrapper + + return decorator + + +@_fromnxfunction_function +def _fromnxfunction_single(npfunc, a, /, *args, **kwargs): + """ + Wraps a NumPy function that can be called with a single array argument followed by + auxiliary args that are passed verbatim for both the data and mask calls. + """ + return masked_array( + data=npfunc(np.asarray(a), *args, **kwargs), + mask=npfunc(getmaskarray(a), *args, **kwargs), + ) + + +@_fromnxfunction_function +def _fromnxfunction_seq(npfunc, arys, /, *args, **kwargs): + """ + Wraps a NumPy function that can be called with a single sequence of arrays followed + by auxiliary args that are passed verbatim for both the data and mask calls. + """ + return masked_array( + data=npfunc(tuple(np.asarray(a) for a in arys), *args, **kwargs), + mask=npfunc(tuple(getmaskarray(a) for a in arys), *args, **kwargs), + ) + +@_fromnxfunction_function +def _fromnxfunction_allargs(npfunc, /, *arys, **kwargs): + """ + Wraps a NumPy function that can be called with multiple array arguments. + All args are converted to arrays even if they are not so already. + This makes it possible to process scalars as 1-D arrays. + Only keyword arguments are passed through verbatim for the data and mask calls. + Arrays arguments are processed independently and the results are returned in a list. + If only one arg is present, the return value is just the processed array instead of + a list. + """ + out = tuple( + masked_array( + data=npfunc(np.asarray(a), **kwargs), + mask=npfunc(getmaskarray(a), **kwargs), + ) + for a in arys + ) + return out[0] if len(out) == 1 else out + + +atleast_1d = _fromnxfunction_allargs(np.atleast_1d) +atleast_2d = _fromnxfunction_allargs(np.atleast_2d) +atleast_3d = _fromnxfunction_allargs(np.atleast_3d) + +vstack = row_stack = _fromnxfunction_seq(np.vstack) +hstack = _fromnxfunction_seq(np.hstack) +column_stack = _fromnxfunction_seq(np.column_stack) +dstack = _fromnxfunction_seq(np.dstack) +stack = _fromnxfunction_seq(np.stack) + +hsplit = _fromnxfunction_single(np.hsplit) +diagflat = _fromnxfunction_single(np.diagflat) + + +#####-------------------------------------------------------------------------- +#---- +#####-------------------------------------------------------------------------- +def flatten_inplace(seq): + """Flatten a sequence in place.""" + k = 0 + while (k != len(seq)): + while hasattr(seq[k], '__iter__'): + seq[k:(k + 1)] = seq[k] + k += 1 + return seq + + +def apply_along_axis(func1d, axis, arr, *args, **kwargs): + """ + (This docstring should be overwritten) + """ + arr = array(arr, copy=False, subok=True) + nd = arr.ndim + axis = normalize_axis_index(axis, nd) + ind = [0] * (nd - 1) + i = np.zeros(nd, 'O') + indlist = list(range(nd)) + indlist.remove(axis) + i[axis] = slice(None, None) + outshape = np.asarray(arr.shape).take(indlist) + i.put(indlist, ind) + res = func1d(arr[tuple(i.tolist())], *args, **kwargs) + # if res is a number, then we have a smaller output array + asscalar = np.isscalar(res) + if not asscalar: + try: + len(res) + except TypeError: + asscalar = True + # Note: we shouldn't set the dtype of the output from the first result + # so we force the type to object, and build a list of dtypes. We'll + # just take the largest, to avoid some downcasting + dtypes = [] + if asscalar: + dtypes.append(np.asarray(res).dtype) + outarr = zeros(outshape, object) + outarr[tuple(ind)] = res + Ntot = np.prod(outshape) + k = 1 + while k < Ntot: + # increment the index + ind[-1] += 1 + n = -1 + while (ind[n] >= outshape[n]) and (n > (1 - nd)): + ind[n - 1] += 1 + ind[n] = 0 + n -= 1 + i.put(indlist, ind) + res = func1d(arr[tuple(i.tolist())], *args, **kwargs) + outarr[tuple(ind)] = res + dtypes.append(asarray(res).dtype) + k += 1 + else: + res = array(res, copy=False, subok=True) + j = i.copy() + j[axis] = ([slice(None, None)] * res.ndim) + j.put(indlist, ind) + Ntot = np.prod(outshape) + holdshape = outshape + outshape = list(arr.shape) + outshape[axis] = res.shape + dtypes.append(asarray(res).dtype) + outshape = flatten_inplace(outshape) + outarr = zeros(outshape, object) + outarr[tuple(flatten_inplace(j.tolist()))] = res + k = 1 + while k < Ntot: + # increment the index + ind[-1] += 1 + n = -1 + while (ind[n] >= holdshape[n]) and (n > (1 - nd)): + ind[n - 1] += 1 + ind[n] = 0 + n -= 1 + i.put(indlist, ind) + j.put(indlist, ind) + res = func1d(arr[tuple(i.tolist())], *args, **kwargs) + outarr[tuple(flatten_inplace(j.tolist()))] = res + dtypes.append(asarray(res).dtype) + k += 1 + max_dtypes = np.dtype(np.asarray(dtypes).max()) + if not hasattr(arr, '_mask'): + result = np.asarray(outarr, dtype=max_dtypes) + else: + result = asarray(outarr, dtype=max_dtypes) + result.fill_value = ma.default_fill_value(result) + return result + + +apply_along_axis.__doc__ = np.apply_along_axis.__doc__ + + +def apply_over_axes(func, a, axes): + """ + (This docstring will be overwritten) + """ + val = asarray(a) + N = a.ndim + if array(axes).ndim == 0: + axes = (axes,) + for axis in axes: + if axis < 0: + axis = N + axis + args = (val, axis) + res = func(*args) + if res.ndim == val.ndim: + val = res + else: + res = ma.expand_dims(res, axis) + if res.ndim == val.ndim: + val = res + else: + raise ValueError("function is not returning " + "an array of the correct shape") + return val + + +if apply_over_axes.__doc__ is not None: + apply_over_axes.__doc__ = np.apply_over_axes.__doc__[ + :np.apply_over_axes.__doc__.find('Notes')].rstrip() + \ + """ + + Examples + -------- + >>> import numpy as np + >>> a = np.ma.arange(24).reshape(2,3,4) + >>> a[:,0,1] = np.ma.masked + >>> a[:,1,:] = np.ma.masked + >>> a + masked_array( + data=[[[0, --, 2, 3], + [--, --, --, --], + [8, 9, 10, 11]], + [[12, --, 14, 15], + [--, --, --, --], + [20, 21, 22, 23]]], + mask=[[[False, True, False, False], + [ True, True, True, True], + [False, False, False, False]], + [[False, True, False, False], + [ True, True, True, True], + [False, False, False, False]]], + fill_value=999999) + >>> np.ma.apply_over_axes(np.ma.sum, a, [0,2]) + masked_array( + data=[[[46], + [--], + [124]]], + mask=[[[False], + [ True], + [False]]], + fill_value=999999) + + Tuple axis arguments to ufuncs are equivalent: + + >>> np.ma.sum(a, axis=(0,2)).reshape((1,-1,1)) + masked_array( + data=[[[46], + [--], + [124]]], + mask=[[[False], + [ True], + [False]]], + fill_value=999999) + """ + + +def average(a, axis=None, weights=None, returned=False, *, + keepdims=np._NoValue): + """ + Return the weighted average of array over the given axis. + + Parameters + ---------- + a : array_like + Data to be averaged. + Masked entries are not taken into account in the computation. + axis : None or int or tuple of ints, optional + Axis or axes along which to average `a`. The default, + `axis=None`, will average over all of the elements of the input array. + If axis is a tuple of ints, averaging is performed on all of the axes + specified in the tuple instead of a single axis or all the axes as + before. + weights : array_like, optional + An array of weights associated with the values in `a`. Each value in + `a` contributes to the average according to its associated weight. + The array of weights must be the same shape as `a` if no axis is + specified, otherwise the weights must have dimensions and shape + consistent with `a` along the specified axis. + If `weights=None`, then all data in `a` are assumed to have a + weight equal to one. + The calculation is:: + + avg = sum(a * weights) / sum(weights) + + where the sum is over all included elements. + The only constraint on the values of `weights` is that `sum(weights)` + must not be 0. + returned : bool, optional + Flag indicating whether a tuple ``(result, sum of weights)`` + should be returned as output (True), or just the result (False). + Default is False. + keepdims : bool, optional + If this is set to True, the axes which are reduced are left + in the result as dimensions with size one. With this option, + the result will broadcast correctly against the original `a`. + *Note:* `keepdims` will not work with instances of `numpy.matrix` + or other classes whose methods do not support `keepdims`. + + .. versionadded:: 1.23.0 + + Returns + ------- + average, [sum_of_weights] : (tuple of) scalar or MaskedArray + The average along the specified axis. When returned is `True`, + return a tuple with the average as the first element and the sum + of the weights as the second element. The return type is `np.float64` + if `a` is of integer type and floats smaller than `float64`, or the + input data-type, otherwise. If returned, `sum_of_weights` is always + `float64`. + + Raises + ------ + ZeroDivisionError + When all weights along axis are zero. See `numpy.ma.average` for a + version robust to this type of error. + TypeError + When `weights` does not have the same shape as `a`, and `axis=None`. + ValueError + When `weights` does not have dimensions and shape consistent with `a` + along specified `axis`. + + Examples + -------- + >>> import numpy as np + >>> a = np.ma.array([1., 2., 3., 4.], mask=[False, False, True, True]) + >>> np.ma.average(a, weights=[3, 1, 0, 0]) + 1.25 + + >>> x = np.ma.arange(6.).reshape(3, 2) + >>> x + masked_array( + data=[[0., 1.], + [2., 3.], + [4., 5.]], + mask=False, + fill_value=1e+20) + >>> data = np.arange(8).reshape((2, 2, 2)) + >>> data + array([[[0, 1], + [2, 3]], + [[4, 5], + [6, 7]]]) + >>> np.ma.average(data, axis=(0, 1), weights=[[1./4, 3./4], [1., 1./2]]) + masked_array(data=[3.4, 4.4], + mask=[False, False], + fill_value=1e+20) + >>> np.ma.average(data, axis=0, weights=[[1./4, 3./4], [1., 1./2]]) + Traceback (most recent call last): + ... + ValueError: Shape of weights must be consistent + with shape of a along specified axis. + + >>> avg, sumweights = np.ma.average(x, axis=0, weights=[1, 2, 3], + ... returned=True) + >>> avg + masked_array(data=[2.6666666666666665, 3.6666666666666665], + mask=[False, False], + fill_value=1e+20) + + With ``keepdims=True``, the following result has shape (3, 1). + + >>> np.ma.average(x, axis=1, keepdims=True) + masked_array( + data=[[0.5], + [2.5], + [4.5]], + mask=False, + fill_value=1e+20) + """ + a = asarray(a) + m = getmask(a) + + if axis is not None: + axis = normalize_axis_tuple(axis, a.ndim, argname="axis") + + if keepdims is np._NoValue: + # Don't pass on the keepdims argument if one wasn't given. + keepdims_kw = {} + else: + keepdims_kw = {'keepdims': keepdims} + + if weights is None: + avg = a.mean(axis, **keepdims_kw) + scl = avg.dtype.type(a.count(axis)) + else: + wgt = asarray(weights) + + if issubclass(a.dtype.type, (np.integer, np.bool)): + result_dtype = np.result_type(a.dtype, wgt.dtype, 'f8') + else: + result_dtype = np.result_type(a.dtype, wgt.dtype) + + # Sanity checks + if a.shape != wgt.shape: + if axis is None: + raise TypeError( + "Axis must be specified when shapes of a and weights " + "differ.") + if wgt.shape != tuple(a.shape[ax] for ax in axis): + raise ValueError( + "Shape of weights must be consistent with " + "shape of a along specified axis.") + + # setup wgt to broadcast along axis + wgt = wgt.transpose(np.argsort(axis)) + wgt = wgt.reshape(tuple((s if ax in axis else 1) + for ax, s in enumerate(a.shape))) + + if m is not nomask: + wgt = wgt * (~a.mask) + wgt.mask |= a.mask + + scl = wgt.sum(axis=axis, dtype=result_dtype, **keepdims_kw) + avg = np.multiply(a, wgt, + dtype=result_dtype).sum(axis, **keepdims_kw) / scl + + if returned: + if scl.shape != avg.shape: + scl = np.broadcast_to(scl, avg.shape).copy() + return avg, scl + else: + return avg + + +def median(a, axis=None, out=None, overwrite_input=False, keepdims=False): + """ + Compute the median along the specified axis. + + Returns the median of the array elements. + + Parameters + ---------- + a : array_like + Input array or object that can be converted to an array. + axis : int, optional + Axis along which the medians are computed. The default (None) is + to compute the median along a flattened version of the array. + out : ndarray, optional + Alternative output array in which to place the result. It must + have the same shape and buffer length as the expected output + but the type will be cast if necessary. + overwrite_input : bool, optional + If True, then allow use of memory of input array (a) for + calculations. The input array will be modified by the call to + median. This will save memory when you do not need to preserve + the contents of the input array. Treat the input as undefined, + but it will probably be fully or partially sorted. Default is + False. Note that, if `overwrite_input` is True, and the input + is not already an `ndarray`, an error will be raised. + keepdims : bool, optional + If this is set to True, the axes which are reduced are left + in the result as dimensions with size one. With this option, + the result will broadcast correctly against the input array. + + Returns + ------- + median : ndarray + A new array holding the result is returned unless out is + specified, in which case a reference to out is returned. + Return data-type is `float64` for integers and floats smaller than + `float64`, or the input data-type, otherwise. + + See Also + -------- + mean + + Notes + ----- + Given a vector ``V`` with ``N`` non masked values, the median of ``V`` + is the middle value of a sorted copy of ``V`` (``Vs``) - i.e. + ``Vs[(N-1)/2]``, when ``N`` is odd, or ``{Vs[N/2 - 1] + Vs[N/2]}/2`` + when ``N`` is even. + + Examples + -------- + >>> import numpy as np + >>> x = np.ma.array(np.arange(8), mask=[0]*4 + [1]*4) + >>> np.ma.median(x) + 1.5 + + >>> x = np.ma.array(np.arange(10).reshape(2, 5), mask=[0]*6 + [1]*4) + >>> np.ma.median(x) + 2.5 + >>> np.ma.median(x, axis=-1, overwrite_input=True) + masked_array(data=[2.0, 5.0], + mask=[False, False], + fill_value=1e+20) + + """ + if not hasattr(a, 'mask'): + m = np.median(getdata(a, subok=True), axis=axis, + out=out, overwrite_input=overwrite_input, + keepdims=keepdims) + if isinstance(m, np.ndarray) and 1 <= m.ndim: + return masked_array(m, copy=False) + else: + return m + + return _ureduce(a, func=_median, keepdims=keepdims, axis=axis, out=out, + overwrite_input=overwrite_input) + + +def _median(a, axis=None, out=None, overwrite_input=False): + # when an unmasked NaN is present return it, so we need to sort the NaN + # values behind the mask + if np.issubdtype(a.dtype, np.inexact): + fill_value = np.inf + else: + fill_value = None + if overwrite_input: + if axis is None: + asorted = a.ravel() + asorted.sort(fill_value=fill_value) + else: + a.sort(axis=axis, fill_value=fill_value) + asorted = a + else: + asorted = sort(a, axis=axis, fill_value=fill_value) + + if axis is None: + axis = 0 + else: + axis = normalize_axis_index(axis, asorted.ndim) + + if asorted.shape[axis] == 0: + # for empty axis integer indices fail so use slicing to get same result + # as median (which is mean of empty slice = nan) + indexer = [slice(None)] * asorted.ndim + indexer[axis] = slice(0, 0) + indexer = tuple(indexer) + return np.ma.mean(asorted[indexer], axis=axis, out=out) + + if asorted.ndim == 1: + idx, odd = divmod(count(asorted), 2) + mid = asorted[idx + odd - 1:idx + 1] + if np.issubdtype(asorted.dtype, np.inexact) and asorted.size > 0: + # avoid inf / x = masked + s = mid.sum(out=out) + if not odd: + s = np.true_divide(s, 2., casting='safe', out=out) + s = np.lib._utils_impl._median_nancheck(asorted, s, axis) + else: + s = mid.mean(out=out) + + # if result is masked either the input contained enough + # minimum_fill_value so that it would be the median or all values + # masked + if np.ma.is_masked(s) and not np.all(asorted.mask): + return np.ma.minimum_fill_value(asorted) + return s + + counts = count(asorted, axis=axis, keepdims=True) + h = counts // 2 + + # duplicate high if odd number of elements so mean does nothing + odd = counts % 2 == 1 + l = np.where(odd, h, h - 1) + + lh = np.concatenate([l, h], axis=axis) + + # get low and high median + low_high = np.take_along_axis(asorted, lh, axis=axis) + + def replace_masked(s): + # Replace masked entries with minimum_full_value unless it all values + # are masked. This is required as the sort order of values equal or + # larger than the fill value is undefined and a valid value placed + # elsewhere, e.g. [4, --, inf]. + if np.ma.is_masked(s): + rep = (~np.all(asorted.mask, axis=axis, keepdims=True)) & s.mask + s.data[rep] = np.ma.minimum_fill_value(asorted) + s.mask[rep] = False + + replace_masked(low_high) + + if np.issubdtype(asorted.dtype, np.inexact): + # avoid inf / x = masked + s = np.ma.sum(low_high, axis=axis, out=out) + np.true_divide(s.data, 2., casting='unsafe', out=s.data) + + s = np.lib._utils_impl._median_nancheck(asorted, s, axis) + else: + s = np.ma.mean(low_high, axis=axis, out=out) + + return s + + +def compress_nd(x, axis=None): + """Suppress slices from multiple dimensions which contain masked values. + + Parameters + ---------- + x : array_like, MaskedArray + The array to operate on. If not a MaskedArray instance (or if no array + elements are masked), `x` is interpreted as a MaskedArray with `mask` + set to `nomask`. + axis : tuple of ints or int, optional + Which dimensions to suppress slices from can be configured with this + parameter. + - If axis is a tuple of ints, those are the axes to suppress slices from. + - If axis is an int, then that is the only axis to suppress slices from. + - If axis is None, all axis are selected. + + Returns + ------- + compress_array : ndarray + The compressed array. + + Examples + -------- + >>> import numpy as np + >>> arr = [[1, 2], [3, 4]] + >>> mask = [[0, 1], [0, 0]] + >>> x = np.ma.array(arr, mask=mask) + >>> np.ma.compress_nd(x, axis=0) + array([[3, 4]]) + >>> np.ma.compress_nd(x, axis=1) + array([[1], + [3]]) + >>> np.ma.compress_nd(x) + array([[3]]) + + """ + x = asarray(x) + m = getmask(x) + # Set axis to tuple of ints + if axis is None: + axis = tuple(range(x.ndim)) + else: + axis = normalize_axis_tuple(axis, x.ndim) + + # Nothing is masked: return x + if m is nomask or not m.any(): + return x._data + # All is masked: return empty + if m.all(): + return nxarray([]) + # Filter elements through boolean indexing + data = x._data + for ax in axis: + axes = tuple(list(range(ax)) + list(range(ax + 1, x.ndim))) + data = data[(slice(None),) * ax + (~m.any(axis=axes),)] + return data + + +def compress_rowcols(x, axis=None): + """ + Suppress the rows and/or columns of a 2-D array that contain + masked values. + + The suppression behavior is selected with the `axis` parameter. + + - If axis is None, both rows and columns are suppressed. + - If axis is 0, only rows are suppressed. + - If axis is 1 or -1, only columns are suppressed. + + Parameters + ---------- + x : array_like, MaskedArray + The array to operate on. If not a MaskedArray instance (or if no array + elements are masked), `x` is interpreted as a MaskedArray with + `mask` set to `nomask`. Must be a 2D array. + axis : int, optional + Axis along which to perform the operation. Default is None. + + Returns + ------- + compressed_array : ndarray + The compressed array. + + Examples + -------- + >>> import numpy as np + >>> x = np.ma.array(np.arange(9).reshape(3, 3), mask=[[1, 0, 0], + ... [1, 0, 0], + ... [0, 0, 0]]) + >>> x + masked_array( + data=[[--, 1, 2], + [--, 4, 5], + [6, 7, 8]], + mask=[[ True, False, False], + [ True, False, False], + [False, False, False]], + fill_value=999999) + + >>> np.ma.compress_rowcols(x) + array([[7, 8]]) + >>> np.ma.compress_rowcols(x, 0) + array([[6, 7, 8]]) + >>> np.ma.compress_rowcols(x, 1) + array([[1, 2], + [4, 5], + [7, 8]]) + + """ + if asarray(x).ndim != 2: + raise NotImplementedError("compress_rowcols works for 2D arrays only.") + return compress_nd(x, axis=axis) + + +def compress_rows(a): + """ + Suppress whole rows of a 2-D array that contain masked values. + + This is equivalent to ``np.ma.compress_rowcols(a, 0)``, see + `compress_rowcols` for details. + + Parameters + ---------- + x : array_like, MaskedArray + The array to operate on. If not a MaskedArray instance (or if no array + elements are masked), `x` is interpreted as a MaskedArray with + `mask` set to `nomask`. Must be a 2D array. + + Returns + ------- + compressed_array : ndarray + The compressed array. + + See Also + -------- + compress_rowcols + + Examples + -------- + >>> import numpy as np + >>> a = np.ma.array(np.arange(9).reshape(3, 3), mask=[[1, 0, 0], + ... [1, 0, 0], + ... [0, 0, 0]]) + >>> np.ma.compress_rows(a) + array([[6, 7, 8]]) + + """ + a = asarray(a) + if a.ndim != 2: + raise NotImplementedError("compress_rows works for 2D arrays only.") + return compress_rowcols(a, 0) + + +def compress_cols(a): + """ + Suppress whole columns of a 2-D array that contain masked values. + + This is equivalent to ``np.ma.compress_rowcols(a, 1)``, see + `compress_rowcols` for details. + + Parameters + ---------- + x : array_like, MaskedArray + The array to operate on. If not a MaskedArray instance (or if no array + elements are masked), `x` is interpreted as a MaskedArray with + `mask` set to `nomask`. Must be a 2D array. + + Returns + ------- + compressed_array : ndarray + The compressed array. + + See Also + -------- + compress_rowcols + + Examples + -------- + >>> import numpy as np + >>> a = np.ma.array(np.arange(9).reshape(3, 3), mask=[[1, 0, 0], + ... [1, 0, 0], + ... [0, 0, 0]]) + >>> np.ma.compress_cols(a) + array([[1, 2], + [4, 5], + [7, 8]]) + + """ + a = asarray(a) + if a.ndim != 2: + raise NotImplementedError("compress_cols works for 2D arrays only.") + return compress_rowcols(a, 1) + + +def mask_rowcols(a, axis=None): + """ + Mask rows and/or columns of a 2D array that contain masked values. + + Mask whole rows and/or columns of a 2D array that contain + masked values. The masking behavior is selected using the + `axis` parameter. + + - If `axis` is None, rows *and* columns are masked. + - If `axis` is 0, only rows are masked. + - If `axis` is 1 or -1, only columns are masked. + + Parameters + ---------- + a : array_like, MaskedArray + The array to mask. If not a MaskedArray instance (or if no array + elements are masked), the result is a MaskedArray with `mask` set + to `nomask` (False). Must be a 2D array. + axis : int, optional + Axis along which to perform the operation. If None, applies to a + flattened version of the array. + + Returns + ------- + a : MaskedArray + A modified version of the input array, masked depending on the value + of the `axis` parameter. + + Raises + ------ + NotImplementedError + If input array `a` is not 2D. + + See Also + -------- + mask_rows : Mask rows of a 2D array that contain masked values. + mask_cols : Mask cols of a 2D array that contain masked values. + masked_where : Mask where a condition is met. + + Notes + ----- + The input array's mask is modified by this function. + + Examples + -------- + >>> import numpy as np + >>> a = np.zeros((3, 3), dtype=int) + >>> a[1, 1] = 1 + >>> a + array([[0, 0, 0], + [0, 1, 0], + [0, 0, 0]]) + >>> a = np.ma.masked_equal(a, 1) + >>> a + masked_array( + data=[[0, 0, 0], + [0, --, 0], + [0, 0, 0]], + mask=[[False, False, False], + [False, True, False], + [False, False, False]], + fill_value=1) + >>> np.ma.mask_rowcols(a) + masked_array( + data=[[0, --, 0], + [--, --, --], + [0, --, 0]], + mask=[[False, True, False], + [ True, True, True], + [False, True, False]], + fill_value=1) + + """ + a = array(a, subok=False) + if a.ndim != 2: + raise NotImplementedError("mask_rowcols works for 2D arrays only.") + m = getmask(a) + # Nothing is masked: return a + if m is nomask or not m.any(): + return a + maskedval = m.nonzero() + a._mask = a._mask.copy() + if not axis: + a[np.unique(maskedval[0])] = masked + if axis in [None, 1, -1]: + a[:, np.unique(maskedval[1])] = masked + return a + + +def mask_rows(a, axis=np._NoValue): + """ + Mask rows of a 2D array that contain masked values. + + This function is a shortcut to ``mask_rowcols`` with `axis` equal to 0. + + See Also + -------- + mask_rowcols : Mask rows and/or columns of a 2D array. + masked_where : Mask where a condition is met. + + Examples + -------- + >>> import numpy as np + >>> a = np.zeros((3, 3), dtype=int) + >>> a[1, 1] = 1 + >>> a + array([[0, 0, 0], + [0, 1, 0], + [0, 0, 0]]) + >>> a = np.ma.masked_equal(a, 1) + >>> a + masked_array( + data=[[0, 0, 0], + [0, --, 0], + [0, 0, 0]], + mask=[[False, False, False], + [False, True, False], + [False, False, False]], + fill_value=1) + + >>> np.ma.mask_rows(a) + masked_array( + data=[[0, 0, 0], + [--, --, --], + [0, 0, 0]], + mask=[[False, False, False], + [ True, True, True], + [False, False, False]], + fill_value=1) + + """ + if axis is not np._NoValue: + # remove the axis argument when this deprecation expires + # NumPy 1.18.0, 2019-11-28 + warnings.warn( + "The axis argument has always been ignored, in future passing it " + "will raise TypeError", DeprecationWarning, stacklevel=2) + return mask_rowcols(a, 0) + + +def mask_cols(a, axis=np._NoValue): + """ + Mask columns of a 2D array that contain masked values. + + This function is a shortcut to ``mask_rowcols`` with `axis` equal to 1. + + See Also + -------- + mask_rowcols : Mask rows and/or columns of a 2D array. + masked_where : Mask where a condition is met. + + Examples + -------- + >>> import numpy as np + >>> a = np.zeros((3, 3), dtype=int) + >>> a[1, 1] = 1 + >>> a + array([[0, 0, 0], + [0, 1, 0], + [0, 0, 0]]) + >>> a = np.ma.masked_equal(a, 1) + >>> a + masked_array( + data=[[0, 0, 0], + [0, --, 0], + [0, 0, 0]], + mask=[[False, False, False], + [False, True, False], + [False, False, False]], + fill_value=1) + >>> np.ma.mask_cols(a) + masked_array( + data=[[0, --, 0], + [0, --, 0], + [0, --, 0]], + mask=[[False, True, False], + [False, True, False], + [False, True, False]], + fill_value=1) + + """ + if axis is not np._NoValue: + # remove the axis argument when this deprecation expires + # NumPy 1.18.0, 2019-11-28 + warnings.warn( + "The axis argument has always been ignored, in future passing it " + "will raise TypeError", DeprecationWarning, stacklevel=2) + return mask_rowcols(a, 1) + + +#####-------------------------------------------------------------------------- +#---- --- arraysetops --- +#####-------------------------------------------------------------------------- + +def ediff1d(arr, to_end=None, to_begin=None): + """ + Compute the differences between consecutive elements of an array. + + This function is the equivalent of `numpy.ediff1d` that takes masked + values into account, see `numpy.ediff1d` for details. + + See Also + -------- + numpy.ediff1d : Equivalent function for ndarrays. + + Examples + -------- + >>> import numpy as np + >>> arr = np.ma.array([1, 2, 4, 7, 0]) + >>> np.ma.ediff1d(arr) + masked_array(data=[ 1, 2, 3, -7], + mask=False, + fill_value=999999) + + """ + arr = ma.asanyarray(arr).flat + ed = arr[1:] - arr[:-1] + arrays = [ed] + # + if to_begin is not None: + arrays.insert(0, to_begin) + if to_end is not None: + arrays.append(to_end) + # + if len(arrays) != 1: + # We'll save ourselves a copy of a potentially large array in the common + # case where neither to_begin or to_end was given. + ed = hstack(arrays) + # + return ed + + +def unique(ar1, return_index=False, return_inverse=False): + """ + Finds the unique elements of an array. + + Masked values are considered the same element (masked). The output array + is always a masked array. See `numpy.unique` for more details. + + See Also + -------- + numpy.unique : Equivalent function for ndarrays. + + Examples + -------- + >>> import numpy as np + >>> a = [1, 2, 1000, 2, 3] + >>> mask = [0, 0, 1, 0, 0] + >>> masked_a = np.ma.masked_array(a, mask) + >>> masked_a + masked_array(data=[1, 2, --, 2, 3], + mask=[False, False, True, False, False], + fill_value=999999) + >>> np.ma.unique(masked_a) + masked_array(data=[1, 2, 3, --], + mask=[False, False, False, True], + fill_value=999999) + >>> np.ma.unique(masked_a, return_index=True) + (masked_array(data=[1, 2, 3, --], + mask=[False, False, False, True], + fill_value=999999), array([0, 1, 4, 2])) + >>> np.ma.unique(masked_a, return_inverse=True) + (masked_array(data=[1, 2, 3, --], + mask=[False, False, False, True], + fill_value=999999), array([0, 1, 3, 1, 2])) + >>> np.ma.unique(masked_a, return_index=True, return_inverse=True) + (masked_array(data=[1, 2, 3, --], + mask=[False, False, False, True], + fill_value=999999), array([0, 1, 4, 2]), array([0, 1, 3, 1, 2])) + """ + output = np.unique(ar1, + return_index=return_index, + return_inverse=return_inverse) + if isinstance(output, tuple): + output = list(output) + output[0] = output[0].view(MaskedArray) + output = tuple(output) + else: + output = output.view(MaskedArray) + return output + + +def intersect1d(ar1, ar2, assume_unique=False): + """ + Returns the unique elements common to both arrays. + + Masked values are considered equal one to the other. + The output is always a masked array. + + See `numpy.intersect1d` for more details. + + See Also + -------- + numpy.intersect1d : Equivalent function for ndarrays. + + Examples + -------- + >>> import numpy as np + >>> x = np.ma.array([1, 3, 3, 3], mask=[0, 0, 0, 1]) + >>> y = np.ma.array([3, 1, 1, 1], mask=[0, 0, 0, 1]) + >>> np.ma.intersect1d(x, y) + masked_array(data=[1, 3, --], + mask=[False, False, True], + fill_value=999999) + + """ + if assume_unique: + aux = ma.concatenate((ar1, ar2)) + else: + # Might be faster than unique( intersect1d( ar1, ar2 ) )? + aux = ma.concatenate((unique(ar1), unique(ar2))) + aux.sort() + return aux[:-1][aux[1:] == aux[:-1]] + + +def setxor1d(ar1, ar2, assume_unique=False): + """ + Set exclusive-or of 1-D arrays with unique elements. + + The output is always a masked array. See `numpy.setxor1d` for more details. + + See Also + -------- + numpy.setxor1d : Equivalent function for ndarrays. + + Examples + -------- + >>> import numpy as np + >>> ar1 = np.ma.array([1, 2, 3, 2, 4]) + >>> ar2 = np.ma.array([2, 3, 5, 7, 5]) + >>> np.ma.setxor1d(ar1, ar2) + masked_array(data=[1, 4, 5, 7], + mask=False, + fill_value=999999) + + """ + if not assume_unique: + ar1 = unique(ar1) + ar2 = unique(ar2) + + aux = ma.concatenate((ar1, ar2), axis=None) + if aux.size == 0: + return aux + aux.sort() + auxf = aux.filled() +# flag = ediff1d( aux, to_end = 1, to_begin = 1 ) == 0 + flag = ma.concatenate(([True], (auxf[1:] != auxf[:-1]), [True])) +# flag2 = ediff1d( flag ) == 0 + flag2 = (flag[1:] == flag[:-1]) + return aux[flag2] + + +def in1d(ar1, ar2, assume_unique=False, invert=False): + """ + Test whether each element of an array is also present in a second + array. + + The output is always a masked array. + + We recommend using :func:`isin` instead of `in1d` for new code. + + See Also + -------- + isin : Version of this function that preserves the shape of ar1. + + Examples + -------- + >>> import numpy as np + >>> ar1 = np.ma.array([0, 1, 2, 5, 0]) + >>> ar2 = [0, 2] + >>> np.ma.in1d(ar1, ar2) + masked_array(data=[ True, False, True, False, True], + mask=False, + fill_value=True) + + """ + if not assume_unique: + ar1, rev_idx = unique(ar1, return_inverse=True) + ar2 = unique(ar2) + + ar = ma.concatenate((ar1, ar2)) + # We need this to be a stable sort, so always use 'mergesort' + # here. The values from the first array should always come before + # the values from the second array. + order = ar.argsort(kind='mergesort') + sar = ar[order] + if invert: + bool_ar = (sar[1:] != sar[:-1]) + else: + bool_ar = (sar[1:] == sar[:-1]) + flag = ma.concatenate((bool_ar, [invert])) + indx = order.argsort(kind='mergesort')[:len(ar1)] + + if assume_unique: + return flag[indx] + else: + return flag[indx][rev_idx] + + +def isin(element, test_elements, assume_unique=False, invert=False): + """ + Calculates `element in test_elements`, broadcasting over + `element` only. + + The output is always a masked array of the same shape as `element`. + See `numpy.isin` for more details. + + See Also + -------- + in1d : Flattened version of this function. + numpy.isin : Equivalent function for ndarrays. + + Examples + -------- + >>> import numpy as np + >>> element = np.ma.array([1, 2, 3, 4, 5, 6]) + >>> test_elements = [0, 2] + >>> np.ma.isin(element, test_elements) + masked_array(data=[False, True, False, False, False, False], + mask=False, + fill_value=True) + + """ + element = ma.asarray(element) + return in1d(element, test_elements, assume_unique=assume_unique, + invert=invert).reshape(element.shape) + + +def union1d(ar1, ar2): + """ + Union of two arrays. + + The output is always a masked array. See `numpy.union1d` for more details. + + See Also + -------- + numpy.union1d : Equivalent function for ndarrays. + + Examples + -------- + >>> import numpy as np + >>> ar1 = np.ma.array([1, 2, 3, 4]) + >>> ar2 = np.ma.array([3, 4, 5, 6]) + >>> np.ma.union1d(ar1, ar2) + masked_array(data=[1, 2, 3, 4, 5, 6], + mask=False, + fill_value=999999) + + """ + return unique(ma.concatenate((ar1, ar2), axis=None)) + + +def setdiff1d(ar1, ar2, assume_unique=False): + """ + Set difference of 1D arrays with unique elements. + + The output is always a masked array. See `numpy.setdiff1d` for more + details. + + See Also + -------- + numpy.setdiff1d : Equivalent function for ndarrays. + + Examples + -------- + >>> import numpy as np + >>> x = np.ma.array([1, 2, 3, 4], mask=[0, 1, 0, 1]) + >>> np.ma.setdiff1d(x, [1, 2]) + masked_array(data=[3, --], + mask=[False, True], + fill_value=999999) + + """ + if assume_unique: + ar1 = ma.asarray(ar1).ravel() + else: + ar1 = unique(ar1) + ar2 = unique(ar2) + return ar1[in1d(ar1, ar2, assume_unique=True, invert=True)] + + +############################################################################### +# Covariance # +############################################################################### + + +def _covhelper(x, y=None, rowvar=True, allow_masked=True): + """ + Private function for the computation of covariance and correlation + coefficients. + + """ + x = ma.array(x, ndmin=2, copy=True, dtype=float) + xmask = ma.getmaskarray(x) + # Quick exit if we can't process masked data + if not allow_masked and xmask.any(): + raise ValueError("Cannot process masked data.") + # + if x.shape[0] == 1: + rowvar = True + # Make sure that rowvar is either 0 or 1 + rowvar = int(bool(rowvar)) + axis = 1 - rowvar + if rowvar: + tup = (slice(None), None) + else: + tup = (None, slice(None)) + # + if y is None: + # Check if we can guarantee that the integers in the (N - ddof) + # normalisation can be accurately represented with single-precision + # before computing the dot product. + if x.shape[0] > 2 ** 24 or x.shape[1] > 2 ** 24: + xnm_dtype = np.float64 + else: + xnm_dtype = np.float32 + xnotmask = np.logical_not(xmask).astype(xnm_dtype) + else: + y = array(y, copy=False, ndmin=2, dtype=float) + ymask = ma.getmaskarray(y) + if not allow_masked and ymask.any(): + raise ValueError("Cannot process masked data.") + if xmask.any() or ymask.any(): + if y.shape == x.shape: + # Define some common mask + common_mask = np.logical_or(xmask, ymask) + if common_mask is not nomask: + xmask = x._mask = y._mask = ymask = common_mask + x._sharedmask = False + y._sharedmask = False + x = ma.concatenate((x, y), axis) + # Check if we can guarantee that the integers in the (N - ddof) + # normalisation can be accurately represented with single-precision + # before computing the dot product. + if x.shape[0] > 2 ** 24 or x.shape[1] > 2 ** 24: + xnm_dtype = np.float64 + else: + xnm_dtype = np.float32 + xnotmask = np.logical_not(np.concatenate((xmask, ymask), axis)).astype( + xnm_dtype + ) + x -= x.mean(axis=rowvar)[tup] + return (x, xnotmask, rowvar) + + +def cov(x, y=None, rowvar=True, bias=False, allow_masked=True, ddof=None): + """ + Estimate the covariance matrix. + + Except for the handling of missing data this function does the same as + `numpy.cov`. For more details and examples, see `numpy.cov`. + + By default, masked values are recognized as such. If `x` and `y` have the + same shape, a common mask is allocated: if ``x[i,j]`` is masked, then + ``y[i,j]`` will also be masked. + Setting `allow_masked` to False will raise an exception if values are + missing in either of the input arrays. + + Parameters + ---------- + x : array_like + A 1-D or 2-D array containing multiple variables and observations. + Each row of `x` represents a variable, and each column a single + observation of all those variables. Also see `rowvar` below. + y : array_like, optional + An additional set of variables and observations. `y` has the same + shape as `x`. + rowvar : bool, optional + If `rowvar` is True (default), then each row represents a + variable, with observations in the columns. Otherwise, the relationship + is transposed: each column represents a variable, while the rows + contain observations. + bias : bool, optional + Default normalization (False) is by ``(N-1)``, where ``N`` is the + number of observations given (unbiased estimate). If `bias` is True, + then normalization is by ``N``. This keyword can be overridden by + the keyword ``ddof`` in numpy versions >= 1.5. + allow_masked : bool, optional + If True, masked values are propagated pair-wise: if a value is masked + in `x`, the corresponding value is masked in `y`. + If False, raises a `ValueError` exception when some values are missing. + ddof : {None, int}, optional + If not ``None`` normalization is by ``(N - ddof)``, where ``N`` is + the number of observations; this overrides the value implied by + ``bias``. The default value is ``None``. + + Raises + ------ + ValueError + Raised if some values are missing and `allow_masked` is False. + + See Also + -------- + numpy.cov + + Examples + -------- + >>> import numpy as np + >>> x = np.ma.array([[0, 1], [1, 1]], mask=[0, 1, 0, 1]) + >>> y = np.ma.array([[1, 0], [0, 1]], mask=[0, 0, 1, 1]) + >>> np.ma.cov(x, y) + masked_array( + data=[[--, --, --, --], + [--, --, --, --], + [--, --, --, --], + [--, --, --, --]], + mask=[[ True, True, True, True], + [ True, True, True, True], + [ True, True, True, True], + [ True, True, True, True]], + fill_value=1e+20, + dtype=float64) + + """ + # Check inputs + if ddof is not None and ddof != int(ddof): + raise ValueError("ddof must be an integer") + # Set up ddof + if ddof is None: + if bias: + ddof = 0 + else: + ddof = 1 + + (x, xnotmask, rowvar) = _covhelper(x, y, rowvar, allow_masked) + if not rowvar: + fact = np.dot(xnotmask.T, xnotmask) - ddof + mask = np.less_equal(fact, 0, dtype=bool) + with np.errstate(divide="ignore", invalid="ignore"): + data = np.dot(filled(x.T, 0), filled(x.conj(), 0)) / fact + result = ma.array(data, mask=mask).squeeze() + else: + fact = np.dot(xnotmask, xnotmask.T) - ddof + mask = np.less_equal(fact, 0, dtype=bool) + with np.errstate(divide="ignore", invalid="ignore"): + data = np.dot(filled(x, 0), filled(x.T.conj(), 0)) / fact + result = ma.array(data, mask=mask).squeeze() + return result + + +def corrcoef(x, y=None, rowvar=True, allow_masked=True, + ): + """ + Return Pearson product-moment correlation coefficients. + + Except for the handling of missing data this function does the same as + `numpy.corrcoef`. For more details and examples, see `numpy.corrcoef`. + + Parameters + ---------- + x : array_like + A 1-D or 2-D array containing multiple variables and observations. + Each row of `x` represents a variable, and each column a single + observation of all those variables. Also see `rowvar` below. + y : array_like, optional + An additional set of variables and observations. `y` has the same + shape as `x`. + rowvar : bool, optional + If `rowvar` is True (default), then each row represents a + variable, with observations in the columns. Otherwise, the relationship + is transposed: each column represents a variable, while the rows + contain observations. + allow_masked : bool, optional + If True, masked values are propagated pair-wise: if a value is masked + in `x`, the corresponding value is masked in `y`. + If False, raises an exception. Because `bias` is deprecated, this + argument needs to be treated as keyword only to avoid a warning. + + See Also + -------- + numpy.corrcoef : Equivalent function in top-level NumPy module. + cov : Estimate the covariance matrix. + + Examples + -------- + >>> import numpy as np + >>> x = np.ma.array([[0, 1], [1, 1]], mask=[0, 1, 0, 1]) + >>> np.ma.corrcoef(x) + masked_array( + data=[[--, --], + [--, --]], + mask=[[ True, True], + [ True, True]], + fill_value=1e+20, + dtype=float64) + + """ + # Estimate the covariance matrix. + corr = cov(x, y, rowvar, allow_masked=allow_masked) + # The non-masked version returns a masked value for a scalar. + try: + std = ma.sqrt(ma.diagonal(corr)) + except ValueError: + return ma.MaskedConstant() + corr /= ma.multiply.outer(std, std) + return corr + +#####-------------------------------------------------------------------------- +#---- --- Concatenation helpers --- +#####-------------------------------------------------------------------------- + +class MAxisConcatenator(AxisConcatenator): + """ + Translate slice objects to concatenation along an axis. + + For documentation on usage, see `mr_class`. + + See Also + -------- + mr_class + + """ + __slots__ = () + + concatenate = staticmethod(concatenate) + + @classmethod + def makemat(cls, arr): + # There used to be a view as np.matrix here, but we may eventually + # deprecate that class. In preparation, we use the unmasked version + # to construct the matrix (with copy=False for backwards compatibility + # with the .view) + data = super().makemat(arr.data, copy=False) + return array(data, mask=arr.mask) + + def __getitem__(self, key): + # matrix builder syntax, like 'a, b; c, d' + if isinstance(key, str): + raise MAError("Unavailable for masked array.") + + return super().__getitem__(key) + + +class mr_class(MAxisConcatenator): + """ + Translate slice objects to concatenation along the first axis. + + This is the masked array version of `r_`. + + See Also + -------- + r_ + + Examples + -------- + >>> import numpy as np + >>> np.ma.mr_[np.ma.array([1,2,3]), 0, 0, np.ma.array([4,5,6])] + masked_array(data=[1, 2, 3, ..., 4, 5, 6], + mask=False, + fill_value=999999) + + """ + __slots__ = () + + def __init__(self): + MAxisConcatenator.__init__(self, 0) + + +mr_ = mr_class() + + +#####-------------------------------------------------------------------------- +#---- Find unmasked data --- +#####-------------------------------------------------------------------------- + +def ndenumerate(a, compressed=True): + """ + Multidimensional index iterator. + + Return an iterator yielding pairs of array coordinates and values, + skipping elements that are masked. With `compressed=False`, + `ma.masked` is yielded as the value of masked elements. This + behavior differs from that of `numpy.ndenumerate`, which yields the + value of the underlying data array. + + Notes + ----- + .. versionadded:: 1.23.0 + + Parameters + ---------- + a : array_like + An array with (possibly) masked elements. + compressed : bool, optional + If True (default), masked elements are skipped. + + See Also + -------- + numpy.ndenumerate : Equivalent function ignoring any mask. + + Examples + -------- + >>> import numpy as np + >>> a = np.ma.arange(9).reshape((3, 3)) + >>> a[1, 0] = np.ma.masked + >>> a[1, 2] = np.ma.masked + >>> a[2, 1] = np.ma.masked + >>> a + masked_array( + data=[[0, 1, 2], + [--, 4, --], + [6, --, 8]], + mask=[[False, False, False], + [ True, False, True], + [False, True, False]], + fill_value=999999) + >>> for index, x in np.ma.ndenumerate(a): + ... print(index, x) + (0, 0) 0 + (0, 1) 1 + (0, 2) 2 + (1, 1) 4 + (2, 0) 6 + (2, 2) 8 + + >>> for index, x in np.ma.ndenumerate(a, compressed=False): + ... print(index, x) + (0, 0) 0 + (0, 1) 1 + (0, 2) 2 + (1, 0) -- + (1, 1) 4 + (1, 2) -- + (2, 0) 6 + (2, 1) -- + (2, 2) 8 + """ + for it, mask in zip(np.ndenumerate(a), getmaskarray(a).flat): + if not mask: + yield it + elif not compressed: + yield it[0], masked + + +def flatnotmasked_edges(a): + """ + Find the indices of the first and last unmasked values. + + Expects a 1-D `MaskedArray`, returns None if all values are masked. + + Parameters + ---------- + a : array_like + Input 1-D `MaskedArray` + + Returns + ------- + edges : ndarray or None + The indices of first and last non-masked value in the array. + Returns None if all values are masked. + + See Also + -------- + flatnotmasked_contiguous, notmasked_contiguous, notmasked_edges + clump_masked, clump_unmasked + + Notes + ----- + Only accepts 1-D arrays. + + Examples + -------- + >>> import numpy as np + >>> a = np.ma.arange(10) + >>> np.ma.flatnotmasked_edges(a) + array([0, 9]) + + >>> mask = (a < 3) | (a > 8) | (a == 5) + >>> a[mask] = np.ma.masked + >>> np.array(a[~a.mask]) + array([3, 4, 6, 7, 8]) + + >>> np.ma.flatnotmasked_edges(a) + array([3, 8]) + + >>> a[:] = np.ma.masked + >>> print(np.ma.flatnotmasked_edges(a)) + None + + """ + m = getmask(a) + if m is nomask or not np.any(m): + return np.array([0, a.size - 1]) + unmasked = np.flatnonzero(~m) + if len(unmasked) > 0: + return unmasked[[0, -1]] + else: + return None + + +def notmasked_edges(a, axis=None): + """ + Find the indices of the first and last unmasked values along an axis. + + If all values are masked, return None. Otherwise, return a list + of two tuples, corresponding to the indices of the first and last + unmasked values respectively. + + Parameters + ---------- + a : array_like + The input array. + axis : int, optional + Axis along which to perform the operation. + If None (default), applies to a flattened version of the array. + + Returns + ------- + edges : ndarray or list + An array of start and end indexes if there are any masked data in + the array. If there are no masked data in the array, `edges` is a + list of the first and last index. + + See Also + -------- + flatnotmasked_contiguous, flatnotmasked_edges, notmasked_contiguous + clump_masked, clump_unmasked + + Examples + -------- + >>> import numpy as np + >>> a = np.arange(9).reshape((3, 3)) + >>> m = np.zeros_like(a) + >>> m[1:, 1:] = 1 + + >>> am = np.ma.array(a, mask=m) + >>> np.array(am[~am.mask]) + array([0, 1, 2, 3, 6]) + + >>> np.ma.notmasked_edges(am) + array([0, 6]) + + """ + a = asarray(a) + if axis is None or a.ndim == 1: + return flatnotmasked_edges(a) + m = getmaskarray(a) + idx = array(np.indices(a.shape), mask=np.asarray([m] * a.ndim)) + return [tuple(idx[i].min(axis).compressed() for i in range(a.ndim)), + tuple(idx[i].max(axis).compressed() for i in range(a.ndim)), ] + + +def flatnotmasked_contiguous(a): + """ + Find contiguous unmasked data in a masked array. + + Parameters + ---------- + a : array_like + The input array. + + Returns + ------- + slice_list : list + A sorted sequence of `slice` objects (start index, end index). + + See Also + -------- + flatnotmasked_edges, notmasked_contiguous, notmasked_edges + clump_masked, clump_unmasked + + Notes + ----- + Only accepts 2-D arrays at most. + + Examples + -------- + >>> import numpy as np + >>> a = np.ma.arange(10) + >>> np.ma.flatnotmasked_contiguous(a) + [slice(0, 10, None)] + + >>> mask = (a < 3) | (a > 8) | (a == 5) + >>> a[mask] = np.ma.masked + >>> np.array(a[~a.mask]) + array([3, 4, 6, 7, 8]) + + >>> np.ma.flatnotmasked_contiguous(a) + [slice(3, 5, None), slice(6, 9, None)] + >>> a[:] = np.ma.masked + >>> np.ma.flatnotmasked_contiguous(a) + [] + + """ + m = getmask(a) + if m is nomask: + return [slice(0, a.size)] + i = 0 + result = [] + for (k, g) in itertools.groupby(m.ravel()): + n = len(list(g)) + if not k: + result.append(slice(i, i + n)) + i += n + return result + + +def notmasked_contiguous(a, axis=None): + """ + Find contiguous unmasked data in a masked array along the given axis. + + Parameters + ---------- + a : array_like + The input array. + axis : int, optional + Axis along which to perform the operation. + If None (default), applies to a flattened version of the array, and this + is the same as `flatnotmasked_contiguous`. + + Returns + ------- + endpoints : list + A list of slices (start and end indexes) of unmasked indexes + in the array. + + If the input is 2d and axis is specified, the result is a list of lists. + + See Also + -------- + flatnotmasked_edges, flatnotmasked_contiguous, notmasked_edges + clump_masked, clump_unmasked + + Notes + ----- + Only accepts 2-D arrays at most. + + Examples + -------- + >>> import numpy as np + >>> a = np.arange(12).reshape((3, 4)) + >>> mask = np.zeros_like(a) + >>> mask[1:, :-1] = 1; mask[0, 1] = 1; mask[-1, 0] = 0 + >>> ma = np.ma.array(a, mask=mask) + >>> ma + masked_array( + data=[[0, --, 2, 3], + [--, --, --, 7], + [8, --, --, 11]], + mask=[[False, True, False, False], + [ True, True, True, False], + [False, True, True, False]], + fill_value=999999) + >>> np.array(ma[~ma.mask]) + array([ 0, 2, 3, 7, 8, 11]) + + >>> np.ma.notmasked_contiguous(ma) + [slice(0, 1, None), slice(2, 4, None), slice(7, 9, None), slice(11, 12, None)] + + >>> np.ma.notmasked_contiguous(ma, axis=0) + [[slice(0, 1, None), slice(2, 3, None)], [], [slice(0, 1, None)], [slice(0, 3, None)]] + + >>> np.ma.notmasked_contiguous(ma, axis=1) + [[slice(0, 1, None), slice(2, 4, None)], [slice(3, 4, None)], [slice(0, 1, None), slice(3, 4, None)]] + + """ # noqa: E501 + a = asarray(a) + nd = a.ndim + if nd > 2: + raise NotImplementedError("Currently limited to at most 2D array.") + if axis is None or nd == 1: + return flatnotmasked_contiguous(a) + # + result = [] + # + other = (axis + 1) % 2 + idx = [0, 0] + idx[axis] = slice(None, None) + # + for i in range(a.shape[other]): + idx[other] = i + result.append(flatnotmasked_contiguous(a[tuple(idx)])) + return result + + +def _ezclump(mask): + """ + Finds the clumps (groups of data with the same values) for a 1D bool array. + + Returns a series of slices. + """ + if mask.ndim > 1: + mask = mask.ravel() + idx = (mask[1:] ^ mask[:-1]).nonzero() + idx = idx[0] + 1 + + if mask[0]: + if len(idx) == 0: + return [slice(0, mask.size)] + + r = [slice(0, idx[0])] + r.extend((slice(left, right) + for left, right in zip(idx[1:-1:2], idx[2::2]))) + else: + if len(idx) == 0: + return [] + + r = [slice(left, right) for left, right in zip(idx[:-1:2], idx[1::2])] + + if mask[-1]: + r.append(slice(idx[-1], mask.size)) + return r + + +def clump_unmasked(a): + """ + Return list of slices corresponding to the unmasked clumps of a 1-D array. + (A "clump" is defined as a contiguous region of the array). + + Parameters + ---------- + a : ndarray + A one-dimensional masked array. + + Returns + ------- + slices : list of slice + The list of slices, one for each continuous region of unmasked + elements in `a`. + + See Also + -------- + flatnotmasked_edges, flatnotmasked_contiguous, notmasked_edges + notmasked_contiguous, clump_masked + + Examples + -------- + >>> import numpy as np + >>> a = np.ma.masked_array(np.arange(10)) + >>> a[[0, 1, 2, 6, 8, 9]] = np.ma.masked + >>> np.ma.clump_unmasked(a) + [slice(3, 6, None), slice(7, 8, None)] + + """ + mask = getattr(a, '_mask', nomask) + if mask is nomask: + return [slice(0, a.size)] + return _ezclump(~mask) + + +def clump_masked(a): + """ + Returns a list of slices corresponding to the masked clumps of a 1-D array. + (A "clump" is defined as a contiguous region of the array). + + Parameters + ---------- + a : ndarray + A one-dimensional masked array. + + Returns + ------- + slices : list of slice + The list of slices, one for each continuous region of masked elements + in `a`. + + See Also + -------- + flatnotmasked_edges, flatnotmasked_contiguous, notmasked_edges + notmasked_contiguous, clump_unmasked + + Examples + -------- + >>> import numpy as np + >>> a = np.ma.masked_array(np.arange(10)) + >>> a[[0, 1, 2, 6, 8, 9]] = np.ma.masked + >>> np.ma.clump_masked(a) + [slice(0, 3, None), slice(6, 7, None), slice(8, 10, None)] + + """ + mask = ma.getmask(a) + if mask is nomask: + return [] + return _ezclump(mask) + + +############################################################################### +# Polynomial fit # +############################################################################### + + +def vander(x, n=None): + """ + Masked values in the input array result in rows of zeros. + + """ + _vander = np.vander(x, n) + m = getmask(x) + if m is not nomask: + _vander[m] = 0 + return _vander + + +vander.__doc__ = ma.doc_note(np.vander.__doc__, vander.__doc__) + + +def polyfit(x, y, deg, rcond=None, full=False, w=None, cov=False): + """ + Any masked values in x is propagated in y, and vice-versa. + + """ + x = asarray(x) + y = asarray(y) + + m = getmask(x) + if y.ndim == 1: + m = mask_or(m, getmask(y)) + elif y.ndim == 2: + my = getmask(mask_rows(y)) + if my is not nomask: + m = mask_or(m, my[:, 0]) + else: + raise TypeError("Expected a 1D or 2D array for y!") + + if w is not None: + w = asarray(w) + if w.ndim != 1: + raise TypeError("expected a 1-d array for weights") + if w.shape[0] != y.shape[0]: + raise TypeError("expected w and y to have the same length") + m = mask_or(m, getmask(w)) + + if m is not nomask: + not_m = ~m + if w is not None: + w = w[not_m] + return np.polyfit(x[not_m], y[not_m], deg, rcond, full, w, cov) + else: + return np.polyfit(x, y, deg, rcond, full, w, cov) + + +polyfit.__doc__ = ma.doc_note(np.polyfit.__doc__, polyfit.__doc__) diff --git a/python/user_packages/Python313/site-packages/numpy/ma/extras.pyi b/python/user_packages/Python313/site-packages/numpy/ma/extras.pyi new file mode 100644 index 0000000000000000000000000000000000000000..a03a198642051aa2fe45652366b5a86aeb0750f3 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/ma/extras.pyi @@ -0,0 +1,297 @@ +from _typeshed import Incomplete +from collections.abc import Sequence +from typing import SupportsIndex, TypeAlias, TypeVar, overload + +import numpy as np +from numpy import _CastingKind +from numpy._typing import ( + ArrayLike, + DTypeLike, + _AnyShape, + _ArrayLike, + _DTypeLike, + _ShapeLike, +) +from numpy.lib._function_base_impl import average +from numpy.lib._index_tricks_impl import AxisConcatenator + +from .core import MaskedArray, dot + +__all__ = [ + "apply_along_axis", + "apply_over_axes", + "atleast_1d", + "atleast_2d", + "atleast_3d", + "average", + "clump_masked", + "clump_unmasked", + "column_stack", + "compress_cols", + "compress_nd", + "compress_rowcols", + "compress_rows", + "corrcoef", + "count_masked", + "cov", + "diagflat", + "dot", + "dstack", + "ediff1d", + "flatnotmasked_contiguous", + "flatnotmasked_edges", + "hsplit", + "hstack", + "in1d", + "intersect1d", + "isin", + "mask_cols", + "mask_rowcols", + "mask_rows", + "masked_all", + "masked_all_like", + "median", + "mr_", + "ndenumerate", + "notmasked_contiguous", + "notmasked_edges", + "polyfit", + "row_stack", + "setdiff1d", + "setxor1d", + "stack", + "union1d", + "unique", + "vander", + "vstack", +] + +_ScalarT = TypeVar("_ScalarT", bound=np.generic) +_ScalarT1 = TypeVar("_ScalarT1", bound=np.generic) +_ScalarT2 = TypeVar("_ScalarT2", bound=np.generic) +_MArrayT = TypeVar("_MArrayT", bound=MaskedArray) + +_MArray: TypeAlias = MaskedArray[_AnyShape, np.dtype[_ScalarT]] + +### + +# keep in sync with `numpy._core.shape_base.atleast_1d` +@overload +def atleast_1d(a0: _ArrayLike[_ScalarT], /) -> _MArray[_ScalarT]: ... +@overload +def atleast_1d(a0: _ArrayLike[_ScalarT1], a1: _ArrayLike[_ScalarT2], /) -> tuple[_MArray[_ScalarT1], _MArray[_ScalarT2]]: ... +@overload +def atleast_1d( + a0: _ArrayLike[_ScalarT], a1: _ArrayLike[_ScalarT], /, *arys: _ArrayLike[_ScalarT] +) -> tuple[_MArray[_ScalarT], ...]: ... +@overload +def atleast_1d(a0: ArrayLike, /) -> _MArray[Incomplete]: ... +@overload +def atleast_1d(a0: ArrayLike, a1: ArrayLike, /) -> tuple[_MArray[Incomplete], _MArray[Incomplete]]: ... +@overload +def atleast_1d(a0: ArrayLike, a1: ArrayLike, /, *ai: ArrayLike) -> tuple[_MArray[Incomplete], ...]: ... + +# keep in sync with `numpy._core.shape_base.atleast_2d` +@overload +def atleast_2d(a0: _ArrayLike[_ScalarT], /) -> _MArray[_ScalarT]: ... +@overload +def atleast_2d(a0: _ArrayLike[_ScalarT1], a1: _ArrayLike[_ScalarT2], /) -> tuple[_MArray[_ScalarT1], _MArray[_ScalarT2]]: ... +@overload +def atleast_2d( + a0: _ArrayLike[_ScalarT], a1: _ArrayLike[_ScalarT], /, *arys: _ArrayLike[_ScalarT] +) -> tuple[_MArray[_ScalarT], ...]: ... +@overload +def atleast_2d(a0: ArrayLike, /) -> _MArray[Incomplete]: ... +@overload +def atleast_2d(a0: ArrayLike, a1: ArrayLike, /) -> tuple[_MArray[Incomplete], _MArray[Incomplete]]: ... +@overload +def atleast_2d(a0: ArrayLike, a1: ArrayLike, /, *ai: ArrayLike) -> tuple[_MArray[Incomplete], ...]: ... + +# keep in sync with `numpy._core.shape_base.atleast_2d` +@overload +def atleast_3d(a0: _ArrayLike[_ScalarT], /) -> _MArray[_ScalarT]: ... +@overload +def atleast_3d(a0: _ArrayLike[_ScalarT1], a1: _ArrayLike[_ScalarT2], /) -> tuple[_MArray[_ScalarT1], _MArray[_ScalarT2]]: ... +@overload +def atleast_3d( + a0: _ArrayLike[_ScalarT], a1: _ArrayLike[_ScalarT], /, *arys: _ArrayLike[_ScalarT] +) -> tuple[_MArray[_ScalarT], ...]: ... +@overload +def atleast_3d(a0: ArrayLike, /) -> _MArray[Incomplete]: ... +@overload +def atleast_3d(a0: ArrayLike, a1: ArrayLike, /) -> tuple[_MArray[Incomplete], _MArray[Incomplete]]: ... +@overload +def atleast_3d(a0: ArrayLike, a1: ArrayLike, /, *ai: ArrayLike) -> tuple[_MArray[Incomplete], ...]: ... + +# keep in sync with `numpy._core.shape_base.vstack` +@overload +def vstack( + tup: Sequence[_ArrayLike[_ScalarT]], + *, + dtype: None = None, + casting: _CastingKind = "same_kind" +) -> _MArray[_ScalarT]: ... +@overload +def vstack( + tup: Sequence[ArrayLike], + *, + dtype: _DTypeLike[_ScalarT], + casting: _CastingKind = "same_kind" +) -> _MArray[_ScalarT]: ... +@overload +def vstack( + tup: Sequence[ArrayLike], + *, + dtype: DTypeLike | None = None, + casting: _CastingKind = "same_kind" +) -> _MArray[Incomplete]: ... + +row_stack = vstack + +# keep in sync with `numpy._core.shape_base.hstack` +@overload +def hstack( + tup: Sequence[_ArrayLike[_ScalarT]], + *, + dtype: None = None, + casting: _CastingKind = "same_kind" +) -> _MArray[_ScalarT]: ... +@overload +def hstack( + tup: Sequence[ArrayLike], + *, + dtype: _DTypeLike[_ScalarT], + casting: _CastingKind = "same_kind" +) -> _MArray[_ScalarT]: ... +@overload +def hstack( + tup: Sequence[ArrayLike], + *, + dtype: DTypeLike | None = None, + casting: _CastingKind = "same_kind" +) -> _MArray[Incomplete]: ... + +# keep in sync with `numpy._core.shape_base_impl.column_stack` +@overload +def column_stack(tup: Sequence[_ArrayLike[_ScalarT]]) -> _MArray[_ScalarT]: ... +@overload +def column_stack(tup: Sequence[ArrayLike]) -> _MArray[Incomplete]: ... + +# keep in sync with `numpy._core.shape_base_impl.dstack` +@overload +def dstack(tup: Sequence[_ArrayLike[_ScalarT]]) -> _MArray[_ScalarT]: ... +@overload +def dstack(tup: Sequence[ArrayLike]) -> _MArray[Incomplete]: ... + +# keep in sync with `numpy._core.shape_base.stack` +@overload +def stack( + arrays: Sequence[_ArrayLike[_ScalarT]], + axis: SupportsIndex = 0, + out: None = None, + *, + dtype: None = None, + casting: _CastingKind = "same_kind" +) -> _MArray[_ScalarT]: ... +@overload +def stack( + arrays: Sequence[ArrayLike], + axis: SupportsIndex = 0, + out: None = None, + *, + dtype: _DTypeLike[_ScalarT], + casting: _CastingKind = "same_kind" +) -> _MArray[_ScalarT]: ... +@overload +def stack( + arrays: Sequence[ArrayLike], + axis: SupportsIndex = 0, + out: None = None, + *, + dtype: DTypeLike | None = None, + casting: _CastingKind = "same_kind" +) -> _MArray[Incomplete]: ... +@overload +def stack( + arrays: Sequence[ArrayLike], + axis: SupportsIndex, + out: _MArrayT, + *, + dtype: DTypeLike | None = None, + casting: _CastingKind = "same_kind", +) -> _MArrayT: ... +@overload +def stack( + arrays: Sequence[ArrayLike], + axis: SupportsIndex = 0, + *, + out: _MArrayT, + dtype: DTypeLike | None = None, + casting: _CastingKind = "same_kind", +) -> _MArrayT: ... + +# keep in sync with `numpy._core.shape_base_impl.hsplit` +@overload +def hsplit(ary: _ArrayLike[_ScalarT], indices_or_sections: _ShapeLike) -> list[_MArray[_ScalarT]]: ... +@overload +def hsplit(ary: ArrayLike, indices_or_sections: _ShapeLike) -> list[_MArray[Incomplete]]: ... + +# keep in sync with `numpy._core.twodim_base_impl.hsplit` +@overload +def diagflat(v: _ArrayLike[_ScalarT], k: int = 0) -> _MArray[_ScalarT]: ... +@overload +def diagflat(v: ArrayLike, k: int = 0) -> _MArray[Incomplete]: ... + +# TODO: everything below + +def count_masked(arr, axis=None): ... +def masked_all(shape, dtype=float): ... # noqa: PYI014 +def masked_all_like(arr): ... + +def apply_along_axis(func1d, axis, arr, *args, **kwargs): ... +def apply_over_axes(func, a, axes): ... +def median(a, axis=None, out=None, overwrite_input=False, keepdims=False): ... +def compress_nd(x, axis=None): ... +def compress_rowcols(x, axis=None): ... +def compress_rows(a): ... +def compress_cols(a): ... +def mask_rows(a, axis=...): ... +def mask_cols(a, axis=...): ... +def ediff1d(arr, to_end=None, to_begin=None): ... +def unique(ar1, return_index=False, return_inverse=False): ... +def intersect1d(ar1, ar2, assume_unique=False): ... +def setxor1d(ar1, ar2, assume_unique=False): ... +def in1d(ar1, ar2, assume_unique=False, invert=False): ... +def isin(element, test_elements, assume_unique=False, invert=False): ... +def union1d(ar1, ar2): ... +def setdiff1d(ar1, ar2, assume_unique=False): ... +def cov(x, y=None, rowvar=True, bias=False, allow_masked=True, ddof=None): ... +def corrcoef(x, y=None, rowvar=True, allow_masked=True): ... + +class MAxisConcatenator(AxisConcatenator): + __slots__ = () + + @staticmethod + def concatenate(arrays: Incomplete, axis: int = 0) -> Incomplete: ... # type: ignore[override] # pyright: ignore[reportIncompatibleMethodOverride] + @classmethod + def makemat(cls, arr: Incomplete) -> Incomplete: ... # type: ignore[override] # pyright: ignore[reportIncompatibleVariableOverride] + +class mr_class(MAxisConcatenator): + __slots__ = () + + def __init__(self) -> None: ... + +mr_: mr_class + +def ndenumerate(a, compressed=True): ... +def flatnotmasked_edges(a): ... +def notmasked_edges(a, axis=None): ... +def flatnotmasked_contiguous(a): ... +def notmasked_contiguous(a, axis=None): ... +def clump_unmasked(a): ... +def clump_masked(a): ... +def vander(x, n=None): ... +def polyfit(x, y, deg, rcond=None, full=False, w=None, cov=False): ... + +# +def mask_rowcols(a: Incomplete, axis: Incomplete | None = None) -> MaskedArray[Incomplete, np.dtype[Incomplete]]: ... diff --git a/python/user_packages/Python313/site-packages/numpy/ma/mrecords.py b/python/user_packages/Python313/site-packages/numpy/ma/mrecords.py new file mode 100644 index 0000000000000000000000000000000000000000..c37767f1beb6a1e95a0fc21876a45edc13ef8596 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/ma/mrecords.py @@ -0,0 +1,762 @@ +""":mod:`numpy.ma..mrecords` + +Defines the equivalent of :class:`numpy.recarrays` for masked arrays, +where fields can be accessed as attributes. +Note that :class:`numpy.ma.MaskedArray` already supports structured datatypes +and the masking of individual fields. + +.. moduleauthor:: Pierre Gerard-Marchant + +""" +# We should make sure that no field is called '_mask','mask','_fieldmask', +# or whatever restricted keywords. An idea would be to no bother in the +# first place, and then rename the invalid fields with a trailing +# underscore. Maybe we could just overload the parser function ? + +import warnings + +import numpy as np +import numpy.ma as ma + +_byteorderconv = np._core.records._byteorderconv + + +_check_fill_value = ma.core._check_fill_value + + +__all__ = [ + 'MaskedRecords', 'mrecarray', 'fromarrays', 'fromrecords', + 'fromtextfile', 'addfield', +] + +reserved_fields = ['_data', '_mask', '_fieldmask', 'dtype'] + + +def _checknames(descr, names=None): + """ + Checks that field names ``descr`` are not reserved keywords. + + If this is the case, a default 'f%i' is substituted. If the argument + `names` is not None, updates the field names to valid names. + + """ + ndescr = len(descr) + default_names = [f'f{i}' for i in range(ndescr)] + if names is None: + new_names = default_names + else: + if isinstance(names, (tuple, list)): + new_names = names + elif isinstance(names, str): + new_names = names.split(',') + else: + raise NameError(f'illegal input names {names!r}') + nnames = len(new_names) + if nnames < ndescr: + new_names += default_names[nnames:] + ndescr = [] + for (n, d, t) in zip(new_names, default_names, descr.descr): + if n in reserved_fields: + if t[0] in reserved_fields: + ndescr.append((d, t[1])) + else: + ndescr.append(t) + else: + ndescr.append((n, t[1])) + return np.dtype(ndescr) + + +def _get_fieldmask(self): + mdescr = [(n, '|b1') for n in self.dtype.names] + fdmask = np.empty(self.shape, dtype=mdescr) + fdmask.flat = tuple([False] * len(mdescr)) + return fdmask + + +class MaskedRecords(ma.MaskedArray): + """ + + Attributes + ---------- + _data : recarray + Underlying data, as a record array. + _mask : boolean array + Mask of the records. A record is masked when all its fields are + masked. + _fieldmask : boolean recarray + Record array of booleans, setting the mask of each individual field + of each record. + _fill_value : record + Filling values for each field. + + """ + + def __new__(cls, shape, dtype=None, buf=None, offset=0, strides=None, + formats=None, names=None, titles=None, + byteorder=None, aligned=False, + mask=ma.nomask, hard_mask=False, fill_value=None, keep_mask=True, + copy=False, + **options): + + self = np.recarray.__new__(cls, shape, dtype=dtype, buf=buf, offset=offset, + strides=strides, formats=formats, names=names, + titles=titles, byteorder=byteorder, + aligned=aligned,) + + mdtype = ma.make_mask_descr(self.dtype) + if mask is ma.nomask or not np.size(mask): + if not keep_mask: + self._mask = tuple([False] * len(mdtype)) + else: + mask = np.array(mask, copy=copy) + if mask.shape != self.shape: + (nd, nm) = (self.size, mask.size) + if nm == 1: + mask = np.resize(mask, self.shape) + elif nm == nd: + mask = np.reshape(mask, self.shape) + else: + msg = (f"Mask and data not compatible: data size is {nd}," + " mask size is {nm}.") + raise ma.MAError(msg) + if not keep_mask: + self.__setmask__(mask) + self._sharedmask = True + else: + if mask.dtype == mdtype: + _mask = mask + else: + _mask = np.array([tuple([m] * len(mdtype)) for m in mask], + dtype=mdtype) + self._mask = _mask + return self + + def __array_finalize__(self, obj): + # Make sure we have a _fieldmask by default + _mask = getattr(obj, '_mask', None) + if _mask is None: + objmask = getattr(obj, '_mask', ma.nomask) + _dtype = np.ndarray.__getattribute__(self, 'dtype') + if objmask is ma.nomask: + _mask = ma.make_mask_none(self.shape, dtype=_dtype) + else: + mdescr = ma.make_mask_descr(_dtype) + _mask = np.array([tuple([m] * len(mdescr)) for m in objmask], + dtype=mdescr).view(np.recarray) + # Update some of the attributes + _dict = self.__dict__ + _dict.update(_mask=_mask) + self._update_from(obj) + if _dict['_baseclass'] == np.ndarray: + _dict['_baseclass'] = np.recarray + + @property + def _data(self): + """ + Returns the data as a recarray. + + """ + return np.ndarray.view(self, np.recarray) + + @property + def _fieldmask(self): + """ + Alias to mask. + + """ + return self._mask + + def __len__(self): + """ + Returns the length + + """ + # We have more than one record + if self.ndim: + return len(self._data) + # We have only one record: return the nb of fields + return len(self.dtype) + + def __getattribute__(self, attr): + try: + return object.__getattribute__(self, attr) + except AttributeError: + # attr must be a fieldname + pass + fielddict = np.ndarray.__getattribute__(self, 'dtype').fields + try: + res = fielddict[attr][:2] + except (TypeError, KeyError) as e: + raise AttributeError( + f'record array has no attribute {attr}') from e + # So far, so good + _localdict = np.ndarray.__getattribute__(self, '__dict__') + _data = np.ndarray.view(self, _localdict['_baseclass']) + obj = _data.getfield(*res) + if obj.dtype.names is not None: + raise NotImplementedError("MaskedRecords is currently limited to" + "simple records.") + # Get some special attributes + # Reset the object's mask + hasmasked = False + _mask = _localdict.get('_mask', None) + if _mask is not None: + try: + _mask = _mask[attr] + except IndexError: + # Couldn't find a mask: use the default (nomask) + pass + tp_len = len(_mask.dtype) + hasmasked = _mask.view((bool, ((tp_len,) if tp_len else ()))).any() + if (obj.shape or hasmasked): + obj = obj.view(ma.MaskedArray) + obj._baseclass = np.ndarray + obj._isfield = True + obj._mask = _mask + # Reset the field values + _fill_value = _localdict.get('_fill_value', None) + if _fill_value is not None: + try: + obj._fill_value = _fill_value[attr] + except ValueError: + obj._fill_value = None + else: + obj = obj.item() + return obj + + def __setattr__(self, attr, val): + """ + Sets the attribute attr to the value val. + + """ + # Should we call __setmask__ first ? + if attr in ['mask', 'fieldmask']: + self.__setmask__(val) + return + # Create a shortcut (so that we don't have to call getattr all the time) + _localdict = object.__getattribute__(self, '__dict__') + # Check whether we're creating a new field + newattr = attr not in _localdict + try: + # Is attr a generic attribute ? + ret = object.__setattr__(self, attr, val) + except Exception: + # Not a generic attribute: exit if it's not a valid field + fielddict = np.ndarray.__getattribute__(self, 'dtype').fields or {} + optinfo = np.ndarray.__getattribute__(self, '_optinfo') or {} + if not (attr in fielddict or attr in optinfo): + raise + else: + # Get the list of names + fielddict = np.ndarray.__getattribute__(self, 'dtype').fields or {} + # Check the attribute + if attr not in fielddict: + return ret + if newattr: + # We just added this one or this setattr worked on an + # internal attribute. + try: + object.__delattr__(self, attr) + except Exception: + return ret + # Let's try to set the field + try: + res = fielddict[attr][:2] + except (TypeError, KeyError) as e: + raise AttributeError( + f'record array has no attribute {attr}') from e + + if val is ma.masked: + _fill_value = _localdict['_fill_value'] + if _fill_value is not None: + dval = _localdict['_fill_value'][attr] + else: + dval = val + mval = True + else: + dval = ma.filled(val) + mval = ma.getmaskarray(val) + obj = np.ndarray.__getattribute__(self, '_data').setfield(dval, *res) + _localdict['_mask'].__setitem__(attr, mval) + return obj + + def __getitem__(self, indx): + """ + Returns all the fields sharing the same fieldname base. + + The fieldname base is either `_data` or `_mask`. + + """ + _localdict = self.__dict__ + _mask = np.ndarray.__getattribute__(self, '_mask') + _data = np.ndarray.view(self, _localdict['_baseclass']) + # We want a field + if isinstance(indx, str): + # Make sure _sharedmask is True to propagate back to _fieldmask + # Don't use _set_mask, there are some copies being made that + # break propagation Don't force the mask to nomask, that wreaks + # easy masking + obj = _data[indx].view(ma.MaskedArray) + obj._mask = _mask[indx] + obj._sharedmask = True + fval = _localdict['_fill_value'] + if fval is not None: + obj._fill_value = fval[indx] + # Force to masked if the mask is True + if not obj.ndim and obj._mask: + return ma.masked + return obj + # We want some elements. + # First, the data. + obj = np.asarray(_data[indx]).view(mrecarray) + obj._mask = np.asarray(_mask[indx]).view(np.recarray) + return obj + + def __setitem__(self, indx, value): + """ + Sets the given record to value. + + """ + ma.MaskedArray.__setitem__(self, indx, value) + if isinstance(indx, str): + self._mask[indx] = ma.getmaskarray(value) + + def __str__(self): + """ + Calculates the string representation. + + """ + if self.size > 1: + mstr = [f"({','.join([str(i) for i in s])})" + for s in zip(*[getattr(self, f) for f in self.dtype.names])] + return f"[{', '.join(mstr)}]" + else: + mstr = [f"{','.join([str(i) for i in s])}" + for s in zip([getattr(self, f) for f in self.dtype.names])] + return f"({', '.join(mstr)})" + + def __repr__(self): + """ + Calculates the repr representation. + + """ + _names = self.dtype.names + fmt = f"%{max(len(n) for n in _names) + 4}s : %s" + reprstr = [fmt % (f, getattr(self, f)) for f in self.dtype.names] + reprstr.insert(0, 'masked_records(') + reprstr.extend([fmt % (' fill_value', self.fill_value), + ' )']) + return str("\n".join(reprstr)) + + def view(self, dtype=None, type=None): + """ + Returns a view of the mrecarray. + + """ + # OK, basic copy-paste from MaskedArray.view. + if dtype is None: + if type is None: + output = np.ndarray.view(self) + else: + output = np.ndarray.view(self, type) + # Here again. + elif type is None: + try: + if issubclass(dtype, np.ndarray): + output = np.ndarray.view(self, dtype) + else: + output = np.ndarray.view(self, dtype) + # OK, there's the change + except TypeError: + dtype = np.dtype(dtype) + # we need to revert to MaskedArray, but keeping the possibility + # of subclasses (eg, TimeSeriesRecords), so we'll force a type + # set to the first parent + if dtype.fields is None: + basetype = self.__class__.__bases__[0] + output = self.__array__().view(dtype, basetype) + output._update_from(self) + else: + output = np.ndarray.view(self, dtype) + output._fill_value = None + else: + output = np.ndarray.view(self, dtype, type) + # Update the mask, just like in MaskedArray.view + if (getattr(output, '_mask', ma.nomask) is not ma.nomask): + mdtype = ma.make_mask_descr(output.dtype) + output._mask = self._mask.view(mdtype, np.ndarray) + output._mask.shape = output.shape + return output + + def harden_mask(self): + """ + Forces the mask to hard. + + """ + self._hardmask = True + + def soften_mask(self): + """ + Forces the mask to soft + + """ + self._hardmask = False + + def copy(self): + """ + Returns a copy of the masked record. + + """ + copied = self._data.copy().view(type(self)) + copied._mask = self._mask.copy() + return copied + + def tolist(self, fill_value=None): + """ + Return the data portion of the array as a list. + + Data items are converted to the nearest compatible Python type. + Masked values are converted to fill_value. If fill_value is None, + the corresponding entries in the output list will be ``None``. + + """ + if fill_value is not None: + return self.filled(fill_value).tolist() + result = np.array(self.filled().tolist(), dtype=object) + mask = np.array(self._mask.tolist()) + result[mask] = None + return result.tolist() + + def __getstate__(self): + """Return the internal state of the masked array. + + This is for pickling. + + """ + state = (1, + self.shape, + self.dtype, + self.flags.fnc, + self._data.tobytes(), + self._mask.tobytes(), + self._fill_value, + ) + return state + + def __setstate__(self, state): + """ + Restore the internal state of the masked array. + + This is for pickling. ``state`` is typically the output of the + ``__getstate__`` output, and is a 5-tuple: + + - class name + - a tuple giving the shape of the data + - a typecode for the data + - a binary string for the data + - a binary string for the mask. + + """ + (ver, shp, typ, isf, raw, msk, flv) = state + np.ndarray.__setstate__(self, (shp, typ, isf, raw)) + mdtype = np.dtype([(k, np.bool) for (k, _) in self.dtype.descr]) + self.__dict__['_mask'].__setstate__((shp, mdtype, isf, msk)) + self.fill_value = flv + + def __reduce__(self): + """ + Return a 3-tuple for pickling a MaskedArray. + + """ + return (_mrreconstruct, + (self.__class__, self._baseclass, (0,), 'b',), + self.__getstate__()) + + +def _mrreconstruct(subtype, baseclass, baseshape, basetype,): + """ + Build a new MaskedArray from the information stored in a pickle. + + """ + _data = np.ndarray.__new__(baseclass, baseshape, basetype).view(subtype) + _mask = np.ndarray.__new__(np.ndarray, baseshape, 'b1') + return subtype.__new__(subtype, _data, mask=_mask, dtype=basetype,) + + +mrecarray = MaskedRecords + + +############################################################################### +# Constructors # +############################################################################### + + +def fromarrays(arraylist, dtype=None, shape=None, formats=None, + names=None, titles=None, aligned=False, byteorder=None, + fill_value=None): + """ + Creates a mrecarray from a (flat) list of masked arrays. + + Parameters + ---------- + arraylist : sequence + A list of (masked) arrays. Each element of the sequence is first converted + to a masked array if needed. If a 2D array is passed as argument, it is + processed line by line + dtype : {None, dtype}, optional + Data type descriptor. + shape : {None, integer}, optional + Number of records. If None, shape is defined from the shape of the + first array in the list. + formats : {None, sequence}, optional + Sequence of formats for each individual field. If None, the formats will + be autodetected by inspecting the fields and selecting the highest dtype + possible. + names : {None, sequence}, optional + Sequence of the names of each field. + fill_value : {None, sequence}, optional + Sequence of data to be used as filling values. + + Notes + ----- + Lists of tuples should be preferred over lists of lists for faster processing. + + """ + datalist = [ma.getdata(x) for x in arraylist] + masklist = [np.atleast_1d(ma.getmaskarray(x)) for x in arraylist] + _array = np.rec.fromarrays(datalist, + dtype=dtype, shape=shape, formats=formats, + names=names, titles=titles, aligned=aligned, + byteorder=byteorder).view(mrecarray) + _array._mask.flat = list(zip(*masklist)) + if fill_value is not None: + _array.fill_value = fill_value + return _array + + +def fromrecords(reclist, dtype=None, shape=None, formats=None, names=None, + titles=None, aligned=False, byteorder=None, + fill_value=None, mask=ma.nomask): + """ + Creates a MaskedRecords from a list of records. + + Parameters + ---------- + reclist : sequence + A list of records. Each element of the sequence is first converted + to a masked array if needed. If a 2D array is passed as argument, it is + processed line by line + dtype : {None, dtype}, optional + Data type descriptor. + shape : {None,int}, optional + Number of records. If None, ``shape`` is defined from the shape of the + first array in the list. + formats : {None, sequence}, optional + Sequence of formats for each individual field. If None, the formats will + be autodetected by inspecting the fields and selecting the highest dtype + possible. + names : {None, sequence}, optional + Sequence of the names of each field. + fill_value : {None, sequence}, optional + Sequence of data to be used as filling values. + mask : {nomask, sequence}, optional. + External mask to apply on the data. + + Notes + ----- + Lists of tuples should be preferred over lists of lists for faster processing. + + """ + # Grab the initial _fieldmask, if needed: + _mask = getattr(reclist, '_mask', None) + # Get the list of records. + if isinstance(reclist, np.ndarray): + # Make sure we don't have some hidden mask + if isinstance(reclist, ma.MaskedArray): + reclist = reclist.filled().view(np.ndarray) + # Grab the initial dtype, just in case + if dtype is None: + dtype = reclist.dtype + reclist = reclist.tolist() + mrec = np.rec.fromrecords(reclist, dtype=dtype, shape=shape, formats=formats, + names=names, titles=titles, + aligned=aligned, byteorder=byteorder).view(mrecarray) + # Set the fill_value if needed + if fill_value is not None: + mrec.fill_value = fill_value + # Now, let's deal w/ the mask + if mask is not ma.nomask: + mask = np.asarray(mask) + maskrecordlength = len(mask.dtype) + if maskrecordlength: + mrec._mask.flat = mask + elif mask.ndim == 2: + mrec._mask.flat = [tuple(m) for m in mask] + else: + mrec.__setmask__(mask) + if _mask is not None: + mrec._mask[:] = _mask + return mrec + + +def _guessvartypes(arr): + """ + Tries to guess the dtypes of the str_ ndarray `arr`. + + Guesses by testing element-wise conversion. Returns a list of dtypes. + The array is first converted to ndarray. If the array is 2D, the test + is performed on the first line. An exception is raised if the file is + 3D or more. + + """ + vartypes = [] + arr = np.asarray(arr) + if arr.ndim == 2: + arr = arr[0] + elif arr.ndim > 2: + raise ValueError("The array should be 2D at most!") + # Start the conversion loop. + for f in arr: + try: + int(f) + except (ValueError, TypeError): + try: + float(f) + except (ValueError, TypeError): + try: + complex(f) + except (ValueError, TypeError): + vartypes.append(arr.dtype) + else: + vartypes.append(np.dtype(complex)) + else: + vartypes.append(np.dtype(float)) + else: + vartypes.append(np.dtype(int)) + return vartypes + + +def openfile(fname): + """ + Opens the file handle of file `fname`. + + """ + # A file handle + if hasattr(fname, 'readline'): + return fname + # Try to open the file and guess its type + try: + f = open(fname) + except FileNotFoundError as e: + raise FileNotFoundError(f"No such file: '{fname}'") from e + if f.readline()[:2] != "\\x": + f.seek(0, 0) + return f + f.close() + raise NotImplementedError("Wow, binary file") + + +def fromtextfile(fname, delimiter=None, commentchar='#', missingchar='', + varnames=None, vartypes=None): + """ + Creates a mrecarray from data stored in the file `filename`. + + Parameters + ---------- + fname : {file name/handle} + Handle of an opened file. + delimiter : {None, string}, optional + Alphanumeric character used to separate columns in the file. + If None, any (group of) white spacestring(s) will be used. + commentchar : {'#', string}, optional + Alphanumeric character used to mark the start of a comment. + missingchar : {'', string}, optional + String indicating missing data, and used to create the masks. + varnames : {None, sequence}, optional + Sequence of the variable names. If None, a list will be created from + the first non empty line of the file. + vartypes : {None, sequence}, optional + Sequence of the variables dtypes. If None, it will be estimated from + the first non-commented line. + + + Ultra simple: the varnames are in the header, one line""" + + # Try to open the file. + ftext = openfile(fname) + + # Get the first non-empty line as the varnames + while True: + line = ftext.readline() + firstline = line[:line.find(commentchar)].strip() + _varnames = firstline.split(delimiter) + if len(_varnames) > 1: + break + if varnames is None: + varnames = _varnames + + # Get the data. + _variables = ma.masked_array([line.strip().split(delimiter) for line in ftext + if line[0] != commentchar and len(line) > 1]) + (_, nfields) = _variables.shape + ftext.close() + + # Try to guess the dtype. + if vartypes is None: + vartypes = _guessvartypes(_variables[0]) + else: + vartypes = [np.dtype(v) for v in vartypes] + if len(vartypes) != nfields: + msg = f"Attempting to {len(vartypes)} dtypes for {nfields} fields!" + msg += " Reverting to default." + warnings.warn(msg, stacklevel=2) + vartypes = _guessvartypes(_variables[0]) + + # Construct the descriptor. + mdescr = list(zip(varnames, vartypes)) + mfillv = [ma.default_fill_value(f) for f in vartypes] + + # Get the data and the mask. + # We just need a list of masked_arrays. It's easier to create it like that: + _mask = (_variables.T == missingchar) + _datalist = [ma.masked_array(a, mask=m, dtype=t, fill_value=f) + for (a, m, t, f) in zip(_variables.T, _mask, vartypes, mfillv)] + + return fromarrays(_datalist, dtype=mdescr) + + +def addfield(mrecord, newfield, newfieldname=None): + """Adds a new field to the masked record array + + Uses `newfield` as data and `newfieldname` as name. If `newfieldname` + is None, the new field name is set to 'fi', where `i` is the number of + existing fields. + + """ + _data = mrecord._data + _mask = mrecord._mask + if newfieldname is None or newfieldname in reserved_fields: + newfieldname = f'f{len(_data.dtype)}' + newfield = ma.array(newfield) + # Get the new data. + # Create a new empty recarray + newdtype = np.dtype(_data.dtype.descr + [(newfieldname, newfield.dtype)]) + newdata = np.recarray(_data.shape, newdtype) + # Add the existing field + [newdata.setfield(_data.getfield(*f), *f) + for f in _data.dtype.fields.values()] + # Add the new field + newdata.setfield(newfield._data, *newdata.dtype.fields[newfieldname]) + newdata = newdata.view(MaskedRecords) + # Get the new mask + # Create a new empty recarray + newmdtype = np.dtype([(n, np.bool) for n in newdtype.names]) + newmask = np.recarray(_data.shape, newmdtype) + # Add the old masks + [newmask.setfield(_mask.getfield(*f), *f) + for f in _mask.dtype.fields.values()] + # Add the mask of the new field + newmask.setfield(ma.getmaskarray(newfield), + *newmask.dtype.fields[newfieldname]) + newdata._mask = newmask + return newdata diff --git a/python/user_packages/Python313/site-packages/numpy/ma/mrecords.pyi b/python/user_packages/Python313/site-packages/numpy/ma/mrecords.pyi new file mode 100644 index 0000000000000000000000000000000000000000..c11df1d064568472e7eb4ee85a1aca16601bf48b --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/ma/mrecords.pyi @@ -0,0 +1,96 @@ +from typing import Any, Generic +from typing_extensions import TypeVar + +import numpy as np +from numpy._typing import _AnyShape + +from .core import MaskedArray + +__all__ = [ + "MaskedRecords", + "mrecarray", + "fromarrays", + "fromrecords", + "fromtextfile", + "addfield", +] + +_ShapeT_co = TypeVar("_ShapeT_co", bound=tuple[int, ...], default=_AnyShape, covariant=True) +_DTypeT_co = TypeVar("_DTypeT_co", bound=np.dtype, default=np.dtype, covariant=True) + +class MaskedRecords(MaskedArray[_ShapeT_co, _DTypeT_co], Generic[_ShapeT_co, _DTypeT_co]): + def __new__( + cls, + shape, + dtype=..., + buf=..., + offset=..., + strides=..., + formats=..., + names=..., + titles=..., + byteorder=..., + aligned=..., + mask=..., + hard_mask=..., + fill_value=..., + keep_mask=..., + copy=..., + **options, + ): ... + _mask: Any + _fill_value: Any + @property + def _data(self): ... + @property + def _fieldmask(self): ... + def __array_finalize__(self, obj): ... + def __len__(self): ... + def __getattribute__(self, attr): ... + def __setattr__(self, attr, val): ... + def __getitem__(self, indx): ... + def __setitem__(self, indx, value): ... + def view(self, dtype=None, type=None): ... + def harden_mask(self): ... + def soften_mask(self): ... + def copy(self): ... + def tolist(self, fill_value=None): ... + def __reduce__(self): ... + +mrecarray = MaskedRecords + +def fromarrays( + arraylist, + dtype=None, + shape=None, + formats=None, + names=None, + titles=None, + aligned=False, + byteorder=None, + fill_value=None, +): ... + +def fromrecords( + reclist, + dtype=None, + shape=None, + formats=None, + names=None, + titles=None, + aligned=False, + byteorder=None, + fill_value=None, + mask=..., +): ... + +def fromtextfile( + fname, + delimiter=None, + commentchar="#", + missingchar="", + varnames=None, + vartypes=None, +): ... + +def addfield(mrecord, newfield, newfieldname=None): ... diff --git a/python/user_packages/Python313/site-packages/numpy/ma/testutils.py b/python/user_packages/Python313/site-packages/numpy/ma/testutils.py new file mode 100644 index 0000000000000000000000000000000000000000..2c72a530c5959aa50cd96008b70686295660d0e4 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/ma/testutils.py @@ -0,0 +1,294 @@ +"""Miscellaneous functions for testing masked arrays and subclasses + +:author: Pierre Gerard-Marchant +:contact: pierregm_at_uga_dot_edu + +""" +import operator + +import numpy as np +import numpy._core.umath as umath +import numpy.testing +from numpy import ndarray +from numpy.testing import ( # noqa: F401 + assert_, + assert_allclose, + assert_array_almost_equal_nulp, + assert_raises, + build_err_msg, +) + +from .core import filled, getmask, mask_or, masked, masked_array, nomask + +__all__masked = [ + 'almost', 'approx', 'assert_almost_equal', 'assert_array_almost_equal', + 'assert_array_approx_equal', 'assert_array_compare', + 'assert_array_equal', 'assert_array_less', 'assert_close', + 'assert_equal', 'assert_equal_records', 'assert_mask_equal', + 'assert_not_equal', 'fail_if_array_equal', + ] + +# Include some normal test functions to avoid breaking other projects who +# have mistakenly included them from this file. SciPy is one. That is +# unfortunate, as some of these functions are not intended to work with +# masked arrays. But there was no way to tell before. +from unittest import TestCase # noqa: F401 + +__some__from_testing = [ + 'TestCase', 'assert_', 'assert_allclose', 'assert_array_almost_equal_nulp', + 'assert_raises' + ] + +__all__ = __all__masked + __some__from_testing # noqa: PLE0605 + + +def approx(a, b, fill_value=True, rtol=1e-5, atol=1e-8): + """ + Returns true if all components of a and b are equal to given tolerances. + + If fill_value is True, masked values considered equal. Otherwise, + masked values are considered unequal. The relative error rtol should + be positive and << 1.0 The absolute error atol comes into play for + those elements of b that are very small or zero; it says how small a + must be also. + + """ + m = mask_or(getmask(a), getmask(b)) + d1 = filled(a) + d2 = filled(b) + if d1.dtype.char == "O" or d2.dtype.char == "O": + return np.equal(d1, d2).ravel() + x = filled( + masked_array(d1, copy=False, mask=m), fill_value + ).astype(np.float64) + y = filled(masked_array(d2, copy=False, mask=m), 1).astype(np.float64) + d = np.less_equal(umath.absolute(x - y), atol + rtol * umath.absolute(y)) + return d.ravel() + + +def almost(a, b, decimal=6, fill_value=True): + """ + Returns True if a and b are equal up to decimal places. + + If fill_value is True, masked values considered equal. Otherwise, + masked values are considered unequal. + + """ + m = mask_or(getmask(a), getmask(b)) + d1 = filled(a) + d2 = filled(b) + if d1.dtype.char == "O" or d2.dtype.char == "O": + return np.equal(d1, d2).ravel() + x = filled( + masked_array(d1, copy=False, mask=m), fill_value + ).astype(np.float64) + y = filled(masked_array(d2, copy=False, mask=m), 1).astype(np.float64) + d = np.around(np.abs(x - y), decimal) <= 10.0 ** (-decimal) + return d.ravel() + + +def _assert_equal_on_sequences(actual, desired, err_msg=''): + """ + Asserts the equality of two non-array sequences. + + """ + assert_equal(len(actual), len(desired), err_msg) + for k in range(len(desired)): + assert_equal(actual[k], desired[k], f'item={k!r}\n{err_msg}') + + +def assert_equal_records(a, b): + """ + Asserts that two records are equal. + + Pretty crude for now. + + """ + assert_equal(a.dtype, b.dtype) + for f in a.dtype.names: + (af, bf) = (operator.getitem(a, f), operator.getitem(b, f)) + if not (af is masked) and not (bf is masked): + assert_equal(operator.getitem(a, f), operator.getitem(b, f)) + + +def assert_equal(actual, desired, err_msg=''): + """ + Asserts that two items are equal. + + """ + # Case #1: dictionary ..... + if isinstance(desired, dict): + if not isinstance(actual, dict): + raise AssertionError(repr(type(actual))) + assert_equal(len(actual), len(desired), err_msg) + for k in desired: + if k not in actual: + raise AssertionError(f"{k} not in {actual}") + assert_equal(actual[k], desired[k], f'key={k!r}\n{err_msg}') + return + # Case #2: lists ..... + if isinstance(desired, (list, tuple)) and isinstance(actual, (list, tuple)): + return _assert_equal_on_sequences(actual, desired, err_msg='') + if not (isinstance(actual, ndarray) or isinstance(desired, ndarray)): + msg = build_err_msg([actual, desired], err_msg,) + if not desired == actual: + raise AssertionError(msg) + return + # Case #4. arrays or equivalent + if ((actual is masked) and not (desired is masked)) or \ + ((desired is masked) and not (actual is masked)): + msg = build_err_msg([actual, desired], + err_msg, header='', names=('x', 'y')) + raise ValueError(msg) + actual = np.asanyarray(actual) + desired = np.asanyarray(desired) + (actual_dtype, desired_dtype) = (actual.dtype, desired.dtype) + if actual_dtype.char == "S" and desired_dtype.char == "S": + return _assert_equal_on_sequences(actual.tolist(), + desired.tolist(), + err_msg='') + return assert_array_equal(actual, desired, err_msg) + + +def fail_if_equal(actual, desired, err_msg='',): + """ + Raises an assertion error if two items are equal. + + """ + if isinstance(desired, dict): + if not isinstance(actual, dict): + raise AssertionError(repr(type(actual))) + fail_if_equal(len(actual), len(desired), err_msg) + for k in desired: + if k not in actual: + raise AssertionError(repr(k)) + fail_if_equal(actual[k], desired[k], f'key={k!r}\n{err_msg}') + return + if isinstance(desired, (list, tuple)) and isinstance(actual, (list, tuple)): + fail_if_equal(len(actual), len(desired), err_msg) + for k in range(len(desired)): + fail_if_equal(actual[k], desired[k], f'item={k!r}\n{err_msg}') + return + if isinstance(actual, np.ndarray) or isinstance(desired, np.ndarray): + return fail_if_array_equal(actual, desired, err_msg) + msg = build_err_msg([actual, desired], err_msg) + if not desired != actual: + raise AssertionError(msg) + + +assert_not_equal = fail_if_equal + + +def assert_almost_equal(actual, desired, decimal=7, err_msg='', verbose=True): + """ + Asserts that two items are almost equal. + + The test is equivalent to abs(desired-actual) < 0.5 * 10**(-decimal). + + """ + if isinstance(actual, np.ndarray) or isinstance(desired, np.ndarray): + return assert_array_almost_equal(actual, desired, decimal=decimal, + err_msg=err_msg, verbose=verbose) + msg = build_err_msg([actual, desired], + err_msg=err_msg, verbose=verbose) + if not round(abs(desired - actual), decimal) == 0: + raise AssertionError(msg) + + +assert_close = assert_almost_equal + + +def assert_array_compare(comparison, x, y, err_msg='', verbose=True, header='', + fill_value=True): + """ + Asserts that comparison between two masked arrays is satisfied. + + The comparison is elementwise. + + """ + # Allocate a common mask and refill + m = mask_or(getmask(x), getmask(y)) + x = masked_array(x, copy=False, mask=m, keep_mask=False, subok=False) + y = masked_array(y, copy=False, mask=m, keep_mask=False, subok=False) + if ((x is masked) and not (y is masked)) or \ + ((y is masked) and not (x is masked)): + msg = build_err_msg([x, y], err_msg=err_msg, verbose=verbose, + header=header, names=('x', 'y')) + raise ValueError(msg) + # OK, now run the basic tests on filled versions + return np.testing.assert_array_compare(comparison, + x.filled(fill_value), + y.filled(fill_value), + err_msg=err_msg, + verbose=verbose, header=header) + + +def assert_array_equal(x, y, err_msg='', verbose=True): + """ + Checks the elementwise equality of two masked arrays. + + """ + assert_array_compare(operator.__eq__, x, y, + err_msg=err_msg, verbose=verbose, + header='Arrays are not equal') + + +def fail_if_array_equal(x, y, err_msg='', verbose=True): + """ + Raises an assertion error if two masked arrays are not equal elementwise. + + """ + def compare(x, y): + return (not np.all(approx(x, y))) + assert_array_compare(compare, x, y, err_msg=err_msg, verbose=verbose, + header='Arrays are not equal') + + +def assert_array_approx_equal(x, y, decimal=6, err_msg='', verbose=True): + """ + Checks the equality of two masked arrays, up to given number odecimals. + + The equality is checked elementwise. + + """ + def compare(x, y): + "Returns the result of the loose comparison between x and y)." + return approx(x, y, rtol=10. ** -decimal) + assert_array_compare(compare, x, y, err_msg=err_msg, verbose=verbose, + header='Arrays are not almost equal') + + +def assert_array_almost_equal(x, y, decimal=6, err_msg='', verbose=True): + """ + Checks the equality of two masked arrays, up to given number odecimals. + + The equality is checked elementwise. + + """ + def compare(x, y): + "Returns the result of the loose comparison between x and y)." + return almost(x, y, decimal) + assert_array_compare(compare, x, y, err_msg=err_msg, verbose=verbose, + header='Arrays are not almost equal') + + +def assert_array_less(x, y, err_msg='', verbose=True): + """ + Checks that x is smaller than y elementwise. + + """ + assert_array_compare(operator.__lt__, x, y, + err_msg=err_msg, verbose=verbose, + header='Arrays are not less-ordered') + + +def assert_mask_equal(m1, m2, err_msg=''): + """ + Asserts the equality of two masks. + + """ + if m1 is nomask: + assert_(m2 is nomask) + if m2 is nomask: + assert_(m1 is nomask) + assert_array_equal(m1, m2, err_msg=err_msg) diff --git a/python/user_packages/Python313/site-packages/numpy/ma/testutils.pyi b/python/user_packages/Python313/site-packages/numpy/ma/testutils.pyi new file mode 100644 index 0000000000000000000000000000000000000000..5760c8cf92fd8bb1a71862d416b5e8f36a3f1e8d --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/ma/testutils.pyi @@ -0,0 +1,69 @@ +import numpy as np +from numpy._typing import NDArray +from numpy.testing import ( + TestCase, + assert_, + assert_allclose, + assert_array_almost_equal_nulp, + assert_raises, +) +from numpy.testing._private.utils import _ComparisonFunc + +__all__ = [ + "TestCase", + "almost", + "approx", + "assert_", + "assert_allclose", + "assert_almost_equal", + "assert_array_almost_equal", + "assert_array_almost_equal_nulp", + "assert_array_approx_equal", + "assert_array_compare", + "assert_array_equal", + "assert_array_less", + "assert_close", + "assert_equal", + "assert_equal_records", + "assert_mask_equal", + "assert_not_equal", + "assert_raises", + "fail_if_array_equal", +] + +def approx( + a: object, b: object, fill_value: bool = True, rtol: float = 1e-5, atol: float = 1e-8 +) -> np.ndarray[tuple[int], np.dtype[np.bool]]: ... +def almost(a: object, b: object, decimal: int = 6, fill_value: bool = True) -> np.ndarray[tuple[int], np.dtype[np.bool]]: ... + +# +def assert_equal_records(a: NDArray[np.void], b: NDArray[np.void]) -> None: ... +def assert_equal(actual: object, desired: object, err_msg: str = "") -> None: ... +def fail_if_equal(actual: object, desired: object, err_msg: str = "") -> None: ... +def assert_almost_equal( + actual: object, desired: object, decimal: int = 7, err_msg: str = "", verbose: bool = True +) -> None: ... + +# +def assert_array_compare( + comparison: _ComparisonFunc, + x: object, + y: object, + err_msg: str = "", + verbose: bool = True, + header: str = "", + fill_value: bool = True, +) -> None: ... +def assert_array_equal(x: object, y: object, err_msg: str = "", verbose: bool = True) -> None: ... +def fail_if_array_equal(x: object, y: object, err_msg: str = "", verbose: bool = True) -> None: ... +def assert_array_approx_equal( + x: object, y: object, decimal: int = 6, err_msg: str = "", verbose: bool = True +) -> None: ... +def assert_array_almost_equal( + x: object, y: object, decimal: int = 6, err_msg: str = "", verbose: bool = True +) -> None: ... +def assert_array_less(x: object, y: object, err_msg: str = "", verbose: bool = True) -> None: ... +def assert_mask_equal(m1: object, m2: object, err_msg: str = "") -> None: ... + +assert_not_equal = fail_if_equal +assert_close = assert_almost_equal diff --git a/python/user_packages/Python313/site-packages/numpy/matrixlib/__init__.py b/python/user_packages/Python313/site-packages/numpy/matrixlib/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e376271aca708c7bd6bb3c34a0a31cba2cd0ff36 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/matrixlib/__init__.py @@ -0,0 +1,12 @@ +"""Sub-package containing the matrix class and related functions. + +""" +from . import defmatrix +from .defmatrix import * + +__all__ = defmatrix.__all__ + +from numpy._pytesttester import PytestTester + +test = PytestTester(__name__) +del PytestTester diff --git a/python/user_packages/Python313/site-packages/numpy/matrixlib/__init__.pyi b/python/user_packages/Python313/site-packages/numpy/matrixlib/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..cb5a8420eacfc2bb7a44331b1ecc8ab320c9d2b5 --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/matrixlib/__init__.pyi @@ -0,0 +1,3 @@ +from .defmatrix import asmatrix, bmat, matrix + +__all__ = ["matrix", "bmat", "asmatrix"] diff --git a/python/user_packages/Python313/site-packages/numpy/matrixlib/defmatrix.py b/python/user_packages/Python313/site-packages/numpy/matrixlib/defmatrix.py new file mode 100644 index 0000000000000000000000000000000000000000..62312a82cc60e9ae15bd8cf7b47481d09c26963c --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/matrixlib/defmatrix.py @@ -0,0 +1,1119 @@ +__all__ = ['matrix', 'bmat', 'asmatrix'] + +import ast +import sys +import warnings + +import numpy._core.numeric as N +from numpy._core.numeric import concatenate, isscalar +from numpy._utils import set_module + +# While not in __all__, matrix_power used to be defined here, so we import +# it for backward compatibility. +from numpy.linalg import matrix_power + + +def _convert_from_string(data): + for char in '[]': + data = data.replace(char, '') + + rows = data.split(';') + newdata = [] + for count, row in enumerate(rows): + trow = row.split(',') + newrow = [] + for col in trow: + temp = col.split() + newrow.extend(map(ast.literal_eval, temp)) + if count == 0: + Ncols = len(newrow) + elif len(newrow) != Ncols: + raise ValueError("Rows not the same size.") + newdata.append(newrow) + return newdata + + +@set_module('numpy') +def asmatrix(data, dtype=None): + """ + Interpret the input as a matrix. + + Unlike `matrix`, `asmatrix` does not make a copy if the input is already + a matrix or an ndarray. Equivalent to ``matrix(data, copy=False)``. + + Parameters + ---------- + data : array_like + Input data. + dtype : data-type + Data-type of the output matrix. + + Returns + ------- + mat : matrix + `data` interpreted as a matrix. + + Examples + -------- + >>> import numpy as np + >>> x = np.array([[1, 2], [3, 4]]) + + >>> m = np.asmatrix(x) + + >>> x[0,0] = 5 + + >>> m + matrix([[5, 2], + [3, 4]]) + + """ + return matrix(data, dtype=dtype, copy=False) + + +@set_module('numpy') +class matrix(N.ndarray): + """ + matrix(data, dtype=None, copy=True) + + Returns a matrix from an array-like object, or from a string of data. + + A matrix is a specialized 2-D array that retains its 2-D nature + through operations. It has certain special operators, such as ``*`` + (matrix multiplication) and ``**`` (matrix power). + + .. note:: It is no longer recommended to use this class, even for linear + algebra. Instead use regular arrays. The class may be removed + in the future. + + Parameters + ---------- + data : array_like or string + If `data` is a string, it is interpreted as a matrix with commas + or spaces separating columns, and semicolons separating rows. + dtype : data-type + Data-type of the output matrix. + copy : bool + If `data` is already an `ndarray`, then this flag determines + whether the data is copied (the default), or whether a view is + constructed. + + See Also + -------- + array + + Examples + -------- + >>> import numpy as np + >>> a = np.matrix('1 2; 3 4') + >>> a + matrix([[1, 2], + [3, 4]]) + + >>> np.matrix([[1, 2], [3, 4]]) + matrix([[1, 2], + [3, 4]]) + + """ + __array_priority__ = 10.0 + + def __new__(subtype, data, dtype=None, copy=True): + warnings.warn('the matrix subclass is not the recommended way to ' + 'represent matrices or deal with linear algebra (see ' + 'https://docs.scipy.org/doc/numpy/user/' + 'numpy-for-matlab-users.html). ' + 'Please adjust your code to use regular ndarray.', + PendingDeprecationWarning, stacklevel=2) + if isinstance(data, matrix): + dtype2 = data.dtype + if (dtype is None): + dtype = dtype2 + if (dtype2 == dtype) and (not copy): + return data + return data.astype(dtype) + + if isinstance(data, N.ndarray): + if dtype is None: + intype = data.dtype + else: + intype = N.dtype(dtype) + new = data.view(subtype) + if intype != data.dtype: + return new.astype(intype) + if copy: + return new.copy() + else: + return new + + if isinstance(data, str): + data = _convert_from_string(data) + + # now convert data to an array + copy = None if not copy else True + arr = N.array(data, dtype=dtype, copy=copy) + ndim = arr.ndim + shape = arr.shape + if (ndim > 2): + raise ValueError("matrix must be 2-dimensional") + elif ndim == 0: + shape = (1, 1) + elif ndim == 1: + shape = (1, shape[0]) + + order = 'C' + if (ndim == 2) and arr.flags.fortran: + order = 'F' + + if not (order or arr.flags.contiguous): + arr = arr.copy() + + ret = N.ndarray.__new__(subtype, shape, arr.dtype, + buffer=arr, + order=order) + return ret + + def __array_finalize__(self, obj): + self._getitem = False + if (isinstance(obj, matrix) and obj._getitem): + return + ndim = self.ndim + if (ndim == 2): + return + if (ndim > 2): + newshape = tuple(x for x in self.shape if x > 1) + ndim = len(newshape) + if ndim == 2: + self.shape = newshape + return + elif (ndim > 2): + raise ValueError("shape too large to be a matrix.") + else: + newshape = self.shape + if ndim == 0: + self.shape = (1, 1) + elif ndim == 1: + self.shape = (1, newshape[0]) + return + + def __getitem__(self, index): + self._getitem = True + + try: + out = N.ndarray.__getitem__(self, index) + finally: + self._getitem = False + + if not isinstance(out, N.ndarray): + return out + + if out.ndim == 0: + return out[()] + if out.ndim == 1: + sh = out.shape[0] + # Determine when we should have a column array + try: + n = len(index) + except Exception: + n = 0 + if n > 1 and isscalar(index[1]): + out.shape = (sh, 1) + else: + out.shape = (1, sh) + return out + + def __mul__(self, other): + if isinstance(other, (N.ndarray, list, tuple)): + # This promotes 1-D vectors to row vectors + return N.dot(self, asmatrix(other)) + if isscalar(other) or not hasattr(other, '__rmul__'): + return N.dot(self, other) + return NotImplemented + + def __rmul__(self, other): + return N.dot(other, self) + + def __imul__(self, other): + self[:] = self * other + return self + + def __pow__(self, other): + return matrix_power(self, other) + + def __ipow__(self, other): + self[:] = self ** other + return self + + def __rpow__(self, other): + return NotImplemented + + def _align(self, axis): + """A convenience function for operations that need to preserve axis + orientation. + """ + if axis is None: + return self[0, 0] + elif axis == 0: + return self + elif axis == 1: + return self.transpose() + else: + raise ValueError("unsupported axis") + + def _collapse(self, axis): + """A convenience function for operations that want to collapse + to a scalar like _align, but are using keepdims=True + """ + if axis is None: + return self[0, 0] + else: + return self + + # Necessary because base-class tolist expects dimension + # reduction by x[0] + def tolist(self): + """ + Return the matrix as a (possibly nested) list. + + See `ndarray.tolist` for full documentation. + + See Also + -------- + ndarray.tolist + + Examples + -------- + >>> x = np.matrix(np.arange(12).reshape((3,4))); x + matrix([[ 0, 1, 2, 3], + [ 4, 5, 6, 7], + [ 8, 9, 10, 11]]) + >>> x.tolist() + [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]] + + """ + return self.__array__().tolist() + + # To preserve orientation of result... + def sum(self, axis=None, dtype=None, out=None): + """ + Returns the sum of the matrix elements, along the given axis. + + Refer to `numpy.sum` for full documentation. + + See Also + -------- + numpy.sum + + Notes + ----- + This is the same as `ndarray.sum`, except that where an `ndarray` would + be returned, a `matrix` object is returned instead. + + Examples + -------- + >>> x = np.matrix([[1, 2], [4, 3]]) + >>> x.sum() + 10 + >>> x.sum(axis=1) + matrix([[3], + [7]]) + >>> x.sum(axis=1, dtype='float') + matrix([[3.], + [7.]]) + >>> out = np.zeros((2, 1), dtype='float') + >>> x.sum(axis=1, dtype='float', out=np.asmatrix(out)) + matrix([[3.], + [7.]]) + + """ + return N.ndarray.sum(self, axis, dtype, out, keepdims=True)._collapse(axis) + + # To update docstring from array to matrix... + def squeeze(self, axis=None): + """ + Return a possibly reshaped matrix. + + Refer to `numpy.squeeze` for more documentation. + + Parameters + ---------- + axis : None or int or tuple of ints, optional + Selects a subset of the axes of length one in the shape. + If an axis is selected with shape entry greater than one, + an error is raised. + + Returns + ------- + squeezed : matrix + The matrix, but as a (1, N) matrix if it had shape (N, 1). + + See Also + -------- + numpy.squeeze : related function + + Notes + ----- + If `m` has a single column then that column is returned + as the single row of a matrix. Otherwise `m` is returned. + The returned matrix is always either `m` itself or a view into `m`. + Supplying an axis keyword argument will not affect the returned matrix + but it may cause an error to be raised. + + Examples + -------- + >>> c = np.matrix([[1], [2]]) + >>> c + matrix([[1], + [2]]) + >>> c.squeeze() + matrix([[1, 2]]) + >>> r = c.T + >>> r + matrix([[1, 2]]) + >>> r.squeeze() + matrix([[1, 2]]) + >>> m = np.matrix([[1, 2], [3, 4]]) + >>> m.squeeze() + matrix([[1, 2], + [3, 4]]) + + """ + return N.ndarray.squeeze(self, axis=axis) + + # To update docstring from array to matrix... + def flatten(self, order='C'): + """ + Return a flattened copy of the matrix. + + All `N` elements of the matrix are placed into a single row. + + Parameters + ---------- + order : {'C', 'F', 'A', 'K'}, optional + 'C' means to flatten in row-major (C-style) order. 'F' means to + flatten in column-major (Fortran-style) order. 'A' means to + flatten in column-major order if `m` is Fortran *contiguous* in + memory, row-major order otherwise. 'K' means to flatten `m` in + the order the elements occur in memory. The default is 'C'. + + Returns + ------- + y : matrix + A copy of the matrix, flattened to a `(1, N)` matrix where `N` + is the number of elements in the original matrix. + + See Also + -------- + ravel : Return a flattened array. + flat : A 1-D flat iterator over the matrix. + + Examples + -------- + >>> m = np.matrix([[1,2], [3,4]]) + >>> m.flatten() + matrix([[1, 2, 3, 4]]) + >>> m.flatten('F') + matrix([[1, 3, 2, 4]]) + + """ + return N.ndarray.flatten(self, order=order) + + def mean(self, axis=None, dtype=None, out=None): + """ + Returns the average of the matrix elements along the given axis. + + Refer to `numpy.mean` for full documentation. + + See Also + -------- + numpy.mean + + Notes + ----- + Same as `ndarray.mean` except that, where that returns an `ndarray`, + this returns a `matrix` object. + + Examples + -------- + >>> x = np.matrix(np.arange(12).reshape((3, 4))) + >>> x + matrix([[ 0, 1, 2, 3], + [ 4, 5, 6, 7], + [ 8, 9, 10, 11]]) + >>> x.mean() + 5.5 + >>> x.mean(0) + matrix([[4., 5., 6., 7.]]) + >>> x.mean(1) + matrix([[ 1.5], + [ 5.5], + [ 9.5]]) + + """ + return N.ndarray.mean(self, axis, dtype, out, keepdims=True)._collapse(axis) + + def std(self, axis=None, dtype=None, out=None, ddof=0): + """ + Return the standard deviation of the array elements along the given axis. + + Refer to `numpy.std` for full documentation. + + See Also + -------- + numpy.std + + Notes + ----- + This is the same as `ndarray.std`, except that where an `ndarray` would + be returned, a `matrix` object is returned instead. + + Examples + -------- + >>> x = np.matrix(np.arange(12).reshape((3, 4))) + >>> x + matrix([[ 0, 1, 2, 3], + [ 4, 5, 6, 7], + [ 8, 9, 10, 11]]) + >>> x.std() + 3.4520525295346629 # may vary + >>> x.std(0) + matrix([[ 3.26598632, 3.26598632, 3.26598632, 3.26598632]]) # may vary + >>> x.std(1) + matrix([[ 1.11803399], + [ 1.11803399], + [ 1.11803399]]) + + """ + return N.ndarray.std(self, axis, dtype, out, ddof, + keepdims=True)._collapse(axis) + + def var(self, axis=None, dtype=None, out=None, ddof=0): + """ + Returns the variance of the matrix elements, along the given axis. + + Refer to `numpy.var` for full documentation. + + See Also + -------- + numpy.var + + Notes + ----- + This is the same as `ndarray.var`, except that where an `ndarray` would + be returned, a `matrix` object is returned instead. + + Examples + -------- + >>> x = np.matrix(np.arange(12).reshape((3, 4))) + >>> x + matrix([[ 0, 1, 2, 3], + [ 4, 5, 6, 7], + [ 8, 9, 10, 11]]) + >>> x.var() + 11.916666666666666 + >>> x.var(0) + matrix([[ 10.66666667, 10.66666667, 10.66666667, 10.66666667]]) # may vary + >>> x.var(1) + matrix([[1.25], + [1.25], + [1.25]]) + + """ + return N.ndarray.var(self, axis, dtype, out, ddof, + keepdims=True)._collapse(axis) + + def prod(self, axis=None, dtype=None, out=None): + """ + Return the product of the array elements over the given axis. + + Refer to `prod` for full documentation. + + See Also + -------- + prod, ndarray.prod + + Notes + ----- + Same as `ndarray.prod`, except, where that returns an `ndarray`, this + returns a `matrix` object instead. + + Examples + -------- + >>> x = np.matrix(np.arange(12).reshape((3,4))); x + matrix([[ 0, 1, 2, 3], + [ 4, 5, 6, 7], + [ 8, 9, 10, 11]]) + >>> x.prod() + 0 + >>> x.prod(0) + matrix([[ 0, 45, 120, 231]]) + >>> x.prod(1) + matrix([[ 0], + [ 840], + [7920]]) + + """ + return N.ndarray.prod(self, axis, dtype, out, keepdims=True)._collapse(axis) + + def any(self, axis=None, out=None): + """ + Test whether any array element along a given axis evaluates to True. + + Refer to `numpy.any` for full documentation. + + Parameters + ---------- + axis : int, optional + Axis along which logical OR is performed + out : ndarray, optional + Output to existing array instead of creating new one, must have + same shape as expected output + + Returns + ------- + any : bool, ndarray + Returns a single bool if `axis` is ``None``; otherwise, + returns `ndarray` + + """ + return N.ndarray.any(self, axis, out, keepdims=True)._collapse(axis) + + def all(self, axis=None, out=None): + """ + Test whether all matrix elements along a given axis evaluate to True. + + Parameters + ---------- + See `numpy.all` for complete descriptions + + See Also + -------- + numpy.all + + Notes + ----- + This is the same as `ndarray.all`, but it returns a `matrix` object. + + Examples + -------- + >>> x = np.matrix(np.arange(12).reshape((3,4))); x + matrix([[ 0, 1, 2, 3], + [ 4, 5, 6, 7], + [ 8, 9, 10, 11]]) + >>> y = x[0]; y + matrix([[0, 1, 2, 3]]) + >>> (x == y) + matrix([[ True, True, True, True], + [False, False, False, False], + [False, False, False, False]]) + >>> (x == y).all() + False + >>> (x == y).all(0) + matrix([[False, False, False, False]]) + >>> (x == y).all(1) + matrix([[ True], + [False], + [False]]) + + """ + return N.ndarray.all(self, axis, out, keepdims=True)._collapse(axis) + + def max(self, axis=None, out=None): + """ + Return the maximum value along an axis. + + Parameters + ---------- + See `amax` for complete descriptions + + See Also + -------- + amax, ndarray.max + + Notes + ----- + This is the same as `ndarray.max`, but returns a `matrix` object + where `ndarray.max` would return an ndarray. + + Examples + -------- + >>> x = np.matrix(np.arange(12).reshape((3,4))); x + matrix([[ 0, 1, 2, 3], + [ 4, 5, 6, 7], + [ 8, 9, 10, 11]]) + >>> x.max() + 11 + >>> x.max(0) + matrix([[ 8, 9, 10, 11]]) + >>> x.max(1) + matrix([[ 3], + [ 7], + [11]]) + + """ + return N.ndarray.max(self, axis, out, keepdims=True)._collapse(axis) + + def argmax(self, axis=None, out=None): + """ + Indexes of the maximum values along an axis. + + Return the indexes of the first occurrences of the maximum values + along the specified axis. If axis is None, the index is for the + flattened matrix. + + Parameters + ---------- + See `numpy.argmax` for complete descriptions + + See Also + -------- + numpy.argmax + + Notes + ----- + This is the same as `ndarray.argmax`, but returns a `matrix` object + where `ndarray.argmax` would return an `ndarray`. + + Examples + -------- + >>> x = np.matrix(np.arange(12).reshape((3,4))); x + matrix([[ 0, 1, 2, 3], + [ 4, 5, 6, 7], + [ 8, 9, 10, 11]]) + >>> x.argmax() + 11 + >>> x.argmax(0) + matrix([[2, 2, 2, 2]]) + >>> x.argmax(1) + matrix([[3], + [3], + [3]]) + + """ + return N.ndarray.argmax(self, axis, out)._align(axis) + + def min(self, axis=None, out=None): + """ + Return the minimum value along an axis. + + Parameters + ---------- + See `amin` for complete descriptions. + + See Also + -------- + amin, ndarray.min + + Notes + ----- + This is the same as `ndarray.min`, but returns a `matrix` object + where `ndarray.min` would return an ndarray. + + Examples + -------- + >>> x = -np.matrix(np.arange(12).reshape((3,4))); x + matrix([[ 0, -1, -2, -3], + [ -4, -5, -6, -7], + [ -8, -9, -10, -11]]) + >>> x.min() + -11 + >>> x.min(0) + matrix([[ -8, -9, -10, -11]]) + >>> x.min(1) + matrix([[ -3], + [ -7], + [-11]]) + + """ + return N.ndarray.min(self, axis, out, keepdims=True)._collapse(axis) + + def argmin(self, axis=None, out=None): + """ + Indexes of the minimum values along an axis. + + Return the indexes of the first occurrences of the minimum values + along the specified axis. If axis is None, the index is for the + flattened matrix. + + Parameters + ---------- + See `numpy.argmin` for complete descriptions. + + See Also + -------- + numpy.argmin + + Notes + ----- + This is the same as `ndarray.argmin`, but returns a `matrix` object + where `ndarray.argmin` would return an `ndarray`. + + Examples + -------- + >>> x = -np.matrix(np.arange(12).reshape((3,4))); x + matrix([[ 0, -1, -2, -3], + [ -4, -5, -6, -7], + [ -8, -9, -10, -11]]) + >>> x.argmin() + 11 + >>> x.argmin(0) + matrix([[2, 2, 2, 2]]) + >>> x.argmin(1) + matrix([[3], + [3], + [3]]) + + """ + return N.ndarray.argmin(self, axis, out)._align(axis) + + def ptp(self, axis=None, out=None): + """ + Peak-to-peak (maximum - minimum) value along the given axis. + + Refer to `numpy.ptp` for full documentation. + + See Also + -------- + numpy.ptp + + Notes + ----- + Same as `ndarray.ptp`, except, where that would return an `ndarray` object, + this returns a `matrix` object. + + Examples + -------- + >>> x = np.matrix(np.arange(12).reshape((3,4))); x + matrix([[ 0, 1, 2, 3], + [ 4, 5, 6, 7], + [ 8, 9, 10, 11]]) + >>> x.ptp() + 11 + >>> x.ptp(0) + matrix([[8, 8, 8, 8]]) + >>> x.ptp(1) + matrix([[3], + [3], + [3]]) + + """ + return N.ptp(self, axis, out)._align(axis) + + @property + def I(self): # noqa: E743 + """ + Returns the (multiplicative) inverse of invertible `self`. + + Parameters + ---------- + None + + Returns + ------- + ret : matrix object + If `self` is non-singular, `ret` is such that ``ret * self`` == + ``self * ret`` == ``np.matrix(np.eye(self[0,:].size))`` all return + ``True``. + + Raises + ------ + numpy.linalg.LinAlgError: Singular matrix + If `self` is singular. + + See Also + -------- + linalg.inv + + Examples + -------- + >>> m = np.matrix('[1, 2; 3, 4]'); m + matrix([[1, 2], + [3, 4]]) + >>> m.getI() + matrix([[-2. , 1. ], + [ 1.5, -0.5]]) + >>> m.getI() * m + matrix([[ 1., 0.], # may vary + [ 0., 1.]]) + + """ + M, N = self.shape + if M == N: + from numpy.linalg import inv as func + else: + from numpy.linalg import pinv as func + return asmatrix(func(self)) + + @property + def A(self): + """ + Return `self` as an `ndarray` object. + + Equivalent to ``np.asarray(self)``. + + Parameters + ---------- + None + + Returns + ------- + ret : ndarray + `self` as an `ndarray` + + Examples + -------- + >>> x = np.matrix(np.arange(12).reshape((3,4))); x + matrix([[ 0, 1, 2, 3], + [ 4, 5, 6, 7], + [ 8, 9, 10, 11]]) + >>> x.getA() + array([[ 0, 1, 2, 3], + [ 4, 5, 6, 7], + [ 8, 9, 10, 11]]) + + """ + return self.__array__() + + @property + def A1(self): + """ + Return `self` as a flattened `ndarray`. + + Equivalent to ``np.asarray(x).ravel()`` + + Parameters + ---------- + None + + Returns + ------- + ret : ndarray + `self`, 1-D, as an `ndarray` + + Examples + -------- + >>> x = np.matrix(np.arange(12).reshape((3,4))); x + matrix([[ 0, 1, 2, 3], + [ 4, 5, 6, 7], + [ 8, 9, 10, 11]]) + >>> x.getA1() + array([ 0, 1, 2, ..., 9, 10, 11]) + + + """ + return self.__array__().ravel() + + def ravel(self, order='C'): + """ + Return a flattened matrix. + + Refer to `numpy.ravel` for more documentation. + + Parameters + ---------- + order : {'C', 'F', 'A', 'K'}, optional + The elements of `m` are read using this index order. 'C' means to + index the elements in C-like order, with the last axis index + changing fastest, back to the first axis index changing slowest. + 'F' means to index the elements in Fortran-like index order, with + the first index changing fastest, and the last index changing + slowest. Note that the 'C' and 'F' options take no account of the + memory layout of the underlying array, and only refer to the order + of axis indexing. 'A' means to read the elements in Fortran-like + index order if `m` is Fortran *contiguous* in memory, C-like order + otherwise. 'K' means to read the elements in the order they occur + in memory, except for reversing the data when strides are negative. + By default, 'C' index order is used. + + Returns + ------- + ret : matrix + Return the matrix flattened to shape `(1, N)` where `N` + is the number of elements in the original matrix. + A copy is made only if necessary. + + See Also + -------- + matrix.flatten : returns a similar output matrix but always a copy + matrix.flat : a flat iterator on the array. + numpy.ravel : related function which returns an ndarray + + """ + return N.ndarray.ravel(self, order=order) + + @property + def T(self): + """ + Returns the transpose of the matrix. + + Does *not* conjugate! For the complex conjugate transpose, use ``.H``. + + Parameters + ---------- + None + + Returns + ------- + ret : matrix object + The (non-conjugated) transpose of the matrix. + + See Also + -------- + transpose, getH + + Examples + -------- + >>> m = np.matrix('[1, 2; 3, 4]') + >>> m + matrix([[1, 2], + [3, 4]]) + >>> m.getT() + matrix([[1, 3], + [2, 4]]) + + """ + return self.transpose() + + @property + def H(self): + """ + Returns the (complex) conjugate transpose of `self`. + + Equivalent to ``np.transpose(self)`` if `self` is real-valued. + + Parameters + ---------- + None + + Returns + ------- + ret : matrix object + complex conjugate transpose of `self` + + Examples + -------- + >>> x = np.matrix(np.arange(12).reshape((3,4))) + >>> z = x - 1j*x; z + matrix([[ 0. +0.j, 1. -1.j, 2. -2.j, 3. -3.j], + [ 4. -4.j, 5. -5.j, 6. -6.j, 7. -7.j], + [ 8. -8.j, 9. -9.j, 10.-10.j, 11.-11.j]]) + >>> z.getH() + matrix([[ 0. -0.j, 4. +4.j, 8. +8.j], + [ 1. +1.j, 5. +5.j, 9. +9.j], + [ 2. +2.j, 6. +6.j, 10.+10.j], + [ 3. +3.j, 7. +7.j, 11.+11.j]]) + + """ + if issubclass(self.dtype.type, N.complexfloating): + return self.transpose().conjugate() + else: + return self.transpose() + + # kept for compatibility + getT = T.fget + getA = A.fget + getA1 = A1.fget + getH = H.fget + getI = I.fget + +def _from_string(str, gdict, ldict): + rows = str.split(';') + rowtup = [] + for row in rows: + trow = row.split(',') + newrow = [] + for x in trow: + newrow.extend(x.split()) + trow = newrow + coltup = [] + for col in trow: + col = col.strip() + try: + thismat = ldict[col] + except KeyError: + try: + thismat = gdict[col] + except KeyError as e: + raise NameError(f"name {col!r} is not defined") from None + + coltup.append(thismat) + rowtup.append(concatenate(coltup, axis=-1)) + return concatenate(rowtup, axis=0) + + +@set_module('numpy') +def bmat(obj, ldict=None, gdict=None): + """ + Build a matrix object from a string, nested sequence, or array. + + Parameters + ---------- + obj : str or array_like + Input data. If a string, variables in the current scope may be + referenced by name. + ldict : dict, optional + A dictionary that replaces local operands in current frame. + Ignored if `obj` is not a string or `gdict` is None. + gdict : dict, optional + A dictionary that replaces global operands in current frame. + Ignored if `obj` is not a string. + + Returns + ------- + out : matrix + Returns a matrix object, which is a specialized 2-D array. + + See Also + -------- + block : + A generalization of this function for N-d arrays, that returns normal + ndarrays. + + Examples + -------- + >>> import numpy as np + >>> A = np.asmatrix('1 1; 1 1') + >>> B = np.asmatrix('2 2; 2 2') + >>> C = np.asmatrix('3 4; 5 6') + >>> D = np.asmatrix('7 8; 9 0') + + All the following expressions construct the same block matrix: + + >>> np.bmat([[A, B], [C, D]]) + matrix([[1, 1, 2, 2], + [1, 1, 2, 2], + [3, 4, 7, 8], + [5, 6, 9, 0]]) + >>> np.bmat(np.r_[np.c_[A, B], np.c_[C, D]]) + matrix([[1, 1, 2, 2], + [1, 1, 2, 2], + [3, 4, 7, 8], + [5, 6, 9, 0]]) + >>> np.bmat('A,B; C,D') + matrix([[1, 1, 2, 2], + [1, 1, 2, 2], + [3, 4, 7, 8], + [5, 6, 9, 0]]) + + """ + if isinstance(obj, str): + if gdict is None: + # get previous frame + frame = sys._getframe().f_back + glob_dict = frame.f_globals + loc_dict = frame.f_locals + else: + glob_dict = gdict + loc_dict = ldict + + return matrix(_from_string(obj, glob_dict, loc_dict)) + + if isinstance(obj, (tuple, list)): + # [[A,B],[C,D]] + arr_rows = [] + for row in obj: + if isinstance(row, N.ndarray): # not 2-d + return matrix(concatenate(obj, axis=-1)) + else: + arr_rows.append(concatenate(row, axis=-1)) + return matrix(concatenate(arr_rows, axis=0)) + if isinstance(obj, N.ndarray): + return matrix(obj) diff --git a/python/user_packages/Python313/site-packages/numpy/matrixlib/defmatrix.pyi b/python/user_packages/Python313/site-packages/numpy/matrixlib/defmatrix.pyi new file mode 100644 index 0000000000000000000000000000000000000000..825ab89ccaef215f1b7dea9b635c014a1b35b8ae --- /dev/null +++ b/python/user_packages/Python313/site-packages/numpy/matrixlib/defmatrix.pyi @@ -0,0 +1,218 @@ +from _typeshed import Incomplete +from collections.abc import Mapping, Sequence +from types import EllipsisType +from typing import Any, ClassVar, Literal as L, Self, SupportsIndex, TypeAlias, overload +from typing_extensions import TypeVar + +import numpy as np +from numpy._typing import ( + ArrayLike, + DTypeLike, + NDArray, + _AnyShape, + _ArrayLikeInt_co, + _NestedSequence, + _ShapeLike, +) + +__all__ = ["asmatrix", "bmat", "matrix"] + +_T = TypeVar("_T") +_ArrayT = TypeVar("_ArrayT", bound=np.ndarray) +_BoolOrIntArrayT = TypeVar("_BoolOrIntArrayT", bound=NDArray[np.integer | np.bool]) +_ScalarT = TypeVar("_ScalarT", bound=np.generic) +_ShapeT_co = TypeVar("_ShapeT_co", bound=_2D, default=_2D, covariant=True) +_DTypeT_co = TypeVar("_DTypeT_co", bound=np.dtype, default=np.dtype, covariant=True) + +_2D: TypeAlias = tuple[int, int] +_Matrix: TypeAlias = matrix[_2D, np.dtype[_ScalarT]] +_ToIndex1: TypeAlias = slice | EllipsisType | NDArray[np.integer | np.bool] | _NestedSequence[int] | None +_ToIndex2: TypeAlias = tuple[_ToIndex1, _ToIndex1 | SupportsIndex] | tuple[_ToIndex1 | SupportsIndex, _ToIndex1] + +class matrix(np.ndarray[_ShapeT_co, _DTypeT_co]): + __array_priority__: ClassVar[float] = 10.0 # pyright: ignore[reportIncompatibleMethodOverride] + + def __new__( + subtype, # pyright: ignore[reportSelfClsParameterName] + data: ArrayLike, + dtype: DTypeLike | None = None, + copy: bool = True, + ) -> _Matrix[Incomplete]: ... + + # + @overload # type: ignore[override] + def __getitem__( + self, key: SupportsIndex | _ArrayLikeInt_co | tuple[SupportsIndex | _ArrayLikeInt_co, ...], / + ) -> Incomplete: ... + @overload + def __getitem__(self, key: _ToIndex1 | _ToIndex2, /) -> matrix[_2D, _DTypeT_co]: ... + @overload + def __getitem__(self: _Matrix[np.void], key: str, /) -> _Matrix[Incomplete]: ... + @overload + def __getitem__(self: _Matrix[np.void], key: list[str], /) -> matrix[_2D, _DTypeT_co]: ... # pyright: ignore[reportIncompatibleMethodOverride] + + # + def __mul__(self, other: ArrayLike, /) -> _Matrix[Incomplete]: ... # type: ignore[override] # pyright: ignore[reportIncompatibleMethodOverride] + def __rmul__(self, other: ArrayLike, /) -> _Matrix[Incomplete]: ... # type: ignore[override] # pyright: ignore[reportIncompatibleMethodOverride] + + # + def __pow__(self, other: ArrayLike, /) -> _Matrix[Incomplete]: ... # type: ignore[override] # pyright: ignore[reportIncompatibleMethodOverride] + def __rpow__(self, other: ArrayLike, /) -> _Matrix[Incomplete]: ... # type: ignore[override] # pyright: ignore[reportIncompatibleMethodOverride] + + # keep in sync with `prod` and `mean` + @overload # type: ignore[override] + def sum(self, axis: None = None, dtype: DTypeLike | None = None, out: None = None) -> Incomplete: ... + @overload + def sum(self, axis: _ShapeLike, dtype: DTypeLike | None = None, out: None = None) -> _Matrix[Incomplete]: ... + @overload + def sum(self, axis: _ShapeLike | None, dtype: DTypeLike | None, out: _ArrayT) -> _ArrayT: ... + @overload + def sum(self, axis: _ShapeLike | None = None, dtype: DTypeLike | None = None, *, out: _ArrayT) -> _ArrayT: ... # pyright: ignore[reportIncompatibleMethodOverride] + + # keep in sync with `sum` and `mean` + @overload # type: ignore[override] + def prod(self, axis: None = None, dtype: DTypeLike | None = None, out: None = None) -> Incomplete: ... + @overload + def prod(self, axis: _ShapeLike, dtype: DTypeLike | None = None, out: None = None) -> _Matrix[Incomplete]: ... + @overload + def prod(self, axis: _ShapeLike | None, dtype: DTypeLike | None, out: _ArrayT) -> _ArrayT: ... + @overload + def prod(self, axis: _ShapeLike | None = None, dtype: DTypeLike | None = None, *, out: _ArrayT) -> _ArrayT: ... # pyright: ignore[reportIncompatibleMethodOverride] + + # keep in sync with `sum` and `prod` + @overload # type: ignore[override] + def mean(self, axis: None = None, dtype: DTypeLike | None = None, out: None = None) -> Incomplete: ... + @overload + def mean(self, axis: _ShapeLike, dtype: DTypeLike | None = None, out: None = None) -> _Matrix[Incomplete]: ... + @overload + def mean(self, axis: _ShapeLike | None, dtype: DTypeLike | None, out: _ArrayT) -> _ArrayT: ... + @overload + def mean(self, axis: _ShapeLike | None = None, dtype: DTypeLike | None = None, *, out: _ArrayT) -> _ArrayT: ... # pyright: ignore[reportIncompatibleMethodOverride] + + # keep in sync with `var` + @overload # type: ignore[override] + def std(self, axis: None = None, dtype: DTypeLike | None = None, out: None = None, ddof: float = 0) -> Incomplete: ... + @overload + def std(self, axis: _ShapeLike, dtype: DTypeLike | None = None, out: None = None, ddof: float = 0) -> _Matrix[Incomplete]: ... + @overload + def std(self, axis: _ShapeLike | None, dtype: DTypeLike | None, out: _ArrayT, ddof: float = 0) -> _ArrayT: ... + @overload + def std( # pyright: ignore[reportIncompatibleMethodOverride] + self, axis: _ShapeLike | None = None, dtype: DTypeLike | None = None, *, out: _ArrayT, ddof: float = 0 + ) -> _ArrayT: ... + + # keep in sync with `std` + @overload # type: ignore[override] + def var(self, axis: None = None, dtype: DTypeLike | None = None, out: None = None, ddof: float = 0) -> Incomplete: ... + @overload + def var(self, axis: _ShapeLike, dtype: DTypeLike | None = None, out: None = None, ddof: float = 0) -> _Matrix[Incomplete]: ... + @overload + def var(self, axis: _ShapeLike | None, dtype: DTypeLike | None, out: _ArrayT, ddof: float = 0) -> _ArrayT: ... + @overload + def var( # pyright: ignore[reportIncompatibleMethodOverride] + self, axis: _ShapeLike | None = None, dtype: DTypeLike | None = None, *, out: _ArrayT, ddof: float = 0 + ) -> _ArrayT: ... + + # keep in sync with `all` + @overload # type: ignore[override] + def any(self, axis: None = None, out: None = None) -> np.bool: ... + @overload + def any(self, axis: _ShapeLike, out: None = None) -> _Matrix[np.bool]: ... + @overload + def any(self, axis: _ShapeLike | None, out: _ArrayT) -> _ArrayT: ... + @overload + def any(self, axis: _ShapeLike | None = None, *, out: _ArrayT) -> _ArrayT: ... # pyright: ignore[reportIncompatibleMethodOverride] + + # keep in sync with `any` + @overload # type: ignore[override] + def all(self, axis: None = None, out: None = None) -> np.bool: ... + @overload + def all(self, axis: _ShapeLike, out: None = None) -> _Matrix[np.bool]: ... + @overload + def all(self, axis: _ShapeLike | None, out: _ArrayT) -> _ArrayT: ... + @overload + def all(self, axis: _ShapeLike | None = None, *, out: _ArrayT) -> _ArrayT: ... # pyright: ignore[reportIncompatibleMethodOverride] + + # keep in sync with `min` and `ptp` + @overload # type: ignore[override] + def max(self: NDArray[_ScalarT], axis: None = None, out: None = None) -> _ScalarT: ... + @overload + def max(self, axis: _ShapeLike, out: None = None) -> matrix[_2D, _DTypeT_co]: ... + @overload + def max(self, axis: _ShapeLike | None, out: _ArrayT) -> _ArrayT: ... + @overload + def max(self, axis: _ShapeLike | None = None, *, out: _ArrayT) -> _ArrayT: ... # pyright: ignore[reportIncompatibleMethodOverride] + + # keep in sync with `max` and `ptp` + @overload # type: ignore[override] + def min(self: NDArray[_ScalarT], axis: None = None, out: None = None) -> _ScalarT: ... + @overload + def min(self, axis: _ShapeLike, out: None = None) -> matrix[_2D, _DTypeT_co]: ... + @overload + def min(self, axis: _ShapeLike | None, out: _ArrayT) -> _ArrayT: ... + @overload + def min(self, axis: _ShapeLike | None = None, *, out: _ArrayT) -> _ArrayT: ... # pyright: ignore[reportIncompatibleMethodOverride] + + # keep in sync with `max` and `min` + @overload + def ptp(self: NDArray[_ScalarT], axis: None = None, out: None = None) -> _ScalarT: ... + @overload + def ptp(self, axis: _ShapeLike, out: None = None) -> matrix[_2D, _DTypeT_co]: ... + @overload + def ptp(self, axis: _ShapeLike | None, out: _ArrayT) -> _ArrayT: ... + @overload + def ptp(self, axis: _ShapeLike | None = None, *, out: _ArrayT) -> _ArrayT: ... # pyright: ignore[reportIncompatibleMethodOverride] + + # keep in sync with `argmin` + @overload # type: ignore[override] + def argmax(self: NDArray[_ScalarT], axis: None = None, out: None = None) -> np.intp: ... + @overload + def argmax(self, axis: _ShapeLike, out: None = None) -> _Matrix[np.intp]: ... + @overload + def argmax(self, axis: _ShapeLike | None, out: _BoolOrIntArrayT) -> _BoolOrIntArrayT: ... + @overload + def argmax(self, axis: _ShapeLike | None = None, *, out: _BoolOrIntArrayT) -> _BoolOrIntArrayT: ... # pyright: ignore[reportIncompatibleMethodOverride] + + # keep in sync with `argmax` + @overload # type: ignore[override] + def argmin(self: NDArray[_ScalarT], axis: None = None, out: None = None) -> np.intp: ... + @overload + def argmin(self, axis: _ShapeLike, out: None = None) -> _Matrix[np.intp]: ... + @overload + def argmin(self, axis: _ShapeLike | None, out: _BoolOrIntArrayT) -> _BoolOrIntArrayT: ... + @overload + def argmin(self, axis: _ShapeLike | None = None, *, out: _BoolOrIntArrayT) -> _BoolOrIntArrayT: ... # pyright: ignore[reportIncompatibleMethodOverride] + + # the second overload handles the (rare) case that the matrix is not 2-d + @overload + def tolist(self: _Matrix[np.generic[_T]]) -> list[list[_T]]: ... # pyright: ignore[reportIncompatibleMethodOverride] + @overload + def tolist(self) -> Incomplete: ... # pyright: ignore[reportIncompatibleMethodOverride] + + # these three methods will at least return a `2-d` array of shape (1, n) + def squeeze(self, /, axis: _ShapeLike | None = None) -> matrix[_2D, _DTypeT_co]: ... + def ravel(self, /, order: L["K", "A", "C", "F"] | None = "C") -> matrix[_2D, _DTypeT_co]: ... # type: ignore[override] # pyright: ignore[reportIncompatibleMethodOverride] + def flatten(self, /, order: L["K", "A", "C", "F"] | None = "C") -> matrix[_2D, _DTypeT_co]: ... # type: ignore[override] # pyright: ignore[reportIncompatibleMethodOverride] + + # matrix.T is inherited from _ScalarOrArrayCommon + def getT(self) -> Self: ... + @property + def I(self) -> _Matrix[Incomplete]: ... # noqa: E743 + def getI(self) -> _Matrix[Incomplete]: ... + @property + def A(self) -> np.ndarray[_2D, _DTypeT_co]: ... + def getA(self) -> np.ndarray[_2D, _DTypeT_co]: ... + @property + def A1(self) -> np.ndarray[_AnyShape, _DTypeT_co]: ... + def getA1(self) -> np.ndarray[_AnyShape, _DTypeT_co]: ... + @property + def H(self) -> matrix[_2D, _DTypeT_co]: ... + def getH(self) -> matrix[_2D, _DTypeT_co]: ... + +def bmat( + obj: str | Sequence[ArrayLike] | NDArray[Any], + ldict: Mapping[str, Any] | None = None, + gdict: Mapping[str, Any] | None = None, +) -> _Matrix[Incomplete]: ... + +def asmatrix(data: ArrayLike, dtype: DTypeLike | None = None) -> _Matrix[Incomplete]: ... diff --git a/python/user_packages/Python313/site-packages/oauthlib-3.3.1.dist-info/licenses/LICENSE b/python/user_packages/Python313/site-packages/oauthlib-3.3.1.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..ffab12676f701309c33ae08d489e7305c9883ccb --- /dev/null +++ b/python/user_packages/Python313/site-packages/oauthlib-3.3.1.dist-info/licenses/LICENSE @@ -0,0 +1,27 @@ +Copyright (c) The OAuthlib Community +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + 3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from this + software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/python/user_packages/Python313/site-packages/oauthlib/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/oauthlib/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a2eda97cbb111e47985de946f6a9d7c7c6a14998 Binary files /dev/null and b/python/user_packages/Python313/site-packages/oauthlib/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/oauthlib/__pycache__/common.cpython-313.pyc b/python/user_packages/Python313/site-packages/oauthlib/__pycache__/common.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..529c466ce3a38d1c6ac56702fc2af20eae9433ab Binary files /dev/null and b/python/user_packages/Python313/site-packages/oauthlib/__pycache__/common.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/oauthlib/__pycache__/signals.cpython-313.pyc b/python/user_packages/Python313/site-packages/oauthlib/__pycache__/signals.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5ce3e13837fb8ec9934ed084af527ded3b9789cd Binary files /dev/null and b/python/user_packages/Python313/site-packages/oauthlib/__pycache__/signals.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/oauthlib/__pycache__/uri_validate.cpython-313.pyc b/python/user_packages/Python313/site-packages/oauthlib/__pycache__/uri_validate.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7153a117b708a9c57e9ed362a64f01f295d34180 Binary files /dev/null and b/python/user_packages/Python313/site-packages/oauthlib/__pycache__/uri_validate.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth1/__init__.py b/python/user_packages/Python313/site-packages/oauthlib/oauth1/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9caf12a90d878efa4460811310818ee3572fcdd4 --- /dev/null +++ b/python/user_packages/Python313/site-packages/oauthlib/oauth1/__init__.py @@ -0,0 +1,23 @@ +""" +oauthlib.oauth1 +~~~~~~~~~~~~~~ + +This module is a wrapper for the most recent implementation of OAuth 1.0 Client +and Server classes. +""" +from .rfc5849 import ( + SIGNATURE_HMAC, SIGNATURE_HMAC_SHA1, SIGNATURE_HMAC_SHA256, + SIGNATURE_HMAC_SHA512, SIGNATURE_PLAINTEXT, SIGNATURE_RSA, + SIGNATURE_RSA_SHA1, SIGNATURE_RSA_SHA256, SIGNATURE_RSA_SHA512, + SIGNATURE_TYPE_AUTH_HEADER, SIGNATURE_TYPE_BODY, SIGNATURE_TYPE_QUERY, + Client, +) +from .rfc5849.endpoints import ( + AccessTokenEndpoint, AuthorizationEndpoint, RequestTokenEndpoint, + ResourceEndpoint, SignatureOnlyEndpoint, WebApplicationServer, +) +from .rfc5849.errors import ( + InsecureTransportError, InvalidClientError, InvalidRequestError, + InvalidSignatureMethodError, OAuth1Error, +) +from .rfc5849.request_validator import RequestValidator diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth1/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/oauthlib/oauth1/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..78c10b6c7a4a4f4e08edfb8a11b653058030f9b2 Binary files /dev/null and b/python/user_packages/Python313/site-packages/oauthlib/oauth1/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/__init__.py b/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..85e0b90b635398a3a2636ed8b5887d5ddb8c59c3 --- /dev/null +++ b/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/__init__.py @@ -0,0 +1,366 @@ +""" +oauthlib.oauth1.rfc5849 +~~~~~~~~~~~~~~ + +This module is an implementation of various logic needed +for signing and checking OAuth 1.0 RFC 5849 requests. + +It supports all three standard signature methods defined in RFC 5849: + +- HMAC-SHA1 +- RSA-SHA1 +- PLAINTEXT + +It also supports signature methods that are not defined in RFC 5849. These are +based on the standard ones but replace SHA-1 with the more secure SHA-256: + +- HMAC-SHA256 +- RSA-SHA256 + +""" +import base64 +import hashlib +import logging +import urllib.parse as urlparse + +from oauthlib.common import ( + Request, generate_nonce, generate_timestamp, to_unicode, urlencode, +) + +from . import parameters, signature + +log = logging.getLogger(__name__) + +# Available signature methods +# +# Note: SIGNATURE_HMAC and SIGNATURE_RSA are kept for backward compatibility +# with previous versions of this library, when it the only HMAC-based and +# RSA-based signature methods were HMAC-SHA1 and RSA-SHA1. But now that it +# supports other hashing algorithms besides SHA1, explicitly identifying which +# hashing algorithm is being used is recommended. +# +# Note: if additional values are defined here, don't forget to update the +# imports in "../__init__.py" so they are available outside this module. + +SIGNATURE_HMAC_SHA1 = "HMAC-SHA1" +SIGNATURE_HMAC_SHA256 = "HMAC-SHA256" +SIGNATURE_HMAC_SHA512 = "HMAC-SHA512" +SIGNATURE_HMAC = SIGNATURE_HMAC_SHA1 # deprecated variable for HMAC-SHA1 + +SIGNATURE_RSA_SHA1 = "RSA-SHA1" +SIGNATURE_RSA_SHA256 = "RSA-SHA256" +SIGNATURE_RSA_SHA512 = "RSA-SHA512" +SIGNATURE_RSA = SIGNATURE_RSA_SHA1 # deprecated variable for RSA-SHA1 + +SIGNATURE_PLAINTEXT = "PLAINTEXT" + +SIGNATURE_METHODS = ( + SIGNATURE_HMAC_SHA1, + SIGNATURE_HMAC_SHA256, + SIGNATURE_HMAC_SHA512, + SIGNATURE_RSA_SHA1, + SIGNATURE_RSA_SHA256, + SIGNATURE_RSA_SHA512, + SIGNATURE_PLAINTEXT +) + +SIGNATURE_TYPE_AUTH_HEADER = 'AUTH_HEADER' +SIGNATURE_TYPE_QUERY = 'QUERY' +SIGNATURE_TYPE_BODY = 'BODY' + +CONTENT_TYPE_FORM_URLENCODED = 'application/x-www-form-urlencoded' + + +class Client: + + """A client used to sign OAuth 1.0 RFC 5849 requests.""" + SIGNATURE_METHODS = { + SIGNATURE_HMAC_SHA1: signature.sign_hmac_sha1_with_client, + SIGNATURE_HMAC_SHA256: signature.sign_hmac_sha256_with_client, + SIGNATURE_HMAC_SHA512: signature.sign_hmac_sha512_with_client, + SIGNATURE_RSA_SHA1: signature.sign_rsa_sha1_with_client, + SIGNATURE_RSA_SHA256: signature.sign_rsa_sha256_with_client, + SIGNATURE_RSA_SHA512: signature.sign_rsa_sha512_with_client, + SIGNATURE_PLAINTEXT: signature.sign_plaintext_with_client + } + + @classmethod + def register_signature_method(cls, method_name, method_callback): + cls.SIGNATURE_METHODS[method_name] = method_callback + + def __init__(self, client_key, + client_secret=None, + resource_owner_key=None, + resource_owner_secret=None, + callback_uri=None, + signature_method=SIGNATURE_HMAC_SHA1, + signature_type=SIGNATURE_TYPE_AUTH_HEADER, + rsa_key=None, verifier=None, realm=None, + encoding='utf-8', decoding=None, + nonce=None, timestamp=None): + """Create an OAuth 1 client. + + :param client_key: Client key (consumer key), mandatory. + :param resource_owner_key: Resource owner key (oauth token). + :param resource_owner_secret: Resource owner secret (oauth token secret). + :param callback_uri: Callback used when obtaining request token. + :param signature_method: SIGNATURE_HMAC, SIGNATURE_RSA or SIGNATURE_PLAINTEXT. + :param signature_type: SIGNATURE_TYPE_AUTH_HEADER (default), + SIGNATURE_TYPE_QUERY or SIGNATURE_TYPE_BODY + depending on where you want to embed the oauth + credentials. + :param rsa_key: RSA key used with SIGNATURE_RSA. + :param verifier: Verifier used when obtaining an access token. + :param realm: Realm (scope) to which access is being requested. + :param encoding: If you provide non-unicode input you may use this + to have oauthlib automatically convert. + :param decoding: If you wish that the returned uri, headers and body + from sign be encoded back from unicode, then set + decoding to your preferred encoding, i.e. utf-8. + :param nonce: Use this nonce instead of generating one. (Mainly for testing) + :param timestamp: Use this timestamp instead of using current. (Mainly for testing) + """ + # Convert to unicode using encoding if given, else assume unicode + def encode(x): + return to_unicode(x, encoding) if encoding else x + + self.client_key = encode(client_key) + self.client_secret = encode(client_secret) + self.resource_owner_key = encode(resource_owner_key) + self.resource_owner_secret = encode(resource_owner_secret) + self.signature_method = encode(signature_method) + self.signature_type = encode(signature_type) + self.callback_uri = encode(callback_uri) + self.rsa_key = encode(rsa_key) + self.verifier = encode(verifier) + self.realm = encode(realm) + self.encoding = encode(encoding) + self.decoding = encode(decoding) + self.nonce = encode(nonce) + self.timestamp = encode(timestamp) + + def __repr__(self): + attrs = vars(self).copy() + attrs['client_secret'] = '****' if attrs['client_secret'] else None + attrs['rsa_key'] = '****' if attrs['rsa_key'] else None + attrs[ + 'resource_owner_secret'] = '****' if attrs['resource_owner_secret'] else None + attribute_str = ', '.join('{}={}'.format(k, v) for k, v in attrs.items()) + return '<{} {}>'.format(self.__class__.__name__, attribute_str) + + def get_oauth_signature(self, request): + """Get an OAuth signature to be used in signing a request + + To satisfy `section 3.4.1.2`_ item 2, if the request argument's + headers dict attribute contains a Host item, its value will + replace any netloc part of the request argument's uri attribute + value. + + .. _`section 3.4.1.2`: https://tools.ietf.org/html/rfc5849#section-3.4.1.2 + """ + if self.signature_method == SIGNATURE_PLAINTEXT: + # fast-path + return signature.sign_plaintext(self.client_secret, + self.resource_owner_secret) + + uri, headers, body = self._render(request) + + collected_params = signature.collect_parameters( + uri_query=urlparse.urlparse(uri).query, + body=body, + headers=headers) + log.debug("Collected params: {}".format(collected_params)) + + normalized_params = signature.normalize_parameters(collected_params) + normalized_uri = signature.base_string_uri(uri, headers.get('Host', None)) + log.debug("Normalized params: {}".format(normalized_params)) + log.debug("Normalized URI: {}".format(normalized_uri)) + + base_string = signature.signature_base_string(request.http_method, + normalized_uri, normalized_params) + + log.debug("Signing: signature base string: {}".format(base_string)) + + if self.signature_method not in self.SIGNATURE_METHODS: + raise ValueError('Invalid signature method.') + + sig = self.SIGNATURE_METHODS[self.signature_method](base_string, self) + + log.debug("Signature: {}".format(sig)) + return sig + + def get_oauth_params(self, request): + """Get the basic OAuth parameters to be used in generating a signature. + """ + nonce = (generate_nonce() + if self.nonce is None else self.nonce) + timestamp = (generate_timestamp() + if self.timestamp is None else self.timestamp) + params = [ + ('oauth_nonce', nonce), + ('oauth_timestamp', timestamp), + ('oauth_version', '1.0'), + ('oauth_signature_method', self.signature_method), + ('oauth_consumer_key', self.client_key), + ] + if self.resource_owner_key: + params.append(('oauth_token', self.resource_owner_key)) + if self.callback_uri: + params.append(('oauth_callback', self.callback_uri)) + if self.verifier: + params.append(('oauth_verifier', self.verifier)) + + # providing body hash for requests other than x-www-form-urlencoded + # as described in https://tools.ietf.org/html/draft-eaton-oauth-bodyhash-00#section-4.1.1 + # 4.1.1. When to include the body hash + # * [...] MUST NOT include an oauth_body_hash parameter on requests with form-encoded request bodies + # * [...] SHOULD include the oauth_body_hash parameter on all other requests. + # Note that SHA-1 is vulnerable. The spec acknowledges that in https://tools.ietf.org/html/draft-eaton-oauth-bodyhash-00#section-6.2 + # At this time, no further effort has been made to replace SHA-1 for the OAuth Request Body Hash extension. + content_type = request.headers.get('Content-Type', None) + content_type_eligible = content_type and content_type.find('application/x-www-form-urlencoded') < 0 + if request.body is not None and content_type_eligible: + params.append(('oauth_body_hash', base64.b64encode(hashlib.sha1(request.body.encode('utf-8')).digest()).decode('utf-8'))) # noqa: S324 + + return params + + def _render(self, request, formencode=False, realm=None): + """Render a signed request according to signature type + + Returns a 3-tuple containing the request URI, headers, and body. + + If the formencode argument is True and the body contains parameters, it + is escaped and returned as a valid formencoded string. + """ + # TODO what if there are body params on a header-type auth? + # TODO what if there are query params on a body-type auth? + + uri, headers, body = request.uri, request.headers, request.body + + # TODO: right now these prepare_* methods are very narrow in scope--they + # only affect their little thing. In some cases (for example, with + # header auth) it might be advantageous to allow these methods to touch + # other parts of the request, like the headers—so the prepare_headers + # method could also set the Content-Type header to x-www-form-urlencoded + # like the spec requires. This would be a fundamental change though, and + # I'm not sure how I feel about it. + if self.signature_type == SIGNATURE_TYPE_AUTH_HEADER: + headers = parameters.prepare_headers( + request.oauth_params, request.headers, realm=realm) + elif self.signature_type == SIGNATURE_TYPE_BODY and request.decoded_body is not None: + body = parameters.prepare_form_encoded_body( + request.oauth_params, request.decoded_body) + if formencode: + body = urlencode(body) + headers['Content-Type'] = 'application/x-www-form-urlencoded' + elif self.signature_type == SIGNATURE_TYPE_QUERY: + uri = parameters.prepare_request_uri_query( + request.oauth_params, request.uri) + else: + raise ValueError('Unknown signature type specified.') + + return uri, headers, body + + def sign(self, uri, http_method='GET', body=None, headers=None, realm=None): + """Sign a request + + Signs an HTTP request with the specified parts. + + Returns a 3-tuple of the signed request's URI, headers, and body. + Note that http_method is not returned as it is unaffected by the OAuth + signing process. Also worth noting is that duplicate parameters + will be included in the signature, regardless of where they are + specified (query, body). + + The body argument may be a dict, a list of 2-tuples, or a formencoded + string. The Content-Type header must be 'application/x-www-form-urlencoded' + if it is present. + + If the body argument is not one of the above, it will be returned + verbatim as it is unaffected by the OAuth signing process. Attempting to + sign a request with non-formencoded data using the OAuth body signature + type is invalid and will raise an exception. + + If the body does contain parameters, it will be returned as a properly- + formatted formencoded string. + + Body may not be included if the http_method is either GET or HEAD as + this changes the semantic meaning of the request. + + All string data MUST be unicode or be encoded with the same encoding + scheme supplied to the Client constructor, default utf-8. This includes + strings inside body dicts, for example. + """ + # normalize request data + request = Request(uri, http_method, body, headers, + encoding=self.encoding) + + # sanity check + content_type = request.headers.get('Content-Type', None) + multipart = content_type and content_type.startswith('multipart/') + should_have_params = content_type == CONTENT_TYPE_FORM_URLENCODED + has_params = request.decoded_body is not None + # 3.4.1.3.1. Parameter Sources + # [Parameters are collected from the HTTP request entity-body, but only + # if [...]: + # * The entity-body is single-part. + if multipart and has_params: + raise ValueError( + "Headers indicate a multipart body but body contains parameters.") + # * The entity-body follows the encoding requirements of the + # "application/x-www-form-urlencoded" content-type as defined by + # [W3C.REC-html40-19980424]. + elif should_have_params and not has_params: + raise ValueError( + "Headers indicate a formencoded body but body was not decodable.") + # * The HTTP request entity-header includes the "Content-Type" + # header field set to "application/x-www-form-urlencoded". + elif not should_have_params and has_params: + raise ValueError( + "Body contains parameters but Content-Type header was {} " + "instead of {}".format(content_type or "not set", + CONTENT_TYPE_FORM_URLENCODED)) + + # 3.5.2. Form-Encoded Body + # Protocol parameters can be transmitted in the HTTP request entity- + # body, but only if the following REQUIRED conditions are met: + # o The entity-body is single-part. + # o The entity-body follows the encoding requirements of the + # "application/x-www-form-urlencoded" content-type as defined by + # [W3C.REC-html40-19980424]. + # o The HTTP request entity-header includes the "Content-Type" header + # field set to "application/x-www-form-urlencoded". + elif self.signature_type == SIGNATURE_TYPE_BODY and not ( + should_have_params and has_params and not multipart): + raise ValueError( + 'Body signatures may only be used with form-urlencoded content') + + # We amend https://tools.ietf.org/html/rfc5849#section-3.4.1.3.1 + # with the clause that parameters from body should only be included + # in non GET or HEAD requests. Extracting the request body parameters + # and including them in the signature base string would give semantic + # meaning to the body, which it should not have according to the + # HTTP 1.1 spec. + elif http_method.upper() in ('GET', 'HEAD') and has_params: + raise ValueError('GET/HEAD requests should not include body.') + + # generate the basic OAuth parameters + request.oauth_params = self.get_oauth_params(request) + + # generate the signature + request.oauth_params.append( + ('oauth_signature', self.get_oauth_signature(request))) + + # render the signed request and return it + uri, headers, body = self._render(request, formencode=True, + realm=(realm or self.realm)) + + if self.decoding: + log.debug('Encoding URI, headers and body to %s.', self.decoding) + uri = uri.encode(self.decoding) + body = body.encode(self.decoding) if body else body + new_headers = {} + for k, v in headers.items(): + new_headers[k.encode(self.decoding)] = v.encode(self.decoding) + headers = new_headers + return uri, headers, body diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e608160381d3ea4049918f2f24f01493884c0f86 Binary files /dev/null and b/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/__pycache__/errors.cpython-313.pyc b/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/__pycache__/errors.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d461221acadf0d8c823cf62407db92138e3d53f9 Binary files /dev/null and b/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/__pycache__/errors.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/__pycache__/parameters.cpython-313.pyc b/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/__pycache__/parameters.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6841399669713f71b8a5910dcc9a84852ce3e40c Binary files /dev/null and b/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/__pycache__/parameters.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/__pycache__/request_validator.cpython-313.pyc b/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/__pycache__/request_validator.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..455cedadbf00a2a9f73068e12bea48a0082c0842 Binary files /dev/null and b/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/__pycache__/request_validator.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/__pycache__/signature.cpython-313.pyc b/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/__pycache__/signature.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..80eca4f9f6a838df605ab5acc0ecff1d8dc477d4 Binary files /dev/null and b/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/__pycache__/signature.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/__pycache__/utils.cpython-313.pyc b/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/__pycache__/utils.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..33013c32bcc67b311394e0f6342211c7cba1b30d Binary files /dev/null and b/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/__pycache__/utils.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/endpoints/__init__.py b/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/endpoints/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9f30389f239929754078e3f59688de418d986e29 --- /dev/null +++ b/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/endpoints/__init__.py @@ -0,0 +1,8 @@ +from .access_token import AccessTokenEndpoint +from .authorization import AuthorizationEndpoint +from .base import BaseEndpoint +from .request_token import RequestTokenEndpoint +from .resource import ResourceEndpoint +from .signature_only import SignatureOnlyEndpoint + +from .pre_configured import WebApplicationServer # isort:skip diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/endpoints/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/endpoints/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2deda8377b3557a457e90247bc5db1bbc388a680 Binary files /dev/null and b/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/endpoints/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/endpoints/__pycache__/access_token.cpython-313.pyc b/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/endpoints/__pycache__/access_token.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..911a077044455c9d33a36f5aaae95d792a0728f4 Binary files /dev/null and b/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/endpoints/__pycache__/access_token.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/endpoints/__pycache__/authorization.cpython-313.pyc b/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/endpoints/__pycache__/authorization.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6f9e70363361fdf0683a12b6f1450fbd089345df Binary files /dev/null and b/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/endpoints/__pycache__/authorization.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/endpoints/__pycache__/base.cpython-313.pyc b/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/endpoints/__pycache__/base.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7759a68eb3f1f44ab981da47cf8e392c4145e32e Binary files /dev/null and b/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/endpoints/__pycache__/base.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/endpoints/__pycache__/pre_configured.cpython-313.pyc b/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/endpoints/__pycache__/pre_configured.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7c6206df93e0a1d9fbe8b94338498f72ddfa9692 Binary files /dev/null and b/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/endpoints/__pycache__/pre_configured.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/endpoints/__pycache__/request_token.cpython-313.pyc b/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/endpoints/__pycache__/request_token.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..36ce430f9c50313aa0c6d53a5f5ff8c0bdc9d6bd Binary files /dev/null and b/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/endpoints/__pycache__/request_token.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/endpoints/__pycache__/resource.cpython-313.pyc b/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/endpoints/__pycache__/resource.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..11eec653b004d537accd472fdf5dd4bbee0d26dd Binary files /dev/null and b/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/endpoints/__pycache__/resource.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/endpoints/__pycache__/signature_only.cpython-313.pyc b/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/endpoints/__pycache__/signature_only.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..57399046b5d95a806d3ef69cbbd8d673507046bc Binary files /dev/null and b/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/endpoints/__pycache__/signature_only.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/endpoints/access_token.py b/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/endpoints/access_token.py new file mode 100644 index 0000000000000000000000000000000000000000..13665db08fda810cfc46fa45448d06fe9ec99ae9 --- /dev/null +++ b/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/endpoints/access_token.py @@ -0,0 +1,215 @@ +# -*- coding: utf-8 -*- +""" +oauthlib.oauth1.rfc5849.endpoints.access_token +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +This module is an implementation of the access token provider logic of +OAuth 1.0 RFC 5849. It validates the correctness of access token requests, +creates and persists tokens as well as create the proper response to be +returned to the client. +""" +import logging + +from oauthlib.common import urlencode + +from .. import errors +from .base import BaseEndpoint + +log = logging.getLogger(__name__) + + +class AccessTokenEndpoint(BaseEndpoint): + + """An endpoint responsible for providing OAuth 1 access tokens. + + Typical use is to instantiate with a request validator and invoke the + ``create_access_token_response`` from a view function. The tuple returned + has all information necessary (body, status, headers) to quickly form + and return a proper response. See :doc:`/oauth1/validator` for details on which + validator methods to implement for this endpoint. + """ + + def create_access_token(self, request, credentials): + """Create and save a new access token. + + Similar to OAuth 2, indication of granted scopes will be included as a + space separated list in ``oauth_authorized_realms``. + + :param request: OAuthlib request. + :type request: oauthlib.common.Request + :returns: The token as an urlencoded string. + """ + request.realms = self.request_validator.get_realms( + request.resource_owner_key, request) + token = { + 'oauth_token': self.token_generator(), + 'oauth_token_secret': self.token_generator(), + # Backport the authorized scopes indication used in OAuth2 + 'oauth_authorized_realms': ' '.join(request.realms) + } + token.update(credentials) + self.request_validator.save_access_token(token, request) + return urlencode(token.items()) + + def create_access_token_response(self, uri, http_method='GET', body=None, + headers=None, credentials=None): + """Create an access token response, with a new request token if valid. + + :param uri: The full URI of the token request. + :param http_method: A valid HTTP verb, i.e. GET, POST, PUT, HEAD, etc. + :param body: The request body as a string. + :param headers: The request headers as a dict. + :param credentials: A list of extra credentials to include in the token. + :returns: A tuple of 3 elements. + 1. A dict of headers to set on the response. + 2. The response body as a string. + 3. The response status code as an integer. + + An example of a valid request:: + + >>> from your_validator import your_validator + >>> from oauthlib.oauth1 import AccessTokenEndpoint + >>> endpoint = AccessTokenEndpoint(your_validator) + >>> h, b, s = endpoint.create_access_token_response( + ... 'https://your.provider/access_token?foo=bar', + ... headers={ + ... 'Authorization': 'OAuth oauth_token=234lsdkf....' + ... }, + ... credentials={ + ... 'my_specific': 'argument', + ... }) + >>> h + {'Content-Type': 'application/x-www-form-urlencoded'} + >>> b + 'oauth_token=lsdkfol23w54jlksdef&oauth_token_secret=qwe089234lkjsdf&oauth_authorized_realms=movies+pics&my_specific=argument' + >>> s + 200 + + An response to invalid request would have a different body and status:: + + >>> b + 'error=invalid_request&description=missing+resource+owner+key' + >>> s + 400 + + The same goes for an an unauthorized request: + + >>> b + '' + >>> s + 401 + """ + resp_headers = {'Content-Type': 'application/x-www-form-urlencoded'} + try: + request = self._create_request(uri, http_method, body, headers) + valid, processed_request = self.validate_access_token_request( + request) + if valid: + token = self.create_access_token(request, credentials or {}) + self.request_validator.invalidate_request_token( + request.client_key, + request.resource_owner_key, + request) + return resp_headers, token, 200 + else: + return {}, None, 401 + except errors.OAuth1Error as e: + return resp_headers, e.urlencoded, e.status_code + + def validate_access_token_request(self, request): + """Validate an access token request. + + :param request: OAuthlib request. + :type request: oauthlib.common.Request + :raises: OAuth1Error if the request is invalid. + :returns: A tuple of 2 elements. + 1. The validation result (True or False). + 2. The request object. + """ + self._check_transport_security(request) + self._check_mandatory_parameters(request) + + if not request.resource_owner_key: + raise errors.InvalidRequestError( + description='Missing resource owner.') + + if not self.request_validator.check_request_token( + request.resource_owner_key): + raise errors.InvalidRequestError( + description='Invalid resource owner key format.') + + if not request.verifier: + raise errors.InvalidRequestError( + description='Missing verifier.') + + if not self.request_validator.check_verifier(request.verifier): + raise errors.InvalidRequestError( + description='Invalid verifier format.') + + if not self.request_validator.validate_timestamp_and_nonce( + request.client_key, request.timestamp, request.nonce, request, + request_token=request.resource_owner_key): + return False, request + + # The server SHOULD return a 401 (Unauthorized) status code when + # receiving a request with invalid client credentials. + # Note: This is postponed in order to avoid timing attacks, instead + # a dummy client is assigned and used to maintain near constant + # time request verification. + # + # Note that early exit would enable client enumeration + valid_client = self.request_validator.validate_client_key( + request.client_key, request) + if not valid_client: + request.client_key = self.request_validator.dummy_client + + # The server SHOULD return a 401 (Unauthorized) status code when + # receiving a request with invalid or expired token. + # Note: This is postponed in order to avoid timing attacks, instead + # a dummy token is assigned and used to maintain near constant + # time request verification. + # + # Note that early exit would enable resource owner enumeration + valid_resource_owner = self.request_validator.validate_request_token( + request.client_key, request.resource_owner_key, request) + if not valid_resource_owner: + request.resource_owner_key = self.request_validator.dummy_request_token + + # The server MUST verify (Section 3.2) the validity of the request, + # ensure that the resource owner has authorized the provisioning of + # token credentials to the client, and ensure that the temporary + # credentials have not expired or been used before. The server MUST + # also verify the verification code received from the client. + # .. _`Section 3.2`: https://tools.ietf.org/html/rfc5849#section-3.2 + # + # Note that early exit would enable resource owner authorization + # verifier enumertion. + valid_verifier = self.request_validator.validate_verifier( + request.client_key, + request.resource_owner_key, + request.verifier, + request) + + valid_signature = self._check_signature(request, is_token_request=True) + + # log the results to the validator_log + # this lets us handle internal reporting and analysis + request.validator_log['client'] = valid_client + request.validator_log['resource_owner'] = valid_resource_owner + request.validator_log['verifier'] = valid_verifier + request.validator_log['signature'] = valid_signature + + # We delay checking validity until the very end, using dummy values for + # calculations and fetching secrets/keys to ensure the flow of every + # request remains almost identical regardless of whether valid values + # have been supplied. This ensures near constant time execution and + # prevents malicious users from guessing sensitive information + v = all((valid_client, valid_resource_owner, valid_verifier, + valid_signature)) + if not v: + log.info("[Failure] request verification failed.") + log.info("Valid client:, %s", valid_client) + log.info("Valid token:, %s", valid_resource_owner) + log.info("Valid verifier:, %s", valid_verifier) + log.info("Valid signature:, %s", valid_signature) + return v, request diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/endpoints/authorization.py b/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/endpoints/authorization.py new file mode 100644 index 0000000000000000000000000000000000000000..00d9576b01ecd9879a4485cf083c2affa79a520c --- /dev/null +++ b/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/endpoints/authorization.py @@ -0,0 +1,158 @@ +# -*- coding: utf-8 -*- +""" +oauthlib.oauth1.rfc5849.endpoints.authorization +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +This module is an implementation of various logic needed +for signing and checking OAuth 1.0 RFC 5849 requests. +""" +from urllib.parse import urlencode + +from oauthlib.common import add_params_to_uri + +from .. import errors +from .base import BaseEndpoint + + +class AuthorizationEndpoint(BaseEndpoint): + + """An endpoint responsible for letting authenticated users authorize access + to their protected resources to a client. + + Typical use would be to have two views, one for displaying the authorization + form and one to process said form on submission. + + The first view will want to utilize ``get_realms_and_credentials`` to fetch + requested realms and useful client credentials, such as name and + description, to be used when creating the authorization form. + + During form processing you can use ``create_authorization_response`` to + validate the request, create a verifier as well as prepare the final + redirection URI used to send the user back to the client. + + See :doc:`/oauth1/validator` for details on which validator methods to implement + for this endpoint. + """ + + def create_verifier(self, request, credentials): + """Create and save a new request token. + + :param request: OAuthlib request. + :type request: oauthlib.common.Request + :param credentials: A dict of extra token credentials. + :returns: The verifier as a dict. + """ + verifier = { + 'oauth_token': request.resource_owner_key, + 'oauth_verifier': self.token_generator(), + } + verifier.update(credentials) + self.request_validator.save_verifier( + request.resource_owner_key, verifier, request) + return verifier + + def create_authorization_response(self, uri, http_method='GET', body=None, + headers=None, realms=None, credentials=None): + """Create an authorization response, with a new request token if valid. + + :param uri: The full URI of the token request. + :param http_method: A valid HTTP verb, i.e. GET, POST, PUT, HEAD, etc. + :param body: The request body as a string. + :param headers: The request headers as a dict. + :param credentials: A list of credentials to include in the verifier. + :returns: A tuple of 3 elements. + 1. A dict of headers to set on the response. + 2. The response body as a string. + 3. The response status code as an integer. + + If the callback URI tied to the current token is "oob", a response with + a 200 status code will be returned. In this case, it may be desirable to + modify the response to better display the verifier to the client. + + An example of an authorization request:: + + >>> from your_validator import your_validator + >>> from oauthlib.oauth1 import AuthorizationEndpoint + >>> endpoint = AuthorizationEndpoint(your_validator) + >>> h, b, s = endpoint.create_authorization_response( + ... 'https://your.provider/authorize?oauth_token=...', + ... credentials={ + ... 'extra': 'argument', + ... }) + >>> h + {'Location': 'https://the.client/callback?oauth_verifier=...&extra=argument'} + >>> b + None + >>> s + 302 + + An example of a request with an "oob" callback:: + + >>> from your_validator import your_validator + >>> from oauthlib.oauth1 import AuthorizationEndpoint + >>> endpoint = AuthorizationEndpoint(your_validator) + >>> h, b, s = endpoint.create_authorization_response( + ... 'https://your.provider/authorize?foo=bar', + ... credentials={ + ... 'extra': 'argument', + ... }) + >>> h + {'Content-Type': 'application/x-www-form-urlencoded'} + >>> b + 'oauth_verifier=...&extra=argument' + >>> s + 200 + """ + request = self._create_request(uri, http_method=http_method, body=body, + headers=headers) + + if not request.resource_owner_key: + raise errors.InvalidRequestError( + 'Missing mandatory parameter oauth_token.') + if not self.request_validator.verify_request_token( + request.resource_owner_key, request): + raise errors.InvalidClientError() + + request.realms = realms + if (request.realms and not self.request_validator.verify_realms( + request.resource_owner_key, request.realms, request)): + raise errors.InvalidRequestError( + description=('User granted access to realms outside of ' + 'what the client may request.')) + + verifier = self.create_verifier(request, credentials or {}) + redirect_uri = self.request_validator.get_redirect_uri( + request.resource_owner_key, request) + if redirect_uri == 'oob': + response_headers = { + 'Content-Type': 'application/x-www-form-urlencoded'} + response_body = urlencode(verifier) + return response_headers, response_body, 200 + else: + populated_redirect = add_params_to_uri( + redirect_uri, verifier.items()) + return {'Location': populated_redirect}, None, 302 + + def get_realms_and_credentials(self, uri, http_method='GET', body=None, + headers=None): + """Fetch realms and credentials for the presented request token. + + :param uri: The full URI of the token request. + :param http_method: A valid HTTP verb, i.e. GET, POST, PUT, HEAD, etc. + :param body: The request body as a string. + :param headers: The request headers as a dict. + :returns: A tuple of 2 elements. + 1. A list of request realms. + 2. A dict of credentials which may be useful in creating the + authorization form. + """ + request = self._create_request(uri, http_method=http_method, body=body, + headers=headers) + + if not self.request_validator.verify_request_token( + request.resource_owner_key, request): + raise errors.InvalidClientError() + + realms = self.request_validator.get_realms( + request.resource_owner_key, request) + return realms, {'resource_owner_key': request.resource_owner_key} diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/endpoints/base.py b/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/endpoints/base.py new file mode 100644 index 0000000000000000000000000000000000000000..8d3d89c6727c430e0e216c5bdb5abb26cabebf40 --- /dev/null +++ b/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/endpoints/base.py @@ -0,0 +1,239 @@ +# -*- coding: utf-8 -*- +""" +oauthlib.oauth1.rfc5849.endpoints.base +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +This module is an implementation of various logic needed +for signing and checking OAuth 1.0 RFC 5849 requests. +""" +import time + +from oauthlib.common import CaseInsensitiveDict, Request, generate_token + +from .. import ( + CONTENT_TYPE_FORM_URLENCODED, SIGNATURE_HMAC_SHA1, SIGNATURE_HMAC_SHA256, + SIGNATURE_HMAC_SHA512, SIGNATURE_PLAINTEXT, SIGNATURE_RSA_SHA1, + SIGNATURE_RSA_SHA256, SIGNATURE_RSA_SHA512, SIGNATURE_TYPE_AUTH_HEADER, + SIGNATURE_TYPE_BODY, SIGNATURE_TYPE_QUERY, errors, signature, utils, +) + + +class BaseEndpoint: + + def __init__(self, request_validator, token_generator=None): + self.request_validator = request_validator + self.token_generator = token_generator or generate_token + + def _get_signature_type_and_params(self, request): + """Extracts parameters from query, headers and body. Signature type + is set to the source in which parameters were found. + """ + # Per RFC5849, only the Authorization header may contain the 'realm' + # optional parameter. + header_params = signature.collect_parameters(headers=request.headers, + exclude_oauth_signature=False, with_realm=True) + body_params = signature.collect_parameters(body=request.body, + exclude_oauth_signature=False) + query_params = signature.collect_parameters(uri_query=request.uri_query, + exclude_oauth_signature=False) + + params = [] + params.extend(header_params) + params.extend(body_params) + params.extend(query_params) + signature_types_with_oauth_params = list(filter(lambda s: s[2], ( + (SIGNATURE_TYPE_AUTH_HEADER, params, + utils.filter_oauth_params(header_params)), + (SIGNATURE_TYPE_BODY, params, + utils.filter_oauth_params(body_params)), + (SIGNATURE_TYPE_QUERY, params, + utils.filter_oauth_params(query_params)) + ))) + + if len(signature_types_with_oauth_params) > 1: + found_types = [s[0] for s in signature_types_with_oauth_params] + raise errors.InvalidRequestError( + description=('oauth_ params must come from only 1 signature' + 'type but were found in %s', + ', '.join(found_types))) + + try: + signature_type, params, oauth_params = signature_types_with_oauth_params[ + 0] + except IndexError: + raise errors.InvalidRequestError( + description='Missing mandatory OAuth parameters.') + + return signature_type, params, oauth_params + + def _create_request(self, uri, http_method, body, headers): + # Only include body data from x-www-form-urlencoded requests + headers = CaseInsensitiveDict(headers or {}) + if "Content-Type" in headers and CONTENT_TYPE_FORM_URLENCODED in headers["Content-Type"]: # noqa: SIM108 + request = Request(uri, http_method, body, headers) + else: + request = Request(uri, http_method, '', headers) + signature_type, params, oauth_params = ( + self._get_signature_type_and_params(request)) + + # The server SHOULD return a 400 (Bad Request) status code when + # receiving a request with duplicated protocol parameters. + if len(dict(oauth_params)) != len(oauth_params): + raise errors.InvalidRequestError( + description='Duplicate OAuth1 entries.') + + oauth_params = dict(oauth_params) + request.signature = oauth_params.get('oauth_signature') + request.client_key = oauth_params.get('oauth_consumer_key') + request.resource_owner_key = oauth_params.get('oauth_token') + request.nonce = oauth_params.get('oauth_nonce') + request.timestamp = oauth_params.get('oauth_timestamp') + request.redirect_uri = oauth_params.get('oauth_callback') + request.verifier = oauth_params.get('oauth_verifier') + request.signature_method = oauth_params.get('oauth_signature_method') + request.realm = dict(params).get('realm') + request.oauth_params = oauth_params + + # Parameters to Client depend on signature method which may vary + # for each request. Note that HMAC-SHA1 and PLAINTEXT share parameters + request.params = [(k, v) for k, v in params if k != "oauth_signature"] + + if 'realm' in request.headers.get('Authorization', ''): + request.params = [(k, v) + for k, v in request.params if k != "realm"] + + return request + + def _check_transport_security(self, request): + # TODO: move into oauthlib.common from oauth2.utils + if (self.request_validator.enforce_ssl and + not request.uri.lower().startswith("https://")): + raise errors.InsecureTransportError() + + def _check_mandatory_parameters(self, request): + # The server SHOULD return a 400 (Bad Request) status code when + # receiving a request with missing parameters. + if not all((request.signature, request.client_key, + request.nonce, request.timestamp, + request.signature_method)): + raise errors.InvalidRequestError( + description='Missing mandatory OAuth parameters.') + + # OAuth does not mandate a particular signature method, as each + # implementation can have its own unique requirements. Servers are + # free to implement and document their own custom methods. + # Recommending any particular method is beyond the scope of this + # specification. Implementers should review the Security + # Considerations section (`Section 4`_) before deciding on which + # method to support. + # .. _`Section 4`: https://tools.ietf.org/html/rfc5849#section-4 + if (request.signature_method not in self.request_validator.allowed_signature_methods): + raise errors.InvalidSignatureMethodError( + description="Invalid signature, {} not in {!r}.".format( + request.signature_method, + self.request_validator.allowed_signature_methods)) + + # Servers receiving an authenticated request MUST validate it by: + # If the "oauth_version" parameter is present, ensuring its value is + # "1.0". + if ('oauth_version' in request.oauth_params and + request.oauth_params['oauth_version'] != '1.0'): + raise errors.InvalidRequestError( + description='Invalid OAuth version.') + + # The timestamp value MUST be a positive integer. Unless otherwise + # specified by the server's documentation, the timestamp is expressed + # in the number of seconds since January 1, 1970 00:00:00 GMT. + if len(request.timestamp) != 10: + raise errors.InvalidRequestError( + description='Invalid timestamp size') + + try: + ts = int(request.timestamp) + + except ValueError: + raise errors.InvalidRequestError( + description='Timestamp must be an integer.') + + else: + # To avoid the need to retain an infinite number of nonce values for + # future checks, servers MAY choose to restrict the time period after + # which a request with an old timestamp is rejected. + if abs(time.time() - ts) > self.request_validator.timestamp_lifetime: + raise errors.InvalidRequestError( + description=('Timestamp given is invalid, differ from ' + 'allowed by over %s seconds.' % ( + self.request_validator.timestamp_lifetime))) + + # Provider specific validation of parameters, used to enforce + # restrictions such as character set and length. + if not self.request_validator.check_client_key(request.client_key): + raise errors.InvalidRequestError( + description='Invalid client key format.') + + if not self.request_validator.check_nonce(request.nonce): + raise errors.InvalidRequestError( + description='Invalid nonce format.') + + def _check_signature(self, request, is_token_request=False): + # ---- RSA Signature verification ---- + if request.signature_method in {SIGNATURE_RSA_SHA1, SIGNATURE_RSA_SHA256, SIGNATURE_RSA_SHA512}: + # RSA-based signature method + + # The server verifies the signature per `[RFC3447] section 8.2.2`_ + # .. _`[RFC3447] section 8.2.2`: https://tools.ietf.org/html/rfc3447#section-8.2.1 + + rsa_key = self.request_validator.get_rsa_key( + request.client_key, request) + + if request.signature_method == SIGNATURE_RSA_SHA1: + valid_signature = signature.verify_rsa_sha1(request, rsa_key) + elif request.signature_method == SIGNATURE_RSA_SHA256: + valid_signature = signature.verify_rsa_sha256(request, rsa_key) + elif request.signature_method == SIGNATURE_RSA_SHA512: + valid_signature = signature.verify_rsa_sha512(request, rsa_key) + else: + valid_signature = False + + # ---- HMAC or Plaintext Signature verification ---- + else: + # Non-RSA based signature method + + # Servers receiving an authenticated request MUST validate it by: + # Recalculating the request signature independently as described in + # `Section 3.4`_ and comparing it to the value received from the + # client via the "oauth_signature" parameter. + # .. _`Section 3.4`: https://tools.ietf.org/html/rfc5849#section-3.4 + + client_secret = self.request_validator.get_client_secret( + request.client_key, request) + + resource_owner_secret = None + if request.resource_owner_key: + if is_token_request: + resource_owner_secret = \ + self.request_validator.get_request_token_secret( + request.client_key, request.resource_owner_key, + request) + else: + resource_owner_secret = \ + self.request_validator.get_access_token_secret( + request.client_key, request.resource_owner_key, + request) + + if request.signature_method == SIGNATURE_HMAC_SHA1: + valid_signature = signature.verify_hmac_sha1( + request, client_secret, resource_owner_secret) + elif request.signature_method == SIGNATURE_HMAC_SHA256: + valid_signature = signature.verify_hmac_sha256( + request, client_secret, resource_owner_secret) + elif request.signature_method == SIGNATURE_HMAC_SHA512: + valid_signature = signature.verify_hmac_sha512( + request, client_secret, resource_owner_secret) + elif request.signature_method == SIGNATURE_PLAINTEXT: + valid_signature = signature.verify_plaintext( + request, client_secret, resource_owner_secret) + else: + valid_signature = False + + return valid_signature diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/endpoints/pre_configured.py b/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/endpoints/pre_configured.py new file mode 100644 index 0000000000000000000000000000000000000000..23e3cfc84e0ee61cd461f476c435ef318945ff66 --- /dev/null +++ b/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/endpoints/pre_configured.py @@ -0,0 +1,14 @@ +from . import ( + AccessTokenEndpoint, AuthorizationEndpoint, RequestTokenEndpoint, + ResourceEndpoint, +) + + +class WebApplicationServer(RequestTokenEndpoint, AuthorizationEndpoint, + AccessTokenEndpoint, ResourceEndpoint): + + def __init__(self, request_validator): + RequestTokenEndpoint.__init__(self, request_validator) + AuthorizationEndpoint.__init__(self, request_validator) + AccessTokenEndpoint.__init__(self, request_validator) + ResourceEndpoint.__init__(self, request_validator) diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/endpoints/request_token.py b/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/endpoints/request_token.py new file mode 100644 index 0000000000000000000000000000000000000000..0323cfb845a7836eab0e181cc9229031788e957e --- /dev/null +++ b/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/endpoints/request_token.py @@ -0,0 +1,209 @@ +# -*- coding: utf-8 -*- +""" +oauthlib.oauth1.rfc5849.endpoints.request_token +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +This module is an implementation of the request token provider logic of +OAuth 1.0 RFC 5849. It validates the correctness of request token requests, +creates and persists tokens as well as create the proper response to be +returned to the client. +""" +import logging + +from oauthlib.common import urlencode + +from .. import errors +from .base import BaseEndpoint + +log = logging.getLogger(__name__) + + +class RequestTokenEndpoint(BaseEndpoint): + + """An endpoint responsible for providing OAuth 1 request tokens. + + Typical use is to instantiate with a request validator and invoke the + ``create_request_token_response`` from a view function. The tuple returned + has all information necessary (body, status, headers) to quickly form + and return a proper response. See :doc:`/oauth1/validator` for details on which + validator methods to implement for this endpoint. + """ + + def create_request_token(self, request, credentials): + """Create and save a new request token. + + :param request: OAuthlib request. + :type request: oauthlib.common.Request + :param credentials: A dict of extra token credentials. + :returns: The token as an urlencoded string. + """ + token = { + 'oauth_token': self.token_generator(), + 'oauth_token_secret': self.token_generator(), + 'oauth_callback_confirmed': 'true' + } + token.update(credentials) + self.request_validator.save_request_token(token, request) + return urlencode(token.items()) + + def create_request_token_response(self, uri, http_method='GET', body=None, + headers=None, credentials=None): + """Create a request token response, with a new request token if valid. + + :param uri: The full URI of the token request. + :param http_method: A valid HTTP verb, i.e. GET, POST, PUT, HEAD, etc. + :param body: The request body as a string. + :param headers: The request headers as a dict. + :param credentials: A list of extra credentials to include in the token. + :returns: A tuple of 3 elements. + 1. A dict of headers to set on the response. + 2. The response body as a string. + 3. The response status code as an integer. + + An example of a valid request:: + + >>> from your_validator import your_validator + >>> from oauthlib.oauth1 import RequestTokenEndpoint + >>> endpoint = RequestTokenEndpoint(your_validator) + >>> h, b, s = endpoint.create_request_token_response( + ... 'https://your.provider/request_token?foo=bar', + ... headers={ + ... 'Authorization': 'OAuth realm=movies user, oauth_....' + ... }, + ... credentials={ + ... 'my_specific': 'argument', + ... }) + >>> h + {'Content-Type': 'application/x-www-form-urlencoded'} + >>> b + 'oauth_token=lsdkfol23w54jlksdef&oauth_token_secret=qwe089234lkjsdf&oauth_callback_confirmed=true&my_specific=argument' + >>> s + 200 + + An response to invalid request would have a different body and status:: + + >>> b + 'error=invalid_request&description=missing+callback+uri' + >>> s + 400 + + The same goes for an an unauthorized request: + + >>> b + '' + >>> s + 401 + """ + resp_headers = {'Content-Type': 'application/x-www-form-urlencoded'} + try: + request = self._create_request(uri, http_method, body, headers) + valid, processed_request = self.validate_request_token_request( + request) + if valid: + token = self.create_request_token(request, credentials or {}) + return resp_headers, token, 200 + else: + return {}, None, 401 + except errors.OAuth1Error as e: + return resp_headers, e.urlencoded, e.status_code + + def validate_request_token_request(self, request): + """Validate a request token request. + + :param request: OAuthlib request. + :type request: oauthlib.common.Request + :raises: OAuth1Error if the request is invalid. + :returns: A tuple of 2 elements. + 1. The validation result (True or False). + 2. The request object. + """ + self._check_transport_security(request) + self._check_mandatory_parameters(request) + + if request.realm: + request.realms = request.realm.split(' ') + else: + request.realms = self.request_validator.get_default_realms( + request.client_key, request) + if not self.request_validator.check_realms(request.realms): + raise errors.InvalidRequestError( + description='Invalid realm {}. Allowed are {!r}.'.format( + request.realms, self.request_validator.realms)) + + if not request.redirect_uri: + raise errors.InvalidRequestError( + description='Missing callback URI.') + + if not self.request_validator.validate_timestamp_and_nonce( + request.client_key, request.timestamp, request.nonce, request, + request_token=request.resource_owner_key): + return False, request + + # The server SHOULD return a 401 (Unauthorized) status code when + # receiving a request with invalid client credentials. + # Note: This is postponed in order to avoid timing attacks, instead + # a dummy client is assigned and used to maintain near constant + # time request verification. + # + # Note that early exit would enable client enumeration + valid_client = self.request_validator.validate_client_key( + request.client_key, request) + if not valid_client: + request.client_key = self.request_validator.dummy_client + + # Note that `realm`_ is only used in authorization headers and how + # it should be interpreted is not included in the OAuth spec. + # However they could be seen as a scope or realm to which the + # client has access and as such every client should be checked + # to ensure it is authorized access to that scope or realm. + # .. _`realm`: https://tools.ietf.org/html/rfc2617#section-1.2 + # + # Note that early exit would enable client realm access enumeration. + # + # The require_realm indicates this is the first step in the OAuth + # workflow where a client requests access to a specific realm. + # This first step (obtaining request token) need not require a realm + # and can then be identified by checking the require_resource_owner + # flag and absence of realm. + # + # Clients obtaining an access token will not supply a realm and it will + # not be checked. Instead the previously requested realm should be + # transferred from the request token to the access token. + # + # Access to protected resources will always validate the realm but note + # that the realm is now tied to the access token and not provided by + # the client. + valid_realm = self.request_validator.validate_requested_realms( + request.client_key, request.realms, request) + + # Callback is normally never required, except for requests for + # a Temporary Credential as described in `Section 2.1`_ + # .._`Section 2.1`: https://tools.ietf.org/html/rfc5849#section-2.1 + valid_redirect = self.request_validator.validate_redirect_uri( + request.client_key, request.redirect_uri, request) + if not request.redirect_uri: + raise NotImplementedError('Redirect URI must either be provided ' + 'or set to a default during validation.') + + valid_signature = self._check_signature(request) + + # log the results to the validator_log + # this lets us handle internal reporting and analysis + request.validator_log['client'] = valid_client + request.validator_log['realm'] = valid_realm + request.validator_log['callback'] = valid_redirect + request.validator_log['signature'] = valid_signature + + # We delay checking validity until the very end, using dummy values for + # calculations and fetching secrets/keys to ensure the flow of every + # request remains almost identical regardless of whether valid values + # have been supplied. This ensures near constant time execution and + # prevents malicious users from guessing sensitive information + v = all((valid_client, valid_realm, valid_redirect, valid_signature)) + if not v: + log.info("[Failure] request verification failed.") + log.info("Valid client: %s.", valid_client) + log.info("Valid realm: %s.", valid_realm) + log.info("Valid callback: %s.", valid_redirect) + log.info("Valid signature: %s.", valid_signature) + return v, request diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/endpoints/resource.py b/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/endpoints/resource.py new file mode 100644 index 0000000000000000000000000000000000000000..8641152e4ee765c889ab608080ae3c6aee3e58e8 --- /dev/null +++ b/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/endpoints/resource.py @@ -0,0 +1,163 @@ +# -*- coding: utf-8 -*- +""" +oauthlib.oauth1.rfc5849.endpoints.resource +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +This module is an implementation of the resource protection provider logic of +OAuth 1.0 RFC 5849. +""" +import logging + +from .. import errors +from .base import BaseEndpoint + +log = logging.getLogger(__name__) + + +class ResourceEndpoint(BaseEndpoint): + + """An endpoint responsible for protecting resources. + + Typical use is to instantiate with a request validator and invoke the + ``validate_protected_resource_request`` in a decorator around a view + function. If the request is valid, invoke and return the response of the + view. If invalid create and return an error response directly from the + decorator. + + See :doc:`/oauth1/validator` for details on which validator methods to implement + for this endpoint. + + An example decorator:: + + from functools import wraps + from your_validator import your_validator + from oauthlib.oauth1 import ResourceEndpoint + endpoint = ResourceEndpoint(your_validator) + + def require_oauth(realms=None): + def decorator(f): + @wraps(f) + def wrapper(request, *args, **kwargs): + v, r = provider.validate_protected_resource_request( + request.url, + http_method=request.method, + body=request.data, + headers=request.headers, + realms=realms or []) + if v: + return f(*args, **kwargs) + else: + return abort(403) + """ + + def validate_protected_resource_request(self, uri, http_method='GET', + body=None, headers=None, realms=None): + """Create a request token response, with a new request token if valid. + + :param uri: The full URI of the token request. + :param http_method: A valid HTTP verb, i.e. GET, POST, PUT, HEAD, etc. + :param body: The request body as a string. + :param headers: The request headers as a dict. + :param realms: A list of realms the resource is protected under. + This will be supplied to the ``validate_realms`` + method of the request validator. + :returns: A tuple of 2 elements. + 1. True if valid, False otherwise. + 2. An oauthlib.common.Request object. + """ + try: + request = self._create_request(uri, http_method, body, headers) + except errors.OAuth1Error: + return False, None + + try: + self._check_transport_security(request) + self._check_mandatory_parameters(request) + except errors.OAuth1Error: + return False, request + + if not request.resource_owner_key: + return False, request + + if not self.request_validator.check_access_token( + request.resource_owner_key): + return False, request + + if not self.request_validator.validate_timestamp_and_nonce( + request.client_key, request.timestamp, request.nonce, request, + access_token=request.resource_owner_key): + return False, request + + # The server SHOULD return a 401 (Unauthorized) status code when + # receiving a request with invalid client credentials. + # Note: This is postponed in order to avoid timing attacks, instead + # a dummy client is assigned and used to maintain near constant + # time request verification. + # + # Note that early exit would enable client enumeration + valid_client = self.request_validator.validate_client_key( + request.client_key, request) + if not valid_client: + request.client_key = self.request_validator.dummy_client + + # The server SHOULD return a 401 (Unauthorized) status code when + # receiving a request with invalid or expired token. + # Note: This is postponed in order to avoid timing attacks, instead + # a dummy token is assigned and used to maintain near constant + # time request verification. + # + # Note that early exit would enable resource owner enumeration + valid_resource_owner = self.request_validator.validate_access_token( + request.client_key, request.resource_owner_key, request) + if not valid_resource_owner: + request.resource_owner_key = self.request_validator.dummy_access_token + + # Note that `realm`_ is only used in authorization headers and how + # it should be interpreted is not included in the OAuth spec. + # However they could be seen as a scope or realm to which the + # client has access and as such every client should be checked + # to ensure it is authorized access to that scope or realm. + # .. _`realm`: https://tools.ietf.org/html/rfc2617#section-1.2 + # + # Note that early exit would enable client realm access enumeration. + # + # The require_realm indicates this is the first step in the OAuth + # workflow where a client requests access to a specific realm. + # This first step (obtaining request token) need not require a realm + # and can then be identified by checking the require_resource_owner + # flag and absence of realm. + # + # Clients obtaining an access token will not supply a realm and it will + # not be checked. Instead the previously requested realm should be + # transferred from the request token to the access token. + # + # Access to protected resources will always validate the realm but note + # that the realm is now tied to the access token and not provided by + # the client. + valid_realm = self.request_validator.validate_realms(request.client_key, + request.resource_owner_key, request, uri=request.uri, + realms=realms) + + valid_signature = self._check_signature(request) + + # log the results to the validator_log + # this lets us handle internal reporting and analysis + request.validator_log['client'] = valid_client + request.validator_log['resource_owner'] = valid_resource_owner + request.validator_log['realm'] = valid_realm + request.validator_log['signature'] = valid_signature + + # We delay checking validity until the very end, using dummy values for + # calculations and fetching secrets/keys to ensure the flow of every + # request remains almost identical regardless of whether valid values + # have been supplied. This ensures near constant time execution and + # prevents malicious users from guessing sensitive information + v = all((valid_client, valid_resource_owner, valid_realm, + valid_signature)) + if not v: + log.info("[Failure] request verification failed.") + log.info("Valid client: %s", valid_client) + log.info("Valid token: %s", valid_resource_owner) + log.info("Valid realm: %s", valid_realm) + log.info("Valid signature: %s", valid_signature) + return v, request diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/endpoints/signature_only.py b/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/endpoints/signature_only.py new file mode 100644 index 0000000000000000000000000000000000000000..d693ccb7f6bf368754223f822a143dc81b8232df --- /dev/null +++ b/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/endpoints/signature_only.py @@ -0,0 +1,82 @@ +# -*- coding: utf-8 -*- +""" +oauthlib.oauth1.rfc5849.endpoints.signature_only +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +This module is an implementation of the signing logic of OAuth 1.0 RFC 5849. +""" + +import logging + +from .. import errors +from .base import BaseEndpoint + +log = logging.getLogger(__name__) + + +class SignatureOnlyEndpoint(BaseEndpoint): + + """An endpoint only responsible for verifying an oauth signature.""" + + def validate_request(self, uri, http_method='GET', + body=None, headers=None): + """Validate a signed OAuth request. + + :param uri: The full URI of the token request. + :param http_method: A valid HTTP verb, i.e. GET, POST, PUT, HEAD, etc. + :param body: The request body as a string. + :param headers: The request headers as a dict. + :returns: A tuple of 2 elements. + 1. True if valid, False otherwise. + 2. An oauthlib.common.Request object. + """ + try: + request = self._create_request(uri, http_method, body, headers) + except errors.OAuth1Error as err: + log.info( + 'Exception caught while validating request, %s.' % err) + return False, None + + try: + self._check_transport_security(request) + self._check_mandatory_parameters(request) + except errors.OAuth1Error as err: + log.info( + 'Exception caught while validating request, %s.' % err) + return False, request + + if not self.request_validator.validate_timestamp_and_nonce( + request.client_key, request.timestamp, request.nonce, request): + log.debug('[Failure] verification failed: timestamp/nonce') + return False, request + + # The server SHOULD return a 401 (Unauthorized) status code when + # receiving a request with invalid client credentials. + # Note: This is postponed in order to avoid timing attacks, instead + # a dummy client is assigned and used to maintain near constant + # time request verification. + # + # Note that early exit would enable client enumeration + valid_client = self.request_validator.validate_client_key( + request.client_key, request) + if not valid_client: + request.client_key = self.request_validator.dummy_client + + valid_signature = self._check_signature(request) + + # log the results to the validator_log + # this lets us handle internal reporting and analysis + request.validator_log['client'] = valid_client + request.validator_log['signature'] = valid_signature + + # We delay checking validity until the very end, using dummy values for + # calculations and fetching secrets/keys to ensure the flow of every + # request remains almost identical regardless of whether valid values + # have been supplied. This ensures near constant time execution and + # prevents malicious users from guessing sensitive information + v = all((valid_client, valid_signature)) + if not v: + log.info("[Failure] request verification failed.") + log.info("Valid client: %s", valid_client) + log.info("Valid signature: %s", valid_signature) + return v, request diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/errors.py b/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/errors.py new file mode 100644 index 0000000000000000000000000000000000000000..8774d40741b4b26a3721be545c66513505aaa8d1 --- /dev/null +++ b/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/errors.py @@ -0,0 +1,76 @@ +""" +oauthlib.oauth1.rfc5849.errors +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Error used both by OAuth 1 clients and provicers to represent the spec +defined error responses for all four core grant types. +""" +from oauthlib.common import add_params_to_uri, urlencode + + +class OAuth1Error(Exception): + error = None + description = '' + + def __init__(self, description=None, uri=None, status_code=400, + request=None): + """ + description: A human-readable ASCII [USASCII] text providing + additional information, used to assist the client + developer in understanding the error that occurred. + Values for the "error_description" parameter MUST NOT + include characters outside the set + x20-21 / x23-5B / x5D-7E. + + uri: A URI identifying a human-readable web page with information + about the error, used to provide the client developer with + additional information about the error. Values for the + "error_uri" parameter MUST conform to the URI- Reference + syntax, and thus MUST NOT include characters outside the set + x21 / x23-5B / x5D-7E. + + state: A CSRF protection value received from the client. + + request: Oauthlib Request object + """ + self.description = description or self.description + message = '({}) {}'.format(self.error, self.description) + if request: + message += ' ' + repr(request) + super().__init__(message) + + self.uri = uri + self.status_code = status_code + + def in_uri(self, uri): + return add_params_to_uri(uri, self.twotuples) + + @property + def twotuples(self): + error = [('error', self.error)] + if self.description: + error.append(('error_description', self.description)) + if self.uri: + error.append(('error_uri', self.uri)) + return error + + @property + def urlencoded(self): + return urlencode(self.twotuples) + + +class InsecureTransportError(OAuth1Error): + error = 'insecure_transport_protocol' + description = 'Only HTTPS connections are permitted.' + + +class InvalidSignatureMethodError(OAuth1Error): + error = 'invalid_signature_method' + + +class InvalidRequestError(OAuth1Error): + error = 'invalid_request' + + +class InvalidClientError(OAuth1Error): + error = 'invalid_client' diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/parameters.py b/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/parameters.py new file mode 100644 index 0000000000000000000000000000000000000000..2163772df3c7f53d539fa8cb0b73cc0e547614f2 --- /dev/null +++ b/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/parameters.py @@ -0,0 +1,133 @@ +""" +oauthlib.parameters +~~~~~~~~~~~~~~~~~~~ + +This module contains methods related to `section 3.5`_ of the OAuth 1.0a spec. + +.. _`section 3.5`: https://tools.ietf.org/html/rfc5849#section-3.5 +""" +from urllib.parse import urlparse, urlunparse + +from oauthlib.common import extract_params, urlencode + +from . import utils + + +# TODO: do we need filter_params now that oauth_params are handled by Request? +# We can easily pass in just oauth protocol params. +@utils.filter_params +def prepare_headers(oauth_params, headers=None, realm=None): + """**Prepare the Authorization header.** + Per `section 3.5.1`_ of the spec. + + Protocol parameters can be transmitted using the HTTP "Authorization" + header field as defined by `RFC2617`_ with the auth-scheme name set to + "OAuth" (case insensitive). + + For example:: + + Authorization: OAuth realm="Example", + oauth_consumer_key="0685bd9184jfhq22", + oauth_token="ad180jjd733klru7", + oauth_signature_method="HMAC-SHA1", + oauth_signature="wOJIO9A2W5mFwDgiDvZbTSMK%2FPY%3D", + oauth_timestamp="137131200", + oauth_nonce="4572616e48616d6d65724c61686176", + oauth_version="1.0" + + + .. _`section 3.5.1`: https://tools.ietf.org/html/rfc5849#section-3.5.1 + .. _`RFC2617`: https://tools.ietf.org/html/rfc2617 + """ + headers = headers or {} + + # Protocol parameters SHALL be included in the "Authorization" header + # field as follows: + authorization_header_parameters_parts = [] + for oauth_parameter_name, value in oauth_params: + # 1. Parameter names and values are encoded per Parameter Encoding + # (`Section 3.6`_) + # + # .. _`Section 3.6`: https://tools.ietf.org/html/rfc5849#section-3.6 + escaped_name = utils.escape(oauth_parameter_name) + escaped_value = utils.escape(value) + + # 2. Each parameter's name is immediately followed by an "=" character + # (ASCII code 61), a """ character (ASCII code 34), the parameter + # value (MAY be empty), and another """ character (ASCII code 34). + part = '{}="{}"'.format(escaped_name, escaped_value) + + authorization_header_parameters_parts.append(part) + + # 3. Parameters are separated by a "," character (ASCII code 44) and + # OPTIONAL linear whitespace per `RFC2617`_. + # + # .. _`RFC2617`: https://tools.ietf.org/html/rfc2617 + authorization_header_parameters = ', '.join( + authorization_header_parameters_parts) + + # 4. The OPTIONAL "realm" parameter MAY be added and interpreted per + # `RFC2617 section 1.2`_. + # + # .. _`RFC2617 section 1.2`: https://tools.ietf.org/html/rfc2617#section-1.2 + if realm: + # NOTE: realm should *not* be escaped + authorization_header_parameters = ('realm="%s", ' % realm + + authorization_header_parameters) + + # the auth-scheme name set to "OAuth" (case insensitive). + authorization_header = 'OAuth %s' % authorization_header_parameters + + # contribute the Authorization header to the given headers + full_headers = {} + full_headers.update(headers) + full_headers['Authorization'] = authorization_header + return full_headers + + +def _append_params(oauth_params, params): + """Append OAuth params to an existing set of parameters. + + Both params and oauth_params is must be lists of 2-tuples. + + Per `section 3.5.2`_ and `3.5.3`_ of the spec. + + .. _`section 3.5.2`: https://tools.ietf.org/html/rfc5849#section-3.5.2 + .. _`3.5.3`: https://tools.ietf.org/html/rfc5849#section-3.5.3 + + """ + merged = list(params) + merged.extend(oauth_params) + # The request URI / entity-body MAY include other request-specific + # parameters, in which case, the protocol parameters SHOULD be appended + # following the request-specific parameters, properly separated by an "&" + # character (ASCII code 38) + merged.sort(key=lambda i: i[0].startswith('oauth_')) + return merged + + +def prepare_form_encoded_body(oauth_params, body): + """Prepare the Form-Encoded Body. + + Per `section 3.5.2`_ of the spec. + + .. _`section 3.5.2`: https://tools.ietf.org/html/rfc5849#section-3.5.2 + + """ + # append OAuth params to the existing body + return _append_params(oauth_params, body) + + +def prepare_request_uri_query(oauth_params, uri): + """Prepare the Request URI Query. + + Per `section 3.5.3`_ of the spec. + + .. _`section 3.5.3`: https://tools.ietf.org/html/rfc5849#section-3.5.3 + + """ + # append OAuth params to the existing set of query components + sch, net, path, par, query, fra = urlparse(uri) + query = urlencode( + _append_params(oauth_params, extract_params(query) or [])) + return urlunparse((sch, net, path, par, query, fra)) diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/request_validator.py b/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/request_validator.py new file mode 100644 index 0000000000000000000000000000000000000000..e937aabf4082850d8e966e75530dde6ff0becb13 --- /dev/null +++ b/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/request_validator.py @@ -0,0 +1,849 @@ +""" +oauthlib.oauth1.rfc5849 +~~~~~~~~~~~~~~ + +This module is an implementation of various logic needed +for signing and checking OAuth 1.0 RFC 5849 requests. +""" +from . import SIGNATURE_METHODS, utils + + +class RequestValidator: + + """A validator/datastore interaction base class for OAuth 1 providers. + + OAuth providers should inherit from RequestValidator and implement the + methods and properties outlined below. Further details are provided in the + documentation for each method and property. + + Methods used to check the format of input parameters. Common tests include + length, character set, membership, range or pattern. These tests are + referred to as `whitelisting or blacklisting`_. Whitelisting is better + but blacklisting can be useful to spot malicious activity. + The following have methods a default implementation: + + - check_client_key + - check_request_token + - check_access_token + - check_nonce + - check_verifier + - check_realms + + The methods above default to whitelist input parameters, checking that they + are alphanumerical and between a minimum and maximum length. Rather than + overloading the methods a few properties can be used to configure these + methods. + + * @safe_characters -> (character set) + * @client_key_length -> (min, max) + * @request_token_length -> (min, max) + * @access_token_length -> (min, max) + * @nonce_length -> (min, max) + * @verifier_length -> (min, max) + * @realms -> [list, of, realms] + + Methods used to validate/invalidate input parameters. These checks usually + hit either persistent or temporary storage such as databases or the + filesystem. See each methods documentation for detailed usage. + The following methods must be implemented: + + - validate_client_key + - validate_request_token + - validate_access_token + - validate_timestamp_and_nonce + - validate_redirect_uri + - validate_requested_realms + - validate_realms + - validate_verifier + - invalidate_request_token + + Methods used to retrieve sensitive information from storage. + The following methods must be implemented: + + - get_client_secret + - get_request_token_secret + - get_access_token_secret + - get_rsa_key + - get_realms + - get_default_realms + - get_redirect_uri + + Methods used to save credentials. + The following methods must be implemented: + + - save_request_token + - save_verifier + - save_access_token + + Methods used to verify input parameters. This methods are used during + authorizing request token by user (AuthorizationEndpoint), to check if + parameters are valid. During token authorization request is not signed, + thus 'validation' methods can not be used. The following methods must be + implemented: + + - verify_realms + - verify_request_token + + To prevent timing attacks it is necessary to not exit early even if the + client key or resource owner key is invalid. Instead dummy values should + be used during the remaining verification process. It is very important + that the dummy client and token are valid input parameters to the methods + get_client_secret, get_rsa_key and get_(access/request)_token_secret and + that the running time of those methods when given a dummy value remain + equivalent to the running time when given a valid client/resource owner. + The following properties must be implemented: + + * @dummy_client + * @dummy_request_token + * @dummy_access_token + + Example implementations have been provided, note that the database used is + a simple dictionary and serves only an illustrative purpose. Use whichever + database suits your project and how to access it is entirely up to you. + The methods are introduced in an order which should make understanding + their use more straightforward and as such it could be worth reading what + follows in chronological order. + + .. _`whitelisting or blacklisting`: https://www.schneier.com/blog/archives/2011/01/whitelisting_vs.html + """ + + def __init__(self): + pass + + @property + def allowed_signature_methods(self): + return SIGNATURE_METHODS + + @property + def safe_characters(self): + return set(utils.UNICODE_ASCII_CHARACTER_SET) + + @property + def client_key_length(self): + return 20, 30 + + @property + def request_token_length(self): + return 20, 30 + + @property + def access_token_length(self): + return 20, 30 + + @property + def timestamp_lifetime(self): + return 600 + + @property + def nonce_length(self): + return 20, 30 + + @property + def verifier_length(self): + return 20, 30 + + @property + def realms(self): + return [] + + @property + def enforce_ssl(self): + return True + + def check_client_key(self, client_key): + """Check that the client key only contains safe characters + and is no shorter than lower and no longer than upper. + """ + lower, upper = self.client_key_length + return (set(client_key) <= self.safe_characters and + lower <= len(client_key) <= upper) + + def check_request_token(self, request_token): + """Checks that the request token contains only safe characters + and is no shorter than lower and no longer than upper. + """ + lower, upper = self.request_token_length + return (set(request_token) <= self.safe_characters and + lower <= len(request_token) <= upper) + + def check_access_token(self, request_token): + """Checks that the token contains only safe characters + and is no shorter than lower and no longer than upper. + """ + lower, upper = self.access_token_length + return (set(request_token) <= self.safe_characters and + lower <= len(request_token) <= upper) + + def check_nonce(self, nonce): + """Checks that the nonce only contains only safe characters + and is no shorter than lower and no longer than upper. + """ + lower, upper = self.nonce_length + return (set(nonce) <= self.safe_characters and + lower <= len(nonce) <= upper) + + def check_verifier(self, verifier): + """Checks that the verifier contains only safe characters + and is no shorter than lower and no longer than upper. + """ + lower, upper = self.verifier_length + return (set(verifier) <= self.safe_characters and + lower <= len(verifier) <= upper) + + def check_realms(self, realms): + """Check that the realm is one of a set allowed realms.""" + return all(r in self.realms for r in realms) + + def _subclass_must_implement(self, fn): + """ + Returns a NotImplementedError for a function that should be implemented. + :param fn: name of the function + """ + m = "Missing function implementation in {}: {}".format(type(self), fn) + return NotImplementedError(m) + + @property + def dummy_client(self): + """Dummy client used when an invalid client key is supplied. + + :returns: The dummy client key string. + + The dummy client should be associated with either a client secret, + a rsa key or both depending on which signature methods are supported. + Providers should make sure that + + get_client_secret(dummy_client) + get_rsa_key(dummy_client) + + return a valid secret or key for the dummy client. + + This method is used by + + * AccessTokenEndpoint + * RequestTokenEndpoint + * ResourceEndpoint + * SignatureOnlyEndpoint + """ + raise self._subclass_must_implement("dummy_client") + + @property + def dummy_request_token(self): + """Dummy request token used when an invalid token was supplied. + + :returns: The dummy request token string. + + The dummy request token should be associated with a request token + secret such that get_request_token_secret(.., dummy_request_token) + returns a valid secret. + + This method is used by + + * AccessTokenEndpoint + """ + raise self._subclass_must_implement("dummy_request_token") + + @property + def dummy_access_token(self): + """Dummy access token used when an invalid token was supplied. + + :returns: The dummy access token string. + + The dummy access token should be associated with an access token + secret such that get_access_token_secret(.., dummy_access_token) + returns a valid secret. + + This method is used by + + * ResourceEndpoint + """ + raise self._subclass_must_implement("dummy_access_token") + + def get_client_secret(self, client_key, request): + """Retrieves the client secret associated with the client key. + + :param client_key: The client/consumer key. + :param request: OAuthlib request. + :type request: oauthlib.common.Request + :returns: The client secret as a string. + + This method must allow the use of a dummy client_key value. + Fetching the secret using the dummy key must take the same amount of + time as fetching a secret for a valid client:: + + # Unlikely to be near constant time as it uses two database + # lookups for a valid client, and only one for an invalid. + from your_datastore import ClientSecret + if ClientSecret.has(client_key): + return ClientSecret.get(client_key) + else: + return 'dummy' + + # Aim to mimic number of latency inducing operations no matter + # whether the client is valid or not. + from your_datastore import ClientSecret + return ClientSecret.get(client_key, 'dummy') + + Note that the returned key must be in plaintext. + + This method is used by + + * AccessTokenEndpoint + * RequestTokenEndpoint + * ResourceEndpoint + * SignatureOnlyEndpoint + """ + raise self._subclass_must_implement('get_client_secret') + + def get_request_token_secret(self, client_key, token, request): + """Retrieves the shared secret associated with the request token. + + :param client_key: The client/consumer key. + :param token: The request token string. + :param request: OAuthlib request. + :type request: oauthlib.common.Request + :returns: The token secret as a string. + + This method must allow the use of a dummy values and the running time + must be roughly equivalent to that of the running time of valid values:: + + # Unlikely to be near constant time as it uses two database + # lookups for a valid client, and only one for an invalid. + from your_datastore import RequestTokenSecret + if RequestTokenSecret.has(client_key): + return RequestTokenSecret.get((client_key, request_token)) + else: + return 'dummy' + + # Aim to mimic number of latency inducing operations no matter + # whether the client is valid or not. + from your_datastore import RequestTokenSecret + return ClientSecret.get((client_key, request_token), 'dummy') + + Note that the returned key must be in plaintext. + + This method is used by + + * AccessTokenEndpoint + """ + raise self._subclass_must_implement('get_request_token_secret') + + def get_access_token_secret(self, client_key, token, request): + """Retrieves the shared secret associated with the access token. + + :param client_key: The client/consumer key. + :param token: The access token string. + :param request: OAuthlib request. + :type request: oauthlib.common.Request + :returns: The token secret as a string. + + This method must allow the use of a dummy values and the running time + must be roughly equivalent to that of the running time of valid values:: + + # Unlikely to be near constant time as it uses two database + # lookups for a valid client, and only one for an invalid. + from your_datastore import AccessTokenSecret + if AccessTokenSecret.has(client_key): + return AccessTokenSecret.get((client_key, request_token)) + else: + return 'dummy' + + # Aim to mimic number of latency inducing operations no matter + # whether the client is valid or not. + from your_datastore import AccessTokenSecret + return ClientSecret.get((client_key, request_token), 'dummy') + + Note that the returned key must be in plaintext. + + This method is used by + + * ResourceEndpoint + """ + raise self._subclass_must_implement("get_access_token_secret") + + def get_default_realms(self, client_key, request): + """Get the default realms for a client. + + :param client_key: The client/consumer key. + :param request: OAuthlib request. + :type request: oauthlib.common.Request + :returns: The list of default realms associated with the client. + + The list of default realms will be set during client registration and + is outside the scope of OAuthLib. + + This method is used by + + * RequestTokenEndpoint + """ + raise self._subclass_must_implement("get_default_realms") + + def get_realms(self, token, request): + """Get realms associated with a request token. + + :param token: The request token string. + :param request: OAuthlib request. + :type request: oauthlib.common.Request + :returns: The list of realms associated with the request token. + + This method is used by + + * AuthorizationEndpoint + * AccessTokenEndpoint + """ + raise self._subclass_must_implement("get_realms") + + def get_redirect_uri(self, token, request): + """Get the redirect URI associated with a request token. + + :param token: The request token string. + :param request: OAuthlib request. + :type request: oauthlib.common.Request + :returns: The redirect URI associated with the request token. + + It may be desirable to return a custom URI if the redirect is set to "oob". + In this case, the user will be redirected to the returned URI and at that + endpoint the verifier can be displayed. + + This method is used by + + * AuthorizationEndpoint + """ + raise self._subclass_must_implement("get_redirect_uri") + + def get_rsa_key(self, client_key, request): + """Retrieves a previously stored client provided RSA key. + + :param client_key: The client/consumer key. + :param request: OAuthlib request. + :type request: oauthlib.common.Request + :returns: The rsa public key as a string. + + This method must allow the use of a dummy client_key value. Fetching + the rsa key using the dummy key must take the same amount of time + as fetching a key for a valid client. The dummy key must also be of + the same bit length as client keys. + + Note that the key must be returned in plaintext. + + This method is used by + + * AccessTokenEndpoint + * RequestTokenEndpoint + * ResourceEndpoint + * SignatureOnlyEndpoint + """ + raise self._subclass_must_implement("get_rsa_key") + + def invalidate_request_token(self, client_key, request_token, request): + """Invalidates a used request token. + + :param client_key: The client/consumer key. + :param request_token: The request token string. + :param request: OAuthlib request. + :type request: oauthlib.common.Request + :returns: None + + Per `Section 2.3`_ of the spec: + + "The server MUST (...) ensure that the temporary + credentials have not expired or been used before." + + .. _`Section 2.3`: https://tools.ietf.org/html/rfc5849#section-2.3 + + This method should ensure that provided token won't validate anymore. + It can be simply removing RequestToken from storage or setting + specific flag that makes it invalid (note that such flag should be + also validated during request token validation). + + This method is used by + + * AccessTokenEndpoint + """ + raise self._subclass_must_implement("invalidate_request_token") + + def validate_client_key(self, client_key, request): + """Validates that supplied client key is a registered and valid client. + + :param client_key: The client/consumer key. + :param request: OAuthlib request. + :type request: oauthlib.common.Request + :returns: True or False + + Note that if the dummy client is supplied it should validate in same + or nearly the same amount of time as a valid one. + + Ensure latency inducing tasks are mimiced even for dummy clients. + For example, use:: + + from your_datastore import Client + try: + return Client.exists(client_key, access_token) + except DoesNotExist: + return False + + Rather than:: + + from your_datastore import Client + if access_token == self.dummy_access_token: + return False + else: + return Client.exists(client_key, access_token) + + This method is used by + + * AccessTokenEndpoint + * RequestTokenEndpoint + * ResourceEndpoint + * SignatureOnlyEndpoint + """ + raise self._subclass_must_implement("validate_client_key") + + def validate_request_token(self, client_key, token, request): + """Validates that supplied request token is registered and valid. + + :param client_key: The client/consumer key. + :param token: The request token string. + :param request: OAuthlib request. + :type request: oauthlib.common.Request + :returns: True or False + + Note that if the dummy request_token is supplied it should validate in + the same nearly the same amount of time as a valid one. + + Ensure latency inducing tasks are mimiced even for dummy clients. + For example, use:: + + from your_datastore import RequestToken + try: + return RequestToken.exists(client_key, access_token) + except DoesNotExist: + return False + + Rather than:: + + from your_datastore import RequestToken + if access_token == self.dummy_access_token: + return False + else: + return RequestToken.exists(client_key, access_token) + + This method is used by + + * AccessTokenEndpoint + """ + raise self._subclass_must_implement("validate_request_token") + + def validate_access_token(self, client_key, token, request): + """Validates that supplied access token is registered and valid. + + :param client_key: The client/consumer key. + :param token: The access token string. + :param request: OAuthlib request. + :type request: oauthlib.common.Request + :returns: True or False + + Note that if the dummy access token is supplied it should validate in + the same or nearly the same amount of time as a valid one. + + Ensure latency inducing tasks are mimiced even for dummy clients. + For example, use:: + + from your_datastore import AccessToken + try: + return AccessToken.exists(client_key, access_token) + except DoesNotExist: + return False + + Rather than:: + + from your_datastore import AccessToken + if access_token == self.dummy_access_token: + return False + else: + return AccessToken.exists(client_key, access_token) + + This method is used by + + * ResourceEndpoint + """ + raise self._subclass_must_implement("validate_access_token") + + def validate_timestamp_and_nonce(self, client_key, timestamp, nonce, + request, request_token=None, access_token=None): + """Validates that the nonce has not been used before. + + :param client_key: The client/consumer key. + :param timestamp: The ``oauth_timestamp`` parameter. + :param nonce: The ``oauth_nonce`` parameter. + :param request_token: Request token string, if any. + :param access_token: Access token string, if any. + :param request: OAuthlib request. + :type request: oauthlib.common.Request + :returns: True or False + + Per `Section 3.3`_ of the spec. + + "A nonce is a random string, uniquely generated by the client to allow + the server to verify that a request has never been made before and + helps prevent replay attacks when requests are made over a non-secure + channel. The nonce value MUST be unique across all requests with the + same timestamp, client credentials, and token combinations." + + .. _`Section 3.3`: https://tools.ietf.org/html/rfc5849#section-3.3 + + One of the first validation checks that will be made is for the validity + of the nonce and timestamp, which are associated with a client key and + possibly a token. If invalid then immediately fail the request + by returning False. If the nonce/timestamp pair has been used before and + you may just have detected a replay attack. Therefore it is an essential + part of OAuth security that you not allow nonce/timestamp reuse. + Note that this validation check is done before checking the validity of + the client and token.:: + + nonces_and_timestamps_database = [ + (u'foo', 1234567890, u'rannoMstrInghere', u'bar') + ] + + def validate_timestamp_and_nonce(self, client_key, timestamp, nonce, + request_token=None, access_token=None): + + return ((client_key, timestamp, nonce, request_token or access_token) + not in self.nonces_and_timestamps_database) + + This method is used by + + * AccessTokenEndpoint + * RequestTokenEndpoint + * ResourceEndpoint + * SignatureOnlyEndpoint + """ + raise self._subclass_must_implement("validate_timestamp_and_nonce") + + def validate_redirect_uri(self, client_key, redirect_uri, request): + """Validates the client supplied redirection URI. + + :param client_key: The client/consumer key. + :param redirect_uri: The URI the client which to redirect back to after + authorization is successful. + :param request: OAuthlib request. + :type request: oauthlib.common.Request + :returns: True or False + + It is highly recommended that OAuth providers require their clients + to register all redirection URIs prior to using them in requests and + register them as absolute URIs. See `CWE-601`_ for more information + about open redirection attacks. + + By requiring registration of all redirection URIs it should be + straightforward for the provider to verify whether the supplied + redirect_uri is valid or not. + + Alternatively per `Section 2.1`_ of the spec: + + "If the client is unable to receive callbacks or a callback URI has + been established via other means, the parameter value MUST be set to + "oob" (case sensitive), to indicate an out-of-band configuration." + + .. _`CWE-601`: http://cwe.mitre.org/top25/index.html#CWE-601 + .. _`Section 2.1`: https://tools.ietf.org/html/rfc5849#section-2.1 + + This method is used by + + * RequestTokenEndpoint + """ + raise self._subclass_must_implement("validate_redirect_uri") + + def validate_requested_realms(self, client_key, realms, request): + """Validates that the client may request access to the realm. + + :param client_key: The client/consumer key. + :param realms: The list of realms that client is requesting access to. + :param request: OAuthlib request. + :type request: oauthlib.common.Request + :returns: True or False + + This method is invoked when obtaining a request token and should + tie a realm to the request token and after user authorization + this realm restriction should transfer to the access token. + + This method is used by + + * RequestTokenEndpoint + """ + raise self._subclass_must_implement("validate_requested_realms") + + def validate_realms(self, client_key, token, request, uri=None, + realms=None): + """Validates access to the request realm. + + :param client_key: The client/consumer key. + :param token: A request token string. + :param request: OAuthlib request. + :type request: oauthlib.common.Request + :param uri: The URI the realms is protecting. + :param realms: A list of realms that must have been granted to + the access token. + :returns: True or False + + How providers choose to use the realm parameter is outside the OAuth + specification but it is commonly used to restrict access to a subset + of protected resources such as "photos". + + realms is a convenience parameter which can be used to provide + a per view method pre-defined list of allowed realms. + + Can be as simple as:: + + from your_datastore import RequestToken + request_token = RequestToken.get(token, None) + + if not request_token: + return False + return set(request_token.realms).issuperset(set(realms)) + + This method is used by + + * ResourceEndpoint + """ + raise self._subclass_must_implement("validate_realms") + + def validate_verifier(self, client_key, token, verifier, request): + """Validates a verification code. + + :param client_key: The client/consumer key. + :param token: A request token string. + :param verifier: The authorization verifier string. + :param request: OAuthlib request. + :type request: oauthlib.common.Request + :returns: True or False + + OAuth providers issue a verification code to clients after the + resource owner authorizes access. This code is used by the client to + obtain token credentials and the provider must verify that the + verifier is valid and associated with the client as well as the + resource owner. + + Verifier validation should be done in near constant time + (to avoid verifier enumeration). To achieve this we need a + constant time string comparison which is provided by OAuthLib + in ``oauthlib.common.safe_string_equals``:: + + from your_datastore import Verifier + correct_verifier = Verifier.get(client_key, request_token) + from oauthlib.common import safe_string_equals + return safe_string_equals(verifier, correct_verifier) + + This method is used by + + * AccessTokenEndpoint + """ + raise self._subclass_must_implement("validate_verifier") + + def verify_request_token(self, token, request): + """Verify that the given OAuth1 request token is valid. + + :param token: A request token string. + :param request: OAuthlib request. + :type request: oauthlib.common.Request + :returns: True or False + + This method is used only in AuthorizationEndpoint to check whether the + oauth_token given in the authorization URL is valid or not. + This request is not signed and thus similar ``validate_request_token`` + method can not be used. + + This method is used by + + * AuthorizationEndpoint + """ + raise self._subclass_must_implement("verify_request_token") + + def verify_realms(self, token, realms, request): + """Verify authorized realms to see if they match those given to token. + + :param token: An access token string. + :param realms: A list of realms the client attempts to access. + :param request: OAuthlib request. + :type request: oauthlib.common.Request + :returns: True or False + + This prevents the list of authorized realms sent by the client during + the authorization step to be altered to include realms outside what + was bound with the request token. + + Can be as simple as:: + + valid_realms = self.get_realms(token) + return all((r in valid_realms for r in realms)) + + This method is used by + + * AuthorizationEndpoint + """ + raise self._subclass_must_implement("verify_realms") + + def save_access_token(self, token, request): + """Save an OAuth1 access token. + + :param token: A dict with token credentials. + :param request: OAuthlib request. + :type request: oauthlib.common.Request + + The token dictionary will at minimum include + + * ``oauth_token`` the access token string. + * ``oauth_token_secret`` the token specific secret used in signing. + * ``oauth_authorized_realms`` a space separated list of realms. + + Client key can be obtained from ``request.client_key``. + + The list of realms (not joined string) can be obtained from + ``request.realm``. + + This method is used by + + * AccessTokenEndpoint + """ + raise self._subclass_must_implement("save_access_token") + + def save_request_token(self, token, request): + """Save an OAuth1 request token. + + :param token: A dict with token credentials. + :param request: OAuthlib request. + :type request: oauthlib.common.Request + + The token dictionary will at minimum include + + * ``oauth_token`` the request token string. + * ``oauth_token_secret`` the token specific secret used in signing. + * ``oauth_callback_confirmed`` the string ``true``. + + Client key can be obtained from ``request.client_key``. + + This method is used by + + * RequestTokenEndpoint + """ + raise self._subclass_must_implement("save_request_token") + + def save_verifier(self, token, verifier, request): + """Associate an authorization verifier with a request token. + + :param token: A request token string. + :param verifier: A dictionary containing the oauth_verifier and + oauth_token + :param request: OAuthlib request. + :type request: oauthlib.common.Request + + We need to associate verifiers with tokens for validation during the + access token request. + + Note that unlike save_x_token token here is the ``oauth_token`` token + string from the request token saved previously. + + This method is used by + + * AuthorizationEndpoint + """ + raise self._subclass_must_implement("save_verifier") diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/signature.py b/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/signature.py new file mode 100644 index 0000000000000000000000000000000000000000..a27cb2e76fcae785b8672401458e04c96ab25cb6 --- /dev/null +++ b/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/signature.py @@ -0,0 +1,852 @@ +""" +This module is an implementation of `section 3.4`_ of RFC 5849. + +**Usage** + +Steps for signing a request: + +1. Collect parameters from the request using ``collect_parameters``. +2. Normalize those parameters using ``normalize_parameters``. +3. Create the *base string URI* using ``base_string_uri``. +4. Create the *signature base string* from the above three components + using ``signature_base_string``. +5. Pass the *signature base string* and the client credentials to one of the + sign-with-client functions. The HMAC-based signing functions needs + client credentials with secrets. The RSA-based signing functions needs + client credentials with an RSA private key. + +To verify a request, pass the request and credentials to one of the verify +functions. The HMAC-based signing functions needs the shared secrets. The +RSA-based verify functions needs the RSA public key. + +**Scope** + +All of the functions in this module should be considered internal to OAuthLib, +since they are not imported into the "oauthlib.oauth1" module. Programs using +OAuthLib should not use directly invoke any of the functions in this module. + +**Deprecated functions** + +The "sign_" methods that are not "_with_client" have been deprecated. They may +be removed in a future release. Since they are all internal functions, this +should have no impact on properly behaving programs. + +.. _`section 3.4`: https://tools.ietf.org/html/rfc5849#section-3.4 +""" + +import binascii +import hashlib +import hmac +import ipaddress +import logging +import urllib.parse as urlparse +import warnings + +from oauthlib.common import extract_params, safe_string_equals, urldecode + +from . import utils +import contextlib + +log = logging.getLogger(__name__) + + +# ==== Common functions ========================================== + +def signature_base_string( + http_method: str, + base_str_uri: str, + normalized_encoded_request_parameters: str) -> str: + """ + Construct the signature base string. + + The *signature base string* is the value that is calculated and signed by + the client. It is also independently calculated by the server to verify + the signature, and therefore must produce the exact same value at both + ends or the signature won't verify. + + The rules for calculating the *signature base string* are defined in + section 3.4.1.1`_ of RFC 5849. + + .. _`section 3.4.1.1`: https://tools.ietf.org/html/rfc5849#section-3.4.1.1 + """ + + # The signature base string is constructed by concatenating together, + # in order, the following HTTP request elements: + + # 1. The HTTP request method in uppercase. For example: "HEAD", + # "GET", "POST", etc. If the request uses a custom HTTP method, it + # MUST be encoded (`Section 3.6`_). + # + # .. _`Section 3.6`: https://tools.ietf.org/html/rfc5849#section-3.6 + base_string = utils.escape(http_method.upper()) + + # 2. An "&" character (ASCII code 38). + base_string += '&' + + # 3. The base string URI from `Section 3.4.1.2`_, after being encoded + # (`Section 3.6`_). + # + # .. _`Section 3.4.1.2`: https://tools.ietf.org/html/rfc5849#section-3.4.1.2 + # .. _`Section 3.6`: https://tools.ietf.org/html/rfc5849#section-3.6 + base_string += utils.escape(base_str_uri) + + # 4. An "&" character (ASCII code 38). + base_string += '&' + + # 5. The request parameters as normalized in `Section 3.4.1.3.2`_, after + # being encoded (`Section 3.6`). + # + # .. _`Sec 3.4.1.3.2`: https://tools.ietf.org/html/rfc5849#section-3.4.1.3.2 + # .. _`Section 3.6`: https://tools.ietf.org/html/rfc5849#section-3.6 + base_string += utils.escape(normalized_encoded_request_parameters) + + return base_string + + +def base_string_uri(uri: str, host: str = None) -> str: + """ + Calculates the _base string URI_. + + The *base string URI* is one of the components that make up the + *signature base string*. + + The ``host`` is optional. If provided, it is used to override any host and + port values in the ``uri``. The value for ``host`` is usually extracted from + the "Host" request header from the HTTP request. Its value may be just the + hostname, or the hostname followed by a colon and a TCP/IP port number + (hostname:port). If a value for the``host`` is provided but it does not + contain a port number, the default port number is used (i.e. if the ``uri`` + contained a port number, it will be discarded). + + The rules for calculating the *base string URI* are defined in + section 3.4.1.2`_ of RFC 5849. + + .. _`section 3.4.1.2`: https://tools.ietf.org/html/rfc5849#section-3.4.1.2 + + :param uri: URI + :param host: hostname with optional port number, separated by a colon + :return: base string URI + """ + + if not isinstance(uri, str): + raise ValueError('uri must be a string.') + + # FIXME: urlparse does not support unicode + output = urlparse.urlparse(uri) + scheme = output.scheme + hostname = output.hostname + port = output.port + path = output.path + params = output.params + + # The scheme, authority, and path of the request resource URI `RFC3986` + # are included by constructing an "http" or "https" URI representing + # the request resource (without the query or fragment) as follows: + # + # .. _`RFC3986`: https://tools.ietf.org/html/rfc3986 + + if not scheme: + raise ValueError('missing scheme') + + # Per `RFC 2616 section 5.1.2`_: + # + # Note that the absolute path cannot be empty; if none is present in + # the original URI, it MUST be given as "/" (the server root). + # + # .. _`RFC 2616 5.1.2`: https://tools.ietf.org/html/rfc2616#section-5.1.2 + if not path: + path = '/' + + # 1. The scheme and host MUST be in lowercase. + scheme = scheme.lower() + # Note: if ``host`` is used, it will be converted to lowercase below + if hostname is not None: + hostname = hostname.lower() + + # 2. The host and port values MUST match the content of the HTTP + # request "Host" header field. + if host is not None: + # NOTE: override value in uri with provided host + # Host argument is equal to netloc. It means it's missing scheme. + # Add it back, before parsing. + + host = host.lower() + host = f"{scheme}://{host}" + output = urlparse.urlparse(host) + hostname = output.hostname + port = output.port + + # 3. The port MUST be included if it is not the default port for the + # scheme, and MUST be excluded if it is the default. Specifically, + # the port MUST be excluded when making an HTTP request `RFC2616`_ + # to port 80 or when making an HTTPS request `RFC2818`_ to port 443. + # All other non-default port numbers MUST be included. + # + # .. _`RFC2616`: https://tools.ietf.org/html/rfc2616 + # .. _`RFC2818`: https://tools.ietf.org/html/rfc2818 + + if hostname is None: + raise ValueError('missing host') + + # NOTE: Try guessing if we're dealing with IP or hostname + with contextlib.suppress(ValueError): + hostname = ipaddress.ip_address(hostname) + + + if isinstance(hostname, ipaddress.IPv6Address): + hostname = f"[{hostname}]" + elif isinstance(hostname, ipaddress.IPv4Address): + hostname = f"{hostname}" + + if port is not None and not (0 < port <= 65535): + raise ValueError('port out of range') # 16-bit unsigned ints + if (scheme, port) in (('http', 80), ('https', 443)): + netloc = hostname # default port for scheme: exclude port num + elif port: + netloc = f"{hostname}:{port}" # use hostname:port + else: + netloc = hostname + + v = urlparse.urlunparse((scheme, netloc, path, params, '', '')) + + # RFC 5849 does not specify which characters are encoded in the + # "base string URI", nor how they are encoded - which is very bad, since + # the signatures won't match if there are any differences. Fortunately, + # most URIs only use characters that are clearly not encoded (e.g. digits + # and A-Z, a-z), so have avoided any differences between implementations. + # + # The example from its section 3.4.1.2 illustrates that spaces in + # the path are percent encoded. But it provides no guidance as to what other + # characters (if any) must be encoded (nor how); nor if characters in the + # other components are to be encoded or not. + # + # This implementation **assumes** that **only** the space is percent-encoded + # and it is done to the entire value (not just to spaces in the path). + # + # This code may need to be changed if it is discovered that other characters + # are expected to be encoded. + # + # Note: the "base string URI" returned by this function will be encoded + # again before being concatenated into the "signature base string". So any + # spaces in the URI will actually appear in the "signature base string" + # as "%2520" (the "%20" further encoded according to section 3.6). + + return v.replace(' ', '%20') + + +def collect_parameters(uri_query='', body=None, headers=None, + exclude_oauth_signature=True, with_realm=False): + """ + Gather the request parameters from all the parameter sources. + + This function is used to extract all the parameters, which are then passed + to ``normalize_parameters`` to produce one of the components that make up + the *signature base string*. + + Parameters starting with `oauth_` will be unescaped. + + Body parameters must be supplied as a dict, a list of 2-tuples, or a + form encoded query string. + + Headers must be supplied as a dict. + + The rules where the parameters must be sourced from are defined in + `section 3.4.1.3.1`_ of RFC 5849. + + .. _`Sec 3.4.1.3.1`: https://tools.ietf.org/html/rfc5849#section-3.4.1.3.1 + """ + if body is None: + body = [] + headers = headers or {} + params = [] + + # The parameters from the following sources are collected into a single + # list of name/value pairs: + + # * The query component of the HTTP request URI as defined by + # `RFC3986, Section 3.4`_. The query component is parsed into a list + # of name/value pairs by treating it as an + # "application/x-www-form-urlencoded" string, separating the names + # and values and decoding them as defined by W3C.REC-html40-19980424 + # `W3C-HTML-4.0`_, Section 17.13.4. + # + # .. _`RFC3986, Sec 3.4`: https://tools.ietf.org/html/rfc3986#section-3.4 + # .. _`W3C-HTML-4.0`: https://www.w3.org/TR/1998/REC-html40-19980424/ + if uri_query: + params.extend(urldecode(uri_query)) + + # * The OAuth HTTP "Authorization" header field (`Section 3.5.1`_) if + # present. The header's content is parsed into a list of name/value + # pairs excluding the "realm" parameter if present. The parameter + # values are decoded as defined by `Section 3.5.1`_. + # + # .. _`Section 3.5.1`: https://tools.ietf.org/html/rfc5849#section-3.5.1 + if headers: + headers_lower = {k.lower(): v for k, v in headers.items()} + authorization_header = headers_lower.get('authorization') + if authorization_header is not None: + params.extend([i for i in utils.parse_authorization_header( + authorization_header) if with_realm or i[0] != 'realm']) + + # * The HTTP request entity-body, but only if all of the following + # conditions are met: + # * The entity-body is single-part. + # + # * The entity-body follows the encoding requirements of the + # "application/x-www-form-urlencoded" content-type as defined by + # W3C.REC-html40-19980424 `W3C-HTML-4.0`_. + + # * The HTTP request entity-header includes the "Content-Type" + # header field set to "application/x-www-form-urlencoded". + # + # .. _`W3C-HTML-4.0`: https://www.w3.org/TR/1998/REC-html40-19980424/ + + # TODO: enforce header param inclusion conditions + bodyparams = extract_params(body) or [] + params.extend(bodyparams) + + # ensure all oauth params are unescaped + unescaped_params = [] + for k, v in params: + if k.startswith('oauth_'): + v = utils.unescape(v) + unescaped_params.append((k, v)) + + # The "oauth_signature" parameter MUST be excluded from the signature + # base string if present. + if exclude_oauth_signature: + unescaped_params = list(filter(lambda i: i[0] != 'oauth_signature', + unescaped_params)) + + return unescaped_params + + +def normalize_parameters(params) -> str: + """ + Calculate the normalized request parameters. + + The *normalized request parameters* is one of the components that make up + the *signature base string*. + + The rules for parameter normalization are defined in `section 3.4.1.3.2`_ of + RFC 5849. + + .. _`Sec 3.4.1.3.2`: https://tools.ietf.org/html/rfc5849#section-3.4.1.3.2 + """ + + # The parameters collected in `Section 3.4.1.3`_ are normalized into a + # single string as follows: + # + # .. _`Section 3.4.1.3`: https://tools.ietf.org/html/rfc5849#section-3.4.1.3 + + # 1. First, the name and value of each parameter are encoded + # (`Section 3.6`_). + # + # .. _`Section 3.6`: https://tools.ietf.org/html/rfc5849#section-3.6 + key_values = [(utils.escape(k), utils.escape(v)) for k, v in params] + + # 2. The parameters are sorted by name, using ascending byte value + # ordering. If two or more parameters share the same name, they + # are sorted by their value. + key_values.sort() + + # 3. The name of each parameter is concatenated to its corresponding + # value using an "=" character (ASCII code 61) as a separator, even + # if the value is empty. + parameter_parts = ['{}={}'.format(k, v) for k, v in key_values] + + # 4. The sorted name/value pairs are concatenated together into a + # single string by using an "&" character (ASCII code 38) as + # separator. + return '&'.join(parameter_parts) + + +# ==== Common functions for HMAC-based signature methods ========= + +def _sign_hmac(hash_algorithm_name: str, + sig_base_str: str, + client_secret: str, + resource_owner_secret: str): + """ + **HMAC-SHA256** + + The "HMAC-SHA256" signature method uses the HMAC-SHA256 signature + algorithm as defined in `RFC4634`_:: + + digest = HMAC-SHA256 (key, text) + + Per `section 3.4.2`_ of the spec. + + .. _`RFC4634`: https://tools.ietf.org/html/rfc4634 + .. _`section 3.4.2`: https://tools.ietf.org/html/rfc5849#section-3.4.2 + """ + + # The HMAC-SHA256 function variables are used in following way: + + # text is set to the value of the signature base string from + # `Section 3.4.1.1`_. + # + # .. _`Section 3.4.1.1`: https://tools.ietf.org/html/rfc5849#section-3.4.1.1 + text = sig_base_str + + # key is set to the concatenated values of: + # 1. The client shared-secret, after being encoded (`Section 3.6`_). + # + # .. _`Section 3.6`: https://tools.ietf.org/html/rfc5849#section-3.6 + key = utils.escape(client_secret or '') + + # 2. An "&" character (ASCII code 38), which MUST be included + # even when either secret is empty. + key += '&' + + # 3. The token shared-secret, after being encoded (`Section 3.6`_). + # + # .. _`Section 3.6`: https://tools.ietf.org/html/rfc5849#section-3.6 + key += utils.escape(resource_owner_secret or '') + + # Get the hashing algorithm to use + + m = { + 'SHA-1': hashlib.sha1, + 'SHA-256': hashlib.sha256, + 'SHA-512': hashlib.sha512, + } + hash_alg = m[hash_algorithm_name] + + # Calculate the signature + + # FIXME: HMAC does not support unicode! + key_utf8 = key.encode('utf-8') + text_utf8 = text.encode('utf-8') + signature = hmac.new(key_utf8, text_utf8, hash_alg) + + # digest is used to set the value of the "oauth_signature" protocol + # parameter, after the result octet string is base64-encoded + # per `RFC2045, Section 6.8`. + # + # .. _`RFC2045, Sec 6.8`: https://tools.ietf.org/html/rfc2045#section-6.8 + return binascii.b2a_base64(signature.digest())[:-1].decode('utf-8') + + +def _verify_hmac(hash_algorithm_name: str, + request, + client_secret=None, + resource_owner_secret=None): + """Verify a HMAC-SHA1 signature. + + Per `section 3.4`_ of the spec. + + .. _`section 3.4`: https://tools.ietf.org/html/rfc5849#section-3.4 + + To satisfy `RFC2616 section 5.2`_ item 1, the request argument's uri + attribute MUST be an absolute URI whose netloc part identifies the + origin server or gateway on which the resource resides. Any Host + item of the request argument's headers dict attribute will be + ignored. + + .. _`RFC2616 section 5.2`: https://tools.ietf.org/html/rfc2616#section-5.2 + + """ + norm_params = normalize_parameters(request.params) + bs_uri = base_string_uri(request.uri) + sig_base_str = signature_base_string(request.http_method, bs_uri, + norm_params) + signature = _sign_hmac(hash_algorithm_name, sig_base_str, + client_secret, resource_owner_secret) + match = safe_string_equals(signature, request.signature) + if not match: + log.debug('Verify HMAC failed: signature base string: %s', sig_base_str) + return match + + +# ==== HMAC-SHA1 ================================================= + +def sign_hmac_sha1_with_client(sig_base_str, client): + return _sign_hmac('SHA-1', sig_base_str, + client.client_secret, client.resource_owner_secret) + + +def verify_hmac_sha1(request, client_secret=None, resource_owner_secret=None): + return _verify_hmac('SHA-1', request, client_secret, resource_owner_secret) + + +def sign_hmac_sha1(base_string, client_secret, resource_owner_secret): + """ + Deprecated function for calculating a HMAC-SHA1 signature. + + This function has been replaced by invoking ``sign_hmac`` with "SHA-1" + as the hash algorithm name. + + This function was invoked by sign_hmac_sha1_with_client and + test_signatures.py, but does any application invoke it directly? If not, + it can be removed. + """ + warnings.warn('use sign_hmac_sha1_with_client instead of sign_hmac_sha1', + DeprecationWarning) + + # For some unknown reason, the original implementation assumed base_string + # could either be bytes or str. The signature base string calculating + # function always returned a str, so the new ``sign_rsa`` only expects that. + + base_string = base_string.decode('ascii') \ + if isinstance(base_string, bytes) else base_string + + return _sign_hmac('SHA-1', base_string, + client_secret, resource_owner_secret) + + +# ==== HMAC-SHA256 =============================================== + +def sign_hmac_sha256_with_client(sig_base_str, client): + return _sign_hmac('SHA-256', sig_base_str, + client.client_secret, client.resource_owner_secret) + + +def verify_hmac_sha256(request, client_secret=None, resource_owner_secret=None): + return _verify_hmac('SHA-256', request, + client_secret, resource_owner_secret) + + +def sign_hmac_sha256(base_string, client_secret, resource_owner_secret): + """ + Deprecated function for calculating a HMAC-SHA256 signature. + + This function has been replaced by invoking ``sign_hmac`` with "SHA-256" + as the hash algorithm name. + + This function was invoked by sign_hmac_sha256_with_client and + test_signatures.py, but does any application invoke it directly? If not, + it can be removed. + """ + warnings.warn( + 'use sign_hmac_sha256_with_client instead of sign_hmac_sha256', + DeprecationWarning) + + # For some unknown reason, the original implementation assumed base_string + # could either be bytes or str. The signature base string calculating + # function always returned a str, so the new ``sign_rsa`` only expects that. + + base_string = base_string.decode('ascii') \ + if isinstance(base_string, bytes) else base_string + + return _sign_hmac('SHA-256', base_string, + client_secret, resource_owner_secret) + + +# ==== HMAC-SHA512 =============================================== + +def sign_hmac_sha512_with_client(sig_base_str: str, + client): + return _sign_hmac('SHA-512', sig_base_str, + client.client_secret, client.resource_owner_secret) + + +def verify_hmac_sha512(request, + client_secret: str = None, + resource_owner_secret: str = None): + return _verify_hmac('SHA-512', request, + client_secret, resource_owner_secret) + + +# ==== Common functions for RSA-based signature methods ========== + +_jwt_rsa = {} # cache of RSA-hash implementations from PyJWT jwt.algorithms + + +def _get_jwt_rsa_algorithm(hash_algorithm_name: str): + """ + Obtains an RSAAlgorithm object that implements RSA with the hash algorithm. + + This method maintains the ``_jwt_rsa`` cache. + + Returns a jwt.algorithm.RSAAlgorithm. + """ + if hash_algorithm_name in _jwt_rsa: + # Found in cache: return it + return _jwt_rsa[hash_algorithm_name] + else: + # Not in cache: instantiate a new RSAAlgorithm + + # PyJWT has some nice pycrypto/cryptography abstractions + import jwt.algorithms as jwt_algorithms # noqa: PLC0415 + m = { + 'SHA-1': jwt_algorithms.hashes.SHA1, + 'SHA-256': jwt_algorithms.hashes.SHA256, + 'SHA-512': jwt_algorithms.hashes.SHA512, + } + v = jwt_algorithms.RSAAlgorithm(m[hash_algorithm_name]) + + _jwt_rsa[hash_algorithm_name] = v # populate cache + + return v + + +def _prepare_key_plus(alg, keystr): + """ + Prepare a PEM encoded key (public or private), by invoking the `prepare_key` + method on alg with the keystr. + + The keystr should be a string or bytes. If the keystr is bytes, it is + decoded as UTF-8 before being passed to prepare_key. Otherwise, it + is passed directly. + """ + if isinstance(keystr, bytes): + keystr = keystr.decode('utf-8') + return alg.prepare_key(keystr) + + +def _sign_rsa(hash_algorithm_name: str, + sig_base_str: str, + rsa_private_key: str): + """ + Calculate the signature for an RSA-based signature method. + + The ``alg`` is used to calculate the digest over the signature base string. + For the "RSA_SHA1" signature method, the alg must be SHA-1. While OAuth 1.0a + only defines the RSA-SHA1 signature method, this function can be used for + other non-standard signature methods that only differ from RSA-SHA1 by the + digest algorithm. + + Signing for the RSA-SHA1 signature method is defined in + `section 3.4.3`_ of RFC 5849. + + The RSASSA-PKCS1-v1_5 signature algorithm used defined by + `RFC3447, Section 8.2`_ (also known as PKCS#1), with the `alg` as the + hash function for EMSA-PKCS1-v1_5. To + use this method, the client MUST have established client credentials + with the server that included its RSA public key (in a manner that is + beyond the scope of this specification). + + .. _`section 3.4.3`: https://tools.ietf.org/html/rfc5849#section-3.4.3 + .. _`RFC3447, Section 8.2`: https://tools.ietf.org/html/rfc3447#section-8.2 + """ + + # Get the implementation of RSA-hash + + alg = _get_jwt_rsa_algorithm(hash_algorithm_name) + + # Check private key + + if not rsa_private_key: + raise ValueError('rsa_private_key required for RSA with ' + + alg.hash_alg.name + ' signature method') + + # Convert the "signature base string" into a sequence of bytes (M) + # + # The signature base string, by definition, only contain printable US-ASCII + # characters. So encoding it as 'ascii' will always work. It will raise a + # ``UnicodeError`` if it can't encode the value, which will never happen + # if the signature base string was created correctly. Therefore, using + # 'ascii' encoding provides an extra level of error checking. + + m = sig_base_str.encode('ascii') + + # Perform signing: S = RSASSA-PKCS1-V1_5-SIGN (K, M) + + key = _prepare_key_plus(alg, rsa_private_key) + s = alg.sign(m, key) + + # base64-encoded per RFC2045 section 6.8. + # + # 1. While b2a_base64 implements base64 defined by RFC 3548. As used here, + # it is the same as base64 defined by RFC 2045. + # 2. b2a_base64 includes a "\n" at the end of its result ([:-1] removes it) + # 3. b2a_base64 produces a binary string. Use decode to produce a str. + # It should only contain only printable US-ASCII characters. + + return binascii.b2a_base64(s)[:-1].decode('ascii') + + +def _verify_rsa(hash_algorithm_name: str, + request, + rsa_public_key: str): + """ + Verify a base64 encoded signature for a RSA-based signature method. + + The ``alg`` is used to calculate the digest over the signature base string. + For the "RSA_SHA1" signature method, the alg must be SHA-1. While OAuth 1.0a + only defines the RSA-SHA1 signature method, this function can be used for + other non-standard signature methods that only differ from RSA-SHA1 by the + digest algorithm. + + Verification for the RSA-SHA1 signature method is defined in + `section 3.4.3`_ of RFC 5849. + + .. _`section 3.4.3`: https://tools.ietf.org/html/rfc5849#section-3.4.3 + + To satisfy `RFC2616 section 5.2`_ item 1, the request argument's uri + attribute MUST be an absolute URI whose netloc part identifies the + origin server or gateway on which the resource resides. Any Host + item of the request argument's headers dict attribute will be + ignored. + + .. _`RFC2616 Sec 5.2`: https://tools.ietf.org/html/rfc2616#section-5.2 + """ + + try: + # Calculate the *signature base string* of the actual received request + + norm_params = normalize_parameters(request.params) + bs_uri = base_string_uri(request.uri) + sig_base_str = signature_base_string( + request.http_method, bs_uri, norm_params) + + # Obtain the signature that was received in the request + + sig = binascii.a2b_base64(request.signature.encode('ascii')) + + # Get the implementation of RSA-with-hash algorithm to use + + alg = _get_jwt_rsa_algorithm(hash_algorithm_name) + + # Verify the received signature was produced by the private key + # corresponding to the `rsa_public_key`, signing exact same + # *signature base string*. + # + # RSASSA-PKCS1-V1_5-VERIFY ((n, e), M, S) + + key = _prepare_key_plus(alg, rsa_public_key) + + # The signature base string only contain printable US-ASCII characters. + # The ``encode`` method with the default "strict" error handling will + # raise a ``UnicodeError`` if it can't encode the value. So using + # "ascii" will always work. + + verify_ok = alg.verify(sig_base_str.encode('ascii'), key, sig) + + if not verify_ok: + log.debug('Verify failed: RSA with ' + alg.hash_alg.name + + ': signature base string=%s' + sig_base_str) + return verify_ok + + except UnicodeError: + # A properly encoded signature will only contain printable US-ASCII + # characters. The ``encode`` method with the default "strict" error + # handling will raise a ``UnicodeError`` if it can't decode the value. + # So using "ascii" will work with all valid signatures. But an + # incorrectly or maliciously produced signature could contain other + # bytes. + # + # This implementation treats that situation as equivalent to the + # signature verification having failed. + # + # Note: simply changing the encode to use 'utf-8' will not remove this + # case, since an incorrect or malicious request can contain bytes which + # are invalid as UTF-8. + return False + + +# ==== RSA-SHA1 ================================================== + +def sign_rsa_sha1_with_client(sig_base_str, client): + # For some reason, this function originally accepts both str and bytes. + # This behaviour is preserved here. But won't be done for the newer + # sign_rsa_sha256_with_client and sign_rsa_sha512_with_client functions, + # which will only accept strings. The function to calculate a + # "signature base string" always produces a string, so it is not clear + # why support for bytes would ever be needed. + sig_base_str = sig_base_str.decode('ascii')\ + if isinstance(sig_base_str, bytes) else sig_base_str + + return _sign_rsa('SHA-1', sig_base_str, client.rsa_key) + + +def verify_rsa_sha1(request, rsa_public_key: str): + return _verify_rsa('SHA-1', request, rsa_public_key) + + +def sign_rsa_sha1(base_string, rsa_private_key): + """ + Deprecated function for calculating a RSA-SHA1 signature. + + This function has been replaced by invoking ``sign_rsa`` with "SHA-1" + as the hash algorithm name. + + This function was invoked by sign_rsa_sha1_with_client and + test_signatures.py, but does any application invoke it directly? If not, + it can be removed. + """ + warnings.warn('use _sign_rsa("SHA-1", ...) instead of sign_rsa_sha1', + DeprecationWarning) + + if isinstance(base_string, bytes): + base_string = base_string.decode('ascii') + + return _sign_rsa('SHA-1', base_string, rsa_private_key) + + +# ==== RSA-SHA256 ================================================ + +def sign_rsa_sha256_with_client(sig_base_str: str, client): + return _sign_rsa('SHA-256', sig_base_str, client.rsa_key) + + +def verify_rsa_sha256(request, rsa_public_key: str): + return _verify_rsa('SHA-256', request, rsa_public_key) + + +# ==== RSA-SHA512 ================================================ + +def sign_rsa_sha512_with_client(sig_base_str: str, client): + return _sign_rsa('SHA-512', sig_base_str, client.rsa_key) + + +def verify_rsa_sha512(request, rsa_public_key: str): + return _verify_rsa('SHA-512', request, rsa_public_key) + + +# ==== PLAINTEXT ================================================= + +def sign_plaintext_with_client(_signature_base_string, client): + # _signature_base_string is not used because the signature with PLAINTEXT + # is just the secret: it isn't a real signature. + return sign_plaintext(client.client_secret, client.resource_owner_secret) + + +def sign_plaintext(client_secret, resource_owner_secret): + """Sign a request using plaintext. + + Per `section 3.4.4`_ of the spec. + + The "PLAINTEXT" method does not employ a signature algorithm. It + MUST be used with a transport-layer mechanism such as TLS or SSL (or + sent over a secure channel with equivalent protections). It does not + utilize the signature base string or the "oauth_timestamp" and + "oauth_nonce" parameters. + + .. _`section 3.4.4`: https://tools.ietf.org/html/rfc5849#section-3.4.4 + + """ + + # The "oauth_signature" protocol parameter is set to the concatenated + # value of: + + # 1. The client shared-secret, after being encoded (`Section 3.6`_). + # + # .. _`Section 3.6`: https://tools.ietf.org/html/rfc5849#section-3.6 + signature = utils.escape(client_secret or '') + + # 2. An "&" character (ASCII code 38), which MUST be included even + # when either secret is empty. + signature += '&' + + # 3. The token shared-secret, after being encoded (`Section 3.6`_). + # + # .. _`Section 3.6`: https://tools.ietf.org/html/rfc5849#section-3.6 + signature += utils.escape(resource_owner_secret or '') + + return signature + + +def verify_plaintext(request, client_secret=None, resource_owner_secret=None): + """Verify a PLAINTEXT signature. + + Per `section 3.4`_ of the spec. + + .. _`section 3.4`: https://tools.ietf.org/html/rfc5849#section-3.4 + """ + signature = sign_plaintext(client_secret, resource_owner_secret) + match = safe_string_equals(signature, request.signature) + if not match: + log.debug('Verify PLAINTEXT failed') + return match diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/utils.py b/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..0915105bcbd0a0d392c68ff84ee0d1cdf80119ca --- /dev/null +++ b/python/user_packages/Python313/site-packages/oauthlib/oauth1/rfc5849/utils.py @@ -0,0 +1,84 @@ +""" +oauthlib.utils +~~~~~~~~~~~~~~ + +This module contains utility methods used by various parts of the OAuth +spec. +""" +import urllib.request as urllib2 + +from oauthlib.common import quote, unquote + +UNICODE_ASCII_CHARACTER_SET = ('abcdefghijklmnopqrstuvwxyz' + 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + '0123456789') + + +def filter_params(target): + """Decorator which filters params to remove non-oauth_* parameters + + Assumes the decorated method takes a params dict or list of tuples as its + first argument. + """ + def wrapper(params, *args, **kwargs): + params = filter_oauth_params(params) + return target(params, *args, **kwargs) + + wrapper.__doc__ = target.__doc__ + return wrapper + + +def filter_oauth_params(params): + """Removes all non oauth parameters from a dict or a list of params.""" + def is_oauth(kv): + return kv[0].startswith('oauth_') + if isinstance(params, dict): + return list(filter(is_oauth, list(params.items()))) + else: + return list(filter(is_oauth, params)) + + +def escape(u): + """Escape a unicode string in an OAuth-compatible fashion. + + Per `section 3.6`_ of the spec. + + .. _`section 3.6`: https://tools.ietf.org/html/rfc5849#section-3.6 + + """ + if not isinstance(u, str): + raise ValueError('Only unicode objects are escapable. ' + + 'Got {!r} of type {}.'.format(u, type(u))) + # Letters, digits, and the characters '_.-' are already treated as safe + # by urllib.quote(). We need to add '~' to fully support rfc5849. + return quote(u, safe=b'~') + + +def unescape(u): + if not isinstance(u, str): + raise ValueError('Only unicode objects are unescapable.') + return unquote(u) + + +def parse_keqv_list(l): # noqa: E741 + """A unicode-safe version of urllib2.parse_keqv_list""" + # With Python 2.6, parse_http_list handles unicode fine + return urllib2.parse_keqv_list(l) + + +def parse_http_list(u): + """A unicode-safe version of urllib2.parse_http_list""" + # With Python 2.6, parse_http_list handles unicode fine + return urllib2.parse_http_list(u) + + +def parse_authorization_header(authorization_header): + """Parse an OAuth authorization header into a list of 2-tuples""" + auth_scheme = 'OAuth '.lower() + if authorization_header[:len(auth_scheme)].lower().startswith(auth_scheme): + items = parse_http_list(authorization_header[len(auth_scheme):]) + try: + return list(parse_keqv_list(items).items()) + except (IndexError, ValueError): + pass + raise ValueError('Malformed authorization header') diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth2/__init__.py b/python/user_packages/Python313/site-packages/oauthlib/oauth2/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3bb51021741f2a0acc423c4a61b3061814ce7b32 --- /dev/null +++ b/python/user_packages/Python313/site-packages/oauthlib/oauth2/__init__.py @@ -0,0 +1,70 @@ +""" +oauthlib.oauth2 +~~~~~~~~~~~~~~ + +This module is a wrapper for the most recent implementation of OAuth 2.0 Client +and Server classes. +""" + +from .rfc6749.clients import ( + BackendApplicationClient, + Client, + LegacyApplicationClient, + MobileApplicationClient, + ServiceApplicationClient, + WebApplicationClient, +) +from .rfc6749.endpoints import ( + AuthorizationEndpoint, + BackendApplicationServer, + IntrospectEndpoint, + LegacyApplicationServer, + MetadataEndpoint, + MobileApplicationServer, + ResourceEndpoint, + RevocationEndpoint, + Server, + TokenEndpoint, + WebApplicationServer, +) +from .rfc6749.errors import ( + AccessDeniedError, + FatalClientError, + InsecureTransportError, + InvalidClientError, + InvalidClientIdError, + InvalidGrantError, + InvalidRedirectURIError, + InvalidRequestError, + InvalidRequestFatalError, + InvalidScopeError, + MismatchingRedirectURIError, + MismatchingStateError, + MissingClientIdError, + MissingCodeError, + MissingRedirectURIError, + MissingResponseTypeError, + MissingTokenError, + MissingTokenTypeError, + OAuth2Error, + ServerError, + TemporarilyUnavailableError, + TokenExpiredError, + UnauthorizedClientError, + UnsupportedGrantTypeError, + UnsupportedResponseTypeError, + UnsupportedTokenTypeError, +) +from .rfc6749.grant_types import ( + AuthorizationCodeGrant, + ClientCredentialsGrant, + ImplicitGrant, + RefreshTokenGrant, + ResourceOwnerPasswordCredentialsGrant, +) +from .rfc6749.request_validator import RequestValidator +from .rfc6749.tokens import BearerToken, OAuth2Token +from .rfc6749.utils import is_secure_transport +from .rfc8628.clients import DeviceClient +from oauthlib.oauth2.rfc8628.endpoints import DeviceAuthorizationEndpoint, DeviceApplicationServer +from oauthlib.oauth2.rfc8628.grant_types import DeviceCodeGrant diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth2/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/oauthlib/oauth2/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f89a94469db7802b8da1609809539d19a8347955 Binary files /dev/null and b/python/user_packages/Python313/site-packages/oauthlib/oauth2/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/__init__.py b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4b75a8a196c6d9e3ff0815c97a7feccf95d9fcd9 --- /dev/null +++ b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/__init__.py @@ -0,0 +1,16 @@ +""" +oauthlib.oauth2.rfc6749 +~~~~~~~~~~~~~~~~~~~~~~~ + +This module is an implementation of various logic needed +for consuming and providing OAuth 2.0 RFC6749. +""" +import functools +import logging + +from .endpoints.base import BaseEndpoint, catch_errors_and_unavailability +from .errors import ( + FatalClientError, OAuth2Error, ServerError, TemporarilyUnavailableError, +) + +log = logging.getLogger(__name__) diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e3266bd86494294790621fde6bd20718030f0d67 Binary files /dev/null and b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/__pycache__/errors.cpython-313.pyc b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/__pycache__/errors.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9b673e67169f3f1ce8e73c73ec866e3d67b310ae Binary files /dev/null and b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/__pycache__/errors.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/__pycache__/parameters.cpython-313.pyc b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/__pycache__/parameters.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0eca6c1c4f691d00083b5a6e0b35598926a92444 Binary files /dev/null and b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/__pycache__/parameters.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/__pycache__/request_validator.cpython-313.pyc b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/__pycache__/request_validator.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..30765e86e81032196afa455ec350f51222da9f74 Binary files /dev/null and b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/__pycache__/request_validator.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/__pycache__/tokens.cpython-313.pyc b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/__pycache__/tokens.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d423725b7755df29c1891683c84f8478cf626d98 Binary files /dev/null and b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/__pycache__/tokens.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/__pycache__/utils.cpython-313.pyc b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/__pycache__/utils.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..776ae0fac31fb44d791cb058b93a0124f6812b84 Binary files /dev/null and b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/__pycache__/utils.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/clients/__init__.py b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/clients/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8fc6c955a24dfecd3181f2a2e876fb587299266e --- /dev/null +++ b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/clients/__init__.py @@ -0,0 +1,14 @@ +# -*- coding: utf-8 -*- +""" +oauthlib.oauth2.rfc6749 +~~~~~~~~~~~~~~~~~~~~~~~ + +This module is an implementation of various logic needed +for consuming OAuth 2.0 RFC6749. +""" +from .backend_application import BackendApplicationClient +from .base import AUTH_HEADER, BODY, URI_QUERY, Client +from .legacy_application import LegacyApplicationClient +from .mobile_application import MobileApplicationClient +from .service_application import ServiceApplicationClient +from .web_application import WebApplicationClient diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/clients/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/clients/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2633bf8a38c6fe273209932333676bc65e08490f Binary files /dev/null and b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/clients/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/clients/__pycache__/backend_application.cpython-313.pyc b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/clients/__pycache__/backend_application.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ad17977de204f4e4c74e36efa194811c083dce35 Binary files /dev/null and b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/clients/__pycache__/backend_application.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/clients/__pycache__/base.cpython-313.pyc b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/clients/__pycache__/base.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..57136e2ae5c5bd8688ef46516483dc3d396d35af Binary files /dev/null and b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/clients/__pycache__/base.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/clients/__pycache__/legacy_application.cpython-313.pyc b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/clients/__pycache__/legacy_application.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f9fef69de47da78639b2ada8012cc0b1012f61c1 Binary files /dev/null and b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/clients/__pycache__/legacy_application.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/clients/__pycache__/mobile_application.cpython-313.pyc b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/clients/__pycache__/mobile_application.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5af28cff60bbfaa0340e0c874023e6a2834e95b6 Binary files /dev/null and b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/clients/__pycache__/mobile_application.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/clients/__pycache__/service_application.cpython-313.pyc b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/clients/__pycache__/service_application.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c862b9c5a1b561c5733045cba8afd68b8f6fd3e6 Binary files /dev/null and b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/clients/__pycache__/service_application.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/clients/__pycache__/web_application.cpython-313.pyc b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/clients/__pycache__/web_application.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9e0184a41f6b39c4e782b47bcc8d415f4f7b85cf Binary files /dev/null and b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/clients/__pycache__/web_application.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/clients/backend_application.py b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/clients/backend_application.py new file mode 100644 index 0000000000000000000000000000000000000000..e11e8fae380fc88784c0d429488b67aac3447dd3 --- /dev/null +++ b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/clients/backend_application.py @@ -0,0 +1,74 @@ +# -*- coding: utf-8 -*- +""" +oauthlib.oauth2.rfc6749 +~~~~~~~~~~~~~~~~~~~~~~~ + +This module is an implementation of various logic needed +for consuming and providing OAuth 2.0 RFC6749. +""" +from ..parameters import prepare_token_request +from .base import Client + + +class BackendApplicationClient(Client): + + """A public client utilizing the client credentials grant workflow. + + The client can request an access token using only its client + credentials (or other supported means of authentication) when the + client is requesting access to the protected resources under its + control, or those of another resource owner which has been previously + arranged with the authorization server (the method of which is beyond + the scope of this specification). + + The client credentials grant type MUST only be used by confidential + clients. + + Since the client authentication is used as the authorization grant, + no additional authorization request is needed. + """ + + grant_type = 'client_credentials' + + def prepare_request_body(self, body='', scope=None, + include_client_id=False, **kwargs): + """Add the client credentials to the request body. + + The client makes a request to the token endpoint by adding the + following parameters using the "application/x-www-form-urlencoded" + format per `Appendix B`_ in the HTTP request entity-body: + + :param body: Existing request body (URL encoded string) to embed parameters + into. This may contain extra parameters. Default ''. + :param scope: The scope of the access request as described by + `Section 3.3`_. + + :param include_client_id: `True` to send the `client_id` in the + body of the upstream request. This is required + if the client is not authenticating with the + authorization server as described in + `Section 3.2.1`_. False otherwise (default). + :type include_client_id: Boolean + + :param kwargs: Extra credentials to include in the token request. + + The client MUST authenticate with the authorization server as + described in `Section 3.2.1`_. + + The prepared body will include all provided credentials as well as + the ``grant_type`` parameter set to ``client_credentials``:: + + >>> from oauthlib.oauth2 import BackendApplicationClient + >>> client = BackendApplicationClient('your_id') + >>> client.prepare_request_body(scope=['hello', 'world']) + 'grant_type=client_credentials&scope=hello+world' + + .. _`Appendix B`: https://tools.ietf.org/html/rfc6749#appendix-B + .. _`Section 3.3`: https://tools.ietf.org/html/rfc6749#section-3.3 + .. _`Section 3.2.1`: https://tools.ietf.org/html/rfc6749#section-3.2.1 + """ + kwargs['client_id'] = self.client_id + kwargs['include_client_id'] = include_client_id + scope = self.scope if scope is None else scope + return prepare_token_request(self.grant_type, body=body, + scope=scope, **kwargs) diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/clients/base.py b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/clients/base.py new file mode 100644 index 0000000000000000000000000000000000000000..17f833d236cb0f1ca7a4dd85f661b2e6be6b087e --- /dev/null +++ b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/clients/base.py @@ -0,0 +1,597 @@ +# -*- coding: utf-8 -*- +""" +oauthlib.oauth2.rfc6749 +~~~~~~~~~~~~~~~~~~~~~~~ + +This module is an implementation of various logic needed +for consuming OAuth 2.0 RFC6749. +""" +import base64 +import hashlib +import time +import warnings + +from oauthlib.common import UNICODE_ASCII_CHARACTER_SET, generate_token +from oauthlib.oauth2.rfc6749 import tokens +from oauthlib.oauth2.rfc6749.errors import ( + InsecureTransportError, TokenExpiredError, +) +from oauthlib.oauth2.rfc6749.parameters import ( + parse_expires, + parse_token_response, prepare_token_request, + prepare_token_revocation_request, +) +from oauthlib.oauth2.rfc6749.utils import is_secure_transport + +AUTH_HEADER = 'auth_header' +URI_QUERY = 'query' +BODY = 'body' + +FORM_ENC_HEADERS = { + 'Content-Type': 'application/x-www-form-urlencoded' +} + + +class Client: + """Base OAuth2 client responsible for access token management. + + This class also acts as a generic interface providing methods common to all + client types such as ``prepare_authorization_request`` and + ``prepare_token_revocation_request``. The ``prepare_x_request`` methods are + the recommended way of interacting with clients (as opposed to the abstract + prepare uri/body/etc methods). They are recommended over the older set + because they are easier to use (more consistent) and add a few additional + security checks, such as HTTPS and state checking. + + Some of these methods require further implementation only provided by the + specific purpose clients such as + :py:class:`oauthlib.oauth2.MobileApplicationClient` and thus you should always + seek to use the client class matching the OAuth workflow you need. For + Python, this is usually :py:class:`oauthlib.oauth2.WebApplicationClient`. + + """ + refresh_token_key = 'refresh_token' + + def __init__(self, client_id, + default_token_placement=AUTH_HEADER, + token_type='Bearer', + access_token=None, + refresh_token=None, + mac_key=None, + mac_algorithm=None, + token=None, + scope=None, + state=None, + redirect_url=None, + state_generator=generate_token, + code_verifier=None, + code_challenge=None, + code_challenge_method=None, + **kwargs): + """Initialize a client with commonly used attributes. + + :param client_id: Client identifier given by the OAuth provider upon + registration. + + :param default_token_placement: Tokens can be supplied in the Authorization + header (default), the URL query component (``query``) or the request + body (``body``). + + :param token_type: OAuth 2 token type. Defaults to Bearer. Change this + if you specify the ``access_token`` parameter and know it is of a + different token type, such as a MAC, JWT or SAML token. Can + also be supplied as ``token_type`` inside the ``token`` dict parameter. + + :param access_token: An access token (string) used to authenticate + requests to protected resources. Can also be supplied inside the + ``token`` dict parameter. + + :param refresh_token: A refresh token (string) used to refresh expired + tokens. Can also be supplied inside the ``token`` dict parameter. + + :param mac_key: Encryption key used with MAC tokens. + + :param mac_algorithm: Hashing algorithm for MAC tokens. + + :param token: A dict of token attributes such as ``access_token``, + ``token_type`` and ``expires_at``. + + :param scope: A list of default scopes to request authorization for. + + :param state: A CSRF protection string used during authorization. + + :param redirect_url: The redirection endpoint on the client side to which + the user returns after authorization. + + :param state_generator: A no argument state generation callable. Defaults + to :py:meth:`oauthlib.common.generate_token`. + + :param code_verifier: PKCE parameter. A cryptographically random string that is used to correlate the + authorization request to the token request. + + :param code_challenge: PKCE parameter. A challenge derived from the code verifier that is sent in the + authorization request, to be verified against later. + + :param code_challenge_method: PKCE parameter. A method that was used to derive code challenge. + Defaults to "plain" if not present in the request. + """ + + self.client_id = client_id + self.default_token_placement = default_token_placement + self.token_type = token_type + self.access_token = access_token + self.refresh_token = refresh_token + self.mac_key = mac_key + self.mac_algorithm = mac_algorithm + self.token = token or {} + self.scope = scope + self.state_generator = state_generator + self.state = state + self.redirect_url = redirect_url + self.code_verifier = code_verifier + self.code_challenge = code_challenge + self.code_challenge_method = code_challenge_method + self.code = None + self.expires_in = None + self._expires_at = None + self.populate_token_attributes(self.token) + + @property + def token_types(self): + """Supported token types and their respective methods + + Additional tokens can be supported by extending this dictionary. + + The Bearer token spec is stable and safe to use. + + The MAC token spec is not yet stable and support for MAC tokens + is experimental and currently matching version 00 of the spec. + """ + return { + 'Bearer': self._add_bearer_token, + 'MAC': self._add_mac_token + } + + def prepare_request_uri(self, *args, **kwargs): + """Abstract method used to create request URIs.""" + raise NotImplementedError("Must be implemented by inheriting classes.") + + def prepare_request_body(self, *args, **kwargs): + """Abstract method used to create request bodies.""" + raise NotImplementedError("Must be implemented by inheriting classes.") + + def parse_request_uri_response(self, *args, **kwargs): + """Abstract method used to parse redirection responses.""" + raise NotImplementedError("Must be implemented by inheriting classes.") + + def add_token(self, uri, http_method='GET', body=None, headers=None, + token_placement=None, **kwargs): + """Add token to the request uri, body or authorization header. + + The access token type provides the client with the information + required to successfully utilize the access token to make a protected + resource request (along with type-specific attributes). The client + MUST NOT use an access token if it does not understand the token + type. + + For example, the "bearer" token type defined in + [`I-D.ietf-oauth-v2-bearer`_] is utilized by simply including the access + token string in the request: + + .. code-block:: http + + GET /resource/1 HTTP/1.1 + Host: example.com + Authorization: Bearer mF_9.B5f-4.1JqM + + while the "mac" token type defined in [`I-D.ietf-oauth-v2-http-mac`_] is + utilized by issuing a MAC key together with the access token which is + used to sign certain components of the HTTP requests: + + .. code-block:: http + + GET /resource/1 HTTP/1.1 + Host: example.com + Authorization: MAC id="h480djs93hd8", + nonce="274312:dj83hs9s", + mac="kDZvddkndxvhGRXZhvuDjEWhGeE=" + + .. _`I-D.ietf-oauth-v2-bearer`: https://tools.ietf.org/html/rfc6749#section-12.2 + .. _`I-D.ietf-oauth-v2-http-mac`: https://tools.ietf.org/html/rfc6749#section-12.2 + """ + if not is_secure_transport(uri): + raise InsecureTransportError() + + token_placement = token_placement or self.default_token_placement + + case_insensitive_token_types = { + k.lower(): v for k, v in self.token_types.items()} + if self.token_type.lower() not in case_insensitive_token_types: + raise ValueError("Unsupported token type: %s" % self.token_type) + + if not (self.access_token or self.token.get('access_token')): + raise ValueError("Missing access token.") + + if self._expires_at and self._expires_at < time.time(): + raise TokenExpiredError() + + return case_insensitive_token_types[self.token_type.lower()](uri, http_method, body, + headers, token_placement, **kwargs) + + def prepare_authorization_request(self, authorization_url, state=None, + redirect_url=None, scope=None, **kwargs): + """Prepare the authorization request. + + This is the first step in many OAuth flows in which the user is + redirected to a certain authorization URL. This method adds + required parameters to the authorization URL. + + :param authorization_url: Provider authorization endpoint URL. + :param state: CSRF protection string. Will be automatically created if + not provided. The generated state is available via the ``state`` + attribute. Clients should verify that the state is unchanged and + present in the authorization response. This verification is done + automatically if using the ``authorization_response`` parameter + with ``prepare_token_request``. + :param redirect_url: Redirect URL to which the user will be returned + after authorization. Must be provided unless previously setup with + the provider. If provided then it must also be provided in the + token request. + :param scope: List of scopes to request. Must be equal to + or a subset of the scopes granted when obtaining the refresh + token. If none is provided, the ones provided in the constructor are + used. + :param kwargs: Additional parameters to included in the request. + :returns: The prepared request tuple with (url, headers, body). + """ + if not is_secure_transport(authorization_url): + raise InsecureTransportError() + + self.state = state or self.state_generator() + self.redirect_url = redirect_url or self.redirect_url + # do not assign scope to self automatically anymore + scope = self.scope if scope is None else scope + auth_url = self.prepare_request_uri( + authorization_url, redirect_uri=self.redirect_url, + scope=scope, state=self.state, **kwargs) + return auth_url, FORM_ENC_HEADERS, '' + + def prepare_token_request(self, token_url, authorization_response=None, + redirect_url=None, state=None, body='', **kwargs): + """Prepare a token creation request. + + Note that these requests usually require client authentication, either + by including client_id or a set of provider specific authentication + credentials. + + :param token_url: Provider token creation endpoint URL. + :param authorization_response: The full redirection URL string, i.e. + the location to which the user was redirected after successful + authorization. Used to mine credentials needed to obtain a token + in this step, such as authorization code. + :param redirect_url: The redirect_url supplied with the authorization + request (if there was one). + :param state: + :param body: Existing request body (URL encoded string) to embed parameters + into. This may contain extra parameters. Default ''. + :param kwargs: Additional parameters to included in the request. + :returns: The prepared request tuple with (url, headers, body). + """ + if not is_secure_transport(token_url): + raise InsecureTransportError() + + state = state or self.state + if authorization_response: + self.parse_request_uri_response( + authorization_response, state=state) + self.redirect_url = redirect_url or self.redirect_url + body = self.prepare_request_body(body=body, + redirect_uri=self.redirect_url, **kwargs) + + return token_url, FORM_ENC_HEADERS, body + + def prepare_refresh_token_request(self, token_url, refresh_token=None, + body='', scope=None, **kwargs): + """Prepare an access token refresh request. + + Expired access tokens can be replaced by new access tokens without + going through the OAuth dance if the client obtained a refresh token. + This refresh token and authentication credentials can be used to + obtain a new access token, and possibly a new refresh token. + + :param token_url: Provider token refresh endpoint URL. + :param refresh_token: Refresh token string. + :param body: Existing request body (URL encoded string) to embed parameters + into. This may contain extra parameters. Default ''. + :param scope: List of scopes to request. Must be equal to + or a subset of the scopes granted when obtaining the refresh + token. If none is provided, the ones provided in the constructor are + used. + :param kwargs: Additional parameters to included in the request. + :returns: The prepared request tuple with (url, headers, body). + """ + if not is_secure_transport(token_url): + raise InsecureTransportError() + + # do not assign scope to self automatically anymore + scope = self.scope if scope is None else scope + body = self.prepare_refresh_body(body=body, + refresh_token=refresh_token, scope=scope, **kwargs) + return token_url, FORM_ENC_HEADERS, body + + def prepare_token_revocation_request(self, revocation_url, token, + token_type_hint="access_token", body='', callback=None, **kwargs): + """Prepare a token revocation request. + + :param revocation_url: Provider token revocation endpoint URL. + :param token: The access or refresh token to be revoked (string). + :param token_type_hint: ``"access_token"`` (default) or + ``"refresh_token"``. This is optional and if you wish to not pass it you + must provide ``token_type_hint=None``. + :param body: + :param callback: A jsonp callback such as ``package.callback`` to be invoked + upon receiving the response. Not that it should not include a () suffix. + :param kwargs: Additional parameters to included in the request. + :returns: The prepared request tuple with (url, headers, body). + + Note that JSONP request may use GET requests as the parameters will + be added to the request URL query as opposed to the request body. + + An example of a revocation request + + .. code-block:: http + + POST /revoke HTTP/1.1 + Host: server.example.com + Content-Type: application/x-www-form-urlencoded + Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW + + token=45ghiukldjahdnhzdauz&token_type_hint=refresh_token + + An example of a jsonp revocation request + + .. code-block:: http + + GET /revoke?token=agabcdefddddafdd&callback=package.myCallback HTTP/1.1 + Host: server.example.com + Content-Type: application/x-www-form-urlencoded + Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW + + and an error response + + .. code-block:: javascript + + package.myCallback({"error":"unsupported_token_type"}); + + Note that these requests usually require client credentials, client_id in + the case for public clients and provider specific authentication + credentials for confidential clients. + """ + if not is_secure_transport(revocation_url): + raise InsecureTransportError() + + return prepare_token_revocation_request(revocation_url, token, + token_type_hint=token_type_hint, body=body, callback=callback, + **kwargs) + + def parse_request_body_response(self, body, scope=None, **kwargs): + """Parse the JSON response body. + + If the access token request is valid and authorized, the + authorization server issues an access token as described in + `Section 5.1`_. A refresh token SHOULD NOT be included. If the request + failed client authentication or is invalid, the authorization server + returns an error response as described in `Section 5.2`_. + + :param body: The response body from the token request. + :param scope: Scopes originally requested. If none is provided, the ones + provided in the constructor are used. + :return: Dictionary of token parameters. + :raises: Warning if scope has changed. :py:class:`oauthlib.oauth2.errors.OAuth2Error` + if response is invalid. + + These response are json encoded and could easily be parsed without + the assistance of OAuthLib. However, there are a few subtle issues + to be aware of regarding the response which are helpfully addressed + through the raising of various errors. + + A successful response should always contain + + **access_token** + The access token issued by the authorization server. Often + a random string. + + **token_type** + The type of the token issued as described in `Section 7.1`_. + Commonly ``Bearer``. + + While it is not mandated it is recommended that the provider include + + **expires_in** + The lifetime in seconds of the access token. For + example, the value "3600" denotes that the access token will + expire in one hour from the time the response was generated. + If omitted, the authorization server SHOULD provide the + expiration time via other means or document the default value. + + **scope** + Providers may supply this in all responses but are required to only + if it has changed since the authorization request. + + .. _`Section 5.1`: https://tools.ietf.org/html/rfc6749#section-5.1 + .. _`Section 5.2`: https://tools.ietf.org/html/rfc6749#section-5.2 + .. _`Section 7.1`: https://tools.ietf.org/html/rfc6749#section-7.1 + """ + scope = self.scope if scope is None else scope + self.token = parse_token_response(body, scope=scope) + self.populate_token_attributes(self.token) + return self.token + + def prepare_refresh_body(self, body='', refresh_token=None, scope=None, **kwargs): + """Prepare an access token request, using a refresh token. + + If the authorization server issued a refresh token to the client, the + client makes a refresh request to the token endpoint by adding the + following parameters using the `application/x-www-form-urlencoded` + format in the HTTP request entity-body: + + :param refresh_token: REQUIRED. The refresh token issued to the client. + :param scope: OPTIONAL. The scope of the access request as described by + Section 3.3. The requested scope MUST NOT include any scope + not originally granted by the resource owner, and if omitted is + treated as equal to the scope originally granted by the + resource owner. Note that if none is provided, the ones provided + in the constructor are used if any. + """ + refresh_token = refresh_token or self.refresh_token + scope = self.scope if scope is None else scope + return prepare_token_request(self.refresh_token_key, body=body, scope=scope, + refresh_token=refresh_token, **kwargs) + + def _add_bearer_token(self, uri, http_method='GET', body=None, + headers=None, token_placement=None): + """Add a bearer token to the request uri, body or authorization header.""" + if token_placement == AUTH_HEADER: + headers = tokens.prepare_bearer_headers(self.access_token, headers) + + elif token_placement == URI_QUERY: + uri = tokens.prepare_bearer_uri(self.access_token, uri) + + elif token_placement == BODY: + body = tokens.prepare_bearer_body(self.access_token, body) + + else: + raise ValueError("Invalid token placement.") + return uri, headers, body + + def create_code_verifier(self, length): + """Create PKCE **code_verifier** used in computing **code_challenge**. + See `RFC7636 Section 4.1`_ + + :param length: REQUIRED. The length of the code_verifier. + + The client first creates a code verifier, "code_verifier", for each + OAuth 2.0 [RFC6749] Authorization Request, in the following manner: + + .. code-block:: text + + code_verifier = high-entropy cryptographic random STRING using the + unreserved characters [A-Z] / [a-z] / [0-9] / "-" / "." / "_" / "~" + from Section 2.3 of [RFC3986], with a minimum length of 43 characters + and a maximum length of 128 characters. + + .. _`RFC7636 Section 4.1`: https://tools.ietf.org/html/rfc7636#section-4.1 + """ + code_verifier = None + + if not length >= 43: + raise ValueError("Length must be greater than or equal to 43") + + if not length <= 128: + raise ValueError("Length must be less than or equal to 128") + + code_verifier = generate_token(length, UNICODE_ASCII_CHARACTER_SET + "-._~") + + self.code_verifier = code_verifier + + return code_verifier + + def create_code_challenge(self, code_verifier, code_challenge_method=None): + """Create PKCE **code_challenge** derived from the **code_verifier**. + See `RFC7636 Section 4.2`_ + + :param code_verifier: REQUIRED. The **code_verifier** generated from `create_code_verifier()`. + :param code_challenge_method: OPTIONAL. The method used to derive the **code_challenge**. Acceptable values include `S256`. DEFAULT is `plain`. + + The client then creates a code challenge derived from the code + verifier by using one of the following transformations on the code + verifier:: + + plain + code_challenge = code_verifier + S256 + code_challenge = BASE64URL-ENCODE(SHA256(ASCII(code_verifier))) + + If the client is capable of using `S256`, it MUST use `S256`, as + `S256` is Mandatory To Implement (MTI) on the server. Clients are + permitted to use `plain` only if they cannot support `S256` for some + technical reason and know via out-of-band configuration that the + server supports `plain`. + + The plain transformation is for compatibility with existing + deployments and for constrained environments that can't use the S256 transformation. + + .. _`RFC7636 Section 4.2`: https://tools.ietf.org/html/rfc7636#section-4.2 + """ + code_challenge = None + + if code_verifier is None: + raise ValueError("Invalid code_verifier") + + if code_challenge_method is None: + code_challenge_method = "plain" + self.code_challenge_method = code_challenge_method + code_challenge = code_verifier + self.code_challenge = code_challenge + + if code_challenge_method == "S256": + h = hashlib.sha256() + h.update(code_verifier.encode(encoding='ascii')) + sha256_val = h.digest() + code_challenge = bytes.decode(base64.urlsafe_b64encode(sha256_val)) + # replace '+' with '-', '/' with '_', and remove trailing '=' + code_challenge = code_challenge.replace("+", "-").replace("/", "_").replace("=", "") + self.code_challenge = code_challenge + + return code_challenge + + def _add_mac_token(self, uri, http_method='GET', body=None, + headers=None, token_placement=AUTH_HEADER, ext=None, **kwargs): + """Add a MAC token to the request authorization header. + + Warning: MAC token support is experimental as the spec is not yet stable. + """ + if token_placement != AUTH_HEADER: + raise ValueError("Invalid token placement.") + + headers = tokens.prepare_mac_header(self.access_token, uri, + self.mac_key, http_method, headers=headers, body=body, ext=ext, + hash_algorithm=self.mac_algorithm, **kwargs) + return uri, headers, body + + def _populate_attributes(self, response): + warnings.warn("Please switch to the public method " + "populate_token_attributes.", DeprecationWarning) + return self.populate_token_attributes(response) + + def populate_code_attributes(self, response): + """Add attributes from an auth code response to self.""" + + if 'code' in response: + self.code = response.get('code') + + def populate_token_attributes(self, response): + """Add attributes from a token exchange response to self.""" + + if 'access_token' in response: + self.access_token = response.get('access_token') + + if 'refresh_token' in response: + self.refresh_token = response.get('refresh_token') + + if 'token_type' in response: + self.token_type = response.get('token_type') + + vin, vat, v_at = parse_expires(response) + if vin: + self.expires_in = vin + if vat: + self.expires_at = vat + if v_at: + self._expires_at = v_at + + if 'mac_key' in response: + self.mac_key = response.get('mac_key') + + if 'mac_algorithm' in response: + self.mac_algorithm = response.get('mac_algorithm') diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/clients/legacy_application.py b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/clients/legacy_application.py new file mode 100644 index 0000000000000000000000000000000000000000..9920981d2c601761492ac1511c3ecd7a6a6a2e51 --- /dev/null +++ b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/clients/legacy_application.py @@ -0,0 +1,84 @@ +# -*- coding: utf-8 -*- +""" +oauthlib.oauth2.rfc6749 +~~~~~~~~~~~~~~~~~~~~~~~ + +This module is an implementation of various logic needed +for consuming and providing OAuth 2.0 RFC6749. +""" +from ..parameters import prepare_token_request +from .base import Client + + +class LegacyApplicationClient(Client): + + """A public client using the resource owner password and username directly. + + The resource owner password credentials grant type is suitable in + cases where the resource owner has a trust relationship with the + client, such as the device operating system or a highly privileged + application. The authorization server should take special care when + enabling this grant type, and only allow it when other flows are not + viable. + + The grant type is suitable for clients capable of obtaining the + resource owner's credentials (username and password, typically using + an interactive form). It is also used to migrate existing clients + using direct authentication schemes such as HTTP Basic or Digest + authentication to OAuth by converting the stored credentials to an + access token. + + The method through which the client obtains the resource owner + credentials is beyond the scope of this specification. The client + MUST discard the credentials once an access token has been obtained. + """ + + grant_type = 'password' + + def __init__(self, client_id, **kwargs): + super().__init__(client_id, **kwargs) + + def prepare_request_body(self, username, password, body='', scope=None, + include_client_id=False, **kwargs): + """Add the resource owner password and username to the request body. + + The client makes a request to the token endpoint by adding the + following parameters using the "application/x-www-form-urlencoded" + format per `Appendix B`_ in the HTTP request entity-body: + + :param username: The resource owner username. + :param password: The resource owner password. + :param body: Existing request body (URL encoded string) to embed parameters + into. This may contain extra parameters. Default ''. + :param scope: The scope of the access request as described by + `Section 3.3`_. + :param include_client_id: `True` to send the `client_id` in the + body of the upstream request. This is required + if the client is not authenticating with the + authorization server as described in + `Section 3.2.1`_. False otherwise (default). + :type include_client_id: Boolean + :param kwargs: Extra credentials to include in the token request. + + If the client type is confidential or the client was issued client + credentials (or assigned other authentication requirements), the + client MUST authenticate with the authorization server as described + in `Section 3.2.1`_. + + The prepared body will include all provided credentials as well as + the ``grant_type`` parameter set to ``password``:: + + >>> from oauthlib.oauth2 import LegacyApplicationClient + >>> client = LegacyApplicationClient('your_id') + >>> client.prepare_request_body(username='foo', password='bar', scope=['hello', 'world']) + 'grant_type=password&username=foo&scope=hello+world&password=bar' + + .. _`Appendix B`: https://tools.ietf.org/html/rfc6749#appendix-B + .. _`Section 3.3`: https://tools.ietf.org/html/rfc6749#section-3.3 + .. _`Section 3.2.1`: https://tools.ietf.org/html/rfc6749#section-3.2.1 + """ + kwargs['client_id'] = self.client_id + kwargs['include_client_id'] = include_client_id + scope = self.scope if scope is None else scope + return prepare_token_request(self.grant_type, body=body, username=username, + password=password, scope=scope, **kwargs) diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/clients/mobile_application.py b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/clients/mobile_application.py new file mode 100644 index 0000000000000000000000000000000000000000..023cf23623ba806446eec8716f34b62d06e00cff --- /dev/null +++ b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/clients/mobile_application.py @@ -0,0 +1,174 @@ +# -*- coding: utf-8 -*- +""" +oauthlib.oauth2.rfc6749 +~~~~~~~~~~~~~~~~~~~~~~~ + +This module is an implementation of various logic needed +for consuming and providing OAuth 2.0 RFC6749. +""" +from ..parameters import parse_implicit_response, prepare_grant_uri +from .base import Client + + +class MobileApplicationClient(Client): + + """A public client utilizing the implicit code grant workflow. + + A user-agent-based application is a public client in which the + client code is downloaded from a web server and executes within a + user-agent (e.g. web browser) on the device used by the resource + owner. Protocol data and credentials are easily accessible (and + often visible) to the resource owner. Since such applications + reside within the user-agent, they can make seamless use of the + user-agent capabilities when requesting authorization. + + The implicit grant type is used to obtain access tokens (it does not + support the issuance of refresh tokens) and is optimized for public + clients known to operate a particular redirection URI. These clients + are typically implemented in a browser using a scripting language + such as JavaScript. + + As a redirection-based flow, the client must be capable of + interacting with the resource owner's user-agent (typically a web + browser) and capable of receiving incoming requests (via redirection) + from the authorization server. + + Unlike the authorization code grant type in which the client makes + separate requests for authorization and access token, the client + receives the access token as the result of the authorization request. + + The implicit grant type does not include client authentication, and + relies on the presence of the resource owner and the registration of + the redirection URI. Because the access token is encoded into the + redirection URI, it may be exposed to the resource owner and other + applications residing on the same device. + """ + + response_type = 'token' + + def prepare_request_uri(self, uri, redirect_uri=None, scope=None, + state=None, **kwargs): + """Prepare the implicit grant request URI. + + The client constructs the request URI by adding the following + parameters to the query component of the authorization endpoint URI + using the "application/x-www-form-urlencoded" format, per `Appendix B`_: + + :param redirect_uri: OPTIONAL. The redirect URI must be an absolute URI + and it should have been registered with the OAuth + provider prior to use. As described in `Section 3.1.2`_. + + :param scope: OPTIONAL. The scope of the access request as described by + Section 3.3`_. These may be any string but are commonly + URIs or various categories such as ``videos`` or ``documents``. + + :param state: RECOMMENDED. An opaque value used by the client to maintain + state between the request and callback. The authorization + server includes this value when redirecting the user-agent back + to the client. The parameter SHOULD be used for preventing + cross-site request forgery as described in `Section 10.12`_. + + :param kwargs: Extra arguments to include in the request URI. + + In addition to supplied parameters, OAuthLib will append the ``client_id`` + that was provided in the constructor as well as the mandatory ``response_type`` + argument, set to ``token``:: + + >>> from oauthlib.oauth2 import MobileApplicationClient + >>> client = MobileApplicationClient('your_id') + >>> client.prepare_request_uri('https://example.com') + 'https://example.com?client_id=your_id&response_type=token' + >>> client.prepare_request_uri('https://example.com', redirect_uri='https://a.b/callback') + 'https://example.com?client_id=your_id&response_type=token&redirect_uri=https%3A%2F%2Fa.b%2Fcallback' + >>> client.prepare_request_uri('https://example.com', scope=['profile', 'pictures']) + 'https://example.com?client_id=your_id&response_type=token&scope=profile+pictures' + >>> client.prepare_request_uri('https://example.com', foo='bar') + 'https://example.com?client_id=your_id&response_type=token&foo=bar' + + .. _`Appendix B`: https://tools.ietf.org/html/rfc6749#appendix-B + .. _`Section 2.2`: https://tools.ietf.org/html/rfc6749#section-2.2 + .. _`Section 3.1.2`: https://tools.ietf.org/html/rfc6749#section-3.1.2 + .. _`Section 3.3`: https://tools.ietf.org/html/rfc6749#section-3.3 + .. _`Section 10.12`: https://tools.ietf.org/html/rfc6749#section-10.12 + """ + scope = self.scope if scope is None else scope + return prepare_grant_uri(uri, self.client_id, self.response_type, + redirect_uri=redirect_uri, state=state, scope=scope, **kwargs) + + def parse_request_uri_response(self, uri, state=None, scope=None): + """Parse the response URI fragment. + + If the resource owner grants the access request, the authorization + server issues an access token and delivers it to the client by adding + the following parameters to the fragment component of the redirection + URI using the "application/x-www-form-urlencoded" format: + + :param uri: The callback URI that resulted from the user being redirected + back from the provider to you, the client. + :param state: The state provided in the authorization request. + :param scope: The scopes provided in the authorization request. + :return: Dictionary of token parameters. + :raises: OAuth2Error if response is invalid. + + A successful response should always contain + + **access_token** + The access token issued by the authorization server. Often + a random string. + + **token_type** + The type of the token issued as described in `Section 7.1`_. + Commonly ``Bearer``. + + **state** + If you provided the state parameter in the authorization phase, then + the provider is required to include that exact state value in the + response. + + While it is not mandated it is recommended that the provider include + + **expires_in** + The lifetime in seconds of the access token. For + example, the value "3600" denotes that the access token will + expire in one hour from the time the response was generated. + If omitted, the authorization server SHOULD provide the + expiration time via other means or document the default value. + + **scope** + Providers may supply this in all responses but are required to only + if it has changed since the authorization request. + + A few example responses can be seen below:: + + >>> response_uri = 'https://example.com/callback#access_token=sdlfkj452&state=ss345asyht&token_type=Bearer&scope=hello+world' + >>> from oauthlib.oauth2 import MobileApplicationClient + >>> client = MobileApplicationClient('your_id') + >>> client.parse_request_uri_response(response_uri) + { + 'access_token': 'sdlfkj452', + 'token_type': 'Bearer', + 'state': 'ss345asyht', + 'scope': [u'hello', u'world'] + } + >>> client.parse_request_uri_response(response_uri, state='other') + Traceback (most recent call last): + File "", line 1, in + File "oauthlib/oauth2/rfc6749/__init__.py", line 598, in parse_request_uri_response + **scope** + File "oauthlib/oauth2/rfc6749/parameters.py", line 197, in parse_implicit_response + raise ValueError("Mismatching or missing state in params.") + ValueError: Mismatching or missing state in params. + >>> def alert_scope_changed(message, old, new): + ... print(message, old, new) + ... + >>> oauthlib.signals.scope_changed.connect(alert_scope_changed) + >>> client.parse_request_body_response(response_body, scope=['other']) + ('Scope has changed from "other" to "hello world".', ['other'], ['hello', 'world']) + + .. _`Section 7.1`: https://tools.ietf.org/html/rfc6749#section-7.1 + .. _`Section 3.3`: https://tools.ietf.org/html/rfc6749#section-3.3 + """ + scope = self.scope if scope is None else scope + self.token = parse_implicit_response(uri, state=state, scope=scope) + self.populate_token_attributes(self.token) + return self.token diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/clients/service_application.py b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/clients/service_application.py new file mode 100644 index 0000000000000000000000000000000000000000..abf22d2d8e8dd52a921bda529341ba01ee59249b --- /dev/null +++ b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/clients/service_application.py @@ -0,0 +1,189 @@ +# -*- coding: utf-8 -*- +""" +oauthlib.oauth2.rfc6749 +~~~~~~~~~~~~~~~~~~~~~~~ + +This module is an implementation of various logic needed +for consuming and providing OAuth 2.0 RFC6749. +""" +import time + +from oauthlib.common import to_unicode + +from ..parameters import prepare_token_request +from .base import Client + + +class ServiceApplicationClient(Client): + """A public client utilizing the JWT bearer grant. + + JWT bearer tokes can be used to request an access token when a client + wishes to utilize an existing trust relationship, expressed through the + semantics of (and digital signature or keyed message digest calculated + over) the JWT, without a direct user approval step at the authorization + server. + + This grant type does not involve an authorization step. It may be + used by both public and confidential clients. + """ + + grant_type = 'urn:ietf:params:oauth:grant-type:jwt-bearer' + + def __init__(self, client_id, private_key=None, subject=None, issuer=None, + audience=None, **kwargs): + """Initialize a JWT client with defaults for implicit use later. + + :param client_id: Client identifier given by the OAuth provider upon + registration. + + :param private_key: Private key used for signing and encrypting. + Must be given as a string. + + :param subject: The principal that is the subject of the JWT, i.e. + which user is the token requested on behalf of. + For example, ``foo@example.com. + + :param issuer: The JWT MUST contain an "iss" (issuer) claim that + contains a unique identifier for the entity that issued + the JWT. For example, ``your-client@provider.com``. + + :param audience: A value identifying the authorization server as an + intended audience, e.g. + ``https://provider.com/oauth2/token``. + + :param kwargs: Additional arguments to pass to base client, such as + state and token. See ``Client.__init__.__doc__`` for + details. + """ + super().__init__(client_id, **kwargs) + self.private_key = private_key + self.subject = subject + self.issuer = issuer + self.audience = audience + + def prepare_request_body(self, + private_key=None, + subject=None, + issuer=None, + audience=None, + expires_at=None, + issued_at=None, + extra_claims=None, + body='', + scope=None, + include_client_id=False, + **kwargs): + """Create and add a JWT assertion to the request body. + + :param private_key: Private key used for signing and encrypting. + Must be given as a string. + + :param subject: (sub) The principal that is the subject of the JWT, + i.e. which user is the token requested on behalf of. + For example, ``foo@example.com. + + :param issuer: (iss) The JWT MUST contain an "iss" (issuer) claim that + contains a unique identifier for the entity that issued + the JWT. For example, ``your-client@provider.com``. + + :param audience: (aud) A value identifying the authorization server as an + intended audience, e.g. + ``https://provider.com/oauth2/token``. + + :param expires_at: A unix expiration timestamp for the JWT. Defaults + to an hour from now, i.e. ``round(time.time()) + 3600``. + + :param issued_at: A unix timestamp of when the JWT was created. + Defaults to now, i.e. ``time.time()``. + + :param extra_claims: A dict of additional claims to include in the JWT. + + :param body: Existing request body (URL encoded string) to embed parameters + into. This may contain extra parameters. Default ''. + + :param scope: The scope of the access request. + + :param include_client_id: `True` to send the `client_id` in the + body of the upstream request. This is required + if the client is not authenticating with the + authorization server as described in + `Section 3.2.1`_. False otherwise (default). + :type include_client_id: Boolean + + :param not_before: A unix timestamp after which the JWT may be used. + Not included unless provided. * + + :param jwt_id: A unique JWT token identifier. Not included unless + provided. * + + :param kwargs: Extra credentials to include in the token request. + + Parameters marked with a `*` above are not explicit arguments in the + function signature, but are specially documented arguments for items + appearing in the generic `**kwargs` keyworded input. + + The "scope" parameter may be used, as defined in the Assertion + Framework for OAuth 2.0 Client Authentication and Authorization Grants + [I-D.ietf-oauth-assertions] specification, to indicate the requested + scope. + + Authentication of the client is optional, as described in + `Section 3.2.1`_ of OAuth 2.0 [RFC6749] and consequently, the + "client_id" is only needed when a form of client authentication that + relies on the parameter is used. + + The following non-normative example demonstrates an Access Token + Request with a JWT as an authorization grant (with extra line breaks + for display purposes only): + + .. code-block: http + + POST /token.oauth2 HTTP/1.1 + Host: as.example.com + Content-Type: application/x-www-form-urlencoded + + grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer + &assertion=eyJhbGciOiJFUzI1NiJ9. + eyJpc3Mi[...omitted for brevity...]. + J9l-ZhwP[...omitted for brevity...] + + .. _`Section 3.2.1`: https://tools.ietf.org/html/rfc6749#section-3.2.1 + """ + import jwt # noqa: PLC0415 + + key = private_key or self.private_key + if not key: + raise ValueError('An encryption key must be supplied to make JWT' + ' token requests.') + claim = { + 'iss': issuer or self.issuer, + 'aud': audience or self.audience, + 'sub': subject or self.subject, + 'exp': int(expires_at or time.time() + 3600), + 'iat': int(issued_at or time.time()), + } + + for attr in ('iss', 'aud', 'sub'): + if claim[attr] is None: + raise ValueError( + 'Claim must include %s but none was given.' % attr) + + if 'not_before' in kwargs: + claim['nbf'] = kwargs.pop('not_before') + + if 'jwt_id' in kwargs: + claim['jti'] = kwargs.pop('jwt_id') + + claim.update(extra_claims or {}) + + assertion = jwt.encode(claim, key, 'RS256') + assertion = to_unicode(assertion) + + kwargs['client_id'] = self.client_id + kwargs['include_client_id'] = include_client_id + scope = self.scope if scope is None else scope + return prepare_token_request(self.grant_type, + body=body, + assertion=assertion, + scope=scope, + **kwargs) diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/clients/web_application.py b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/clients/web_application.py new file mode 100644 index 0000000000000000000000000000000000000000..3bf94c4b51b30c85a94edf261394ddfce5bce2a5 --- /dev/null +++ b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/clients/web_application.py @@ -0,0 +1,222 @@ +# -*- coding: utf-8 -*- +""" +oauthlib.oauth2.rfc6749 +~~~~~~~~~~~~~~~~~~~~~~~ + +This module is an implementation of various logic needed +for consuming and providing OAuth 2.0 RFC6749. +""" +import warnings + +from ..parameters import ( + parse_authorization_code_response, prepare_grant_uri, + prepare_token_request, +) +from .base import Client + + +class WebApplicationClient(Client): + + """A client utilizing the authorization code grant workflow. + + A web application is a confidential client running on a web + server. Resource owners access the client via an HTML user + interface rendered in a user-agent on the device used by the + resource owner. The client credentials as well as any access + token issued to the client are stored on the web server and are + not exposed to or accessible by the resource owner. + + The authorization code grant type is used to obtain both access + tokens and refresh tokens and is optimized for confidential clients. + As a redirection-based flow, the client must be capable of + interacting with the resource owner's user-agent (typically a web + browser) and capable of receiving incoming requests (via redirection) + from the authorization server. + """ + + grant_type = 'authorization_code' + + def __init__(self, client_id, code=None, **kwargs): + super().__init__(client_id, **kwargs) + self.code = code + + def prepare_request_uri(self, uri, redirect_uri=None, scope=None, + state=None, code_challenge=None, code_challenge_method='plain', **kwargs): + """Prepare the authorization code request URI + + The client constructs the request URI by adding the following + parameters to the query component of the authorization endpoint URI + using the "application/x-www-form-urlencoded" format, per `Appendix B`_: + + :param redirect_uri: OPTIONAL. The redirect URI must be an absolute URI + and it should have been registered with the OAuth + provider prior to use. As described in `Section 3.1.2`_. + + :param scope: OPTIONAL. The scope of the access request as described by + Section 3.3`_. These may be any string but are commonly + URIs or various categories such as ``videos`` or ``documents``. + + :param state: RECOMMENDED. An opaque value used by the client to maintain + state between the request and callback. The authorization + server includes this value when redirecting the user-agent back + to the client. The parameter SHOULD be used for preventing + cross-site request forgery as described in `Section 10.12`_. + + :param code_challenge: OPTIONAL. PKCE parameter. REQUIRED if PKCE is enforced. + A challenge derived from the code_verifier that is sent in the + authorization request, to be verified against later. + + :param code_challenge_method: OPTIONAL. PKCE parameter. A method that was used to derive code challenge. + Defaults to "plain" if not present in the request. + + :param kwargs: Extra arguments to include in the request URI. + + In addition to supplied parameters, OAuthLib will append the ``client_id`` + that was provided in the constructor as well as the mandatory ``response_type`` + argument, set to ``code``:: + + >>> from oauthlib.oauth2 import WebApplicationClient + >>> client = WebApplicationClient('your_id') + >>> client.prepare_request_uri('https://example.com') + 'https://example.com?client_id=your_id&response_type=code' + >>> client.prepare_request_uri('https://example.com', redirect_uri='https://a.b/callback') + 'https://example.com?client_id=your_id&response_type=code&redirect_uri=https%3A%2F%2Fa.b%2Fcallback' + >>> client.prepare_request_uri('https://example.com', scope=['profile', 'pictures']) + 'https://example.com?client_id=your_id&response_type=code&scope=profile+pictures' + >>> client.prepare_request_uri('https://example.com', code_challenge='kjasBS523KdkAILD2k78NdcJSk2k3KHG6') + 'https://example.com?client_id=your_id&response_type=code&code_challenge=kjasBS523KdkAILD2k78NdcJSk2k3KHG6' + >>> client.prepare_request_uri('https://example.com', code_challenge_method='S256') + 'https://example.com?client_id=your_id&response_type=code&code_challenge_method=S256' + >>> client.prepare_request_uri('https://example.com', foo='bar') + 'https://example.com?client_id=your_id&response_type=code&foo=bar' + + .. _`Appendix B`: https://tools.ietf.org/html/rfc6749#appendix-B + .. _`Section 2.2`: https://tools.ietf.org/html/rfc6749#section-2.2 + .. _`Section 3.1.2`: https://tools.ietf.org/html/rfc6749#section-3.1.2 + .. _`Section 3.3`: https://tools.ietf.org/html/rfc6749#section-3.3 + .. _`Section 10.12`: https://tools.ietf.org/html/rfc6749#section-10.12 + """ + scope = self.scope if scope is None else scope + return prepare_grant_uri(uri, self.client_id, 'code', + redirect_uri=redirect_uri, scope=scope, state=state, code_challenge=code_challenge, + code_challenge_method=code_challenge_method, **kwargs) + + def prepare_request_body(self, code=None, redirect_uri=None, body='', + include_client_id=True, code_verifier=None, **kwargs): + """Prepare the access token request body. + + The client makes a request to the token endpoint by adding the + following parameters using the "application/x-www-form-urlencoded" + format in the HTTP request entity-body: + + :param code: REQUIRED. The authorization code received from the + authorization server. + + :param redirect_uri: REQUIRED, if the "redirect_uri" parameter was included in the + authorization request as described in `Section 4.1.1`_, and their + values MUST be identical. + + :param body: Existing request body (URL encoded string) to embed parameters + into. This may contain extra parameters. Default ''. + + :param include_client_id: `True` (default) to send the `client_id` in the + body of the upstream request. This is required + if the client is not authenticating with the + authorization server as described in `Section 3.2.1`_. + :type include_client_id: Boolean + + :param code_verifier: OPTIONAL. A cryptographically random string that is used to correlate the + authorization request to the token request. + + :param kwargs: Extra parameters to include in the token request. + + In addition OAuthLib will add the ``grant_type`` parameter set to + ``authorization_code``. + + If the client type is confidential or the client was issued client + credentials (or assigned other authentication requirements), the + client MUST authenticate with the authorization server as described + in `Section 3.2.1`_:: + + >>> from oauthlib.oauth2 import WebApplicationClient + >>> client = WebApplicationClient('your_id') + >>> client.prepare_request_body(code='sh35ksdf09sf') + 'grant_type=authorization_code&code=sh35ksdf09sf' + >>> client.prepare_request_body(code_verifier='KB46DCKJ873NCGXK5GD682NHDKK34GR') + 'grant_type=authorization_code&code_verifier=KB46DCKJ873NCGXK5GD682NHDKK34GR' + >>> client.prepare_request_body(code='sh35ksdf09sf', foo='bar') + 'grant_type=authorization_code&code=sh35ksdf09sf&foo=bar' + + `Section 3.2.1` also states: + In the "authorization_code" "grant_type" request to the token + endpoint, an unauthenticated client MUST send its "client_id" to + prevent itself from inadvertently accepting a code intended for a + client with a different "client_id". This protects the client from + substitution of the authentication code. (It provides no additional + security for the protected resource.) + + .. _`Section 4.1.1`: https://tools.ietf.org/html/rfc6749#section-4.1.1 + .. _`Section 3.2.1`: https://tools.ietf.org/html/rfc6749#section-3.2.1 + """ + code = code or self.code + if 'client_id' in kwargs: + warnings.warn("`client_id` has been deprecated in favor of " + "`include_client_id`, a boolean value which will " + "include the already configured `self.client_id`.", + DeprecationWarning) + if kwargs['client_id'] != self.client_id: + raise ValueError("`client_id` was supplied as an argument, but " + "it does not match `self.client_id`") + + kwargs['client_id'] = self.client_id + kwargs['include_client_id'] = include_client_id + return prepare_token_request(self.grant_type, code=code, body=body, + redirect_uri=redirect_uri, code_verifier=code_verifier, **kwargs) + + def parse_request_uri_response(self, uri, state=None): + """Parse the URI query for code and state. + + If the resource owner grants the access request, the authorization + server issues an authorization code and delivers it to the client by + adding the following parameters to the query component of the + redirection URI using the "application/x-www-form-urlencoded" format: + + :param uri: The callback URI that resulted from the user being redirected + back from the provider to you, the client. + :param state: The state provided in the authorization request. + + **code** + The authorization code generated by the authorization server. + The authorization code MUST expire shortly after it is issued + to mitigate the risk of leaks. A maximum authorization code + lifetime of 10 minutes is RECOMMENDED. The client MUST NOT + use the authorization code more than once. If an authorization + code is used more than once, the authorization server MUST deny + the request and SHOULD revoke (when possible) all tokens + previously issued based on that authorization code. + The authorization code is bound to the client identifier and + redirection URI. + + **state** + If the "state" parameter was present in the authorization request. + + This method is mainly intended to enforce strict state checking with + the added benefit of easily extracting parameters from the URI:: + + >>> from oauthlib.oauth2 import WebApplicationClient + >>> client = WebApplicationClient('your_id') + >>> uri = 'https://example.com/callback?code=sdfkjh345&state=sfetw45' + >>> client.parse_request_uri_response(uri, state='sfetw45') + {'state': 'sfetw45', 'code': 'sdfkjh345'} + >>> client.parse_request_uri_response(uri, state='other') + Traceback (most recent call last): + File "", line 1, in + File "oauthlib/oauth2/rfc6749/__init__.py", line 357, in parse_request_uri_response + back from the provider to you, the client. + File "oauthlib/oauth2/rfc6749/parameters.py", line 153, in parse_authorization_code_response + raise MismatchingStateError() + oauthlib.oauth2.rfc6749.errors.MismatchingStateError + """ + response = parse_authorization_code_response(uri, state=state) + self.populate_code_attributes(response) + return response diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/endpoints/__init__.py b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/endpoints/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1695b41b663eded80893849ec0b4ecc6f69c0e5c --- /dev/null +++ b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/endpoints/__init__.py @@ -0,0 +1,17 @@ +""" +oauthlib.oauth2.rfc6749 +~~~~~~~~~~~~~~~~~~~~~~~ + +This module is an implementation of various logic needed +for consuming and providing OAuth 2.0 RFC6749. +""" +from .authorization import AuthorizationEndpoint +from .introspect import IntrospectEndpoint +from .metadata import MetadataEndpoint +from .pre_configured import ( + BackendApplicationServer, LegacyApplicationServer, MobileApplicationServer, + Server, WebApplicationServer, +) +from .resource import ResourceEndpoint +from .revocation import RevocationEndpoint +from .token import TokenEndpoint diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/endpoints/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/endpoints/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6bef1fcfa1da3cee221de071f8c402c402533f83 Binary files /dev/null and b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/endpoints/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/endpoints/__pycache__/authorization.cpython-313.pyc b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/endpoints/__pycache__/authorization.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1d2e358877045a089899741b6aa4d62b23e53759 Binary files /dev/null and b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/endpoints/__pycache__/authorization.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/endpoints/__pycache__/base.cpython-313.pyc b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/endpoints/__pycache__/base.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8fddfb9f819b02f3490b01de67358b4efcc20a02 Binary files /dev/null and b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/endpoints/__pycache__/base.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/endpoints/__pycache__/introspect.cpython-313.pyc b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/endpoints/__pycache__/introspect.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..312d4adc0f0731b47ae0434351d2ebedffde46ed Binary files /dev/null and b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/endpoints/__pycache__/introspect.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/endpoints/__pycache__/metadata.cpython-313.pyc b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/endpoints/__pycache__/metadata.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9898008c71ba5d3abf7b714f670680c6a4334798 Binary files /dev/null and b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/endpoints/__pycache__/metadata.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/endpoints/__pycache__/pre_configured.cpython-313.pyc b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/endpoints/__pycache__/pre_configured.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b9d209fc1a0fa5bcf1aaee8ccb2c028b677c9958 Binary files /dev/null and b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/endpoints/__pycache__/pre_configured.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/endpoints/__pycache__/resource.cpython-313.pyc b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/endpoints/__pycache__/resource.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..83bb5d696e72b42d2ab0f5d2b55c7701fd94f0ee Binary files /dev/null and b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/endpoints/__pycache__/resource.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/endpoints/__pycache__/revocation.cpython-313.pyc b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/endpoints/__pycache__/revocation.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..175f9eaa1c74bf1f90b35758eb970da1a8b62339 Binary files /dev/null and b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/endpoints/__pycache__/revocation.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/endpoints/__pycache__/token.cpython-313.pyc b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/endpoints/__pycache__/token.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2437d33305380539027ddbc3106418e80bfde9e4 Binary files /dev/null and b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/endpoints/__pycache__/token.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/endpoints/authorization.py b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/endpoints/authorization.py new file mode 100644 index 0000000000000000000000000000000000000000..71967865dce4a1d6cc344036a732f7bc008dbaeb --- /dev/null +++ b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/endpoints/authorization.py @@ -0,0 +1,114 @@ +""" +oauthlib.oauth2.rfc6749 +~~~~~~~~~~~~~~~~~~~~~~~ + +This module is an implementation of various logic needed +for consuming and providing OAuth 2.0 RFC6749. +""" +import logging + +from oauthlib.common import Request +from oauthlib.oauth2.rfc6749 import utils + +from .base import BaseEndpoint, catch_errors_and_unavailability + +log = logging.getLogger(__name__) + + +class AuthorizationEndpoint(BaseEndpoint): + + """Authorization endpoint - used by the client to obtain authorization + from the resource owner via user-agent redirection. + + The authorization endpoint is used to interact with the resource + owner and obtain an authorization grant. The authorization server + MUST first verify the identity of the resource owner. The way in + which the authorization server authenticates the resource owner (e.g. + username and password login, session cookies) is beyond the scope of + this specification. + + The endpoint URI MAY include an "application/x-www-form-urlencoded" + formatted (per `Appendix B`_) query component, + which MUST be retained when adding additional query parameters. The + endpoint URI MUST NOT include a fragment component:: + + https://example.com/path?query=component # OK + https://example.com/path?query=component#fragment # Not OK + + Since requests to the authorization endpoint result in user + authentication and the transmission of clear-text credentials (in the + HTTP response), the authorization server MUST require the use of TLS + as described in Section 1.6 when sending requests to the + authorization endpoint:: + + # We will deny any request which URI schema is not with https + + The authorization server MUST support the use of the HTTP "GET" + method [RFC2616] for the authorization endpoint, and MAY support the + use of the "POST" method as well:: + + # HTTP method is currently not enforced + + Parameters sent without a value MUST be treated as if they were + omitted from the request. The authorization server MUST ignore + unrecognized request parameters. Request and response parameters + MUST NOT be included more than once:: + + # Enforced through the design of oauthlib.common.Request + + .. _`Appendix B`: https://tools.ietf.org/html/rfc6749#appendix-B + """ + + def __init__(self, default_response_type, default_token_type, + response_types): + BaseEndpoint.__init__(self) + self._response_types = response_types + self._default_response_type = default_response_type + self._default_token_type = default_token_type + + @property + def response_types(self): + return self._response_types + + @property + def default_response_type(self): + return self._default_response_type + + @property + def default_response_type_handler(self): + return self.response_types.get(self.default_response_type) + + @property + def default_token_type(self): + return self._default_token_type + + @catch_errors_and_unavailability + def create_authorization_response(self, uri, http_method='GET', body=None, + headers=None, scopes=None, credentials=None): + """Extract response_type and route to the designated handler.""" + request = Request( + uri, http_method=http_method, body=body, headers=headers) + request.scopes = scopes + # TODO: decide whether this should be a required argument + request.user = None # TODO: explain this in docs + for k, v in (credentials or {}).items(): + setattr(request, k, v) + response_type_handler = self.response_types.get( + request.response_type, self.default_response_type_handler) + log.debug('Dispatching response_type %s request to %r.', + request.response_type, response_type_handler) + return response_type_handler.create_authorization_response( + request, self.default_token_type) + + @catch_errors_and_unavailability + def validate_authorization_request(self, uri, http_method='GET', body=None, + headers=None): + """Extract response_type and route to the designated handler.""" + request = Request( + uri, http_method=http_method, body=body, headers=headers) + + request.scopes = utils.scope_to_list(request.scope) + + response_type_handler = self.response_types.get( + request.response_type, self.default_response_type_handler) + return response_type_handler.validate_authorization_request(request) diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/endpoints/base.py b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/endpoints/base.py new file mode 100644 index 0000000000000000000000000000000000000000..987fac6a8fbd272ce98008e5e21d43fa7f9bcd67 --- /dev/null +++ b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/endpoints/base.py @@ -0,0 +1,113 @@ +""" +oauthlib.oauth2.rfc6749 +~~~~~~~~~~~~~~~~~~~~~~~ + +This module is an implementation of various logic needed +for consuming and providing OAuth 2.0 RFC6749. +""" +import functools +import logging + +from ..errors import ( + FatalClientError, InvalidClientError, InvalidRequestError, OAuth2Error, + ServerError, TemporarilyUnavailableError, UnsupportedTokenTypeError, +) + +log = logging.getLogger(__name__) + + +class BaseEndpoint: + + def __init__(self): + self._available = True + self._catch_errors = False + self._valid_request_methods = None + + @property + def valid_request_methods(self): + return self._valid_request_methods + + @valid_request_methods.setter + def valid_request_methods(self, valid_request_methods): + if valid_request_methods is not None: + valid_request_methods = [x.upper() for x in valid_request_methods] + self._valid_request_methods = valid_request_methods + + + @property + def available(self): + return self._available + + @available.setter + def available(self, available): + self._available = available + + @property + def catch_errors(self): + return self._catch_errors + + @catch_errors.setter + def catch_errors(self, catch_errors): + self._catch_errors = catch_errors + + def _raise_on_missing_token(self, request): + """Raise error on missing token.""" + if not request.token: + raise InvalidRequestError(request=request, + description='Missing token parameter.') + def _raise_on_invalid_client(self, request): + """Raise on failed client authentication.""" + if self.request_validator.client_authentication_required(request): + if not self.request_validator.authenticate_client(request): + log.debug('Client authentication failed, %r.', request) + raise InvalidClientError(request=request) + elif not self.request_validator.authenticate_client_id(request.client_id, request): + log.debug('Client authentication failed, %r.', request) + raise InvalidClientError(request=request) + + def _raise_on_unsupported_token(self, request): + """Raise on unsupported tokens.""" + if (request.token_type_hint and + request.token_type_hint in self.valid_token_types and + request.token_type_hint not in self.supported_token_types): + raise UnsupportedTokenTypeError(request=request) + + def _raise_on_bad_method(self, request): + if self.valid_request_methods is None: + raise ValueError('Configure "valid_request_methods" property first') + if request.http_method.upper() not in self.valid_request_methods: + raise InvalidRequestError(request=request, + description=('Unsupported request method %s' % request.http_method.upper())) + + def _raise_on_bad_post_request(self, request): + """Raise if invalid POST request received + """ + if request.http_method.upper() == 'POST': + query_params = request.uri_query or "" + if query_params: + raise InvalidRequestError(request=request, + description=('URL query parameters are not allowed')) + +def catch_errors_and_unavailability(f): + @functools.wraps(f) + def wrapper(endpoint, uri, *args, **kwargs): + if not endpoint.available: + e = TemporarilyUnavailableError() + log.info('Endpoint unavailable, ignoring request %s.' % uri) + return {}, e.json, 503 + + if endpoint.catch_errors: + try: + return f(endpoint, uri, *args, **kwargs) + except OAuth2Error: + raise + except FatalClientError: + raise + except Exception as e: + error = ServerError() + log.warning( + 'Exception caught while processing request, %s.' % e) + return {}, error.json, 500 + else: + return f(endpoint, uri, *args, **kwargs) + return wrapper diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/endpoints/introspect.py b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/endpoints/introspect.py new file mode 100644 index 0000000000000000000000000000000000000000..ef73988d48db03e7fc64d54e9fb6315f32923fde --- /dev/null +++ b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/endpoints/introspect.py @@ -0,0 +1,120 @@ +""" +oauthlib.oauth2.rfc6749.endpoint.introspect +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +An implementation of the OAuth 2.0 `Token Introspection`. + +.. _`Token Introspection`: https://tools.ietf.org/html/rfc7662 +""" +import json +import logging + +from oauthlib.common import Request + +from ..errors import OAuth2Error +from .base import BaseEndpoint, catch_errors_and_unavailability + +log = logging.getLogger(__name__) + + +class IntrospectEndpoint(BaseEndpoint): + + """Introspect token endpoint. + + This endpoint defines a method to query an OAuth 2.0 authorization + server to determine the active state of an OAuth 2.0 token and to + determine meta-information about this token. OAuth 2.0 deployments + can use this method to convey information about the authorization + context of the token from the authorization server to the protected + resource. + + To prevent the values of access tokens from leaking into + server-side logs via query parameters, an authorization server + offering token introspection MAY disallow the use of HTTP GET on + the introspection endpoint and instead require the HTTP POST method + to be used at the introspection endpoint. + """ + + valid_token_types = ('access_token', 'refresh_token') + valid_request_methods = ('POST',) + + def __init__(self, request_validator, supported_token_types=None): + BaseEndpoint.__init__(self) + self.request_validator = request_validator + self.supported_token_types = ( + supported_token_types or self.valid_token_types) + + @catch_errors_and_unavailability + def create_introspect_response(self, uri, http_method='POST', body=None, + headers=None): + """Create introspect valid or invalid response + + If the authorization server is unable to determine the state + of the token without additional information, it SHOULD return + an introspection response indicating the token is not active + as described in Section 2.2. + """ + resp_headers = { + 'Content-Type': 'application/json', + 'Cache-Control': 'no-store', + 'Pragma': 'no-cache', + } + request = Request(uri, http_method, body, headers) + try: + self.validate_introspect_request(request) + log.debug('Token introspect valid for %r.', request) + except OAuth2Error as e: + log.debug('Client error during validation of %r. %r.', request, e) + resp_headers.update(e.headers) + return resp_headers, e.json, e.status_code + + claims = self.request_validator.introspect_token( + request.token, + request.token_type_hint, + request + ) + if claims is None: + return resp_headers, json.dumps({'active': False}), 200 + if "active" in claims: + claims.pop("active") + return resp_headers, json.dumps(dict(active=True, **claims)), 200 + + def validate_introspect_request(self, request): + """Ensure the request is valid. + + The protected resource calls the introspection endpoint using + an HTTP POST request with parameters sent as + "application/x-www-form-urlencoded". + + * token REQUIRED. The string value of the token. + * token_type_hint OPTIONAL. + + A hint about the type of the token submitted for + introspection. The protected resource MAY pass this parameter to + help the authorization server optimize the token lookup. If the + server is unable to locate the token using the given hint, it MUST + extend its search across all of its supported token types. An + authorization server MAY ignore this parameter, particularly if it + is able to detect the token type automatically. + + * access_token: An Access Token as defined in [`RFC6749`], `section 1.4`_ + * refresh_token: A Refresh Token as defined in [`RFC6749`], `section 1.5`_ + + The introspection endpoint MAY accept other OPTIONAL + parameters to provide further context to the query. For + instance, an authorization server may desire to know the IP + address of the client accessing the protected resource to + determine if the correct client is likely to be presenting the + token. The definition of this or any other parameters are + outside the scope of this specification, to be defined by + service documentation or extensions to this specification. + + .. _`section 1.4`: http://tools.ietf.org/html/rfc6749#section-1.4 + .. _`section 1.5`: http://tools.ietf.org/html/rfc6749#section-1.5 + .. _`RFC6749`: http://tools.ietf.org/html/rfc6749 + """ + self._raise_on_bad_method(request) + self._raise_on_bad_post_request(request) + self._raise_on_missing_token(request) + self._raise_on_invalid_client(request) + self._raise_on_unsupported_token(request) diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/endpoints/metadata.py b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/endpoints/metadata.py new file mode 100644 index 0000000000000000000000000000000000000000..34274cba67baf4699d9c3f82ecc421a6af824d8e --- /dev/null +++ b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/endpoints/metadata.py @@ -0,0 +1,238 @@ +""" +oauthlib.oauth2.rfc6749.endpoint.metadata +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +An implementation of the `OAuth 2.0 Authorization Server Metadata`. + +.. _`OAuth 2.0 Authorization Server Metadata`: https://tools.ietf.org/html/rfc8414 +""" +import copy +import json +import logging + +from .. import grant_types, utils +from .authorization import AuthorizationEndpoint +from .base import BaseEndpoint, catch_errors_and_unavailability +from .introspect import IntrospectEndpoint +from .revocation import RevocationEndpoint +from .token import TokenEndpoint + +log = logging.getLogger(__name__) + + +class MetadataEndpoint(BaseEndpoint): + + """OAuth2.0 Authorization Server Metadata endpoint. + + This specification generalizes the metadata format defined by + `OpenID Connect Discovery 1.0` in a way that is compatible + with OpenID Connect Discovery while being applicable to a wider set + of OAuth 2.0 use cases. This is intentionally parallel to the way + that OAuth 2.0 Dynamic Client Registration Protocol [`RFC7591`_] + generalized the dynamic client registration mechanisms defined by + OpenID Connect Dynamic Client Registration 1.0 + in a way that is compatible with it. + + .. _`OpenID Connect Discovery 1.0`: https://openid.net/specs/openid-connect-discovery-1_0.html + .. _`RFC7591`: https://tools.ietf.org/html/rfc7591 + """ + + def __init__(self, endpoints, claims={}, raise_errors=True): + assert isinstance(claims, dict) # noqa: S101 + for endpoint in endpoints: + assert isinstance(endpoint, BaseEndpoint) # noqa: S101 + + BaseEndpoint.__init__(self) + self.raise_errors = raise_errors + self.endpoints = endpoints + self.initial_claims = claims + self.claims = self.validate_metadata_server() + + @catch_errors_and_unavailability + def create_metadata_response(self, uri, http_method='GET', body=None, + headers=None): + """Create metadata response + """ + headers = { + 'Content-Type': 'application/json', + 'Access-Control-Allow-Origin': '*', + } + return headers, json.dumps(self.claims), 200 + + def validate_metadata(self, array, key, is_required=False, is_list=False, is_url=False, is_issuer=False): + if not self.raise_errors: + return + + if key not in array: + if is_required: + raise ValueError("key {} is a mandatory metadata.".format(key)) + + elif is_issuer: + if not utils.is_secure_transport(array[key]): + raise ValueError("key {}: {} must be an HTTPS URL".format(key, array[key])) + if "?" in array[key] or "&" in array[key] or "#" in array[key]: + raise ValueError("key {}: {} must not contain query or fragment components".format(key, array[key])) + + elif is_url: + if not array[key].startswith("http"): + raise ValueError("key {}: {} must be an URL".format(key, array[key])) + + elif is_list: + if not isinstance(array[key], list): + raise ValueError("key {}: {} must be an Array".format(key, array[key])) + for elem in array[key]: + if not isinstance(elem, str): + raise ValueError("array {}: {} must contains only string (not {})".format(key, array[key], elem)) + + def validate_metadata_token(self, claims, endpoint): + """ + If the token endpoint is used in the grant type, the value of this + parameter MUST be the same as the value of the "grant_type" + parameter passed to the token endpoint defined in the grant type + definition. + """ + self._grant_types.extend(endpoint._grant_types.keys()) + claims.setdefault("token_endpoint_auth_methods_supported", ["client_secret_post", "client_secret_basic"]) + + self.validate_metadata(claims, "token_endpoint_auth_methods_supported", is_list=True) + self.validate_metadata(claims, "token_endpoint_auth_signing_alg_values_supported", is_list=True) + self.validate_metadata(claims, "token_endpoint", is_required=True, is_url=True) + + def validate_metadata_authorization(self, claims, endpoint): + claims.setdefault("response_types_supported", + list(filter(lambda x: x != "none", endpoint._response_types.keys()))) + claims.setdefault("response_modes_supported", ["query", "fragment"]) + + # The OAuth2.0 Implicit flow is defined as a "grant type" but it is not + # using the "token" endpoint, as such, we have to add it explicitly to + # the list of "grant_types_supported" when enabled. + if "token" in claims["response_types_supported"]: + self._grant_types.append("implicit") + + self.validate_metadata(claims, "response_types_supported", is_required=True, is_list=True) + self.validate_metadata(claims, "response_modes_supported", is_list=True) + if "code" in claims["response_types_supported"]: + code_grant = endpoint._response_types["code"] + if not isinstance(code_grant, grant_types.AuthorizationCodeGrant) and hasattr(code_grant, "default_grant"): + code_grant = code_grant.default_grant + + claims.setdefault("code_challenge_methods_supported", + list(code_grant._code_challenge_methods.keys())) + self.validate_metadata(claims, "code_challenge_methods_supported", is_list=True) + self.validate_metadata(claims, "authorization_endpoint", is_required=True, is_url=True) + + def validate_metadata_revocation(self, claims, endpoint): + claims.setdefault("revocation_endpoint_auth_methods_supported", + ["client_secret_post", "client_secret_basic"]) + + self.validate_metadata(claims, "revocation_endpoint_auth_methods_supported", is_list=True) + self.validate_metadata(claims, "revocation_endpoint_auth_signing_alg_values_supported", is_list=True) + self.validate_metadata(claims, "revocation_endpoint", is_required=True, is_url=True) + + def validate_metadata_introspection(self, claims, endpoint): + claims.setdefault("introspection_endpoint_auth_methods_supported", + ["client_secret_post", "client_secret_basic"]) + + self.validate_metadata(claims, "introspection_endpoint_auth_methods_supported", is_list=True) + self.validate_metadata(claims, "introspection_endpoint_auth_signing_alg_values_supported", is_list=True) + self.validate_metadata(claims, "introspection_endpoint", is_required=True, is_url=True) + + def validate_metadata_server(self): + """ + Authorization servers can have metadata describing their + configuration. The following authorization server metadata values + are used by this specification. More details can be found in + `RFC8414 section 2`_ : + + issuer + REQUIRED + + authorization_endpoint + URL of the authorization server's authorization endpoint + [`RFC6749#Authorization`_]. This is REQUIRED unless no grant types are supported + that use the authorization endpoint. + + token_endpoint + URL of the authorization server's token endpoint [`RFC6749#Token`_]. This + is REQUIRED unless only the implicit grant type is supported. + + scopes_supported + RECOMMENDED. + + response_types_supported + REQUIRED. + + Other OPTIONAL fields: + jwks_uri, + registration_endpoint, + response_modes_supported + + grant_types_supported + OPTIONAL. JSON array containing a list of the OAuth 2.0 grant + type values that this authorization server supports. The array + values used are the same as those used with the "grant_types" + parameter defined by "OAuth 2.0 Dynamic Client Registration + Protocol" [`RFC7591`_]. If omitted, the default value is + "["authorization_code", "implicit"]". + + token_endpoint_auth_methods_supported + + token_endpoint_auth_signing_alg_values_supported + + service_documentation + + ui_locales_supported + + op_policy_uri + + op_tos_uri + + revocation_endpoint + + revocation_endpoint_auth_methods_supported + + revocation_endpoint_auth_signing_alg_values_supported + + introspection_endpoint + + introspection_endpoint_auth_methods_supported + + introspection_endpoint_auth_signing_alg_values_supported + + code_challenge_methods_supported + + Additional authorization server metadata parameters MAY also be used. + Some are defined by other specifications, such as OpenID Connect + Discovery 1.0 [`OpenID.Discovery`_]. + + .. _`RFC8414 section 2`: https://tools.ietf.org/html/rfc8414#section-2 + .. _`RFC6749#Authorization`: https://tools.ietf.org/html/rfc6749#section-3.1 + .. _`RFC6749#Token`: https://tools.ietf.org/html/rfc6749#section-3.2 + .. _`RFC7591`: https://tools.ietf.org/html/rfc7591 + .. _`OpenID.Discovery`: https://openid.net/specs/openid-connect-discovery-1_0.html + """ + claims = copy.deepcopy(self.initial_claims) + self.validate_metadata(claims, "issuer", is_required=True, is_issuer=True) + self.validate_metadata(claims, "jwks_uri", is_url=True) + self.validate_metadata(claims, "scopes_supported", is_list=True) + self.validate_metadata(claims, "service_documentation", is_url=True) + self.validate_metadata(claims, "ui_locales_supported", is_list=True) + self.validate_metadata(claims, "op_policy_uri", is_url=True) + self.validate_metadata(claims, "op_tos_uri", is_url=True) + + self._grant_types = [] + for endpoint in self.endpoints: + if isinstance(endpoint, TokenEndpoint): + self.validate_metadata_token(claims, endpoint) + if isinstance(endpoint, AuthorizationEndpoint): + self.validate_metadata_authorization(claims, endpoint) + if isinstance(endpoint, RevocationEndpoint): + self.validate_metadata_revocation(claims, endpoint) + if isinstance(endpoint, IntrospectEndpoint): + self.validate_metadata_introspection(claims, endpoint) + + # "grant_types_supported" is a combination of all OAuth2 grant types + # allowed in the current provider implementation. + claims.setdefault("grant_types_supported", self._grant_types) + self.validate_metadata(claims, "grant_types_supported", is_list=True) + return claims diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/endpoints/pre_configured.py b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/endpoints/pre_configured.py new file mode 100644 index 0000000000000000000000000000000000000000..8f6aa32b7420c4447e0b7419276143955ead1e8a --- /dev/null +++ b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/endpoints/pre_configured.py @@ -0,0 +1,287 @@ +""" +oauthlib.oauth2.rfc6749.endpoints.pre_configured +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +This module is an implementation of various endpoints needed +for providing OAuth 2.0 RFC6749 servers. +""" + +from ..grant_types import ( + AuthorizationCodeGrant, + ClientCredentialsGrant, + ImplicitGrant, + RefreshTokenGrant, + ResourceOwnerPasswordCredentialsGrant, +) +from ..tokens import BearerToken +from .authorization import AuthorizationEndpoint +from .introspect import IntrospectEndpoint +from .resource import ResourceEndpoint +from .revocation import RevocationEndpoint +from .token import TokenEndpoint +from oauthlib.oauth2.rfc8628.grant_types import DeviceCodeGrant + + +class Server( + AuthorizationEndpoint, IntrospectEndpoint, TokenEndpoint, ResourceEndpoint, RevocationEndpoint +): + """ + An all-in-one endpoint featuring all four major grant types + and extension grants. + """ + + def __init__( + self, + request_validator, + token_expires_in=None, + token_generator=None, + refresh_token_generator=None, + *args, + **kwargs, + ): + """Construct a new all-grants-in-one server. + + :param request_validator: An implementation of + oauthlib.oauth2.RequestValidator. + :param token_expires_in: An int or a function to generate a token + expiration offset (in seconds) given a + oauthlib.common.Request object. + :param token_generator: A function to generate a token from a request. + :param refresh_token_generator: A function to generate a token from a + request for the refresh token. + :param kwargs: Extra parameters to pass to authorization-, + token-, resource-, and revocation-endpoint constructors. + """ + self.auth_grant = AuthorizationCodeGrant(request_validator) + self.implicit_grant = ImplicitGrant(request_validator) + self.password_grant = ResourceOwnerPasswordCredentialsGrant(request_validator) + self.credentials_grant = ClientCredentialsGrant(request_validator) + self.refresh_grant = RefreshTokenGrant(request_validator) + self.device_code_grant = DeviceCodeGrant(request_validator, **kwargs) + + self.bearer = BearerToken( + request_validator, token_generator, token_expires_in, refresh_token_generator + ) + + AuthorizationEndpoint.__init__( + self, + default_response_type="code", + response_types={ + "code": self.auth_grant, + "token": self.implicit_grant, + "none": self.auth_grant, + }, + default_token_type=self.bearer, + ) + + TokenEndpoint.__init__( + self, + default_grant_type="authorization_code", + grant_types={ + "authorization_code": self.auth_grant, + "password": self.password_grant, + "client_credentials": self.credentials_grant, + "refresh_token": self.refresh_grant, + "urn:ietf:params:oauth:grant-type:device_code": self.device_code_grant, + }, + default_token_type=self.bearer, + ) + ResourceEndpoint.__init__( + self, default_token="Bearer", token_types={"Bearer": self.bearer} + ) + RevocationEndpoint.__init__(self, request_validator) + IntrospectEndpoint.__init__(self, request_validator) + + +class WebApplicationServer( + AuthorizationEndpoint, IntrospectEndpoint, TokenEndpoint, ResourceEndpoint, RevocationEndpoint +): + """An all-in-one endpoint featuring Authorization code grant and Bearer tokens.""" + + def __init__( + self, + request_validator, + token_generator=None, + token_expires_in=None, + refresh_token_generator=None, + **kwargs, + ): + """Construct a new web application server. + + :param request_validator: An implementation of + oauthlib.oauth2.RequestValidator. + :param token_expires_in: An int or a function to generate a token + expiration offset (in seconds) given a + oauthlib.common.Request object. + :param token_generator: A function to generate a token from a request. + :param refresh_token_generator: A function to generate a token from a + request for the refresh token. + :param kwargs: Extra parameters to pass to authorization-, + token-, resource-, and revocation-endpoint constructors. + """ + self.auth_grant = AuthorizationCodeGrant(request_validator) + self.refresh_grant = RefreshTokenGrant(request_validator) + self.bearer = BearerToken( + request_validator, token_generator, token_expires_in, refresh_token_generator + ) + AuthorizationEndpoint.__init__( + self, + default_response_type="code", + response_types={"code": self.auth_grant}, + default_token_type=self.bearer, + ) + TokenEndpoint.__init__( + self, + default_grant_type="authorization_code", + grant_types={ + "authorization_code": self.auth_grant, + "refresh_token": self.refresh_grant, + }, + default_token_type=self.bearer, + ) + ResourceEndpoint.__init__( + self, default_token="Bearer", token_types={"Bearer": self.bearer} + ) + RevocationEndpoint.__init__(self, request_validator) + IntrospectEndpoint.__init__(self, request_validator) + + +class MobileApplicationServer( + AuthorizationEndpoint, IntrospectEndpoint, ResourceEndpoint, RevocationEndpoint +): + """An all-in-one endpoint featuring Implicit code grant and Bearer tokens.""" + + def __init__( + self, + request_validator, + token_generator=None, + token_expires_in=None, + refresh_token_generator=None, + **kwargs, + ): + """Construct a new implicit grant server. + + :param request_validator: An implementation of + oauthlib.oauth2.RequestValidator. + :param token_expires_in: An int or a function to generate a token + expiration offset (in seconds) given a + oauthlib.common.Request object. + :param token_generator: A function to generate a token from a request. + :param refresh_token_generator: A function to generate a token from a + request for the refresh token. + :param kwargs: Extra parameters to pass to authorization-, + token-, resource-, and revocation-endpoint constructors. + """ + self.implicit_grant = ImplicitGrant(request_validator) + self.bearer = BearerToken( + request_validator, token_generator, token_expires_in, refresh_token_generator + ) + AuthorizationEndpoint.__init__( + self, + default_response_type="token", + response_types={"token": self.implicit_grant}, + default_token_type=self.bearer, + ) + ResourceEndpoint.__init__( + self, default_token="Bearer", token_types={"Bearer": self.bearer} + ) + RevocationEndpoint.__init__( + self, request_validator, supported_token_types=["access_token"] + ) + IntrospectEndpoint.__init__( + self, request_validator, supported_token_types=["access_token"] + ) + + +class LegacyApplicationServer( + TokenEndpoint, IntrospectEndpoint, ResourceEndpoint, RevocationEndpoint +): + """An all-in-one endpoint featuring Resource Owner Password Credentials grant and Bearer tokens.""" + + def __init__( + self, + request_validator, + token_generator=None, + token_expires_in=None, + refresh_token_generator=None, + **kwargs, + ): + """Construct a resource owner password credentials grant server. + + :param request_validator: An implementation of + oauthlib.oauth2.RequestValidator. + :param token_expires_in: An int or a function to generate a token + expiration offset (in seconds) given a + oauthlib.common.Request object. + :param token_generator: A function to generate a token from a request. + :param refresh_token_generator: A function to generate a token from a + request for the refresh token. + :param kwargs: Extra parameters to pass to authorization-, + token-, resource-, and revocation-endpoint constructors. + """ + self.password_grant = ResourceOwnerPasswordCredentialsGrant(request_validator) + self.refresh_grant = RefreshTokenGrant(request_validator) + self.bearer = BearerToken( + request_validator, token_generator, token_expires_in, refresh_token_generator + ) + TokenEndpoint.__init__( + self, + default_grant_type="password", + grant_types={ + "password": self.password_grant, + "refresh_token": self.refresh_grant, + }, + default_token_type=self.bearer, + ) + ResourceEndpoint.__init__( + self, default_token="Bearer", token_types={"Bearer": self.bearer} + ) + RevocationEndpoint.__init__(self, request_validator) + IntrospectEndpoint.__init__(self, request_validator) + + +class BackendApplicationServer( + TokenEndpoint, IntrospectEndpoint, ResourceEndpoint, RevocationEndpoint +): + """An all-in-one endpoint featuring Client Credentials grant and Bearer tokens.""" + + def __init__( + self, + request_validator, + token_generator=None, + token_expires_in=None, + refresh_token_generator=None, + **kwargs, + ): + """Construct a client credentials grant server. + + :param request_validator: An implementation of + oauthlib.oauth2.RequestValidator. + :param token_expires_in: An int or a function to generate a token + expiration offset (in seconds) given a + oauthlib.common.Request object. + :param token_generator: A function to generate a token from a request. + :param refresh_token_generator: A function to generate a token from a + request for the refresh token. + :param kwargs: Extra parameters to pass to authorization-, + token-, resource-, and revocation-endpoint constructors. + """ + self.credentials_grant = ClientCredentialsGrant(request_validator) + self.bearer = BearerToken( + request_validator, token_generator, token_expires_in, refresh_token_generator + ) + TokenEndpoint.__init__( + self, + default_grant_type="client_credentials", + grant_types={"client_credentials": self.credentials_grant}, + default_token_type=self.bearer, + ) + ResourceEndpoint.__init__( + self, default_token="Bearer", token_types={"Bearer": self.bearer} + ) + RevocationEndpoint.__init__( + self, request_validator, supported_token_types=["access_token"] + ) + IntrospectEndpoint.__init__( + self, request_validator, supported_token_types=["access_token"] + ) diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/endpoints/resource.py b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/endpoints/resource.py new file mode 100644 index 0000000000000000000000000000000000000000..d1ff5049d858311a88c4a4115f59437cf20f6243 --- /dev/null +++ b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/endpoints/resource.py @@ -0,0 +1,84 @@ +""" +oauthlib.oauth2.rfc6749 +~~~~~~~~~~~~~~~~~~~~~~~ + +This module is an implementation of various logic needed +for consuming and providing OAuth 2.0 RFC6749. +""" +import logging + +from oauthlib.common import Request + +from .base import BaseEndpoint, catch_errors_and_unavailability + +log = logging.getLogger(__name__) + + +class ResourceEndpoint(BaseEndpoint): + + """Authorizes access to protected resources. + + The client accesses protected resources by presenting the access + token to the resource server. The resource server MUST validate the + access token and ensure that it has not expired and that its scope + covers the requested resource. The methods used by the resource + server to validate the access token (as well as any error responses) + are beyond the scope of this specification but generally involve an + interaction or coordination between the resource server and the + authorization server:: + + # For most cases, returning a 403 should suffice. + + The method in which the client utilizes the access token to + authenticate with the resource server depends on the type of access + token issued by the authorization server. Typically, it involves + using the HTTP "Authorization" request header field [RFC2617] with an + authentication scheme defined by the specification of the access + token type used, such as [RFC6750]:: + + # Access tokens may also be provided in query and body + https://example.com/protected?access_token=kjfch2345sdf # Query + access_token=sdf23409df # Body + """ + + def __init__(self, default_token, token_types): + BaseEndpoint.__init__(self) + self._tokens = token_types + self._default_token = default_token + + @property + def default_token(self): + return self._default_token + + @property + def default_token_type_handler(self): + return self.tokens.get(self.default_token) + + @property + def tokens(self): + return self._tokens + + @catch_errors_and_unavailability + def verify_request(self, uri, http_method='GET', body=None, headers=None, + scopes=None): + """Validate client, code etc, return body + headers""" + request = Request(uri, http_method, body, headers) + request.token_type = self.find_token_type(request) + request.scopes = scopes + token_type_handler = self.tokens.get(request.token_type, + self.default_token_type_handler) + log.debug('Dispatching token_type %s request to %r.', + request.token_type, token_type_handler) + return token_type_handler.validate_request(request), request + + def find_token_type(self, request): + """Token type identification. + + RFC 6749 does not provide a method for easily differentiating between + different token types during protected resource access. We estimate + the most likely token type (if any) by asking each known token type + to give an estimation based on the request. + """ + estimates = sorted(((t.estimate_type(request), n) + for n, t in self.tokens.items()), reverse=True) + return estimates[0][1] if estimates else None diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/endpoints/revocation.py b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/endpoints/revocation.py new file mode 100644 index 0000000000000000000000000000000000000000..596d0860fae67017a86b1042fcf9edb674fdf38d --- /dev/null +++ b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/endpoints/revocation.py @@ -0,0 +1,126 @@ +""" +oauthlib.oauth2.rfc6749.endpoint.revocation +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +An implementation of the OAuth 2 `Token Revocation`_ spec (draft 11). + +.. _`Token Revocation`: https://tools.ietf.org/html/draft-ietf-oauth-revocation-11 +""" +import logging + +from oauthlib.common import Request + +from ..errors import OAuth2Error +from .base import BaseEndpoint, catch_errors_and_unavailability + +log = logging.getLogger(__name__) + + +class RevocationEndpoint(BaseEndpoint): + + """Token revocation endpoint. + + Endpoint used by authenticated clients to revoke access and refresh tokens. + Commonly this will be part of the Authorization Endpoint. + """ + + valid_token_types = ('access_token', 'refresh_token') + valid_request_methods = ('POST',) + + def __init__(self, request_validator, supported_token_types=None, + enable_jsonp=False): + BaseEndpoint.__init__(self) + self.request_validator = request_validator + self.supported_token_types = ( + supported_token_types or self.valid_token_types) + self.enable_jsonp = enable_jsonp + + @catch_errors_and_unavailability + def create_revocation_response(self, uri, http_method='POST', body=None, + headers=None): + """Revoke supplied access or refresh token. + + + The authorization server responds with HTTP status code 200 if the + token has been revoked successfully or if the client submitted an + invalid token. + + Note: invalid tokens do not cause an error response since the client + cannot handle such an error in a reasonable way. Moreover, the purpose + of the revocation request, invalidating the particular token, is + already achieved. + + The content of the response body is ignored by the client as all + necessary information is conveyed in the response code. + + An invalid token type hint value is ignored by the authorization server + and does not influence the revocation response. + """ + resp_headers = { + 'Content-Type': 'application/json', + 'Cache-Control': 'no-store', + 'Pragma': 'no-cache', + } + request = Request( + uri, http_method=http_method, body=body, headers=headers) + try: + self.validate_revocation_request(request) + log.debug('Token revocation valid for %r.', request) + except OAuth2Error as e: + log.debug('Client error during validation of %r. %r.', request, e) + response_body = e.json + if self.enable_jsonp and request.callback: + response_body = '{}({});'.format(request.callback, response_body) + resp_headers.update(e.headers) + return resp_headers, response_body, e.status_code + + self.request_validator.revoke_token(request.token, + request.token_type_hint, request) + + response_body = '' + if self.enable_jsonp and request.callback: + response_body = request.callback + '();' + return {}, response_body, 200 + + def validate_revocation_request(self, request): + """Ensure the request is valid. + + The client constructs the request by including the following parameters + using the "application/x-www-form-urlencoded" format in the HTTP + request entity-body: + + token (REQUIRED). The token that the client wants to get revoked. + + token_type_hint (OPTIONAL). A hint about the type of the token + submitted for revocation. Clients MAY pass this parameter in order to + help the authorization server to optimize the token lookup. If the + server is unable to locate the token using the given hint, it MUST + extend its search across all of its supported token types. An + authorization server MAY ignore this parameter, particularly if it is + able to detect the token type automatically. This specification + defines two such values: + + * access_token: An Access Token as defined in [RFC6749], + `section 1.4`_ + + * refresh_token: A Refresh Token as defined in [RFC6749], + `section 1.5`_ + + Specific implementations, profiles, and extensions of this + specification MAY define other values for this parameter using + the registry defined in `Section 4.1.2`_. + + The client also includes its authentication credentials as described in + `Section 2.3`_. of [`RFC6749`_]. + + .. _`section 1.4`: https://tools.ietf.org/html/rfc6749#section-1.4 + .. _`section 1.5`: https://tools.ietf.org/html/rfc6749#section-1.5 + .. _`section 2.3`: https://tools.ietf.org/html/rfc6749#section-2.3 + .. _`Section 4.1.2`: https://tools.ietf.org/html/draft-ietf-oauth-revocation-11#section-4.1.2 + .. _`RFC6749`: https://tools.ietf.org/html/rfc6749 + """ + self._raise_on_bad_method(request) + self._raise_on_bad_post_request(request) + self._raise_on_missing_token(request) + self._raise_on_invalid_client(request) + self._raise_on_unsupported_token(request) diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/endpoints/token.py b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/endpoints/token.py new file mode 100644 index 0000000000000000000000000000000000000000..ab9e0918b30da3271335fbbac370d5667c9b1d61 --- /dev/null +++ b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/endpoints/token.py @@ -0,0 +1,119 @@ +""" +oauthlib.oauth2.rfc6749 +~~~~~~~~~~~~~~~~~~~~~~~ + +This module is an implementation of various logic needed +for consuming and providing OAuth 2.0 RFC6749. +""" +import logging + +from oauthlib.common import Request +from oauthlib.oauth2.rfc6749 import utils + +from .base import BaseEndpoint, catch_errors_and_unavailability + +log = logging.getLogger(__name__) + + +class TokenEndpoint(BaseEndpoint): + + """Token issuing endpoint. + + The token endpoint is used by the client to obtain an access token by + presenting its authorization grant or refresh token. The token + endpoint is used with every authorization grant except for the + implicit grant type (since an access token is issued directly). + + The means through which the client obtains the location of the token + endpoint are beyond the scope of this specification, but the location + is typically provided in the service documentation. + + The endpoint URI MAY include an "application/x-www-form-urlencoded" + formatted (per `Appendix B`_) query component, + which MUST be retained when adding additional query parameters. The + endpoint URI MUST NOT include a fragment component:: + + https://example.com/path?query=component # OK + https://example.com/path?query=component#fragment # Not OK + + Since requests to the token endpoint result in the transmission of + clear-text credentials (in the HTTP request and response), the + authorization server MUST require the use of TLS as described in + Section 1.6 when sending requests to the token endpoint:: + + # We will deny any request which URI schema is not with https + + The client MUST use the HTTP "POST" method when making access token + requests:: + + # HTTP method is currently not enforced + + Parameters sent without a value MUST be treated as if they were + omitted from the request. The authorization server MUST ignore + unrecognized request parameters. Request and response parameters + MUST NOT be included more than once:: + + # Delegated to each grant type. + + .. _`Appendix B`: https://tools.ietf.org/html/rfc6749#appendix-B + """ + + valid_request_methods = ('POST',) + + def __init__(self, default_grant_type, default_token_type, grant_types): + BaseEndpoint.__init__(self) + self._grant_types = grant_types + self._default_token_type = default_token_type + self._default_grant_type = default_grant_type + + @property + def grant_types(self): + return self._grant_types + + @property + def default_grant_type(self): + return self._default_grant_type + + @property + def default_grant_type_handler(self): + return self.grant_types.get(self.default_grant_type) + + @property + def default_token_type(self): + return self._default_token_type + + @catch_errors_and_unavailability + def create_token_response(self, uri, http_method='POST', body=None, + headers=None, credentials=None, grant_type_for_scope=None, + claims=None): + """Extract grant_type and route to the designated handler.""" + request = Request( + uri, http_method=http_method, body=body, headers=headers) + self.validate_token_request(request) + # 'scope' is an allowed Token Request param in both the "Resource Owner Password Credentials Grant" + # and "Client Credentials Grant" flows + # https://tools.ietf.org/html/rfc6749#section-4.3.2 + # https://tools.ietf.org/html/rfc6749#section-4.4.2 + request.scopes = utils.scope_to_list(request.scope) + + request.extra_credentials = credentials + if grant_type_for_scope: + request.grant_type = grant_type_for_scope + + # OpenID Connect claims, if provided. The server using oauthlib might choose + # to implement the claims parameter of the Authorization Request. In this case + # it should retrieve those claims and pass them via the claims argument here, + # as a dict. + if claims: + request.claims = claims + + grant_type_handler = self.grant_types.get(request.grant_type, + self.default_grant_type_handler) + log.debug('Dispatching grant_type %s request to %r.', + request.grant_type, grant_type_handler) + return grant_type_handler.create_token_response( + request, self.default_token_type) + + def validate_token_request(self, request): + self._raise_on_bad_method(request) + self._raise_on_bad_post_request(request) diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/errors.py b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/errors.py new file mode 100644 index 0000000000000000000000000000000000000000..be8e7a1ec6d74c00df1509d4d7a18b6213bdbf23 --- /dev/null +++ b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/errors.py @@ -0,0 +1,399 @@ +""" +oauthlib.oauth2.rfc6749.errors +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Error used both by OAuth 2 clients and providers to represent the spec +defined error responses for all four core grant types. +""" +import json +import inspect +import sys + +from oauthlib.common import add_params_to_uri, urlencode + + +class OAuth2Error(Exception): + error = None + status_code = 400 + description = '' + + def __init__(self, description=None, uri=None, state=None, + status_code=None, request=None): + """ + :param description: A human-readable ASCII [USASCII] text providing + additional information, used to assist the client + developer in understanding the error that occurred. + Values for the "error_description" parameter + MUST NOT include characters outside the set + x20-21 / x23-5B / x5D-7E. + + :param uri: A URI identifying a human-readable web page with information + about the error, used to provide the client developer with + additional information about the error. Values for the + "error_uri" parameter MUST conform to the URI- Reference + syntax, and thus MUST NOT include characters outside the set + x21 / x23-5B / x5D-7E. + + :param state: A CSRF protection value received from the client. + + :param status_code: + + :param request: OAuthlib request. + :type request: oauthlib.common.Request + """ + if description is not None: + self.description = description + + message = '({}) {}'.format(self.error, self.description) + if request: + message += ' ' + repr(request) + super().__init__(message) + + self.uri = uri + self.state = state + + if status_code: + self.status_code = status_code + + if request: + self.redirect_uri = request.redirect_uri + self.client_id = request.client_id + self.scopes = request.scopes + self.response_type = request.response_type + self.response_mode = request.response_mode + self.grant_type = request.grant_type + if state is None: + self.state = request.state + else: + self.redirect_uri = None + self.client_id = None + self.scopes = None + self.response_type = None + self.response_mode = None + self.grant_type = None + + def in_uri(self, uri): + fragment = self.response_mode == "fragment" + return add_params_to_uri(uri, self.twotuples, fragment) + + @property + def twotuples(self): + error = [('error', self.error)] + if self.description: + error.append(('error_description', self.description)) + if self.uri: + error.append(('error_uri', self.uri)) + if self.state: + error.append(('state', self.state)) + return error + + @property + def urlencoded(self): + return urlencode(self.twotuples) + + @property + def json(self): + return json.dumps(dict(self.twotuples)) + + @property + def headers(self): + if self.status_code == 401: + """ + https://tools.ietf.org/html/rfc6750#section-3 + + All challenges defined by this specification MUST use the auth-scheme + value "Bearer". This scheme MUST be followed by one or more + auth-param values. + """ + authvalues = ['error="{}"'.format(self.error)] + if self.description: + authvalues.append('error_description="{}"'.format(self.description)) + if self.uri: + authvalues.append('error_uri="{}"'.format(self.uri)) + return {"WWW-Authenticate": "Bearer " + ", ".join(authvalues)} + return {} + + +class TokenExpiredError(OAuth2Error): + error = 'token_expired' + + +class InsecureTransportError(OAuth2Error): + error = 'insecure_transport' + description = 'OAuth 2 MUST utilize https.' + + +class MismatchingStateError(OAuth2Error): + error = 'mismatching_state' + description = 'CSRF Warning! State not equal in request and response.' + + +class MissingCodeError(OAuth2Error): + error = 'missing_code' + + +class MissingTokenError(OAuth2Error): + error = 'missing_token' + + +class MissingTokenTypeError(OAuth2Error): + error = 'missing_token_type' + + +class FatalClientError(OAuth2Error): + """ + Errors during authorization where user should not be redirected back. + + If the request fails due to a missing, invalid, or mismatching + redirection URI, or if the client identifier is missing or invalid, + the authorization server SHOULD inform the resource owner of the + error and MUST NOT automatically redirect the user-agent to the + invalid redirection URI. + + Instead the user should be informed of the error by the provider itself. + """ + + +class InvalidRequestFatalError(FatalClientError): + """ + For fatal errors, the request is missing a required parameter, includes + an invalid parameter value, includes a parameter more than once, or is + otherwise malformed. + """ + error = 'invalid_request' + + +class InvalidRedirectURIError(InvalidRequestFatalError): + description = 'Invalid redirect URI.' + + +class MissingRedirectURIError(InvalidRequestFatalError): + description = 'Missing redirect URI.' + + +class MismatchingRedirectURIError(InvalidRequestFatalError): + description = 'Mismatching redirect URI.' + + +class InvalidClientIdError(InvalidRequestFatalError): + description = 'Invalid client_id parameter value.' + + +class MissingClientIdError(InvalidRequestFatalError): + description = 'Missing client_id parameter.' + + +class InvalidRequestError(OAuth2Error): + """ + The request is missing a required parameter, includes an invalid + parameter value, includes a parameter more than once, or is + otherwise malformed. + """ + error = 'invalid_request' + + +class MissingResponseTypeError(InvalidRequestError): + description = 'Missing response_type parameter.' + + +class MissingCodeChallengeError(InvalidRequestError): + """ + If the server requires Proof Key for Code Exchange (PKCE) by OAuth + public clients and the client does not send the "code_challenge" in + the request, the authorization endpoint MUST return the authorization + error response with the "error" value set to "invalid_request". The + "error_description" or the response of "error_uri" SHOULD explain the + nature of error, e.g., code challenge required. + """ + description = 'Code challenge required.' + + +class MissingCodeVerifierError(InvalidRequestError): + """ + The request to the token endpoint, when PKCE is enabled, has + the parameter `code_verifier` REQUIRED. + """ + description = 'Code verifier required.' + + +class AccessDeniedError(OAuth2Error): + """ + The resource owner or authorization server denied the request. + """ + error = 'access_denied' + + +class UnsupportedResponseTypeError(OAuth2Error): + """ + The authorization server does not support obtaining an authorization + code using this method. + """ + error = 'unsupported_response_type' + + +class UnsupportedCodeChallengeMethodError(InvalidRequestError): + """ + If the server supporting PKCE does not support the requested + transformation, the authorization endpoint MUST return the + authorization error response with "error" value set to + "invalid_request". The "error_description" or the response of + "error_uri" SHOULD explain the nature of error, e.g., transform + algorithm not supported. + """ + description = 'Transform algorithm not supported.' + + +class InvalidScopeError(OAuth2Error): + """ + The requested scope is invalid, unknown, or malformed, or + exceeds the scope granted by the resource owner. + + https://tools.ietf.org/html/rfc6749#section-5.2 + """ + error = 'invalid_scope' + + +class ServerError(OAuth2Error): + """ + The authorization server encountered an unexpected condition that + prevented it from fulfilling the request. (This error code is needed + because a 500 Internal Server Error HTTP status code cannot be returned + to the client via a HTTP redirect.) + """ + error = 'server_error' + + +class TemporarilyUnavailableError(OAuth2Error): + """ + The authorization server is currently unable to handle the request + due to a temporary overloading or maintenance of the server. + (This error code is needed because a 503 Service Unavailable HTTP + status code cannot be returned to the client via a HTTP redirect.) + """ + error = 'temporarily_unavailable' + + +class InvalidClientError(FatalClientError): + """ + Client authentication failed (e.g. unknown client, no client + authentication included, or unsupported authentication method). + The authorization server MAY return an HTTP 401 (Unauthorized) status + code to indicate which HTTP authentication schemes are supported. + If the client attempted to authenticate via the "Authorization" request + header field, the authorization server MUST respond with an + HTTP 401 (Unauthorized) status code, and include the "WWW-Authenticate" + response header field matching the authentication scheme used by the + client. + """ + error = 'invalid_client' + status_code = 401 + + +class InvalidGrantError(OAuth2Error): + """ + The provided authorization grant (e.g. authorization code, resource + owner credentials) or refresh token is invalid, expired, revoked, does + not match the redirection URI used in the authorization request, or was + issued to another client. + + https://tools.ietf.org/html/rfc6749#section-5.2 + """ + error = 'invalid_grant' + status_code = 400 + + +class UnauthorizedClientError(OAuth2Error): + """ + The authenticated client is not authorized to use this authorization + grant type. + """ + error = 'unauthorized_client' + + +class UnsupportedGrantTypeError(OAuth2Error): + """ + The authorization grant type is not supported by the authorization + server. + """ + error = 'unsupported_grant_type' + + +class UnsupportedTokenTypeError(OAuth2Error): + """ + The authorization server does not support the hint of the + presented token type. I.e. the client tried to revoke an access token + on a server not supporting this feature. + """ + error = 'unsupported_token_type' + + +class InvalidTokenError(OAuth2Error): + """ + The access token provided is expired, revoked, malformed, or + invalid for other reasons. The resource SHOULD respond with + the HTTP 401 (Unauthorized) status code. The client MAY + request a new access token and retry the protected resource + request. + """ + error = 'invalid_token' + status_code = 401 + description = ("The access token provided is expired, revoked, malformed, " + "or invalid for other reasons.") + + +class InsufficientScopeError(OAuth2Error): + """ + The request requires higher privileges than provided by the + access token. The resource server SHOULD respond with the HTTP + 403 (Forbidden) status code and MAY include the "scope" + attribute with the scope necessary to access the protected + resource. + """ + error = 'insufficient_scope' + status_code = 403 + description = ("The request requires higher privileges than provided by " + "the access token.") + + +class ConsentRequired(OAuth2Error): + """ + The Authorization Server requires End-User consent. + + This error MAY be returned when the prompt parameter value in the + Authentication Request is none, but the Authentication Request cannot be + completed without displaying a user interface for End-User consent. + """ + error = 'consent_required' + + +class LoginRequired(OAuth2Error): + """ + The Authorization Server requires End-User authentication. + + This error MAY be returned when the prompt parameter value in the + Authentication Request is none, but the Authentication Request cannot be + completed without displaying a user interface for End-User authentication. + """ + error = 'login_required' + + +class CustomOAuth2Error(OAuth2Error): + """ + This error is a placeholder for all custom errors not described by the RFC. + Some of the popular OAuth2 providers are using custom errors. + """ + def __init__(self, error, *args, **kwargs): + self.error = error + super().__init__(*args, **kwargs) + + +def raise_from_error(error, params=None): + kwargs = { + 'description': params.get('error_description'), + 'uri': params.get('error_uri'), + 'state': params.get('state') + } + for _, cls in inspect.getmembers(sys.modules[__name__], inspect.isclass): + if cls.error == error: + raise cls(**kwargs) + raise CustomOAuth2Error(error=error, **kwargs) diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/grant_types/__init__.py b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/grant_types/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..eb88cfc2e9749d22780532fd75af2fc8b7c2fae2 --- /dev/null +++ b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/grant_types/__init__.py @@ -0,0 +1,11 @@ +""" +oauthlib.oauth2.rfc6749.grant_types +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +""" +from .authorization_code import AuthorizationCodeGrant +from .client_credentials import ClientCredentialsGrant +from .implicit import ImplicitGrant +from .refresh_token import RefreshTokenGrant +from .resource_owner_password_credentials import ( + ResourceOwnerPasswordCredentialsGrant, +) diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/grant_types/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/grant_types/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..da9bc931045e5bac888fda26c45b57f431c7e855 Binary files /dev/null and b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/grant_types/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/grant_types/__pycache__/authorization_code.cpython-313.pyc b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/grant_types/__pycache__/authorization_code.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..75b76aa2c8a5a8495231fc44dd496a795266c5b2 Binary files /dev/null and b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/grant_types/__pycache__/authorization_code.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/grant_types/__pycache__/base.cpython-313.pyc b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/grant_types/__pycache__/base.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d76d575f3812e03baf4bdc2d2b340289ac695aba Binary files /dev/null and b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/grant_types/__pycache__/base.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/grant_types/__pycache__/client_credentials.cpython-313.pyc b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/grant_types/__pycache__/client_credentials.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..63508ba0debd53303b87992dfd778d5154e60e4d Binary files /dev/null and b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/grant_types/__pycache__/client_credentials.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/grant_types/__pycache__/implicit.cpython-313.pyc b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/grant_types/__pycache__/implicit.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b5877a403d24355936746b4d5ba5b193464b2f23 Binary files /dev/null and b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/grant_types/__pycache__/implicit.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/grant_types/__pycache__/refresh_token.cpython-313.pyc b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/grant_types/__pycache__/refresh_token.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d3a6034e61d99e629d764889e1278ca6a66101e5 Binary files /dev/null and b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/grant_types/__pycache__/refresh_token.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/grant_types/__pycache__/resource_owner_password_credentials.cpython-313.pyc b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/grant_types/__pycache__/resource_owner_password_credentials.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bfc6c9c6b70c366ec897c31590f75ec15ec63d04 Binary files /dev/null and b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/grant_types/__pycache__/resource_owner_password_credentials.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/grant_types/authorization_code.py b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/grant_types/authorization_code.py new file mode 100644 index 0000000000000000000000000000000000000000..09dc619988941ea1dd83e15b4b4f11689b45bb36 --- /dev/null +++ b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/grant_types/authorization_code.py @@ -0,0 +1,547 @@ +""" +oauthlib.oauth2.rfc6749.grant_types +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +""" +import base64 +import hashlib +import json +import logging + +from oauthlib import common + +from .. import errors +from .base import GrantTypeBase + +log = logging.getLogger(__name__) + + +def code_challenge_method_s256(verifier, challenge): + """ + If the "code_challenge_method" from `Section 4.3`_ was "S256", the + received "code_verifier" is hashed by SHA-256, base64url-encoded, and + then compared to the "code_challenge", i.e.: + + BASE64URL-ENCODE(SHA256(ASCII(code_verifier))) == code_challenge + + How to implement a base64url-encoding + function without padding, based upon the standard base64-encoding + function that uses padding. + + To be concrete, example C# code implementing these functions is shown + below. Similar code could be used in other languages. + + static string base64urlencode(byte [] arg) + { + string s = Convert.ToBase64String(arg); // Regular base64 encoder + s = s.Split('=')[0]; // Remove any trailing '='s + s = s.Replace('+', '-'); // 62nd char of encoding + s = s.Replace('/', '_'); // 63rd char of encoding + return s; + } + + In python urlsafe_b64encode is already replacing '+' and '/', but preserve + the trailing '='. So we have to remove it. + + .. _`Section 4.3`: https://tools.ietf.org/html/rfc7636#section-4.3 + """ + return base64.urlsafe_b64encode( + hashlib.sha256(verifier.encode()).digest() + ).decode().rstrip('=') == challenge + + +def code_challenge_method_plain(verifier, challenge): + """ + If the "code_challenge_method" from `Section 4.3`_ was "plain", they are + compared directly, i.e.: + + code_verifier == code_challenge. + + .. _`Section 4.3`: https://tools.ietf.org/html/rfc7636#section-4.3 + """ + return verifier == challenge + + +class AuthorizationCodeGrant(GrantTypeBase): + + """`Authorization Code Grant`_ + + The authorization code grant type is used to obtain both access + tokens and refresh tokens and is optimized for confidential clients. + Since this is a redirection-based flow, the client must be capable of + interacting with the resource owner's user-agent (typically a web + browser) and capable of receiving incoming requests (via redirection) + from the authorization server:: + + +----------+ + | Resource | + | Owner | + | | + +----------+ + ^ + | + (B) + +----|-----+ Client Identifier +---------------+ + | -+----(A)-- & Redirection URI ---->| | + | User- | | Authorization | + | Agent -+----(B)-- User authenticates --->| Server | + | | | | + | -+----(C)-- Authorization Code ---<| | + +-|----|---+ +---------------+ + | | ^ v + (A) (C) | | + | | | | + ^ v | | + +---------+ | | + | |>---(D)-- Authorization Code ---------' | + | Client | & Redirection URI | + | | | + | |<---(E)----- Access Token -------------------' + +---------+ (w/ Optional Refresh Token) + + Note: The lines illustrating steps (A), (B), and (C) are broken into + two parts as they pass through the user-agent. + + Figure 3: Authorization Code Flow + + The flow illustrated in Figure 3 includes the following steps: + + (A) The client initiates the flow by directing the resource owner's + user-agent to the authorization endpoint. The client includes + its client identifier, requested scope, local state, and a + redirection URI to which the authorization server will send the + user-agent back once access is granted (or denied). + + (B) The authorization server authenticates the resource owner (via + the user-agent) and establishes whether the resource owner + grants or denies the client's access request. + + (C) Assuming the resource owner grants access, the authorization + server redirects the user-agent back to the client using the + redirection URI provided earlier (in the request or during + client registration). The redirection URI includes an + authorization code and any local state provided by the client + earlier. + + (D) The client requests an access token from the authorization + server's token endpoint by including the authorization code + received in the previous step. When making the request, the + client authenticates with the authorization server. The client + includes the redirection URI used to obtain the authorization + code for verification. + + (E) The authorization server authenticates the client, validates the + authorization code, and ensures that the redirection URI + received matches the URI used to redirect the client in + step (C). If valid, the authorization server responds back with + an access token and, optionally, a refresh token. + + OAuth 2.0 public clients utilizing the Authorization Code Grant are + susceptible to the authorization code interception attack. + + A technique to mitigate against the threat through the use of Proof Key for Code + Exchange (PKCE, pronounced "pixy") is implemented in the current oauthlib + implementation. + + .. _`Authorization Code Grant`: https://tools.ietf.org/html/rfc6749#section-4.1 + .. _`PKCE`: https://tools.ietf.org/html/rfc7636 + """ + + default_response_mode = 'query' + response_types = ['code'] + + # This dict below is private because as RFC mention it: + # "S256" is Mandatory To Implement (MTI) on the server. + # + _code_challenge_methods = { + 'plain': code_challenge_method_plain, + 'S256': code_challenge_method_s256 + } + + def create_authorization_code(self, request): + """ + Generates an authorization grant represented as a dictionary. + + :param request: OAuthlib request. + :type request: oauthlib.common.Request + """ + grant = {'code': common.generate_token()} + if hasattr(request, 'state') and request.state: + grant['state'] = request.state + log.debug('Created authorization code grant %r for request %r.', + grant, request) + return grant + + def create_authorization_response(self, request, token_handler): + """ + The client constructs the request URI by adding the following + parameters to the query component of the authorization endpoint URI + using the "application/x-www-form-urlencoded" format, per `Appendix B`_: + + response_type + REQUIRED. Value MUST be set to "code" for standard OAuth2 + authorization flow. For OpenID Connect it must be one of + "code token", "code id_token", or "code token id_token" - we + essentially test that "code" appears in the response_type. + client_id + REQUIRED. The client identifier as described in `Section 2.2`_. + redirect_uri + OPTIONAL. As described in `Section 3.1.2`_. + scope + OPTIONAL. The scope of the access request as described by + `Section 3.3`_. + state + RECOMMENDED. An opaque value used by the client to maintain + state between the request and callback. The authorization + server includes this value when redirecting the user-agent back + to the client. The parameter SHOULD be used for preventing + cross-site request forgery as described in `Section 10.12`_. + + The client directs the resource owner to the constructed URI using an + HTTP redirection response, or by other means available to it via the + user-agent. + + :param request: OAuthlib request. + :type request: oauthlib.common.Request + :param token_handler: A token handler instance, for example of type + oauthlib.oauth2.BearerToken. + :returns: headers, body, status + :raises: FatalClientError on invalid redirect URI or client id. + + A few examples:: + + >>> from your_validator import your_validator + >>> request = Request('https://example.com/authorize?client_id=valid' + ... '&redirect_uri=http%3A%2F%2Fclient.com%2F') + >>> from oauthlib.common import Request + >>> from oauthlib.oauth2 import AuthorizationCodeGrant, BearerToken + >>> token = BearerToken(your_validator) + >>> grant = AuthorizationCodeGrant(your_validator) + >>> request.scopes = ['authorized', 'in', 'some', 'form'] + >>> grant.create_authorization_response(request, token) + (u'http://client.com/?error=invalid_request&error_description=Missing+response_type+parameter.', None, None, 400) + >>> request = Request('https://example.com/authorize?client_id=valid' + ... '&redirect_uri=http%3A%2F%2Fclient.com%2F' + ... '&response_type=code') + >>> request.scopes = ['authorized', 'in', 'some', 'form'] + >>> grant.create_authorization_response(request, token) + (u'http://client.com/?code=u3F05aEObJuP2k7DordviIgW5wl52N', None, None, 200) + >>> # If the client id or redirect uri fails validation + >>> grant.create_authorization_response(request, token) + Traceback (most recent call last): + File "", line 1, in + File "oauthlib/oauth2/rfc6749/grant_types.py", line 515, in create_authorization_response + >>> grant.create_authorization_response(request, token) + File "oauthlib/oauth2/rfc6749/grant_types.py", line 591, in validate_authorization_request + oauthlib.oauth2.rfc6749.errors.InvalidClientIdError + + .. _`Appendix B`: https://tools.ietf.org/html/rfc6749#appendix-B + .. _`Section 2.2`: https://tools.ietf.org/html/rfc6749#section-2.2 + .. _`Section 3.1.2`: https://tools.ietf.org/html/rfc6749#section-3.1.2 + .. _`Section 3.3`: https://tools.ietf.org/html/rfc6749#section-3.3 + .. _`Section 10.12`: https://tools.ietf.org/html/rfc6749#section-10.12 + """ + try: + self.validate_authorization_request(request) + log.debug('Pre resource owner authorization validation ok for %r.', + request) + + # If the request fails due to a missing, invalid, or mismatching + # redirection URI, or if the client identifier is missing or invalid, + # the authorization server SHOULD inform the resource owner of the + # error and MUST NOT automatically redirect the user-agent to the + # invalid redirection URI. + except errors.FatalClientError as e: + log.debug('Fatal client error during validation of %r. %r.', + request, e) + raise + + # If the resource owner denies the access request or if the request + # fails for reasons other than a missing or invalid redirection URI, + # the authorization server informs the client by adding the following + # parameters to the query component of the redirection URI using the + # "application/x-www-form-urlencoded" format, per Appendix B: + # https://tools.ietf.org/html/rfc6749#appendix-B + except errors.OAuth2Error as e: + log.debug('Client error during validation of %r. %r.', request, e) + request.redirect_uri = request.redirect_uri or self.error_uri + redirect_uri = common.add_params_to_uri( + request.redirect_uri, e.twotuples, + fragment=request.response_mode == "fragment") + return {'Location': redirect_uri}, None, 302 + + grant = self.create_authorization_code(request) + for modifier in self._code_modifiers: + grant = modifier(grant, token_handler, request) + if 'access_token' in grant: + self.request_validator.save_token(grant, request) + log.debug('Saving grant %r for %r.', grant, request) + self.request_validator.save_authorization_code( + request.client_id, grant, request) + return self.prepare_authorization_response( + request, grant, {}, None, 302) + + def create_token_response(self, request, token_handler): + """Validate the authorization code. + + The client MUST NOT use the authorization code more than once. If an + authorization code is used more than once, the authorization server + MUST deny the request and SHOULD revoke (when possible) all tokens + previously issued based on that authorization code. The authorization + code is bound to the client identifier and redirection URI. + + :param request: OAuthlib request. + :type request: oauthlib.common.Request + :param token_handler: A token handler instance, for example of type + oauthlib.oauth2.BearerToken. + + """ + headers = self._get_default_headers() + try: + self.validate_token_request(request) + log.debug('Token request validation ok for %r.', request) + except errors.OAuth2Error as e: + log.debug('Client error during validation of %r. %r.', request, e) + headers.update(e.headers) + return headers, e.json, e.status_code + + token = token_handler.create_token(request, refresh_token=self.refresh_token) + + for modifier in self._token_modifiers: + token = modifier(token, token_handler, request) + + self.request_validator.save_token(token, request) + self.request_validator.invalidate_authorization_code( + request.client_id, request.code, request) + headers.update(self._create_cors_headers(request)) + return headers, json.dumps(token), 200 + + def validate_authorization_request(self, request): + """Check the authorization request for normal and fatal errors. + + A normal error could be a missing response_type parameter or the client + attempting to access scope it is not allowed to ask authorization for. + Normal errors can safely be included in the redirection URI and + sent back to the client. + + Fatal errors occur when the client_id or redirect_uri is invalid or + missing. These must be caught by the provider and handled, how this + is done is outside of the scope of OAuthLib but showing an error + page describing the issue is a good idea. + + :param request: OAuthlib request. + :type request: oauthlib.common.Request + """ + + # First check for fatal errors + + # If the request fails due to a missing, invalid, or mismatching + # redirection URI, or if the client identifier is missing or invalid, + # the authorization server SHOULD inform the resource owner of the + # error and MUST NOT automatically redirect the user-agent to the + # invalid redirection URI. + + # First check duplicate parameters + for param in ('client_id', 'response_type', 'redirect_uri', 'scope', 'state'): + try: + duplicate_params = request.duplicate_params + except ValueError: + raise errors.InvalidRequestFatalError(description='Unable to parse query string', request=request) + if param in duplicate_params: + raise errors.InvalidRequestFatalError(description='Duplicate %s parameter.' % param, request=request) + + # REQUIRED. The client identifier as described in Section 2.2. + # https://tools.ietf.org/html/rfc6749#section-2.2 + if not request.client_id: + raise errors.MissingClientIdError(request=request) + + if not self.request_validator.validate_client_id(request.client_id, request): + raise errors.InvalidClientIdError(request=request) + + # OPTIONAL. As described in Section 3.1.2. + # https://tools.ietf.org/html/rfc6749#section-3.1.2 + log.debug('Validating redirection uri %s for client %s.', + request.redirect_uri, request.client_id) + + # OPTIONAL. As described in Section 3.1.2. + # https://tools.ietf.org/html/rfc6749#section-3.1.2 + self._handle_redirects(request) + + # Then check for normal errors. + + # If the resource owner denies the access request or if the request + # fails for reasons other than a missing or invalid redirection URI, + # the authorization server informs the client by adding the following + # parameters to the query component of the redirection URI using the + # "application/x-www-form-urlencoded" format, per Appendix B. + # https://tools.ietf.org/html/rfc6749#appendix-B + + # Note that the correct parameters to be added are automatically + # populated through the use of specific exceptions. + + request_info = {} + for validator in self.custom_validators.pre_auth: + request_info.update(validator(request)) + + # REQUIRED. + if request.response_type is None: + raise errors.MissingResponseTypeError(request=request) + # Value MUST be set to "code" or one of the OpenID authorization code including + # response_types "code token", "code id_token", "code token id_token" + elif 'code' not in request.response_type and request.response_type != 'none': + raise errors.UnsupportedResponseTypeError(request=request) + + if not self.request_validator.validate_response_type(request.client_id, + request.response_type, + request.client, request): + + log.debug('Client %s is not authorized to use response_type %s.', + request.client_id, request.response_type) + raise errors.UnauthorizedClientError(request=request) + + # OPTIONAL. Validate PKCE request or reply with "error"/"invalid_request" + # https://tools.ietf.org/html/rfc6749#section-4.4.1 + if self.request_validator.is_pkce_required(request.client_id, request) is True and request.code_challenge is None: + raise errors.MissingCodeChallengeError(request=request) + + if request.code_challenge is not None: + request_info["code_challenge"] = request.code_challenge + + # OPTIONAL, defaults to "plain" if not present in the request. + if request.code_challenge_method is None: + request.code_challenge_method = "plain" + + if request.code_challenge_method not in self._code_challenge_methods: + raise errors.UnsupportedCodeChallengeMethodError(request=request) + request_info["code_challenge_method"] = request.code_challenge_method + + # OPTIONAL. The scope of the access request as described by Section 3.3 + # https://tools.ietf.org/html/rfc6749#section-3.3 + self.validate_scopes(request) + + request_info.update({ + 'client_id': request.client_id, + 'redirect_uri': request.redirect_uri, + 'response_type': request.response_type, + 'state': request.state, + 'request': request + }) + + for validator in self.custom_validators.post_auth: + request_info.update(validator(request)) + + return request.scopes, request_info + + def validate_token_request(self, request): + """ + :param request: OAuthlib request. + :type request: oauthlib.common.Request + """ + # REQUIRED. Value MUST be set to "authorization_code". + if request.grant_type not in ('authorization_code', 'openid'): + raise errors.UnsupportedGrantTypeError(request=request) + + for validator in self.custom_validators.pre_token: + validator(request) + + if request.code is None: + raise errors.InvalidRequestError( + description='Missing code parameter.', request=request) + + for param in ('client_id', 'grant_type', 'redirect_uri'): + if param in request.duplicate_params: + raise errors.InvalidRequestError(description='Duplicate %s parameter.' % param, + request=request) + + if self.request_validator.client_authentication_required(request): + # If the client type is confidential or the client was issued client + # credentials (or assigned other authentication requirements), the + # client MUST authenticate with the authorization server as described + # in Section 3.2.1. + # https://tools.ietf.org/html/rfc6749#section-3.2.1 + if not self.request_validator.authenticate_client(request): + log.debug('Client authentication failed, %r.', request) + raise errors.InvalidClientError(request=request) + elif not self.request_validator.authenticate_client_id(request.client_id, request): + # REQUIRED, if the client is not authenticating with the + # authorization server as described in Section 3.2.1. + # https://tools.ietf.org/html/rfc6749#section-3.2.1 + log.debug('Client authentication failed, %r.', request) + raise errors.InvalidClientError(request=request) + + if not hasattr(request.client, 'client_id'): + raise NotImplementedError('Authenticate client must set the ' + 'request.client.client_id attribute ' + 'in authenticate_client.') + + request.client_id = request.client_id or request.client.client_id + + # Ensure client is authorized use of this grant type + self.validate_grant_type(request) + + # REQUIRED. The authorization code received from the + # authorization server. + if not self.request_validator.validate_code(request.client_id, + request.code, request.client, request): + log.debug('Client, %r (%r), is not allowed access to scopes %r.', + request.client_id, request.client, request.scopes) + raise errors.InvalidGrantError(request=request) + + # OPTIONAL. Validate PKCE code_verifier + challenge = self.request_validator.get_code_challenge(request.code, request) + + if challenge is not None: + if request.code_verifier is None: + raise errors.MissingCodeVerifierError(request=request) + + challenge_method = self.request_validator.get_code_challenge_method(request.code, request) + if challenge_method is None: + raise errors.InvalidGrantError(request=request, description="Challenge method not found") + + if challenge_method not in self._code_challenge_methods: + raise errors.ServerError( + description="code_challenge_method {} is not supported.".format(challenge_method), + request=request + ) + + if not self.validate_code_challenge(challenge, + challenge_method, + request.code_verifier): + log.debug('request provided a invalid code_verifier.') + raise errors.InvalidGrantError(request=request) + elif self.request_validator.is_pkce_required(request.client_id, request) is True: + if request.code_verifier is None: + raise errors.MissingCodeVerifierError(request=request) + raise errors.InvalidGrantError(request=request, description="Challenge not found") + + for attr in ('user', 'scopes'): + if getattr(request, attr, None) is None: + log.debug('request.%s was not set on code validation.', attr) + + # REQUIRED, if the "redirect_uri" parameter was included in the + # authorization request as described in Section 4.1.1, and their + # values MUST be identical. + if request.redirect_uri is None: + request.using_default_redirect_uri = True + request.redirect_uri = self.request_validator.get_default_redirect_uri( + request.client_id, request) + log.debug('Using default redirect_uri %s.', request.redirect_uri) + if not request.redirect_uri: + raise errors.MissingRedirectURIError(request=request) + else: + request.using_default_redirect_uri = False + log.debug('Using provided redirect_uri %s', request.redirect_uri) + + if not self.request_validator.confirm_redirect_uri(request.client_id, request.code, + request.redirect_uri, request.client, + request): + log.debug('Redirect_uri (%r) invalid for client %r (%r).', + request.redirect_uri, request.client_id, request.client) + raise errors.MismatchingRedirectURIError(request=request) + + for validator in self.custom_validators.post_token: + validator(request) + + def validate_code_challenge(self, challenge, challenge_method, verifier): + if challenge_method in self._code_challenge_methods: + return self._code_challenge_methods[challenge_method](verifier, challenge) + raise NotImplementedError('Unknown challenge_method %s' % challenge_method) diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/grant_types/base.py b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/grant_types/base.py new file mode 100644 index 0000000000000000000000000000000000000000..d96a2db4fae8f8a73bdda5240afe2f1080e52982 --- /dev/null +++ b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/grant_types/base.py @@ -0,0 +1,265 @@ +""" +oauthlib.oauth2.rfc6749.grant_types +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +""" +import logging +from itertools import chain + +from oauthlib.common import add_params_to_uri +from oauthlib.oauth2.rfc6749 import errors, utils +from oauthlib.uri_validate import is_absolute_uri + +from ..request_validator import RequestValidator +from ..utils import is_secure_transport + +log = logging.getLogger(__name__) + + +class ValidatorsContainer: + """ + Container object for holding custom validator callables to be invoked + as part of the grant type `validate_authorization_request()` or + `validate_authorization_request()` methods on the various grant types. + + Authorization validators must be callables that take a request object and + return a dict, which may contain items to be added to the `request_info` + returned from the grant_type after validation. + + Token validators must be callables that take a request object and + return None. + + Both authorization validators and token validators may raise OAuth2 + exceptions if validation conditions fail. + + Authorization validators added to `pre_auth` will be run BEFORE + the standard validations (but after the critical ones that raise + fatal errors) as part of `validate_authorization_request()` + + Authorization validators added to `post_auth` will be run AFTER + the standard validations as part of `validate_authorization_request()` + + Token validators added to `pre_token` will be run BEFORE + the standard validations as part of `validate_token_request()` + + Token validators added to `post_token` will be run AFTER + the standard validations as part of `validate_token_request()` + + For example: + + >>> def my_auth_validator(request): + ... return {'myval': True} + >>> auth_code_grant = AuthorizationCodeGrant(request_validator) + >>> auth_code_grant.custom_validators.pre_auth.append(my_auth_validator) + >>> def my_token_validator(request): + ... if not request.everything_okay: + ... raise errors.OAuth2Error("uh-oh") + >>> auth_code_grant.custom_validators.post_token.append(my_token_validator) + """ + + def __init__(self, post_auth, post_token, + pre_auth, pre_token): + self.pre_auth = pre_auth + self.post_auth = post_auth + self.pre_token = pre_token + self.post_token = post_token + + @property + def all_pre(self): + return chain(self.pre_auth, self.pre_token) + + @property + def all_post(self): + return chain(self.post_auth, self.post_token) + + +class GrantTypeBase: + error_uri = None + request_validator = None + default_response_mode = 'fragment' + refresh_token = True + response_types = ['code'] + + def __init__(self, request_validator=None, **kwargs): + self.request_validator = request_validator or RequestValidator() + + # Transforms class variables into instance variables: + self.response_types = self.response_types + self.refresh_token = self.refresh_token + self._setup_custom_validators(kwargs) + self._code_modifiers = [] + self._token_modifiers = [] + + for kw, val in kwargs.items(): + setattr(self, kw, val) + + def _setup_custom_validators(self, kwargs): + post_auth = kwargs.get('post_auth', []) + post_token = kwargs.get('post_token', []) + pre_auth = kwargs.get('pre_auth', []) + pre_token = kwargs.get('pre_token', []) + if not hasattr(self, 'validate_authorization_request'): + if post_auth or pre_auth: + msg = ("{} does not support authorization validators. Use " + "token validators instead.").format(self.__class__.__name__) + raise ValueError(msg) + # Using tuples here because they can't be appended to: + post_auth, pre_auth = (), () + self.custom_validators = ValidatorsContainer(post_auth, post_token, + pre_auth, pre_token) + + def register_response_type(self, response_type): + self.response_types.append(response_type) + + def register_code_modifier(self, modifier): + self._code_modifiers.append(modifier) + + def register_token_modifier(self, modifier): + self._token_modifiers.append(modifier) + + def create_authorization_response(self, request, token_handler): + """ + :param request: OAuthlib request. + :type request: oauthlib.common.Request + :param token_handler: A token handler instance, for example of type + oauthlib.oauth2.BearerToken. + """ + raise NotImplementedError('Subclasses must implement this method.') + + def create_token_response(self, request, token_handler): + """ + :param request: OAuthlib request. + :type request: oauthlib.common.Request + :param token_handler: A token handler instance, for example of type + oauthlib.oauth2.BearerToken. + """ + raise NotImplementedError('Subclasses must implement this method.') + + def add_token(self, token, token_handler, request): + """ + :param token: + :param token_handler: A token handler instance, for example of type + oauthlib.oauth2.BearerToken. + :param request: OAuthlib request. + :type request: oauthlib.common.Request + """ + # Only add a hybrid access token on auth step if asked for + if request.response_type not in ["token", "code token", "id_token token", "code id_token token"]: + return token + + token.update(token_handler.create_token(request, refresh_token=False)) + return token + + def validate_grant_type(self, request): + """ + :param request: OAuthlib request. + :type request: oauthlib.common.Request + """ + client_id = getattr(request, 'client_id', None) + if not self.request_validator.validate_grant_type(client_id, + request.grant_type, request.client, request): + log.debug('Unauthorized from %r (%r) access to grant type %s.', + request.client_id, request.client, request.grant_type) + raise errors.UnauthorizedClientError(request=request) + + def validate_scopes(self, request): + """ + :param request: OAuthlib request. + :type request: oauthlib.common.Request + """ + if not request.scopes: + request.scopes = utils.scope_to_list(request.scope) or utils.scope_to_list( + self.request_validator.get_default_scopes(request.client_id, request)) + log.debug('Validating access to scopes %r for client %r (%r).', + request.scopes, request.client_id, request.client) + if not self.request_validator.validate_scopes(request.client_id, + request.scopes, request.client, request): + raise errors.InvalidScopeError(request=request) + + def prepare_authorization_response(self, request, token, headers, body, status): + """Place token according to response mode. + + Base classes can define a default response mode for their authorization + response by overriding the static `default_response_mode` member. + + :param request: OAuthlib request. + :type request: oauthlib.common.Request + :param token: + :param headers: + :param body: + :param status: + """ + request.response_mode = request.response_mode or self.default_response_mode + + if request.response_mode not in ('query', 'fragment'): + log.debug('Overriding invalid response mode %s with %s', + request.response_mode, self.default_response_mode) + request.response_mode = self.default_response_mode + + token_items = token.items() + + if request.response_type == 'none': + state = token.get('state', None) + token_items = [('state', state)] if state else [] + + if request.response_mode == 'query': + headers['Location'] = add_params_to_uri( + request.redirect_uri, token_items, fragment=False) + return headers, body, status + + if request.response_mode == 'fragment': + headers['Location'] = add_params_to_uri( + request.redirect_uri, token_items, fragment=True) + return headers, body, status + + raise NotImplementedError( + 'Subclasses must set a valid default_response_mode') + + def _get_default_headers(self): + """Create default headers for grant responses.""" + return { + 'Content-Type': 'application/json', + 'Cache-Control': 'no-store', + 'Pragma': 'no-cache', + } + + def _handle_redirects(self, request): + if request.redirect_uri is not None: + request.using_default_redirect_uri = False + log.debug('Using provided redirect_uri %s', request.redirect_uri) + if not is_absolute_uri(request.redirect_uri): + raise errors.InvalidRedirectURIError(request=request) + + # The authorization server MUST verify that the redirection URI + # to which it will redirect the access token matches a + # redirection URI registered by the client as described in + # Section 3.1.2. + # https://tools.ietf.org/html/rfc6749#section-3.1.2 + if not self.request_validator.validate_redirect_uri( + request.client_id, request.redirect_uri, request): + raise errors.MismatchingRedirectURIError(request=request) + else: + request.redirect_uri = self.request_validator.get_default_redirect_uri( + request.client_id, request) + request.using_default_redirect_uri = True + log.debug('Using default redirect_uri %s.', request.redirect_uri) + if not request.redirect_uri: + raise errors.MissingRedirectURIError(request=request) + if not is_absolute_uri(request.redirect_uri): + raise errors.InvalidRedirectURIError(request=request) + + def _create_cors_headers(self, request): + """If CORS is allowed, create the appropriate headers.""" + if 'origin' not in request.headers: + return {} + + origin = request.headers['origin'] + if not is_secure_transport(origin): + log.debug('Origin "%s" is not HTTPS, CORS not allowed.', origin) + return {} + elif not self.request_validator.is_origin_allowed( + request.client_id, origin, request): + log.debug('Invalid origin "%s", CORS not allowed.', origin) + return {} + else: + log.debug('Valid origin "%s", injecting CORS headers.', origin) + return {'Access-Control-Allow-Origin': origin} diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/grant_types/client_credentials.py b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/grant_types/client_credentials.py new file mode 100644 index 0000000000000000000000000000000000000000..35c544027ec8b89cd7a5d092e293869de8dd91a5 --- /dev/null +++ b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/grant_types/client_credentials.py @@ -0,0 +1,122 @@ +""" +oauthlib.oauth2.rfc6749.grant_types +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +""" +import json +import logging + +from .. import errors +from .base import GrantTypeBase + +log = logging.getLogger(__name__) + + +class ClientCredentialsGrant(GrantTypeBase): + + """`Client Credentials Grant`_ + + The client can request an access token using only its client + credentials (or other supported means of authentication) when the + client is requesting access to the protected resources under its + control, or those of another resource owner that have been previously + arranged with the authorization server (the method of which is beyond + the scope of this specification). + + The client credentials grant type MUST only be used by confidential + clients:: + + +---------+ +---------------+ + : : : : + : :>-- A - Client Authentication --->: Authorization : + : Client : : Server : + : :<-- B ---- Access Token ---------<: : + : : : : + +---------+ +---------------+ + + Figure 6: Client Credentials Flow + + The flow illustrated in Figure 6 includes the following steps: + + (A) The client authenticates with the authorization server and + requests an access token from the token endpoint. + + (B) The authorization server authenticates the client, and if valid, + issues an access token. + + .. _`Client Credentials Grant`: https://tools.ietf.org/html/rfc6749#section-4.4 + """ + + def create_token_response(self, request, token_handler): + """Return token or error in JSON format. + + :param request: OAuthlib request. + :type request: oauthlib.common.Request + :param token_handler: A token handler instance, for example of type + oauthlib.oauth2.BearerToken. + + If the access token request is valid and authorized, the + authorization server issues an access token as described in + `Section 5.1`_. A refresh token SHOULD NOT be included. If the request + failed client authentication or is invalid, the authorization server + returns an error response as described in `Section 5.2`_. + + .. _`Section 5.1`: https://tools.ietf.org/html/rfc6749#section-5.1 + .. _`Section 5.2`: https://tools.ietf.org/html/rfc6749#section-5.2 + """ + headers = self._get_default_headers() + try: + log.debug('Validating access token request, %r.', request) + self.validate_token_request(request) + except errors.OAuth2Error as e: + log.debug('Client error in token request. %s.', e) + headers.update(e.headers) + return headers, e.json, e.status_code + + token = token_handler.create_token(request, refresh_token=False) + + for modifier in self._token_modifiers: + token = modifier(token) + + self.request_validator.save_token(token, request) + + log.debug('Issuing token to client id %r (%r), %r.', + request.client_id, request.client, token) + return headers, json.dumps(token), 200 + + def validate_token_request(self, request): + """ + :param request: OAuthlib request. + :type request: oauthlib.common.Request + """ + for validator in self.custom_validators.pre_token: + validator(request) + + if not getattr(request, 'grant_type', None): + raise errors.InvalidRequestError('Request is missing grant type.', + request=request) + + if not request.grant_type == 'client_credentials': + raise errors.UnsupportedGrantTypeError(request=request) + + for param in ('grant_type', 'scope'): + if param in request.duplicate_params: + raise errors.InvalidRequestError(description='Duplicate %s parameter.' % param, + request=request) + + log.debug('Authenticating client, %r.', request) + if not self.request_validator.authenticate_client(request): + log.debug('Client authentication failed, %r.', request) + raise errors.InvalidClientError(request=request) + elif not hasattr(request.client, 'client_id'): + raise NotImplementedError('Authenticate client must set the ' + 'request.client.client_id attribute ' + 'in authenticate_client.') + # Ensure client is authorized use of this grant type + self.validate_grant_type(request) + + request.client_id = request.client_id or request.client.client_id + log.debug('Authorizing access to client %r.', request.client_id) + self.validate_scopes(request) + + for validator in self.custom_validators.post_token: + validator(request) diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/grant_types/implicit.py b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/grant_types/implicit.py new file mode 100644 index 0000000000000000000000000000000000000000..cd3bfeb643b1e8e77a04804ef7d3809e07355420 --- /dev/null +++ b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/grant_types/implicit.py @@ -0,0 +1,373 @@ +""" +oauthlib.oauth2.rfc6749.grant_types +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +""" +import logging + +from oauthlib import common + +from .. import errors +from .base import GrantTypeBase + +log = logging.getLogger(__name__) + + +class ImplicitGrant(GrantTypeBase): + + """`Implicit Grant`_ + + The implicit grant type is used to obtain access tokens (it does not + support the issuance of refresh tokens) and is optimized for public + clients known to operate a particular redirection URI. These clients + are typically implemented in a browser using a scripting language + such as JavaScript. + + Unlike the authorization code grant type, in which the client makes + separate requests for authorization and for an access token, the + client receives the access token as the result of the authorization + request. + + The implicit grant type does not include client authentication, and + relies on the presence of the resource owner and the registration of + the redirection URI. Because the access token is encoded into the + redirection URI, it may be exposed to the resource owner and other + applications residing on the same device:: + + +----------+ + | Resource | + | Owner | + | | + +----------+ + ^ + | + (B) + +----|-----+ Client Identifier +---------------+ + | -+----(A)-- & Redirection URI --->| | + | User- | | Authorization | + | Agent -|----(B)-- User authenticates -->| Server | + | | | | + | |<---(C)--- Redirection URI ----<| | + | | with Access Token +---------------+ + | | in Fragment + | | +---------------+ + | |----(D)--- Redirection URI ---->| Web-Hosted | + | | without Fragment | Client | + | | | Resource | + | (F) |<---(E)------- Script ---------<| | + | | +---------------+ + +-|--------+ + | | + (A) (G) Access Token + | | + ^ v + +---------+ + | | + | Client | + | | + +---------+ + + Note: The lines illustrating steps (A) and (B) are broken into two + parts as they pass through the user-agent. + + Figure 4: Implicit Grant Flow + + The flow illustrated in Figure 4 includes the following steps: + + (A) The client initiates the flow by directing the resource owner's + user-agent to the authorization endpoint. The client includes + its client identifier, requested scope, local state, and a + redirection URI to which the authorization server will send the + user-agent back once access is granted (or denied). + + (B) The authorization server authenticates the resource owner (via + the user-agent) and establishes whether the resource owner + grants or denies the client's access request. + + (C) Assuming the resource owner grants access, the authorization + server redirects the user-agent back to the client using the + redirection URI provided earlier. The redirection URI includes + the access token in the URI fragment. + + (D) The user-agent follows the redirection instructions by making a + request to the web-hosted client resource (which does not + include the fragment per [RFC2616]). The user-agent retains the + fragment information locally. + + (E) The web-hosted client resource returns a web page (typically an + HTML document with an embedded script) capable of accessing the + full redirection URI including the fragment retained by the + user-agent, and extracting the access token (and other + parameters) contained in the fragment. + + (F) The user-agent executes the script provided by the web-hosted + client resource locally, which extracts the access token. + + (G) The user-agent passes the access token to the client. + + See `Section 10.3`_ and `Section 10.16`_ for important security considerations + when using the implicit grant. + + .. _`Implicit Grant`: https://tools.ietf.org/html/rfc6749#section-4.2 + .. _`Section 10.3`: https://tools.ietf.org/html/rfc6749#section-10.3 + .. _`Section 10.16`: https://tools.ietf.org/html/rfc6749#section-10.16 + """ + + response_types = ['token'] + grant_allows_refresh_token = False + + def create_authorization_response(self, request, token_handler): + """Create an authorization response. + + :param request: OAuthlib request. + :type request: oauthlib.common.Request + :param token_handler: A token handler instance, for example of type + oauthlib.oauth2.BearerToken. + + The client constructs the request URI by adding the following + parameters to the query component of the authorization endpoint URI + using the "application/x-www-form-urlencoded" format, per `Appendix B`_: + + response_type + REQUIRED. Value MUST be set to "token" for standard OAuth2 implicit flow + or "id_token token" or just "id_token" for OIDC implicit flow + + client_id + REQUIRED. The client identifier as described in `Section 2.2`_. + + redirect_uri + OPTIONAL. As described in `Section 3.1.2`_. + + scope + OPTIONAL. The scope of the access request as described by + `Section 3.3`_. + + state + RECOMMENDED. An opaque value used by the client to maintain + state between the request and callback. The authorization + server includes this value when redirecting the user-agent back + to the client. The parameter SHOULD be used for preventing + cross-site request forgery as described in `Section 10.12`_. + + The authorization server validates the request to ensure that all + required parameters are present and valid. The authorization server + MUST verify that the redirection URI to which it will redirect the + access token matches a redirection URI registered by the client as + described in `Section 3.1.2`_. + + .. _`Section 2.2`: https://tools.ietf.org/html/rfc6749#section-2.2 + .. _`Section 3.1.2`: https://tools.ietf.org/html/rfc6749#section-3.1.2 + .. _`Section 3.3`: https://tools.ietf.org/html/rfc6749#section-3.3 + .. _`Section 10.12`: https://tools.ietf.org/html/rfc6749#section-10.12 + .. _`Appendix B`: https://tools.ietf.org/html/rfc6749#appendix-B + """ + return self.create_token_response(request, token_handler) + + def create_token_response(self, request, token_handler): + """Return token or error embedded in the URI fragment. + + :param request: OAuthlib request. + :type request: oauthlib.common.Request + :param token_handler: A token handler instance, for example of type + oauthlib.oauth2.BearerToken. + + If the resource owner grants the access request, the authorization + server issues an access token and delivers it to the client by adding + the following parameters to the fragment component of the redirection + URI using the "application/x-www-form-urlencoded" format, per + `Appendix B`_: + + access_token + REQUIRED. The access token issued by the authorization server. + + token_type + REQUIRED. The type of the token issued as described in + `Section 7.1`_. Value is case insensitive. + + expires_in + RECOMMENDED. The lifetime in seconds of the access token. For + example, the value "3600" denotes that the access token will + expire in one hour from the time the response was generated. + If omitted, the authorization server SHOULD provide the + expiration time via other means or document the default value. + + scope + OPTIONAL, if identical to the scope requested by the client; + otherwise, REQUIRED. The scope of the access token as + described by `Section 3.3`_. + + state + REQUIRED if the "state" parameter was present in the client + authorization request. The exact value received from the + client. + + The authorization server MUST NOT issue a refresh token. + + .. _`Appendix B`: https://tools.ietf.org/html/rfc6749#appendix-B + .. _`Section 3.3`: https://tools.ietf.org/html/rfc6749#section-3.3 + .. _`Section 7.1`: https://tools.ietf.org/html/rfc6749#section-7.1 + """ + try: + self.validate_token_request(request) + + # If the request fails due to a missing, invalid, or mismatching + # redirection URI, or if the client identifier is missing or invalid, + # the authorization server SHOULD inform the resource owner of the + # error and MUST NOT automatically redirect the user-agent to the + # invalid redirection URI. + except errors.FatalClientError as e: + log.debug('Fatal client error during validation of %r. %r.', + request, e) + raise + + # If the resource owner denies the access request or if the request + # fails for reasons other than a missing or invalid redirection URI, + # the authorization server informs the client by adding the following + # parameters to the fragment component of the redirection URI using the + # "application/x-www-form-urlencoded" format, per Appendix B: + # https://tools.ietf.org/html/rfc6749#appendix-B + except errors.OAuth2Error as e: + log.debug('Client error during validation of %r. %r.', request, e) + return {'Location': common.add_params_to_uri(request.redirect_uri, e.twotuples, + fragment=True)}, None, 302 + + # In OIDC implicit flow it is possible to have a request_type that does not include the access_token! + # "id_token token" - return the access token and the id token + # "id_token" - don't return the access token + token = token_handler.create_token(request, refresh_token=False) if 'token' in request.response_type.split() else {} + + if request.state is not None: + token['state'] = request.state + + for modifier in self._token_modifiers: + token = modifier(token, token_handler, request) + + # In OIDC implicit flow it is possible to have a request_type that does + # not include the access_token! In this case there is no need to save a token. + if "token" in request.response_type.split(): + self.request_validator.save_token(token, request) + + return self.prepare_authorization_response( + request, token, {}, None, 302) + + def validate_authorization_request(self, request): + """ + :param request: OAuthlib request. + :type request: oauthlib.common.Request + """ + return self.validate_token_request(request) + + def validate_token_request(self, request): + """Check the token request for normal and fatal errors. + + :param request: OAuthlib request. + :type request: oauthlib.common.Request + + This method is very similar to validate_authorization_request in + the AuthorizationCodeGrant but differ in a few subtle areas. + + A normal error could be a missing response_type parameter or the client + attempting to access scope it is not allowed to ask authorization for. + Normal errors can safely be included in the redirection URI and + sent back to the client. + + Fatal errors occur when the client_id or redirect_uri is invalid or + missing. These must be caught by the provider and handled, how this + is done is outside of the scope of OAuthLib but showing an error + page describing the issue is a good idea. + """ + + # First check for fatal errors + + # If the request fails due to a missing, invalid, or mismatching + # redirection URI, or if the client identifier is missing or invalid, + # the authorization server SHOULD inform the resource owner of the + # error and MUST NOT automatically redirect the user-agent to the + # invalid redirection URI. + + # First check duplicate parameters + for param in ('client_id', 'response_type', 'redirect_uri', 'scope', 'state'): + try: + duplicate_params = request.duplicate_params + except ValueError: + raise errors.InvalidRequestFatalError(description='Unable to parse query string', request=request) + if param in duplicate_params: + raise errors.InvalidRequestFatalError(description='Duplicate %s parameter.' % param, request=request) + + # REQUIRED. The client identifier as described in Section 2.2. + # https://tools.ietf.org/html/rfc6749#section-2.2 + if not request.client_id: + raise errors.MissingClientIdError(request=request) + + if not self.request_validator.validate_client_id(request.client_id, request): + raise errors.InvalidClientIdError(request=request) + + # OPTIONAL. As described in Section 3.1.2. + # https://tools.ietf.org/html/rfc6749#section-3.1.2 + self._handle_redirects(request) + + # Then check for normal errors. + + request_info = self._run_custom_validators(request, + self.custom_validators.all_pre) + + # If the resource owner denies the access request or if the request + # fails for reasons other than a missing or invalid redirection URI, + # the authorization server informs the client by adding the following + # parameters to the fragment component of the redirection URI using the + # "application/x-www-form-urlencoded" format, per Appendix B. + # https://tools.ietf.org/html/rfc6749#appendix-B + + # Note that the correct parameters to be added are automatically + # populated through the use of specific exceptions + + # REQUIRED. + if request.response_type is None: + raise errors.MissingResponseTypeError(request=request) + # Value MUST be one of our registered types: "token" by default or if using OIDC "id_token" or "id_token token" + elif not set(request.response_type.split()).issubset(self.response_types): + raise errors.UnsupportedResponseTypeError(request=request) + + log.debug('Validating use of response_type token for client %r (%r).', + request.client_id, request.client) + if not self.request_validator.validate_response_type(request.client_id, + request.response_type, + request.client, request): + + log.debug('Client %s is not authorized to use response_type %s.', + request.client_id, request.response_type) + raise errors.UnauthorizedClientError(request=request) + + # OPTIONAL. The scope of the access request as described by Section 3.3 + # https://tools.ietf.org/html/rfc6749#section-3.3 + self.validate_scopes(request) + + request_info.update({ + 'client_id': request.client_id, + 'redirect_uri': request.redirect_uri, + 'response_type': request.response_type, + 'state': request.state, + 'request': request, + }) + + request_info = self._run_custom_validators( + request, + self.custom_validators.all_post, + request_info + ) + + return request.scopes, request_info + + def _run_custom_validators(self, + request, + validations, + request_info=None): + # Make a copy so we don't modify the existing request_info dict + request_info = {} if request_info is None else request_info.copy() + # For implicit grant, auth_validators and token_validators are + # basically equivalent since the token is returned from the + # authorization endpoint. + for validator in validations: + result = validator(request) + if result is not None: + request_info.update(result) + return request_info diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/grant_types/refresh_token.py b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/grant_types/refresh_token.py new file mode 100644 index 0000000000000000000000000000000000000000..43bf55ac908a7fe93ceff81b10c93a4418d8851c --- /dev/null +++ b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/grant_types/refresh_token.py @@ -0,0 +1,139 @@ +""" +oauthlib.oauth2.rfc6749.grant_types +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +""" +import json +import logging + +from .. import errors, utils +from .base import GrantTypeBase + +log = logging.getLogger(__name__) + + +class RefreshTokenGrant(GrantTypeBase): + + """`Refresh token grant`_ + + .. _`Refresh token grant`: https://tools.ietf.org/html/rfc6749#section-6 + """ + + def __init__(self, request_validator=None, + issue_new_refresh_tokens=True, + **kwargs): + super().__init__( + request_validator, + issue_new_refresh_tokens=issue_new_refresh_tokens, + **kwargs) + + def create_token_response(self, request, token_handler): + """Create a new access token from a refresh_token. + + :param request: OAuthlib request. + :type request: oauthlib.common.Request + :param token_handler: A token handler instance, for example of type + oauthlib.oauth2.BearerToken. + + If valid and authorized, the authorization server issues an access + token as described in `Section 5.1`_. If the request failed + verification or is invalid, the authorization server returns an error + response as described in `Section 5.2`_. + + The authorization server MAY issue a new refresh token, in which case + the client MUST discard the old refresh token and replace it with the + new refresh token. The authorization server MAY revoke the old + refresh token after issuing a new refresh token to the client. If a + new refresh token is issued, the refresh token scope MUST be + identical to that of the refresh token included by the client in the + request. + + .. _`Section 5.1`: https://tools.ietf.org/html/rfc6749#section-5.1 + .. _`Section 5.2`: https://tools.ietf.org/html/rfc6749#section-5.2 + """ + headers = self._get_default_headers() + try: + log.debug('Validating refresh token request, %r.', request) + self.validate_token_request(request) + except errors.OAuth2Error as e: + log.debug('Client error in token request, %s.', e) + headers.update(e.headers) + return headers, e.json, e.status_code + + token = token_handler.create_token(request, + refresh_token=self.issue_new_refresh_tokens) + + for modifier in self._token_modifiers: + token = modifier(token, token_handler, request) + + self.request_validator.save_token(token, request) + + log.debug('Issuing new token to client id %r (%r), %r.', + request.client_id, request.client, token) + headers.update(self._create_cors_headers(request)) + return headers, json.dumps(token), 200 + + def validate_token_request(self, request): + """ + :param request: OAuthlib request. + :type request: oauthlib.common.Request + """ + # REQUIRED. Value MUST be set to "refresh_token". + if request.grant_type != 'refresh_token': + raise errors.UnsupportedGrantTypeError(request=request) + + for validator in self.custom_validators.pre_token: + validator(request) + + if request.refresh_token is None: + raise errors.InvalidRequestError( + description='Missing refresh token parameter.', + request=request) + + # Because refresh tokens are typically long-lasting credentials used to + # request additional access tokens, the refresh token is bound to the + # client to which it was issued. If the client type is confidential or + # the client was issued client credentials (or assigned other + # authentication requirements), the client MUST authenticate with the + # authorization server as described in Section 3.2.1. + # https://tools.ietf.org/html/rfc6749#section-3.2.1 + if self.request_validator.client_authentication_required(request): + log.debug('Authenticating client, %r.', request) + if not self.request_validator.authenticate_client(request): + log.debug('Invalid client (%r), denying access.', request) + raise errors.InvalidClientError(request=request) + # Ensure that request.client_id is set. + if request.client_id is None and request.client is not None: + request.client_id = request.client.client_id + elif not self.request_validator.authenticate_client_id(request.client_id, request): + log.debug('Client authentication failed, %r.', request) + raise errors.InvalidClientError(request=request) + + # Ensure client is authorized use of this grant type + self.validate_grant_type(request) + + # REQUIRED. The refresh token issued to the client. + log.debug('Validating refresh token %s for client %r.', + request.refresh_token, request.client) + if not self.request_validator.validate_refresh_token( + request.refresh_token, request.client, request): + log.debug('Invalid refresh token, %s, for client %r.', + request.refresh_token, request.client) + raise errors.InvalidGrantError(request=request) + + original_scopes = utils.scope_to_list( + self.request_validator.get_original_scopes( + request.refresh_token, request)) + + if request.scope: + request.scopes = utils.scope_to_list(request.scope) + if (not all(s in original_scopes for s in request.scopes) + and not self.request_validator.is_within_original_scope( + request.scopes, request.refresh_token, request)): + log.debug('Refresh token %s lack requested scopes, %r.', + request.refresh_token, request.scopes) + raise errors.InvalidScopeError(request=request) + else: + request.scopes = original_scopes + + for validator in self.custom_validators.post_token: + validator(request) diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/grant_types/resource_owner_password_credentials.py b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/grant_types/resource_owner_password_credentials.py new file mode 100644 index 0000000000000000000000000000000000000000..55d928709a3b80a4a3af7b95a5854a78d312af2a --- /dev/null +++ b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/grant_types/resource_owner_password_credentials.py @@ -0,0 +1,198 @@ +""" +oauthlib.oauth2.rfc6749.grant_types +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +""" +import json +import logging + +from .. import errors +from .base import GrantTypeBase + +log = logging.getLogger(__name__) + + +class ResourceOwnerPasswordCredentialsGrant(GrantTypeBase): + + """`Resource Owner Password Credentials Grant`_ + + The resource owner password credentials grant type is suitable in + cases where the resource owner has a trust relationship with the + client, such as the device operating system or a highly privileged + application. The authorization server should take special care when + enabling this grant type and only allow it when other flows are not + viable. + + This grant type is suitable for clients capable of obtaining the + resource owner's credentials (username and password, typically using + an interactive form). It is also used to migrate existing clients + using direct authentication schemes such as HTTP Basic or Digest + authentication to OAuth by converting the stored credentials to an + access token:: + + +----------+ + | Resource | + | Owner | + | | + +----------+ + v + | Resource Owner + (A) Password Credentials + | + v + +---------+ +---------------+ + | |>--(B)---- Resource Owner ------->| | + | | Password Credentials | Authorization | + | Client | | Server | + | |<--(C)---- Access Token ---------<| | + | | (w/ Optional Refresh Token) | | + +---------+ +---------------+ + + Figure 5: Resource Owner Password Credentials Flow + + The flow illustrated in Figure 5 includes the following steps: + + (A) The resource owner provides the client with its username and + password. + + (B) The client requests an access token from the authorization + server's token endpoint by including the credentials received + from the resource owner. When making the request, the client + authenticates with the authorization server. + + (C) The authorization server authenticates the client and validates + the resource owner credentials, and if valid, issues an access + token. + + .. _`Resource Owner Password Credentials Grant`: https://tools.ietf.org/html/rfc6749#section-4.3 + """ + + def create_token_response(self, request, token_handler): + """Return token or error in json format. + + :param request: OAuthlib request. + :type request: oauthlib.common.Request + :param token_handler: A token handler instance, for example of type + oauthlib.oauth2.BearerToken. + + If the access token request is valid and authorized, the + authorization server issues an access token and optional refresh + token as described in `Section 5.1`_. If the request failed client + authentication or is invalid, the authorization server returns an + error response as described in `Section 5.2`_. + + .. _`Section 5.1`: https://tools.ietf.org/html/rfc6749#section-5.1 + .. _`Section 5.2`: https://tools.ietf.org/html/rfc6749#section-5.2 + """ + headers = self._get_default_headers() + try: + if self.request_validator.client_authentication_required(request): + log.debug('Authenticating client, %r.', request) + if not self.request_validator.authenticate_client(request): + log.debug('Client authentication failed, %r.', request) + raise errors.InvalidClientError(request=request) + elif not self.request_validator.authenticate_client_id(request.client_id, request): + log.debug('Client authentication failed, %r.', request) + raise errors.InvalidClientError(request=request) + log.debug('Validating access token request, %r.', request) + self.validate_token_request(request) + except errors.OAuth2Error as e: + log.debug('Client error in token request, %s.', e) + headers.update(e.headers) + return headers, e.json, e.status_code + + token = token_handler.create_token(request, self.refresh_token) + + for modifier in self._token_modifiers: + token = modifier(token) + + self.request_validator.save_token(token, request) + + log.debug('Issuing token %r to client id %r (%r) and username %s.', + token, request.client_id, request.client, request.username) + return headers, json.dumps(token), 200 + + def validate_token_request(self, request): + """ + :param request: OAuthlib request. + :type request: oauthlib.common.Request + + The client makes a request to the token endpoint by adding the + following parameters using the "application/x-www-form-urlencoded" + format per Appendix B with a character encoding of UTF-8 in the HTTP + request entity-body: + + grant_type + REQUIRED. Value MUST be set to "password". + + username + REQUIRED. The resource owner username. + + password + REQUIRED. The resource owner password. + + scope + OPTIONAL. The scope of the access request as described by + `Section 3.3`_. + + If the client type is confidential or the client was issued client + credentials (or assigned other authentication requirements), the + client MUST authenticate with the authorization server as described + in `Section 3.2.1`_. + + The authorization server MUST: + + o require client authentication for confidential clients or for any + client that was issued client credentials (or with other + authentication requirements), + + o authenticate the client if client authentication is included, and + + o validate the resource owner password credentials using its + existing password validation algorithm. + + Since this access token request utilizes the resource owner's + password, the authorization server MUST protect the endpoint against + brute force attacks (e.g., using rate-limitation or generating + alerts). + + .. _`Section 3.3`: https://tools.ietf.org/html/rfc6749#section-3.3 + .. _`Section 3.2.1`: https://tools.ietf.org/html/rfc6749#section-3.2.1 + """ + for validator in self.custom_validators.pre_token: + validator(request) + + for param in ('grant_type', 'username', 'password'): + if not getattr(request, param, None): + raise errors.InvalidRequestError( + 'Request is missing %s parameter.' % param, request=request) + + for param in ('grant_type', 'username', 'password', 'scope'): + if param in request.duplicate_params: + raise errors.InvalidRequestError(description='Duplicate %s parameter.' % param, request=request) + + # This error should rarely (if ever) occur if requests are routed to + # grant type handlers based on the grant_type parameter. + if not request.grant_type == 'password': + raise errors.UnsupportedGrantTypeError(request=request) + + log.debug('Validating username %s.', request.username) + if not self.request_validator.validate_user(request.username, + request.password, request.client, request): + raise errors.InvalidGrantError( + 'Invalid credentials given.', request=request) + elif not hasattr(request.client, 'client_id'): + raise NotImplementedError( + 'Validate user must set the ' + 'request.client.client_id attribute ' + 'in authenticate_client.') + log.debug('Authorizing access to user %r.', request.user) + + # Ensure client is authorized use of this grant type + self.validate_grant_type(request) + + if request.client: + request.client_id = request.client_id or request.client.client_id + self.validate_scopes(request) + + for validator in self.custom_validators.post_token: + validator(request) diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/parameters.py b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/parameters.py new file mode 100644 index 0000000000000000000000000000000000000000..8268ef927cc2d174f44a00e60cf07156fb223db7 --- /dev/null +++ b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/parameters.py @@ -0,0 +1,528 @@ +""" +oauthlib.oauth2.rfc6749.parameters +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +This module contains methods related to `Section 4`_ of the OAuth 2 RFC. + +.. _`Section 4`: https://tools.ietf.org/html/rfc6749#section-4 +""" +import json +import os +import time +import urllib.parse as urlparse + +from oauthlib.common import add_params_to_qs, add_params_to_uri +from oauthlib.signals import scope_changed + +from .errors import ( + InsecureTransportError, MismatchingStateError, MissingCodeError, + MissingTokenError, MissingTokenTypeError, raise_from_error, +) +from .tokens import OAuth2Token +from .utils import is_secure_transport, list_to_scope, scope_to_list + + +def prepare_grant_uri(uri, client_id, response_type, redirect_uri=None, + scope=None, state=None, code_challenge=None, code_challenge_method='plain', **kwargs): + """Prepare the authorization grant request URI. + + The client constructs the request URI by adding the following + parameters to the query component of the authorization endpoint URI + using the ``application/x-www-form-urlencoded`` format as defined by + [`W3C.REC-html401-19991224`_]: + + :param uri: + :param client_id: The client identifier as described in `Section 2.2`_. + :param response_type: To indicate which OAuth 2 grant/flow is required, + "code" and "token". + :param redirect_uri: The client provided URI to redirect back to after + authorization as described in `Section 3.1.2`_. + :param scope: The scope of the access request as described by + `Section 3.3`_. + :param state: An opaque value used by the client to maintain + state between the request and callback. The authorization + server includes this value when redirecting the user-agent + back to the client. The parameter SHOULD be used for + preventing cross-site request forgery as described in + `Section 10.12`_. + :param code_challenge: PKCE parameter. A challenge derived from the + code_verifier that is sent in the authorization + request, to be verified against later. + :param code_challenge_method: PKCE parameter. A method that was used to derive the + code_challenge. Defaults to "plain" if not present in the request. + :param kwargs: Extra arguments to embed in the grant/authorization URL. + + An example of an authorization code grant authorization URL: + + .. code-block:: http + + GET /authorize?response_type=code&client_id=s6BhdRkqt3&state=xyz + &code_challenge=kjasBS523KdkAILD2k78NdcJSk2k3KHG6&code_challenge_method=S256 + &redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb HTTP/1.1 + Host: server.example.com + + .. _`W3C.REC-html401-19991224`: https://tools.ietf.org/html/rfc6749#ref-W3C.REC-html401-19991224 + .. _`Section 2.2`: https://tools.ietf.org/html/rfc6749#section-2.2 + .. _`Section 3.1.2`: https://tools.ietf.org/html/rfc6749#section-3.1.2 + .. _`Section 3.3`: https://tools.ietf.org/html/rfc6749#section-3.3 + .. _`section 10.12`: https://tools.ietf.org/html/rfc6749#section-10.12 + """ + if not is_secure_transport(uri): + raise InsecureTransportError() + + params = [(('response_type', response_type)), + (('client_id', client_id))] + + if redirect_uri: + params.append(('redirect_uri', redirect_uri)) + if scope: + params.append(('scope', list_to_scope(scope))) + if state: + params.append(('state', state)) + if code_challenge is not None: + params.append(('code_challenge', code_challenge)) + params.append(('code_challenge_method', code_challenge_method)) + + for k in kwargs: + if kwargs[k]: + params.append((str(k), kwargs[k])) + + return add_params_to_uri(uri, params) + + +def prepare_token_request(grant_type, body='', include_client_id=True, code_verifier=None, **kwargs): + """Prepare the access token request. + + The client makes a request to the token endpoint by adding the + following parameters using the ``application/x-www-form-urlencoded`` + format in the HTTP request entity-body: + + :param grant_type: To indicate grant type being used, i.e. "password", + "authorization_code" or "client_credentials". + + :param body: Existing request body (URL encoded string) to embed parameters + into. This may contain extra parameters. Default ''. + + :param include_client_id: `True` (default) to send the `client_id` in the + body of the upstream request. This is required + if the client is not authenticating with the + authorization server as described in + `Section 3.2.1`_. + :type include_client_id: Boolean + + :param client_id: Unicode client identifier. Will only appear if + `include_client_id` is True. * + + :param client_secret: Unicode client secret. Will only appear if set to a + value that is not `None`. Invoking this function with + an empty string will send an empty `client_secret` + value to the server. * + + :param code: If using authorization_code grant, pass the previously + obtained authorization code as the ``code`` argument. * + + :param redirect_uri: If the "redirect_uri" parameter was included in the + authorization request as described in + `Section 4.1.1`_, and their values MUST be identical. * + + :param code_verifier: PKCE parameter. A cryptographically random string that is used to correlate the + authorization request to the token request. + + :param kwargs: Extra arguments to embed in the request body. + + Parameters marked with a `*` above are not explicit arguments in the + function signature, but are specially documented arguments for items + appearing in the generic `**kwargs` keyworded input. + + An example of an authorization code token request body: + + .. code-block:: http + + grant_type=authorization_code&code=SplxlOBeZQQYbYS6WxSbIA + &redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb + + .. _`Section 4.1.1`: https://tools.ietf.org/html/rfc6749#section-4.1.1 + """ + params = [('grant_type', grant_type)] + + if 'scope' in kwargs: + kwargs['scope'] = list_to_scope(kwargs['scope']) + + # pull the `client_id` out of the kwargs. + client_id = kwargs.pop('client_id', None) + if include_client_id and client_id is not None: + params.append(('client_id', client_id)) + + # use code_verifier if code_challenge was passed in the authorization request + if code_verifier is not None: + params.append(('code_verifier', code_verifier)) + + # the kwargs iteration below only supports including boolean truth (truthy) + # values, but some servers may require an empty string for `client_secret` + client_secret = kwargs.pop('client_secret', None) + if client_secret is not None: + params.append(('client_secret', client_secret)) + + # this handles: `code`, `redirect_uri`, and other undocumented params + for k in kwargs: + if kwargs[k]: + params.append((str(k), kwargs[k])) + + return add_params_to_qs(body, params) + + +def prepare_token_revocation_request(url, token, token_type_hint="access_token", + callback=None, body='', **kwargs): + """Prepare a token revocation request. + + The client constructs the request by including the following parameters + using the ``application/x-www-form-urlencoded`` format in the HTTP request + entity-body: + + :param token: REQUIRED. The token that the client wants to get revoked. + + :param token_type_hint: OPTIONAL. A hint about the type of the token + submitted for revocation. Clients MAY pass this + parameter in order to help the authorization server + to optimize the token lookup. If the server is + unable to locate the token using the given hint, it + MUST extend its search across all of its supported + token types. An authorization server MAY ignore + this parameter, particularly if it is able to detect + the token type automatically. + + This specification defines two values for `token_type_hint`: + + * access_token: An access token as defined in [RFC6749], + `Section 1.4`_ + + * refresh_token: A refresh token as defined in [RFC6749], + `Section 1.5`_ + + Specific implementations, profiles, and extensions of this + specification MAY define other values for this parameter using the + registry defined in `Section 4.1.2`_. + + .. _`Section 1.4`: https://tools.ietf.org/html/rfc6749#section-1.4 + .. _`Section 1.5`: https://tools.ietf.org/html/rfc6749#section-1.5 + .. _`Section 4.1.2`: https://tools.ietf.org/html/rfc7009#section-4.1.2 + + """ + if not is_secure_transport(url): + raise InsecureTransportError() + + params = [('token', token)] + + if token_type_hint: + params.append(('token_type_hint', token_type_hint)) + + for k in kwargs: + if kwargs[k]: + params.append((str(k), kwargs[k])) + + headers = {'Content-Type': 'application/x-www-form-urlencoded'} + + if callback: + params.append(('callback', callback)) + return add_params_to_uri(url, params), headers, body + else: + return url, headers, add_params_to_qs(body, params) + + +def parse_authorization_code_response(uri, state=None): + """Parse authorization grant response URI into a dict. + + If the resource owner grants the access request, the authorization + server issues an authorization code and delivers it to the client by + adding the following parameters to the query component of the + redirection URI using the ``application/x-www-form-urlencoded`` format: + + **code** + REQUIRED. The authorization code generated by the + authorization server. The authorization code MUST expire + shortly after it is issued to mitigate the risk of leaks. A + maximum authorization code lifetime of 10 minutes is + RECOMMENDED. The client MUST NOT use the authorization code + more than once. If an authorization code is used more than + once, the authorization server MUST deny the request and SHOULD + revoke (when possible) all tokens previously issued based on + that authorization code. The authorization code is bound to + the client identifier and redirection URI. + + **state** + REQUIRED if the "state" parameter was present in the client + authorization request. The exact value received from the + client. + + :param uri: The full redirect URL back to the client. + :param state: The state parameter from the authorization request. + + For example, the authorization server redirects the user-agent by + sending the following HTTP response: + + .. code-block:: http + + HTTP/1.1 302 Found + Location: https://client.example.com/cb?code=SplxlOBeZQQYbYS6WxSbIA + &state=xyz + + """ + if not is_secure_transport(uri): + raise InsecureTransportError() + + query = urlparse.urlparse(uri).query + params = dict(urlparse.parse_qsl(query)) + + if state and params.get('state') != state: + raise MismatchingStateError() + + if 'error' in params: + raise_from_error(params.get('error'), params) + + if 'code' not in params: + raise MissingCodeError("Missing code parameter in response.") + + return params + + +def parse_implicit_response(uri, state=None, scope=None): + """Parse the implicit token response URI into a dict. + + If the resource owner grants the access request, the authorization + server issues an access token and delivers it to the client by adding + the following parameters to the fragment component of the redirection + URI using the ``application/x-www-form-urlencoded`` format: + + **access_token** + REQUIRED. The access token issued by the authorization server. + + **token_type** + REQUIRED. The type of the token issued as described in + Section 7.1. Value is case insensitive. + + **expires_in** + RECOMMENDED. The lifetime in seconds of the access token. For + example, the value "3600" denotes that the access token will + expire in one hour from the time the response was generated. + If omitted, the authorization server SHOULD provide the + expiration time via other means or document the default value. + + **scope** + OPTIONAL, if identical to the scope requested by the client, + otherwise REQUIRED. The scope of the access token as described + by Section 3.3. + + **state** + REQUIRED if the "state" parameter was present in the client + authorization request. The exact value received from the + client. + + :param uri: + :param state: + :param scope: + + Similar to the authorization code response, but with a full token provided + in the URL fragment: + + .. code-block:: http + + HTTP/1.1 302 Found + Location: http://example.com/cb#access_token=2YotnFZFEjr1zCsicMWpAA + &state=xyz&token_type=example&expires_in=3600 + """ + if not is_secure_transport(uri): + raise InsecureTransportError() + + fragment = urlparse.urlparse(uri).fragment + params = dict(urlparse.parse_qsl(fragment, keep_blank_values=True)) + + if 'scope' in params: + params['scope'] = scope_to_list(params['scope']) + + vin, vat, v_at = parse_expires(params) + if vin: + params['expires_in'] = vin + elif 'expires_in' in params: + params.pop('expires_in') + if vat: + params['expires_at'] = vat + elif 'expires_at' in params: + params.pop('expires_at') + + if state and params.get('state') != state: + raise ValueError("Mismatching or missing state in params.") + + params = OAuth2Token(params, old_scope=scope) + validate_token_parameters(params) + return params + + +def parse_token_response(body, scope=None): + """Parse the JSON token response body into a dict. + + The authorization server issues an access token and optional refresh + token, and constructs the response by adding the following parameters + to the entity body of the HTTP response with a 200 (OK) status code: + + access_token + REQUIRED. The access token issued by the authorization server. + token_type + REQUIRED. The type of the token issued as described in + `Section 7.1`_. Value is case insensitive. + expires_in + RECOMMENDED. The lifetime in seconds of the access token. For + example, the value "3600" denotes that the access token will + expire in one hour from the time the response was generated. + If omitted, the authorization server SHOULD provide the + expiration time via other means or document the default value. + refresh_token + OPTIONAL. The refresh token which can be used to obtain new + access tokens using the same authorization grant as described + in `Section 6`_. + scope + OPTIONAL, if identical to the scope requested by the client, + otherwise REQUIRED. The scope of the access token as described + by `Section 3.3`_. + + The parameters are included in the entity body of the HTTP response + using the "application/json" media type as defined by [`RFC4627`_]. The + parameters are serialized into a JSON structure by adding each + parameter at the highest structure level. Parameter names and string + values are included as JSON strings. Numerical values are included + as JSON numbers. The order of parameters does not matter and can + vary. + + :param body: The full json encoded response body. + :param scope: The scope requested during authorization. + + For example: + + .. code-block:: http + + HTTP/1.1 200 OK + Content-Type: application/json + Cache-Control: no-store + Pragma: no-cache + + { + "access_token":"2YotnFZFEjr1zCsicMWpAA", + "token_type":"example", + "expires_in":3600, + "refresh_token":"tGzv3JOkF0XG5Qx2TlKWIA", + "example_parameter":"example_value" + } + + .. _`Section 7.1`: https://tools.ietf.org/html/rfc6749#section-7.1 + .. _`Section 6`: https://tools.ietf.org/html/rfc6749#section-6 + .. _`Section 3.3`: https://tools.ietf.org/html/rfc6749#section-3.3 + .. _`RFC4627`: https://tools.ietf.org/html/rfc4627 + """ + try: + params = json.loads(body) + except ValueError: + + # Fall back to URL-encoded string, to support old implementations, + # including (at time of writing) Facebook. See: + # https://github.com/oauthlib/oauthlib/issues/267 + + params = dict(urlparse.parse_qsl(body)) + + if 'scope' in params: + params['scope'] = scope_to_list(params['scope']) + + vin, vat, v_at = parse_expires(params) + if vin: + params['expires_in'] = vin + elif 'expires_in' in params: + params.pop('expires_in') + if vat: + params['expires_at'] = vat + elif 'expires_at' in params: + params.pop('expires_at') + + params = OAuth2Token(params, old_scope=scope) + validate_token_parameters(params) + return params + + +def validate_token_parameters(params): + """Ensures token presence, token type, expiration and scope in params.""" + if 'error' in params: + raise_from_error(params.get('error'), params) + + if 'access_token' not in params: + raise MissingTokenError(description="Missing access token parameter.") + + if 'token_type' not in params and os.environ.get('OAUTHLIB_STRICT_TOKEN_TYPE'): + raise MissingTokenTypeError() + + # If the issued access token scope is different from the one requested by + # the client, the authorization server MUST include the "scope" response + # parameter to inform the client of the actual scope granted. + # https://tools.ietf.org/html/rfc6749#section-3.3 + if params.scope_changed: + message = 'Scope has changed from "{old}" to "{new}".'.format( + old=params.old_scope, new=params.scope, + ) + scope_changed.send(message=message, old=params.old_scopes, new=params.scopes) + if not os.environ.get('OAUTHLIB_RELAX_TOKEN_SCOPE', None): + w = Warning(message) + w.token = params + w.old_scope = params.old_scopes + w.new_scope = params.scopes + raise w + +def parse_expires(params): + """Parse `expires_in`, `expires_at` fields from params + + Parse following these rules: + - `expires_in` must be either integer, float or None. If a float, it is converted into an integer. + - `expires_at` is not in specification so it does its best to: + - convert into a int, else + - convert into a float, else + - reuse the same type as-is (usually string) + - `_expires_at` is a special internal value returned to be always an `int`, based + either on the presence of `expires_at`, or reuse the current time plus + `expires_in`. This is typically used to validate token expiry. + + :param params: Dict with expires_in and expires_at optionally set + :return: Tuple of `expires_in`, `expires_at`, and `_expires_at`. None if not set. + """ + expires_in = None + expires_at = None + _expires_at = None + + if 'expires_in' in params: + if isinstance(params.get('expires_in'), int): + expires_in = params.get('expires_in') + elif isinstance(params.get('expires_in'), float): + expires_in = int(params.get('expires_in')) + elif isinstance(params.get('expires_in'), str): + try: + # Attempt to convert to int + expires_in = int(params.get('expires_in')) + except ValueError: + raise ValueError("expires_in must be an int") + elif params.get('expires_in') is not None: + raise ValueError("expires_in must be an int") + + if 'expires_at' in params: + if isinstance(params.get('expires_at'), (float, int)): + expires_at = params.get('expires_at') + _expires_at = expires_at + elif isinstance(params.get('expires_at'), str): + try: + # Attempt to convert to int first, then float if int fails + expires_at = int(params.get('expires_at')) + _expires_at = expires_at + except ValueError: + try: + expires_at = float(params.get('expires_at')) + _expires_at = expires_at + except ValueError: + # no change from str + expires_at = params.get('expires_at') + if _expires_at is None and expires_in: + expires_at = round(time.time()) + expires_in + _expires_at = expires_at + return expires_in, expires_at, _expires_at diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/request_validator.py b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/request_validator.py new file mode 100644 index 0000000000000000000000000000000000000000..6d6ebaa8e983c72c235dd1a07ff9ee778c864b06 --- /dev/null +++ b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/request_validator.py @@ -0,0 +1,680 @@ +""" +oauthlib.oauth2.rfc6749.request_validator +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +""" +import logging + +log = logging.getLogger(__name__) + + +class RequestValidator: + + def client_authentication_required(self, request, *args, **kwargs): + """Determine if client authentication is required for current request. + + According to the rfc6749, client authentication is required in the following cases: + - Resource Owner Password Credentials Grant, when Client type is Confidential or when + Client was issued client credentials or whenever Client provided client + authentication, see `Section 4.3.2`_. + - Authorization Code Grant, when Client type is Confidential or when Client was issued + client credentials or whenever Client provided client authentication, + see `Section 4.1.3`_. + - Refresh Token Grant, when Client type is Confidential or when Client was issued + client credentials or whenever Client provided client authentication, see + `Section 6`_ + + :param request: OAuthlib request. + :type request: oauthlib.common.Request + :rtype: True or False + + Method is used by: + - Authorization Code Grant + - Resource Owner Password Credentials Grant + - Refresh Token Grant + + .. _`Section 4.3.2`: https://tools.ietf.org/html/rfc6749#section-4.3.2 + .. _`Section 4.1.3`: https://tools.ietf.org/html/rfc6749#section-4.1.3 + .. _`Section 6`: https://tools.ietf.org/html/rfc6749#section-6 + """ + return True + + def authenticate_client(self, request, *args, **kwargs): + """Authenticate client through means outside the OAuth 2 spec. + + Means of authentication is negotiated beforehand and may for example + be `HTTP Basic Authentication Scheme`_ which utilizes the Authorization + header. + + Headers may be accesses through request.headers and parameters found in + both body and query can be obtained by direct attribute access, i.e. + request.client_id for client_id in the URL query. + + The authentication process is required to contain the identification of + the client (i.e. search the database based on the client_id). In case the + client doesn't exist based on the received client_id, this method has to + return False and the HTTP response created by the library will contain + 'invalid_client' message. + + After the client identification succeeds, this method needs to set the + client on the request, i.e. request.client = client. A client object's + class must contain the 'client_id' attribute and the 'client_id' must have + a value. + + :param request: OAuthlib request. + :type request: oauthlib.common.Request + :rtype: True or False + + Method is used by: + - Authorization Code Grant + - Resource Owner Password Credentials Grant (may be disabled) + - Client Credentials Grant + - Refresh Token Grant + + .. _`HTTP Basic Authentication Scheme`: https://tools.ietf.org/html/rfc1945#section-11.1 + """ + raise NotImplementedError('Subclasses must implement this method.') + + def authenticate_client_id(self, client_id, request, *args, **kwargs): + """Ensure client_id belong to a non-confidential client. + + A non-confidential client is one that is not required to authenticate + through other means, such as using HTTP Basic. + + Note, while not strictly necessary it can often be very convenient + to set request.client to the client object associated with the + given client_id. + + :param client_id: Unicode client identifier. + :param request: OAuthlib request. + :type request: oauthlib.common.Request + :rtype: True or False + + Method is used by: + - Authorization Code Grant + """ + raise NotImplementedError('Subclasses must implement this method.') + + def confirm_redirect_uri(self, client_id, code, redirect_uri, client, request, + *args, **kwargs): + """Ensure that the authorization process represented by this authorization + code began with this 'redirect_uri'. + + If the client specifies a redirect_uri when obtaining code then that + redirect URI must be bound to the code and verified equal in this + method, according to RFC 6749 section 4.1.3. Do not compare against + the client's allowed redirect URIs, but against the URI used when the + code was saved. + + :param client_id: Unicode client identifier. + :param code: Unicode authorization_code. + :param redirect_uri: Unicode absolute URI. + :param client: Client object set by you, see ``.authenticate_client``. + :param request: OAuthlib request. + :type request: oauthlib.common.Request + :rtype: True or False + + Method is used by: + - Authorization Code Grant (during token request) + """ + raise NotImplementedError('Subclasses must implement this method.') + + def get_default_redirect_uri(self, client_id, request, *args, **kwargs): + """Get the default redirect URI for the client. + + :param client_id: Unicode client identifier. + :param request: OAuthlib request. + :type request: oauthlib.common.Request + :rtype: The default redirect URI for the client + + Method is used by: + - Authorization Code Grant + - Implicit Grant + """ + raise NotImplementedError('Subclasses must implement this method.') + + def get_default_scopes(self, client_id, request, *args, **kwargs): + """Get the default scopes for the client. + + :param client_id: Unicode client identifier. + :param request: OAuthlib request. + :type request: oauthlib.common.Request + :rtype: List of default scopes + + Method is used by all core grant types: + - Authorization Code Grant + - Implicit Grant + - Resource Owner Password Credentials Grant + - Client Credentials grant + """ + raise NotImplementedError('Subclasses must implement this method.') + + def get_original_scopes(self, refresh_token, request, *args, **kwargs): + """Get the list of scopes associated with the refresh token. + + :param refresh_token: Unicode refresh token. + :param request: OAuthlib request. + :type request: oauthlib.common.Request + :rtype: List of scopes. + + Method is used by: + - Refresh token grant + """ + raise NotImplementedError('Subclasses must implement this method.') + + def is_within_original_scope(self, request_scopes, refresh_token, request, *args, **kwargs): + """Check if requested scopes are within a scope of the refresh token. + + When access tokens are refreshed the scope of the new token + needs to be within the scope of the original token. This is + ensured by checking that all requested scopes strings are on + the list returned by the get_original_scopes. If this check + fails, is_within_original_scope is called. The method can be + used in situations where returning all valid scopes from the + get_original_scopes is not practical. + + :param request_scopes: A list of scopes that were requested by client. + :param refresh_token: Unicode refresh_token. + :param request: OAuthlib request. + :type request: oauthlib.common.Request + :rtype: True or False + + Method is used by: + - Refresh token grant + """ + return False + + def introspect_token(self, token, token_type_hint, request, *args, **kwargs): + """Introspect an access or refresh token. + + Called once the introspect request is validated. This method should + verify the *token* and either return a dictionary with the list of + claims associated, or `None` in case the token is unknown. + + Below the list of registered claims you should be interested in: + + - scope : space-separated list of scopes + - client_id : client identifier + - username : human-readable identifier for the resource owner + - token_type : type of the token + - exp : integer timestamp indicating when this token will expire + - iat : integer timestamp indicating when this token was issued + - nbf : integer timestamp indicating when it can be "not-before" used + - sub : subject of the token - identifier of the resource owner + - aud : list of string identifiers representing the intended audience + - iss : string representing issuer of this token + - jti : string identifier for the token + + Note that most of them are coming directly from JWT RFC. More details + can be found in `Introspect Claims`_ or `JWT Claims`_. + + The implementation can use *token_type_hint* to improve lookup + efficiency, but must fallback to other types to be compliant with RFC. + + The dict of claims is added to request.token after this method. + + :param token: The token string. + :param token_type_hint: access_token or refresh_token. + :param request: OAuthlib request. + :type request: oauthlib.common.Request + + Method is used by: + - Introspect Endpoint (all grants are compatible) + + .. _`Introspect Claims`: https://tools.ietf.org/html/rfc7662#section-2.2 + .. _`JWT Claims`: https://tools.ietf.org/html/rfc7519#section-4 + """ + raise NotImplementedError('Subclasses must implement this method.') + + def invalidate_authorization_code(self, client_id, code, request, *args, **kwargs): + """Invalidate an authorization code after use. + + :param client_id: Unicode client identifier. + :param code: The authorization code grant (request.code). + :param request: OAuthlib request. + :type request: oauthlib.common.Request + + Method is used by: + - Authorization Code Grant + """ + raise NotImplementedError('Subclasses must implement this method.') + + def revoke_token(self, token, token_type_hint, request, *args, **kwargs): + """Revoke an access or refresh token. + + :param token: The token string. + :param token_type_hint: access_token or refresh_token. + :param request: OAuthlib request. + :type request: oauthlib.common.Request + + Method is used by: + - Revocation Endpoint + """ + raise NotImplementedError('Subclasses must implement this method.') + + def rotate_refresh_token(self, request): + """Determine whether to rotate the refresh token. Default, yes. + + When access tokens are refreshed the old refresh token can be kept + or replaced with a new one (rotated). Return True to rotate and + and False for keeping original. + + :param request: OAuthlib request. + :type request: oauthlib.common.Request + :rtype: True or False + + Method is used by: + - Refresh Token Grant + """ + return True + + def save_authorization_code(self, client_id, code, request, *args, **kwargs): + """Persist the authorization_code. + + The code should at minimum be stored with: + - the client_id (``client_id``) + - the redirect URI used (``request.redirect_uri``) + - a resource owner / user (``request.user``) + - the authorized scopes (``request.scopes``) + + To support PKCE, you MUST associate the code with: + - Code Challenge (``request.code_challenge``) and + - Code Challenge Method (``request.code_challenge_method``) + + To support OIDC, you MUST associate the code with: + - nonce, if present (``code["nonce"]``) + + The ``code`` argument is actually a dictionary, containing at least a + ``code`` key with the actual authorization code: + + ``{'code': 'sdf345jsdf0934f'}`` + + It may also have a ``claims`` parameter which, when present, will be a dict + deserialized from JSON as described at + http://openid.net/specs/openid-connect-core-1_0.html#ClaimsParameter + This value should be saved in this method and used again in ``.validate_code``. + + :param client_id: Unicode client identifier. + :param code: A dict of the authorization code grant and, optionally, state. + :param request: OAuthlib request. + :type request: oauthlib.common.Request + + Method is used by: + - Authorization Code Grant + """ + raise NotImplementedError('Subclasses must implement this method.') + + def save_token(self, token, request, *args, **kwargs): + """Persist the token with a token type specific method. + + Currently, only save_bearer_token is supported. + + :param token: A (Bearer) token dict. + :param request: OAuthlib request. + :type request: oauthlib.common.Request + """ + return self.save_bearer_token(token, request, *args, **kwargs) + + def save_bearer_token(self, token, request, *args, **kwargs): + """Persist the Bearer token. + + The Bearer token should at minimum be associated with: + - a client and it's client_id, if available + - a resource owner / user (request.user) + - authorized scopes (request.scopes) + - an expiration time + - a refresh token, if issued + - a claims document, if present in request.claims + + The Bearer token dict may hold a number of items:: + + { + 'token_type': 'Bearer', + 'access_token': 'askfjh234as9sd8', + 'expires_in': 3600, + 'scope': 'string of space separated authorized scopes', + 'refresh_token': '23sdf876234', # if issued + 'state': 'given_by_client', # if supplied by client (implicit ONLY) + } + + Note that while "scope" is a string-separated list of authorized scopes, + the original list is still available in request.scopes. + + The token dict is passed as a reference so any changes made to the dictionary + will go back to the user. If additional information must return to the client + user, and it is only possible to get this information after writing the token + to storage, it should be added to the token dictionary. If the token + dictionary must be modified but the changes should not go back to the user, + a copy of the dictionary must be made before making the changes. + + Also note that if an Authorization Code grant request included a valid claims + parameter (for OpenID Connect) then the request.claims property will contain + the claims dict, which should be saved for later use when generating the + id_token and/or UserInfo response content. + + :param token: A Bearer token dict. + :param request: OAuthlib request. + :type request: oauthlib.common.Request + :rtype: The default redirect URI for the client + + Method is used by all core grant types issuing Bearer tokens: + - Authorization Code Grant + - Implicit Grant + - Resource Owner Password Credentials Grant (might not associate a client) + - Client Credentials grant + """ + raise NotImplementedError('Subclasses must implement this method.') + + def validate_bearer_token(self, token, scopes, request): + """Ensure the Bearer token is valid and authorized access to scopes. + + :param token: A string of random characters. + :param scopes: A list of scopes associated with the protected resource. + :param request: OAuthlib request. + :type request: oauthlib.common.Request + + A key to OAuth 2 security and restricting impact of leaked tokens is + the short expiration time of tokens, *always ensure the token has not + expired!*. + + Two different approaches to scope validation: + + 1) all(scopes). The token must be authorized access to all scopes + associated with the resource. For example, the + token has access to ``read-only`` and ``images``, + thus the client can view images but not upload new. + Allows for fine grained access control through + combining various scopes. + + 2) any(scopes). The token must be authorized access to one of the + scopes associated with the resource. For example, + token has access to ``read-only-images``. + Allows for fine grained, although arguably less + convenient, access control. + + A powerful way to use scopes would mimic UNIX ACLs and see a scope + as a group with certain privileges. For a restful API these might + map to HTTP verbs instead of read, write and execute. + + Note, the request.user attribute can be set to the resource owner + associated with this token. Similarly the request.client and + request.scopes attribute can be set to associated client object + and authorized scopes. If you then use a decorator such as the + one provided for django these attributes will be made available + in all protected views as keyword arguments. + + :param token: Unicode Bearer token + :param scopes: List of scopes (defined by you) + :param request: OAuthlib request. + :type request: oauthlib.common.Request + :rtype: True or False + + Method is indirectly used by all core Bearer token issuing grant types: + - Authorization Code Grant + - Implicit Grant + - Resource Owner Password Credentials Grant + - Client Credentials Grant + """ + raise NotImplementedError('Subclasses must implement this method.') + + def validate_client_id(self, client_id, request, *args, **kwargs): + """Ensure client_id belong to a valid and active client. + + Note, while not strictly necessary it can often be very convenient + to set request.client to the client object associated with the + given client_id. + + :param client_id: Unicode client identifier. + :param request: OAuthlib request. + :type request: oauthlib.common.Request + :rtype: True or False + + Method is used by: + - Authorization Code Grant + - Implicit Grant + """ + raise NotImplementedError('Subclasses must implement this method.') + + def validate_code(self, client_id, code, client, request, *args, **kwargs): + """Verify that the authorization_code is valid and assigned to the given + client. + + Before returning true, set the following based on the information stored + with the code in 'save_authorization_code': + + - request.user + - request.scopes + - request.claims (if given) + + OBS! The request.user attribute should be set to the resource owner + associated with this authorization code. Similarly request.scopes + must also be set. + + The request.claims property, if it was given, should assigned a dict. + + If PKCE is enabled (see 'is_pkce_required' and 'save_authorization_code') + you MUST set the following based on the information stored: + + - request.code_challenge + - request.code_challenge_method + + :param client_id: Unicode client identifier. + :param code: Unicode authorization code. + :param client: Client object set by you, see ``.authenticate_client``. + :param request: OAuthlib request. + :type request: oauthlib.common.Request + :rtype: True or False + + Method is used by: + - Authorization Code Grant + """ + raise NotImplementedError('Subclasses must implement this method.') + + def validate_grant_type(self, client_id, grant_type, client, request, *args, **kwargs): + """Ensure client is authorized to use the grant_type requested. + + :param client_id: Unicode client identifier. + :param grant_type: Unicode grant type, i.e. authorization_code, password. + :param client: Client object set by you, see ``.authenticate_client``. + :param request: OAuthlib request. + :type request: oauthlib.common.Request + :rtype: True or False + + Method is used by: + - Authorization Code Grant + - Resource Owner Password Credentials Grant + - Client Credentials Grant + - Refresh Token Grant + """ + raise NotImplementedError('Subclasses must implement this method.') + + def validate_redirect_uri(self, client_id, redirect_uri, request, *args, **kwargs): + """Ensure client is authorized to redirect to the redirect_uri requested. + + All clients should register the absolute URIs of all URIs they intend + to redirect to. The registration is outside of the scope of oauthlib. + + :param client_id: Unicode client identifier. + :param redirect_uri: Unicode absolute URI. + :param request: OAuthlib request. + :type request: oauthlib.common.Request + :rtype: True or False + + Method is used by: + - Authorization Code Grant + - Implicit Grant + """ + raise NotImplementedError('Subclasses must implement this method.') + + def validate_refresh_token(self, refresh_token, client, request, *args, **kwargs): + """Ensure the Bearer token is valid and authorized access to scopes. + + OBS! The request.user attribute should be set to the resource owner + associated with this refresh token. + + :param refresh_token: Unicode refresh token. + :param client: Client object set by you, see ``.authenticate_client``. + :param request: OAuthlib request. + :type request: oauthlib.common.Request + :rtype: True or False + + Method is used by: + - Authorization Code Grant (indirectly by issuing refresh tokens) + - Resource Owner Password Credentials Grant (also indirectly) + - Refresh Token Grant + """ + raise NotImplementedError('Subclasses must implement this method.') + + def validate_response_type(self, client_id, response_type, client, request, *args, **kwargs): + """Ensure client is authorized to use the response_type requested. + + :param client_id: Unicode client identifier. + :param response_type: Unicode response type, i.e. code, token. + :param client: Client object set by you, see ``.authenticate_client``. + :param request: OAuthlib request. + :type request: oauthlib.common.Request + :rtype: True or False + + Method is used by: + - Authorization Code Grant + - Implicit Grant + """ + raise NotImplementedError('Subclasses must implement this method.') + + def validate_scopes(self, client_id, scopes, client, request, *args, **kwargs): + """Ensure the client is authorized access to requested scopes. + + :param client_id: Unicode client identifier. + :param scopes: List of scopes (defined by you). + :param client: Client object set by you, see ``.authenticate_client``. + :param request: OAuthlib request. + :type request: oauthlib.common.Request + :rtype: True or False + + Method is used by all core grant types: + - Authorization Code Grant + - Implicit Grant + - Resource Owner Password Credentials Grant + - Client Credentials Grant + """ + raise NotImplementedError('Subclasses must implement this method.') + + def validate_user(self, username, password, client, request, *args, **kwargs): + """Ensure the username and password is valid. + + OBS! The validation should also set the user attribute of the request + to a valid resource owner, i.e. request.user = username or similar. If + not set you will be unable to associate a token with a user in the + persistence method used (commonly, save_bearer_token). + + :param username: Unicode username. + :param password: Unicode password. + :param client: Client object set by you, see ``.authenticate_client``. + :param request: OAuthlib request. + :type request: oauthlib.common.Request + :rtype: True or False + + Method is used by: + - Resource Owner Password Credentials Grant + """ + raise NotImplementedError('Subclasses must implement this method.') + + def is_pkce_required(self, client_id, request): + """Determine if current request requires PKCE. Default, False. + This is called for both "authorization" and "token" requests. + + Override this method by ``return True`` to enable PKCE for everyone. + You might want to enable it only for public clients. + Note that PKCE can also be used in addition of a client authentication. + + OAuth 2.0 public clients utilizing the Authorization Code Grant are + susceptible to the authorization code interception attack. This + specification describes the attack as well as a technique to mitigate + against the threat through the use of Proof Key for Code Exchange + (PKCE, pronounced "pixy"). See `RFC7636`_. + + :param client_id: Client identifier. + :param request: OAuthlib request. + :type request: oauthlib.common.Request + :rtype: True or False + + Method is used by: + - Authorization Code Grant + + .. _`RFC7636`: https://tools.ietf.org/html/rfc7636 + """ + return False + + def get_code_challenge(self, code, request): + """Is called for every "token" requests. + + When the server issues the authorization code in the authorization + response, it MUST associate the ``code_challenge`` and + ``code_challenge_method`` values with the authorization code so it can + be verified later. + + Typically, the ``code_challenge`` and ``code_challenge_method`` values + are stored in encrypted form in the ``code`` itself but could + alternatively be stored on the server associated with the code. The + server MUST NOT include the ``code_challenge`` value in client requests + in a form that other entities can extract. + + Return the ``code_challenge`` associated to the code. + If ``None`` is returned, code is considered to not be associated to any + challenges. + + :param code: Authorization code. + :param request: OAuthlib request. + :type request: oauthlib.common.Request + :rtype: code_challenge string + + Method is used by: + - Authorization Code Grant - when PKCE is active + + """ + return None + + def get_code_challenge_method(self, code, request): + """Is called during the "token" request processing, when a + ``code_verifier`` and a ``code_challenge`` has been provided. + + See ``.get_code_challenge``. + + Must return ``plain`` or ``S256``. You can return a custom value if you have + implemented your own ``AuthorizationCodeGrant`` class. + + :param code: Authorization code. + :param request: OAuthlib request. + :type request: oauthlib.common.Request + :rtype: code_challenge_method string + + Method is used by: + - Authorization Code Grant - when PKCE is active + + """ + raise NotImplementedError('Subclasses must implement this method.') + + def is_origin_allowed(self, client_id, origin, request, *args, **kwargs): + """Indicate if the given origin is allowed to access the token endpoint + via Cross-Origin Resource Sharing (CORS). CORS is used by browser-based + clients, such as Single-Page Applications, to perform the Authorization + Code Grant. + + (Note: If performing Authorization Code Grant via a public client such + as a browser, you should use PKCE as well.) + + If this method returns true, the appropriate CORS headers will be added + to the response. By default this method always returns False, meaning + CORS is disabled. + + :param client_id: Unicode client identifier. + :param redirect_uri: Unicode origin. + :param request: OAuthlib request. + :type request: oauthlib.common.Request + :rtype: bool + + Method is used by: + - Authorization Code Grant + - Refresh Token Grant + + """ + return False diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/tokens.py b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/tokens.py new file mode 100644 index 0000000000000000000000000000000000000000..73b8c66a9621aa2b81f3adb7a97b84fc051b4142 --- /dev/null +++ b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/tokens.py @@ -0,0 +1,350 @@ +""" +oauthlib.oauth2.rfc6749.tokens +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +This module contains methods for adding two types of access tokens to requests. + +- Bearer https://tools.ietf.org/html/rfc6750 +- MAC https://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac-01 +""" +import hashlib +import hmac +import warnings +from binascii import b2a_base64 +from urllib.parse import urlparse + +from oauthlib import common +from oauthlib.common import add_params_to_qs, add_params_to_uri + +from . import utils + + +class OAuth2Token(dict): + + def __init__(self, params, old_scope=None): + super().__init__(params) + self._new_scope = None + if params.get('scope'): + self._new_scope = set(utils.scope_to_list(params['scope'])) + if old_scope is not None: + self._old_scope = set(utils.scope_to_list(old_scope)) + if self._new_scope is None: + # the rfc says that if the scope hasn't changed, it's optional + # in params so set the new scope to the old scope + self._new_scope = self._old_scope + else: + self._old_scope = self._new_scope + + @property + def scope_changed(self): + return self._new_scope != self._old_scope + + @property + def old_scope(self): + return utils.list_to_scope(self._old_scope) + + @property + def old_scopes(self): + return list(self._old_scope) + + @property + def scope(self): + return utils.list_to_scope(self._new_scope) + + @property + def scopes(self): + return list(self._new_scope) + + @property + def missing_scopes(self): + return list(self._old_scope - self._new_scope) + + @property + def additional_scopes(self): + return list(self._new_scope - self._old_scope) + + +def prepare_mac_header(token, uri, key, http_method, + nonce=None, + headers=None, + body=None, + ext='', + hash_algorithm='hmac-sha-1', + issue_time=None, + draft=0): + """Add an `MAC Access Authentication`_ signature to headers. + + Unlike OAuth 1, this HMAC signature does not require inclusion of the + request payload/body, neither does it use a combination of client_secret + and token_secret but rather a mac_key provided together with the access + token. + + Currently two algorithms are supported, "hmac-sha-1" and "hmac-sha-256", + `extension algorithms`_ are not supported. + + Example MAC Authorization header, linebreaks added for clarity + + Authorization: MAC id="h480djs93hd8", + nonce="1336363200:dj83hs9s", + mac="bhCQXTVyfj5cmA9uKkPFx1zeOXM=" + + .. _`MAC Access Authentication`: https://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac-01 + .. _`extension algorithms`: https://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac-01#section-7.1 + + :param token: + :param uri: Request URI. + :param key: MAC given provided by token endpoint. + :param http_method: HTTP Request method. + :param nonce: + :param headers: Request headers as a dictionary. + :param body: + :param ext: + :param hash_algorithm: HMAC algorithm provided by token endpoint. + :param issue_time: Time when the MAC credentials were issued (datetime). + :param draft: MAC authentication specification version. + :return: headers dictionary with the authorization field added. + """ + http_method = http_method.upper() + host, port = utils.host_from_uri(uri) + + if hash_algorithm.lower() == 'hmac-sha-1': + h = hashlib.sha1 + elif hash_algorithm.lower() == 'hmac-sha-256': + h = hashlib.sha256 + else: + raise ValueError('unknown hash algorithm') + + if draft == 0: + nonce = nonce or '{}:{}'.format(utils.generate_age(issue_time), + common.generate_nonce()) + else: + ts = common.generate_timestamp() + nonce = common.generate_nonce() + + sch, net, path, par, query, fra = urlparse(uri) + + request_uri = path + '?' + query if query else path + + # Hash the body/payload + if body is not None and draft == 0: + body = body.encode('utf-8') + bodyhash = b2a_base64(h(body).digest())[:-1].decode('utf-8') + else: + bodyhash = '' + + # Create the normalized base string + base = [] + if draft == 0: + base.append(nonce) + else: + base.append(ts) + base.append(nonce) + base.append(http_method.upper()) + base.append(request_uri) + base.append(host) + base.append(port) + if draft == 0: + base.append(bodyhash) + base.append(ext or '') + base_string = '\n'.join(base) + '\n' + + # hmac struggles with unicode strings - http://bugs.python.org/issue5285 + if isinstance(key, str): + key = key.encode('utf-8') + sign = hmac.new(key, base_string.encode('utf-8'), h) + sign = b2a_base64(sign.digest())[:-1].decode('utf-8') + + header = [] + header.append('MAC id="%s"' % token) + if draft != 0: + header.append('ts="%s"' % ts) + header.append('nonce="%s"' % nonce) + if bodyhash: + header.append('bodyhash="%s"' % bodyhash) + if ext: + header.append('ext="%s"' % ext) + header.append('mac="%s"' % sign) + + headers = headers or {} + headers['Authorization'] = ', '.join(header) + return headers + + +def prepare_bearer_uri(token, uri): + """Add a `Bearer Token`_ to the request URI. + Not recommended, use only if client can't use authorization header or body. + + http://www.example.com/path?access_token=h480djs93hd8 + + .. _`Bearer Token`: https://tools.ietf.org/html/rfc6750 + + :param token: + :param uri: + """ + return add_params_to_uri(uri, [(('access_token', token))]) + + +def prepare_bearer_headers(token, headers=None): + """Add a `Bearer Token`_ to the request URI. + Recommended method of passing bearer tokens. + + Authorization: Bearer h480djs93hd8 + + .. _`Bearer Token`: https://tools.ietf.org/html/rfc6750 + + :param token: + :param headers: + """ + headers = headers or {} + headers['Authorization'] = 'Bearer %s' % token + return headers + + +def prepare_bearer_body(token, body=''): + """Add a `Bearer Token`_ to the request body. + + access_token=h480djs93hd8 + + .. _`Bearer Token`: https://tools.ietf.org/html/rfc6750 + + :param token: + :param body: + """ + return add_params_to_qs(body, [(('access_token', token))]) + + +def random_token_generator(request, refresh_token=False): + """ + :param request: OAuthlib request. + :type request: oauthlib.common.Request + :param refresh_token: + """ + return common.generate_token() + + +def signed_token_generator(private_pem, **kwargs): + """ + :param private_pem: + """ + def signed_token_generator(request): + request.claims = kwargs + return common.generate_signed_token(private_pem, request) + + return signed_token_generator + + +def get_token_from_header(request): + """ + Helper function to extract a token from the request header. + + :param request: OAuthlib request. + :type request: oauthlib.common.Request + :return: Return the token or None if the Authorization header is malformed. + """ + token = None + + if 'Authorization' in request.headers: + split_header = request.headers.get('Authorization').split() + if len(split_header) == 2 and split_header[0].lower() == 'bearer': + token = split_header[1] + else: + token = request.access_token + + return token + + +class TokenBase: + __slots__ = () + + def __call__(self, request, refresh_token=False): + raise NotImplementedError('Subclasses must implement this method.') + + def validate_request(self, request): + """ + :param request: OAuthlib request. + :type request: oauthlib.common.Request + """ + raise NotImplementedError('Subclasses must implement this method.') + + def estimate_type(self, request): + """ + :param request: OAuthlib request. + :type request: oauthlib.common.Request + """ + raise NotImplementedError('Subclasses must implement this method.') + + +class BearerToken(TokenBase): + __slots__ = ( + 'request_validator', 'token_generator', + 'refresh_token_generator', 'expires_in' + ) + + def __init__(self, request_validator=None, token_generator=None, + expires_in=None, refresh_token_generator=None): + self.request_validator = request_validator + self.token_generator = token_generator or random_token_generator + self.refresh_token_generator = ( + refresh_token_generator or self.token_generator + ) + self.expires_in = expires_in or 3600 + + def create_token(self, request, refresh_token=False, **kwargs): + """ + Create a BearerToken, by default without refresh token. + + :param request: OAuthlib request. + :type request: oauthlib.common.Request + :param refresh_token: + """ + if "save_token" in kwargs: + warnings.warn("`save_token` has been deprecated, it was not called internally." + "If you do, call `request_validator.save_token()` instead.", + DeprecationWarning) + + expires_in = self.expires_in(request) if callable(self.expires_in) else self.expires_in + + request.expires_in = expires_in + + token = { + 'access_token': self.token_generator(request), + 'expires_in': expires_in, + 'token_type': 'Bearer', + } + + # If provided, include - this is optional in some cases https://tools.ietf.org/html/rfc6749#section-3.3 but + # there is currently no mechanism to coordinate issuing a token for only a subset of the requested scopes so + # all tokens issued are for the entire set of requested scopes. + if request.scopes is not None: + token['scope'] = ' '.join(request.scopes) + + if refresh_token: + if (request.refresh_token and + not self.request_validator.rotate_refresh_token(request)): + token['refresh_token'] = request.refresh_token + else: + token['refresh_token'] = self.refresh_token_generator(request) + + token.update(request.extra_credentials or {}) + return OAuth2Token(token) + + def validate_request(self, request): + """ + :param request: OAuthlib request. + :type request: oauthlib.common.Request + """ + token = get_token_from_header(request) + return self.request_validator.validate_bearer_token( + token, request.scopes, request) + + def estimate_type(self, request): + """ + :param request: OAuthlib request. + :type request: oauthlib.common.Request + """ + if request.headers.get('Authorization', '').split(' ')[0].lower() == 'bearer': + return 9 + elif request.access_token is not None: + return 5 + else: + return 0 diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/utils.py b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..7dc27b3dff480bbb89e113f478cec27945af8e2d --- /dev/null +++ b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc6749/utils.py @@ -0,0 +1,83 @@ +""" +oauthlib.utils +~~~~~~~~~~~~~~ + +This module contains utility methods used by various parts of the OAuth 2 spec. +""" +import datetime +import os +from urllib.parse import quote, urlparse + +from oauthlib.common import urldecode + + +def list_to_scope(scope): + """Convert a list of scopes to a space separated string.""" + if isinstance(scope, str) or scope is None: + return scope + elif isinstance(scope, (set, tuple, list)): + return " ".join([str(s) for s in scope]) + else: + raise ValueError("Invalid scope (%s), must be string, tuple, set, or list." % scope) + + +def scope_to_list(scope): + """Convert a space separated string to a list of scopes.""" + if isinstance(scope, (tuple, list, set)): + return [str(s) for s in scope] + elif scope is None: + return None + else: + return scope.strip().split(" ") + + +def params_from_uri(uri): + params = dict(urldecode(urlparse(uri).query)) + if 'scope' in params: + params['scope'] = scope_to_list(params['scope']) + return params + + +def host_from_uri(uri): + """Extract hostname and port from URI. + + Will use default port for HTTP and HTTPS if none is present in the URI. + """ + default_ports = { + 'HTTP': '80', + 'HTTPS': '443', + } + + sch, netloc, path, par, query, fra = urlparse(uri) + if ':' in netloc: + netloc, port = netloc.split(':', 1) + else: + port = default_ports.get(sch.upper()) + + return netloc, port + + +def escape(u): + """Escape a string in an OAuth-compatible fashion. + + TODO: verify whether this can in fact be used for OAuth 2 + + """ + if not isinstance(u, str): + raise ValueError('Only unicode objects are escapable.') + return quote(u.encode('utf-8'), safe=b'~') + + +def generate_age(issue_time): + """Generate a age parameter for MAC authentication draft 00.""" + td = datetime.datetime.now() - issue_time + age = (td.microseconds + (td.seconds + td.days * 24 * 3600) + * 10 ** 6) / 10 ** 6 + return str(age) + + +def is_secure_transport(uri): + """Check if the uri is over ssl.""" + if os.environ.get('OAUTHLIB_INSECURE_TRANSPORT'): + return True + return uri.lower().startswith('https://') diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc8628/__init__.py b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc8628/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..65891445e3e687f136fc12896a7d745b70b1594d --- /dev/null +++ b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc8628/__init__.py @@ -0,0 +1,16 @@ +""" +oauthlib.oauth2.rfc8628 +~~~~~~~~~~~~~~~~~~~~~~~ + +This module is an implementation of various logic needed +for consuming and providing OAuth 2.0 Device Authorization RFC8628. +""" + +from oauthlib.oauth2.rfc8628.errors import ( + SlowDownError, + AuthorizationPendingError, + ExpiredTokenError, +) +import logging + +log = logging.getLogger(__name__) diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc8628/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc8628/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a02185e3c1cb0b247f1e25fbd46cdb07757df8a8 Binary files /dev/null and b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc8628/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc8628/__pycache__/errors.cpython-313.pyc b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc8628/__pycache__/errors.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0e2fcf1f4ec7bacbe7c5d040a26864c91d198dc1 Binary files /dev/null and b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc8628/__pycache__/errors.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc8628/__pycache__/request_validator.cpython-313.pyc b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc8628/__pycache__/request_validator.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2d1fcadf9360c7daece5fe4dc4fbc09ba1147494 Binary files /dev/null and b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc8628/__pycache__/request_validator.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc8628/clients/__init__.py b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc8628/clients/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..130b52e3814bc40c0f483b1ab60b034d1374049c --- /dev/null +++ b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc8628/clients/__init__.py @@ -0,0 +1,8 @@ +""" +oauthlib.oauth2.rfc8628 +~~~~~~~~~~~~~~~~~~~~~~~ + +This module is an implementation of various logic needed +for consuming OAuth 2.0 Device Authorization RFC8628. +""" +from .device import DeviceClient diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc8628/clients/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc8628/clients/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..76b1a277ed9dc31c50e3e94cf7706091a30b84ee Binary files /dev/null and b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc8628/clients/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc8628/clients/__pycache__/device.cpython-313.pyc b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc8628/clients/__pycache__/device.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a4b560d5a9934b23dd13eb93b3f1a2e951b78f35 Binary files /dev/null and b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc8628/clients/__pycache__/device.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc8628/clients/device.py b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc8628/clients/device.py new file mode 100644 index 0000000000000000000000000000000000000000..ee0ccf8d61897ac5dae0ecd9028f13a929006129 --- /dev/null +++ b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc8628/clients/device.py @@ -0,0 +1,95 @@ +""" +oauthlib.oauth2.rfc8628 +~~~~~~~~~~~~~~~~~~~~~~~ + +This module is an implementation of various logic needed +for consuming and providing OAuth 2.0 Device Authorization RFC8628. +""" +from oauthlib.common import add_params_to_uri +from oauthlib.oauth2 import BackendApplicationClient, Client +from oauthlib.oauth2.rfc6749.errors import InsecureTransportError +from oauthlib.oauth2.rfc6749.parameters import prepare_token_request +from oauthlib.oauth2.rfc6749.utils import is_secure_transport, list_to_scope + + +class DeviceClient(Client): + + """A public client utilizing the device authorization workflow. + + The client can request an access token using a device code and + a public client id associated with the device code as defined + in RFC8628. + + The device authorization grant type can be used to obtain both + access tokens and refresh tokens and is intended to be used in + a scenario where the device being authorized does not have a + user interface that is suitable for performing authentication. + """ + + grant_type = 'urn:ietf:params:oauth:grant-type:device_code' + + def __init__(self, client_id, **kwargs): + super().__init__(client_id, **kwargs) + self.client_secret = kwargs.get('client_secret') + + def prepare_request_uri(self, uri, scope=None, **kwargs): + if not is_secure_transport(uri): + raise InsecureTransportError() + + scope = self.scope if scope is None else scope + params = [(('client_id', self.client_id)), (('grant_type', self.grant_type))] + + if self.client_secret is not None: + params.append(('client_secret', self.client_secret)) + + if scope: + params.append(('scope', list_to_scope(scope))) + + for k,v in kwargs.items(): + if v: + params.append((str(k), v)) + + return add_params_to_uri(uri, params) + + def prepare_request_body(self, device_code, body='', scope=None, + include_client_id=False, **kwargs): + """Add device_code to request body + + The client makes a request to the token endpoint by adding the + device_code as a parameter using the + "application/x-www-form-urlencoded" format to the HTTP request + body. + + :param body: Existing request body (URL encoded string) to embed parameters + into. This may contain extra parameters. Default ''. + :param scope: The scope of the access request as described by + `Section 3.3`_. + + :param include_client_id: `True` to send the `client_id` in the + body of the upstream request. This is required + if the client is not authenticating with the + authorization server as described in + `Section 3.2.1`_. False otherwise (default). + :type include_client_id: Boolean + + :param kwargs: Extra credentials to include in the token request. + + The prepared body will include all provided device_code as well as + the ``grant_type`` parameter set to + ``urn:ietf:params:oauth:grant-type:device_code``:: + + >>> from oauthlib.oauth2 import DeviceClient + >>> client = DeviceClient('your_id', 'your_code') + >>> client.prepare_request_body(scope=['hello', 'world']) + 'grant_type=urn:ietf:params:oauth:grant-type:device_code&scope=hello+world' + + .. _`Section 3.2.1`: https://datatracker.ietf.org/doc/html/rfc6749#section-3.2.1 + .. _`Section 3.3`: https://datatracker.ietf.org/doc/html/rfc6749#section-3.3 + .. _`Section 3.4`: https://datatracker.ietf.org/doc/html/rfc8628#section-3.4 + """ + + kwargs['client_id'] = self.client_id + kwargs['include_client_id'] = include_client_id + scope = self.scope if scope is None else scope + return prepare_token_request(self.grant_type, body=body, device_code=device_code, + scope=scope, **kwargs) diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc8628/endpoints/__init__.py b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc8628/endpoints/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..dc834797cd7e0f1f3f5f0c997a2f00cd5d7c0d38 --- /dev/null +++ b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc8628/endpoints/__init__.py @@ -0,0 +1,10 @@ +""" +oauthlib.oauth2.rfc8628 +~~~~~~~~~~~~~~~~~~~~~~~ + +This module is an implementation of various logic needed +for consuming and providing OAuth 2.0 Device Authorization RFC8628. +""" + +from .device_authorization import DeviceAuthorizationEndpoint +from .pre_configured import DeviceApplicationServer diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc8628/endpoints/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc8628/endpoints/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7918f6bfb787ad371048a46ef7d755db96aa2221 Binary files /dev/null and b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc8628/endpoints/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc8628/endpoints/__pycache__/device_authorization.cpython-313.pyc b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc8628/endpoints/__pycache__/device_authorization.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3a7408b036563689a5a25069c6a0ebd318761685 Binary files /dev/null and b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc8628/endpoints/__pycache__/device_authorization.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc8628/endpoints/__pycache__/pre_configured.cpython-313.pyc b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc8628/endpoints/__pycache__/pre_configured.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f0e04d208d220633cebb61823b55b570678f23a0 Binary files /dev/null and b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc8628/endpoints/__pycache__/pre_configured.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc8628/endpoints/device_authorization.py b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc8628/endpoints/device_authorization.py new file mode 100644 index 0000000000000000000000000000000000000000..3f38a540590a9d38d42e3d84a79f6acfe440cac7 --- /dev/null +++ b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc8628/endpoints/device_authorization.py @@ -0,0 +1,232 @@ +""" +oauthlib.oauth2.rfc8628 +~~~~~~~~~~~~~~~~~~~~~~~ + +This module is an implementation of various logic needed +for consuming and providing OAuth 2.0 RFC8628. +""" + +import logging +from typing import Callable + +from oauthlib.common import Request, generate_token +from oauthlib.oauth2.rfc6749 import errors +from oauthlib.oauth2.rfc6749.endpoints.base import ( + BaseEndpoint, + catch_errors_and_unavailability, +) + +log = logging.getLogger(__name__) + + +class DeviceAuthorizationEndpoint(BaseEndpoint): + """DeviceAuthorization endpoint - used by the client to initiate + the authorization flow by requesting a set of verification codes + from the authorization server by making an HTTP "POST" request to + the device authorization endpoint. + + The client authentication requirements of Section 3.2.1 of [RFC6749] + apply to requests on this endpoint, which means that confidential + clients (those that have established client credentials) authenticate + in the same manner as when making requests to the token endpoint, and + public clients provide the "client_id" parameter to identify + themselves. + """ + + def __init__( + self, + request_validator, + verification_uri, + expires_in=1800, + interval=None, + verification_uri_complete=None, + user_code_generator: Callable[[None], str] = None, + ): + """ + :param request_validator: An instance of RequestValidator. + :type request_validator: oauthlib.oauth2.rfc6749.RequestValidator. + :param verification_uri: a string containing the URL that can be polled by the client application + :param expires_in: a number that represents the lifetime of the `user_code` and `device_code` + :param interval: an option number that represents the number of seconds between each poll requests + :param verification_uri_complete: a string of a function that can be called with `user_data` as parameter + :param user_code_generator: a callable that returns a configurable user code + """ + self.request_validator = request_validator + self._expires_in = expires_in + self._interval = interval + self._verification_uri = verification_uri + self._verification_uri_complete = verification_uri_complete + self.user_code_generator = user_code_generator + + BaseEndpoint.__init__(self) + + @property + def interval(self): + """The minimum amount of time in seconds that the client + SHOULD wait between polling requests to the token endpoint. If no + value is provided, clients MUST use 5 as the default. + """ + return self._interval + + @property + def expires_in(self): + """The lifetime in seconds of the "device_code" and "user_code".""" + return self._expires_in + + @property + def verification_uri(self): + """The end-user verification URI on the authorization + server. The URI should be short and easy to remember as end users + will be asked to manually type it into their user agent. + """ + return self._verification_uri + + def verification_uri_complete(self, user_code): + if not self._verification_uri_complete: + return None + if isinstance(self._verification_uri_complete, str): + return self._verification_uri_complete.format(user_code=user_code) + if callable(self._verification_uri_complete): + return self._verification_uri_complete(user_code) + return None + + @catch_errors_and_unavailability + def validate_device_authorization_request(self, request): + """Validate the device authorization request. + + The client_id is required if the client is not authenticating with the + authorization server as described in `Section 3.2.1. of [RFC6749]`_. + The client identifier as described in `Section 2.2 of [RFC6749]`_. + + .. _`Section 3.2.1. of [RFC6749]`: https://www.rfc-editor.org/rfc/rfc6749#section-3.2.1 + .. _`Section 2.2 of [RFC6749]`: https://www.rfc-editor.org/rfc/rfc6749#section-2.2 + """ + + # First check duplicate parameters + for param in ("client_id", "scope"): + try: + duplicate_params = request.duplicate_params + except ValueError: + raise errors.InvalidRequestFatalError( + description="Unable to parse query string", request=request + ) + if param in duplicate_params: + raise errors.InvalidRequestFatalError( + description="Duplicate %s parameter." % param, request=request + ) + + # the "application/x-www-form-urlencoded" format, per Appendix B of [RFC6749] + # https://www.rfc-editor.org/rfc/rfc6749#appendix-B + if request.headers["Content-Type"] != "application/x-www-form-urlencoded": + raise errors.InvalidRequestError( + "Content-Type must be application/x-www-form-urlencoded", + request=request, + ) + + # REQUIRED. The client identifier as described in Section 2.2. + # https://tools.ietf.org/html/rfc6749#section-2.2 + # TODO: extract client_id an helper validation function. + if not request.client_id: + raise errors.MissingClientIdError(request=request) + + if not self.request_validator.validate_client_id(request.client_id, request): + raise errors.InvalidClientIdError(request=request) + + # The client authentication requirements of Section 3.2.1 of [RFC6749] + # apply to requests on this endpoint, which means that confidential + # clients (those that have established client credentials) authenticate + # in the same manner as when making requests to the token endpoint, and + # public clients provide the "client_id" parameter to identify + # themselves. + self._raise_on_invalid_client(request) + + @catch_errors_and_unavailability + def create_device_authorization_response( + self, uri, http_method="POST", body=None, headers=None + ): + """ + Generate a unique device verification code and an end-user code that are valid for a limited time. + Include them in the HTTP response body using the "application/json" format [RFC8259] with a + 200 (OK) status code, as described in `Section-3.2`_. + + :param uri: The full URI of the token request. + :type uri: str + :param request: OAuthlib request. + :type request: oauthlib.common.Request + :param user_code_generator: + A callable that returns a string for the user code. + This allows the caller to decide how the `user_code` should be formatted. + :type user_code_generator: Callable[[], str] + :return: A tuple of three elements: + 1. A dict of headers to set on the response. + 2. The response body as a string. + 3. The response status code as an integer. + :rtype: tuple + + The response contains the following parameters: + + device_code + **REQUIRED.** The device verification code. + + user_code + **REQUIRED.** The end-user verification code. + + verification_uri + **REQUIRED.** The end-user verification URI on the authorization server. + The URI should be short and easy to remember as end users will be asked + to manually type it into their user agent. + + verification_uri_complete + **OPTIONAL.** A verification URI that includes the `user_code` (or + other information with the same function as the `user_code`), which is + designed for non-textual transmission. + + expires_in + **REQUIRED.** The lifetime in seconds of the `device_code` and `user_code`. + + interval + **OPTIONAL.** The minimum amount of time in seconds that the client + SHOULD wait between polling requests to the token endpoint. If no + value is provided, clients MUST use 5 as the default. + + **For example:** + + .. code-block:: http + + HTTP/1.1 200 OK + Content-Type: application/json + Cache-Control: no-store + + { + "device_code": "GmRhmhcxhwAzkoEqiMEg_DnyEysNkuNhszIySk9eS", + "user_code": "WDJB-MJHT", + "verification_uri": "https://example.com/device", + "verification_uri_complete": + "https://example.com/device?user_code=WDJB-MJHT", + "expires_in": 1800, + "interval": 5 + } + + .. _`Section-3.2`: https://www.rfc-editor.org/rfc/rfc8628#section-3.2 + """ + request = Request(uri, http_method, body, headers) + self.validate_device_authorization_request(request) + log.debug("Pre resource owner authorization validation ok for %r.", request) + + headers = {} + user_code = self.user_code_generator() if self.user_code_generator else generate_token() + data = { + "verification_uri": self.verification_uri, + "expires_in": self.expires_in, + "user_code": user_code, + "device_code": generate_token(), + } + if self.interval is not None: + data["interval"] = self.interval + + + verification_uri_complete = self.verification_uri_complete(user_code) + if verification_uri_complete: + data["verification_uri_complete"] = verification_uri_complete + + return headers, data, 200 diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc8628/endpoints/pre_configured.py b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc8628/endpoints/pre_configured.py new file mode 100644 index 0000000000000000000000000000000000000000..6cce683304ba7d86c78533fec44862f4568f7bfc --- /dev/null +++ b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc8628/endpoints/pre_configured.py @@ -0,0 +1,36 @@ +from oauthlib.oauth2.rfc8628.endpoints.device_authorization import ( + DeviceAuthorizationEndpoint, +) + +from typing import Callable, Optional +from oauthlib.openid.connect.core.request_validator import RequestValidator + + +class DeviceApplicationServer(DeviceAuthorizationEndpoint): + """An all-in-one endpoint featuring Authorization code grant and Bearer tokens.""" + + def __init__( + self, + request_validator: RequestValidator, + verification_uri: str, + interval: int = 5, + verification_uri_complete: Optional[str] = None, # noqa: FA100 + user_code_generator: Callable[[None], str] = None, + **kwargs, + ): + """Construct a new web application server. + + :param request_validator: An implementation of + oauthlib.oauth2.rfc8626.RequestValidator. + :param interval: How long the device needs to wait before polling the server + :param verification_uri: the verification_uri to be send back. + :param user_code_generator: a callable that allows the user code to be configured. + """ + DeviceAuthorizationEndpoint.__init__( + self, + request_validator, + interval=interval, + verification_uri=verification_uri, + user_code_generator=user_code_generator, + verification_uri_complete=verification_uri_complete, + ) diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc8628/errors.py b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc8628/errors.py new file mode 100644 index 0000000000000000000000000000000000000000..a43593898ebb927d70d45f1482f1e5da465d3949 --- /dev/null +++ b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc8628/errors.py @@ -0,0 +1,55 @@ +from oauthlib.oauth2.rfc6749.errors import OAuth2Error + +""" +oauthlib.oauth2.rfc8628.errors +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Error used both by OAuth2 clients and providers to represent the spec +defined error responses specific to the the device grant +""" + + +class AuthorizationPendingError(OAuth2Error): + """ + For the device authorization grant; + The authorization request is still pending as the end user hasn't + yet completed the user-interaction steps (Section 3.3). The + client SHOULD repeat the access token request to the token + endpoint (a process known as polling). Before each new request, + the client MUST wait at least the number of seconds specified by + the "interval" parameter of the device authorization response, + or 5 seconds if none was provided, and respect any + increase in the polling interval required by the "slow_down" + error. + """ + + error = "authorization_pending" + + +class SlowDownError(OAuth2Error): + """ + A variant of "authorization_pending", the authorization request is + still pending and polling should continue, but the interval MUST + be increased by 5 seconds for this and all subsequent requests. + """ + + error = "slow_down" + + +class ExpiredTokenError(OAuth2Error): + """ + The "device_code" has expired, and the device authorization + session has concluded. The client MAY commence a new device + authorization request but SHOULD wait for user interaction before + restarting to avoid unnecessary polling. + """ + + error = "expired_token" + + +class AccessDenied(OAuth2Error): + """ + The authorization request was denied. + """ + + error = "access_denied" diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc8628/grant_types/__init__.py b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc8628/grant_types/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..418dba775d13c97c76086b1882753165d7e154c6 --- /dev/null +++ b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc8628/grant_types/__init__.py @@ -0,0 +1 @@ +from oauthlib.oauth2.rfc8628.grant_types.device_code import DeviceCodeGrant diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc8628/grant_types/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc8628/grant_types/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..86662d1f2e38ac2d20b3ea39dd2b5210dd70b4a1 Binary files /dev/null and b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc8628/grant_types/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc8628/grant_types/__pycache__/device_code.cpython-313.pyc b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc8628/grant_types/__pycache__/device_code.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fb1ab3005b3c731e9b2b14d93afff644fd2e7a49 Binary files /dev/null and b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc8628/grant_types/__pycache__/device_code.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc8628/grant_types/device_code.py b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc8628/grant_types/device_code.py new file mode 100644 index 0000000000000000000000000000000000000000..082daf0fccf04fdc33656ddb3f833419648949d2 --- /dev/null +++ b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc8628/grant_types/device_code.py @@ -0,0 +1,111 @@ +from __future__ import annotations +import json + +from typing import Callable + +from oauthlib import common # noqa: TC001 + +from oauthlib.oauth2.rfc6749 import errors as rfc6749_errors +from oauthlib.oauth2.rfc6749.grant_types.base import GrantTypeBase + + +class DeviceCodeGrant(GrantTypeBase): + def create_authorization_response( + self, request: common.Request, token_handler: Callable + ) -> tuple[dict, str, int]: + """ + Validate the device flow request -> create the access token + -> persist the token -> return the token. + """ + headers = self._get_default_headers() + try: + self.validate_token_request(request) + except rfc6749_errors.OAuth2Error as e: + headers.update(e.headers) + return headers, e.json, e.status_code + + token = token_handler.create_token(request, refresh_token=False) + + for modifier in self._token_modifiers: + token = modifier(token) + + self.request_validator.save_token(token, request) + + return self.create_token_response(request, token_handler) + + def validate_token_request(self, request: common.Request) -> None: + """ + Performs the necessary check against the request to ensure + it's allowed to retrieve a token. + """ + for validator in self.custom_validators.pre_token: + validator(request) + + if not getattr(request, "grant_type", None): + raise rfc6749_errors.InvalidRequestError( + "Request is missing grant type.", request=request + ) + + if request.grant_type != "urn:ietf:params:oauth:grant-type:device_code": + raise rfc6749_errors.UnsupportedGrantTypeError(request=request) + + for param in ("grant_type", "scope"): + if param in request.duplicate_params: + raise rfc6749_errors.InvalidRequestError( + description=f"Duplicate {param} parameter.", request=request + ) + + if not self.request_validator.authenticate_client(request): + raise rfc6749_errors.InvalidClientError(request=request) + elif not hasattr(request.client, "client_id"): + raise NotImplementedError( + "Authenticate client must set the " + "request.client.client_id attribute " + "in authenticate_client." + ) + + # Ensure client is authorized use of this grant type + self.validate_grant_type(request) + + request.client_id = request.client_id or request.client.client_id + self.validate_scopes(request) + + for validator in self.custom_validators.post_token: + validator(request) + + def create_token_response( + self, request: common.Request, token_handler: Callable + ) -> tuple[dict, str, int]: + """Return token or error in json format. + + :param request: OAuthlib request. + :type request: oauthlib.common.Request + :param token_handler: A token handler instance, for example of type + oauthlib.oauth2.BearerToken. + + If the access token request is valid and authorized, the + authorization server issues an access token and optional refresh + token as described in `Section 5.1`_. If the request failed client + authentication or is invalid, the authorization server returns an + error response as described in `Section 5.2`_. + .. _`Section 5.1`: https://tools.ietf.org/html/rfc6749#section-5.1 + .. _`Section 5.2`: https://tools.ietf.org/html/rfc6749#section-5.2 + """ + headers = self._get_default_headers() + try: + if self.request_validator.client_authentication_required( + request + ) and not self.request_validator.authenticate_client(request): + raise rfc6749_errors.InvalidClientError(request=request) + + self.validate_token_request(request) + + except rfc6749_errors.OAuth2Error as e: + headers.update(e.headers) + return headers, e.json, e.status_code + + token = token_handler.create_token(request, self.refresh_token) + + self.request_validator.save_token(token, request) + + return headers, json.dumps(token), 200 diff --git a/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc8628/request_validator.py b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc8628/request_validator.py new file mode 100644 index 0000000000000000000000000000000000000000..70ee7824e92dae12b5b44d073f11c708ebd07577 --- /dev/null +++ b/python/user_packages/Python313/site-packages/oauthlib/oauth2/rfc8628/request_validator.py @@ -0,0 +1,25 @@ +from oauthlib.oauth2 import RequestValidator as OAuth2RequestValidator + + +class RequestValidator(OAuth2RequestValidator): + def client_authentication_required(self, request, *args, **kwargs): + """Determine if client authentication is required for current request. + + According to the rfc8628, client authentication is required in the following cases: + - Device Authorization Request follows the, the client authentication requirements + of Section 3.2.1 of [RFC6749] apply to requests on this endpoint, which means that + confidential clients (those that have established client credentials) authenticate + in the same manner as when making requests to the token endpoint, and + public clients provide the "client_id" parameter to identify themselves, + see `Section 3.1`_. + + :param request: OAuthlib request. + :type request: oauthlib.common.Request + :rtype: True or False + + Method is used by: + - Device Authorization Request + + .. _`Section 3.1`: https://www.rfc-editor.org/rfc/rfc8628#section-3.1 + """ + return True diff --git a/python/user_packages/Python313/site-packages/oauthlib/openid/__init__.py b/python/user_packages/Python313/site-packages/oauthlib/openid/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e3174374798f21cc8d5f23e67b2077f14234a1a6 --- /dev/null +++ b/python/user_packages/Python313/site-packages/oauthlib/openid/__init__.py @@ -0,0 +1,7 @@ +""" +oauthlib.openid +~~~~~~~~~~~~~~ + +""" +from .connect.core.endpoints import Server, UserInfoEndpoint +from .connect.core.request_validator import RequestValidator diff --git a/python/user_packages/Python313/site-packages/oauthlib/openid/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/oauthlib/openid/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e75c5867ff3e8207376bfb133aac9d74a66c66b1 Binary files /dev/null and b/python/user_packages/Python313/site-packages/oauthlib/openid/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/oauthlib/openid/connect/__init__.py b/python/user_packages/Python313/site-packages/oauthlib/openid/connect/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/python/user_packages/Python313/site-packages/oauthlib/openid/connect/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/oauthlib/openid/connect/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8f34f37d6181aa4a1de0d0b00fabfd22e69513fb Binary files /dev/null and b/python/user_packages/Python313/site-packages/oauthlib/openid/connect/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/__init__.py b/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4a78671bdd10403d40e5d4508233c0fcb17992f8 Binary files /dev/null and b/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/__pycache__/exceptions.cpython-313.pyc b/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/__pycache__/exceptions.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2b63b0b42a5429b20b0153da5d66fefb81ba2f9c Binary files /dev/null and b/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/__pycache__/exceptions.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/__pycache__/request_validator.cpython-313.pyc b/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/__pycache__/request_validator.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..219a2ec3859d6ad3edea3925508f09fc660525ff Binary files /dev/null and b/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/__pycache__/request_validator.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/__pycache__/tokens.cpython-313.pyc b/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/__pycache__/tokens.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f3a6cd6ea5321ffcc53cf52fa4f8fb3144f54f09 Binary files /dev/null and b/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/__pycache__/tokens.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/endpoints/__init__.py b/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/endpoints/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7017ff4f3211d2007ee5d297cfff47c0a5b27fd4 --- /dev/null +++ b/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/endpoints/__init__.py @@ -0,0 +1,9 @@ +""" +oauthlib.oopenid.core +~~~~~~~~~~~~~~~~~~~~~~~ + +This module is an implementation of various logic needed +for consuming and providing OpenID Connect +""" +from .pre_configured import Server +from .userinfo import UserInfoEndpoint diff --git a/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/endpoints/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/endpoints/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a2be815b26686ccc05dab20e90d7d0eee8208339 Binary files /dev/null and b/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/endpoints/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/endpoints/__pycache__/pre_configured.cpython-313.pyc b/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/endpoints/__pycache__/pre_configured.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..30e0dafd71655929065eda9801d1c74772d5adb7 Binary files /dev/null and b/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/endpoints/__pycache__/pre_configured.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/endpoints/__pycache__/userinfo.cpython-313.pyc b/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/endpoints/__pycache__/userinfo.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cc84f6e8d5f22de62fb0cc887eecc5852a85cd1f Binary files /dev/null and b/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/endpoints/__pycache__/userinfo.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/endpoints/pre_configured.py b/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/endpoints/pre_configured.py new file mode 100644 index 0000000000000000000000000000000000000000..17df516d17e9409dedc8902fa3a9ae38195c2067 --- /dev/null +++ b/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/endpoints/pre_configured.py @@ -0,0 +1,139 @@ +""" +oauthlib.openid.connect.core.endpoints.pre_configured +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +This module is an implementation of various endpoints needed +for providing OpenID Connect servers. +""" + +from oauthlib.oauth2.rfc6749.endpoints import ( + AuthorizationEndpoint, + IntrospectEndpoint, + ResourceEndpoint, + RevocationEndpoint, + TokenEndpoint, +) +from oauthlib.oauth2.rfc6749.grant_types import ( + AuthorizationCodeGrant as OAuth2AuthorizationCodeGrant, + ClientCredentialsGrant, + ImplicitGrant as OAuth2ImplicitGrant, + ResourceOwnerPasswordCredentialsGrant, +) +from oauthlib.oauth2.rfc8628.grant_types import DeviceCodeGrant +from oauthlib.oauth2.rfc6749.tokens import BearerToken + +from ..grant_types import ( + AuthorizationCodeGrant, + HybridGrant, + ImplicitGrant, + RefreshTokenGrant, +) +from ..grant_types.dispatchers import ( + AuthorizationCodeGrantDispatcher, + AuthorizationTokenGrantDispatcher, + ImplicitTokenGrantDispatcher, +) +from ..tokens import JWTToken +from .userinfo import UserInfoEndpoint + + +class Server( + AuthorizationEndpoint, + IntrospectEndpoint, + TokenEndpoint, + ResourceEndpoint, + RevocationEndpoint, + UserInfoEndpoint, +): + """ + An all-in-one endpoint featuring all four major grant types + and extension grants. + """ + + def __init__( + self, + request_validator, + token_expires_in=None, + token_generator=None, + refresh_token_generator=None, + *args, + **kwargs, + ): + """Construct a new all-grants-in-one server. + + :param request_validator: An implementation of + oauthlib.oauth2.RequestValidator. + :param token_expires_in: An int or a function to generate a token + expiration offset (in seconds) given a + oauthlib.common.Request object. + :param token_generator: A function to generate a token from a request. + :param refresh_token_generator: A function to generate a token from a + request for the refresh token. + :param kwargs: Extra parameters to pass to authorization-, + token-, resource-, and revocation-endpoint constructors. + """ + self.auth_grant = OAuth2AuthorizationCodeGrant(request_validator) + self.implicit_grant = OAuth2ImplicitGrant(request_validator) + self.password_grant = ResourceOwnerPasswordCredentialsGrant(request_validator) + self.credentials_grant = ClientCredentialsGrant(request_validator) + self.refresh_grant = RefreshTokenGrant(request_validator) + self.openid_connect_auth = AuthorizationCodeGrant(request_validator) + self.openid_connect_implicit = ImplicitGrant(request_validator) + self.openid_connect_hybrid = HybridGrant(request_validator) + self.device_code_grant = DeviceCodeGrant(request_validator, **kwargs) + + self.bearer = BearerToken( + request_validator, token_generator, token_expires_in, refresh_token_generator + ) + + self.jwt = JWTToken( + request_validator, token_generator, token_expires_in, refresh_token_generator + ) + + self.auth_grant_choice = AuthorizationCodeGrantDispatcher( + default_grant=self.auth_grant, oidc_grant=self.openid_connect_auth + ) + self.implicit_grant_choice = ImplicitTokenGrantDispatcher( + default_grant=self.implicit_grant, oidc_grant=self.openid_connect_implicit + ) + + # See http://openid.net/specs/oauth-v2-multiple-response-types-1_0.html#Combinations for valid combinations + # internally our AuthorizationEndpoint will ensure they can appear in any order for any valid combination + AuthorizationEndpoint.__init__( + self, + default_response_type="code", + response_types={ + "code": self.auth_grant_choice, + "token": self.implicit_grant_choice, + "id_token": self.openid_connect_implicit, + "id_token token": self.openid_connect_implicit, + "code token": self.openid_connect_hybrid, + "code id_token": self.openid_connect_hybrid, + "code id_token token": self.openid_connect_hybrid, + "none": self.auth_grant, + }, + default_token_type=self.bearer, + ) + + self.token_grant_choice = AuthorizationTokenGrantDispatcher( + request_validator, default_grant=self.auth_grant, oidc_grant=self.openid_connect_auth + ) + + TokenEndpoint.__init__( + self, + default_grant_type="authorization_code", + grant_types={ + "authorization_code": self.token_grant_choice, + "password": self.password_grant, + "client_credentials": self.credentials_grant, + "refresh_token": self.refresh_grant, + "urn:ietf:params:oauth:grant-type:device_code": self.device_code_grant, + }, + default_token_type=self.bearer, + ) + ResourceEndpoint.__init__( + self, default_token="Bearer", token_types={"Bearer": self.bearer, "JWT": self.jwt} + ) + RevocationEndpoint.__init__(self, request_validator) + IntrospectEndpoint.__init__(self, request_validator) + UserInfoEndpoint.__init__(self, request_validator) diff --git a/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/endpoints/userinfo.py b/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/endpoints/userinfo.py new file mode 100644 index 0000000000000000000000000000000000000000..7aa2bbe97d34fa5afce4168256aafe1c8ce5fcae --- /dev/null +++ b/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/endpoints/userinfo.py @@ -0,0 +1,106 @@ +""" +oauthlib.openid.connect.core.endpoints.userinfo +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +This module is an implementation of userinfo endpoint. +""" +import json +import logging + +from oauthlib.common import Request +from oauthlib.oauth2.rfc6749 import errors +from oauthlib.oauth2.rfc6749.endpoints.base import ( + BaseEndpoint, catch_errors_and_unavailability, +) +from oauthlib.oauth2.rfc6749.tokens import BearerToken + +log = logging.getLogger(__name__) + + +class UserInfoEndpoint(BaseEndpoint): + """Authorizes access to userinfo resource. + """ + def __init__(self, request_validator): + self.bearer = BearerToken(request_validator, None, None, None) + self.request_validator = request_validator + BaseEndpoint.__init__(self) + + @catch_errors_and_unavailability + def create_userinfo_response(self, uri, http_method='GET', body=None, headers=None): + """Validate BearerToken and return userinfo from RequestValidator + + The UserInfo Endpoint MUST return a + content-type header to indicate which format is being returned. The + content-type of the HTTP response MUST be application/json if the + response body is a text JSON object; the response body SHOULD be encoded + using UTF-8. + """ + request = Request(uri, http_method, body, headers) + request.scopes = ["openid"] + self.validate_userinfo_request(request) + + claims = self.request_validator.get_userinfo_claims(request) + if claims is None: + log.error('Userinfo MUST have claims for %r.', request) + raise errors.ServerError(status_code=500) + + if isinstance(claims, dict): + resp_headers = { + 'Content-Type': 'application/json' + } + if "sub" not in claims: + log.error('Userinfo MUST have "sub" for %r.', request) + raise errors.ServerError(status_code=500) + body = json.dumps(claims) + elif isinstance(claims, str): + resp_headers = { + 'Content-Type': 'application/jwt' + } + body = claims + else: + log.error('Userinfo return unknown response for %r.', request) + raise errors.ServerError(status_code=500) + log.debug('Userinfo access valid for %r.', request) + return resp_headers, body, 200 + + def validate_userinfo_request(self, request): + """Ensure the request is valid. + + 5.3.1. UserInfo Request + The Client sends the UserInfo Request using either HTTP GET or HTTP + POST. The Access Token obtained from an OpenID Connect Authentication + Request MUST be sent as a Bearer Token, per `Section 2`_ of OAuth 2.0 + Bearer Token Usage [RFC6750]. + + It is RECOMMENDED that the request use the HTTP GET method and the + Access Token be sent using the Authorization header field. + + The following is a non-normative example of a UserInfo Request: + + .. code-block:: http + + GET /userinfo HTTP/1.1 + Host: server.example.com + Authorization: Bearer SlAV32hkKG + + 5.3.3. UserInfo Error Response + When an error condition occurs, the UserInfo Endpoint returns an Error + Response as defined in `Section 3`_ of OAuth 2.0 Bearer Token Usage + [RFC6750]. (HTTP errors unrelated to RFC 6750 are returned to the User + Agent using the appropriate HTTP status code.) + + The following is a non-normative example of a UserInfo Error Response: + + .. code-block:: http + + HTTP/1.1 401 Unauthorized + WWW-Authenticate: Bearer error="invalid_token", + error_description="The Access Token expired" + + .. _`Section 2`: https://datatracker.ietf.org/doc/html/rfc6750#section-2 + .. _`Section 3`: https://datatracker.ietf.org/doc/html/rfc6750#section-3 + """ + if not self.bearer.validate_request(request): + raise errors.InvalidTokenError() + if "openid" not in request.scopes: + raise errors.InsufficientScopeError() diff --git a/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/exceptions.py b/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..291cf13776871147e9660a35254bb70a595fc791 --- /dev/null +++ b/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/exceptions.py @@ -0,0 +1,150 @@ +""" +oauthlib.oauth2.rfc6749.errors +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Error used both by OAuth 2 clients and providers to represent the spec +defined error responses for all four core grant types. +""" +import inspect +import sys + +from oauthlib.oauth2.rfc6749.errors import FatalClientError, OAuth2Error + + +class FatalOpenIDClientError(FatalClientError): + pass + + +class OpenIDClientError(OAuth2Error): + pass + + +class InteractionRequired(OpenIDClientError): + """ + The Authorization Server requires End-User interaction to proceed. + + This error MAY be returned when the prompt parameter value in the + Authentication Request is none, but the Authentication Request cannot be + completed without displaying a user interface for End-User interaction. + """ + error = 'interaction_required' + status_code = 401 + + +class LoginRequired(OpenIDClientError): + """ + The Authorization Server requires End-User authentication. + + This error MAY be returned when the prompt parameter value in the + Authentication Request is none, but the Authentication Request cannot be + completed without displaying a user interface for End-User authentication. + """ + error = 'login_required' + status_code = 401 + + +class AccountSelectionRequired(OpenIDClientError): + """ + The End-User is REQUIRED to select a session at the Authorization Server. + + The End-User MAY be authenticated at the Authorization Server with + different associated accounts, but the End-User did not select a session. + This error MAY be returned when the prompt parameter value in the + Authentication Request is none, but the Authentication Request cannot be + completed without displaying a user interface to prompt for a session to + use. + """ + error = 'account_selection_required' + + +class ConsentRequired(OpenIDClientError): + """ + The Authorization Server requires End-User consent. + + This error MAY be returned when the prompt parameter value in the + Authentication Request is none, but the Authentication Request cannot be + completed without displaying a user interface for End-User consent. + """ + error = 'consent_required' + status_code = 401 + + +class InvalidRequestURI(OpenIDClientError): + """ + The request_uri in the Authorization Request returns an error or + contains invalid data. + """ + error = 'invalid_request_uri' + description = ('The request_uri in the Authorization Request returns an ' + 'error or contains invalid data.') + + +class InvalidRequestObject(OpenIDClientError): + """ + The request parameter contains an invalid Request Object. + """ + error = 'invalid_request_object' + description = 'The request parameter contains an invalid Request Object.' + + +class RequestNotSupported(OpenIDClientError): + """ + The OP does not support use of the request parameter. + """ + error = 'request_not_supported' + description = 'The request parameter is not supported.' + + +class RequestURINotSupported(OpenIDClientError): + """ + The OP does not support use of the request_uri parameter. + """ + error = 'request_uri_not_supported' + description = 'The request_uri parameter is not supported.' + + +class RegistrationNotSupported(OpenIDClientError): + """ + The OP does not support use of the registration parameter. + """ + error = 'registration_not_supported' + description = 'The registration parameter is not supported.' + + +class InvalidTokenError(OAuth2Error): + """ + The access token provided is expired, revoked, malformed, or + invalid for other reasons. The resource SHOULD respond with + the HTTP 401 (Unauthorized) status code. The client MAY + request a new access token and retry the protected resource + request. + """ + error = 'invalid_token' + status_code = 401 + description = ("The access token provided is expired, revoked, malformed, " + "or invalid for other reasons.") + + +class InsufficientScopeError(OAuth2Error): + """ + The request requires higher privileges than provided by the + access token. The resource server SHOULD respond with the HTTP + 403 (Forbidden) status code and MAY include the "scope" + attribute with the scope necessary to access the protected + resource. + """ + error = 'insufficient_scope' + status_code = 403 + description = ("The request requires higher privileges than provided by " + "the access token.") + + +def raise_from_error(error, params=None): + kwargs = { + 'description': params.get('error_description'), + 'uri': params.get('error_uri'), + 'state': params.get('state') + } + for _, cls in inspect.getmembers(sys.modules[__name__], inspect.isclass): + if cls.error == error: + raise cls(**kwargs) diff --git a/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/grant_types/__init__.py b/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/grant_types/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8dad5f607b9856704b3f074d31f3b701ddfafd94 --- /dev/null +++ b/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/grant_types/__init__.py @@ -0,0 +1,13 @@ +""" +oauthlib.openid.connect.core.grant_types +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +""" +from .authorization_code import AuthorizationCodeGrant +from .base import GrantTypeBase +from .dispatchers import ( + AuthorizationCodeGrantDispatcher, AuthorizationTokenGrantDispatcher, + ImplicitTokenGrantDispatcher, +) +from .hybrid import HybridGrant +from .implicit import ImplicitGrant +from .refresh_token import RefreshTokenGrant diff --git a/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/grant_types/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/grant_types/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b4a87c00a5928e7c911de9a000aac3e7f35ee6ee Binary files /dev/null and b/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/grant_types/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/grant_types/__pycache__/authorization_code.cpython-313.pyc b/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/grant_types/__pycache__/authorization_code.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e12a4277486f13569bb6cf826eba26ba791b4f72 Binary files /dev/null and b/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/grant_types/__pycache__/authorization_code.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/grant_types/__pycache__/base.cpython-313.pyc b/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/grant_types/__pycache__/base.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f57fb16132ed9a1971ababd3e1b7dfa4523330d2 Binary files /dev/null and b/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/grant_types/__pycache__/base.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/grant_types/__pycache__/dispatchers.cpython-313.pyc b/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/grant_types/__pycache__/dispatchers.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1482f6f791f05a9f53951ac0a2a7db6aec0bef72 Binary files /dev/null and b/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/grant_types/__pycache__/dispatchers.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/grant_types/__pycache__/hybrid.cpython-313.pyc b/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/grant_types/__pycache__/hybrid.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7f3a9fc7b8c417f74f3fc42faedcbd9cbbdbd8ac Binary files /dev/null and b/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/grant_types/__pycache__/hybrid.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/grant_types/__pycache__/implicit.cpython-313.pyc b/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/grant_types/__pycache__/implicit.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..58441db4fd6643fd3321267f5c6a0f89e7a03c61 Binary files /dev/null and b/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/grant_types/__pycache__/implicit.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/grant_types/__pycache__/refresh_token.cpython-313.pyc b/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/grant_types/__pycache__/refresh_token.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e9b699d91b61fee4658b9ee1cfb18c7672ff4e38 Binary files /dev/null and b/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/grant_types/__pycache__/refresh_token.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/grant_types/authorization_code.py b/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/grant_types/authorization_code.py new file mode 100644 index 0000000000000000000000000000000000000000..6b2dcc3bdd12d27d280890494286efc5f0c9befb --- /dev/null +++ b/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/grant_types/authorization_code.py @@ -0,0 +1,43 @@ +""" +oauthlib.openid.connect.core.grant_types +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +""" +import logging + +from oauthlib.oauth2.rfc6749.grant_types.authorization_code import ( + AuthorizationCodeGrant as OAuth2AuthorizationCodeGrant, +) + +from .base import GrantTypeBase + +log = logging.getLogger(__name__) + + +class AuthorizationCodeGrant(GrantTypeBase): + + def __init__(self, request_validator=None, **kwargs): + self.proxy_target = OAuth2AuthorizationCodeGrant( + request_validator=request_validator, **kwargs) + self.custom_validators.post_auth.append( + self.openid_authorization_validator) + self.register_token_modifier(self.add_id_token) + + def add_id_token(self, token, token_handler, request): + """ + Construct an initial version of id_token, and let the + request_validator sign or encrypt it. + + The authorization_code version of this method is used to + retrieve the nonce accordingly to the code storage. + """ + # Treat it as normal OAuth 2 auth code request if openid is not present + if not request.scopes or 'openid' not in request.scopes: + return token + + nonce = self.request_validator.get_authorization_code_nonce( + request.client_id, + request.code, + request.redirect_uri, + request + ) + return super().add_id_token(token, token_handler, request, nonce=nonce) diff --git a/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/grant_types/base.py b/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/grant_types/base.py new file mode 100644 index 0000000000000000000000000000000000000000..29d583eb1c0677a5167ddccee274d596e3b1aca7 --- /dev/null +++ b/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/grant_types/base.py @@ -0,0 +1,330 @@ +import base64 +import hashlib +import logging +import time +from json import loads + +from oauthlib.oauth2.rfc6749.errors import ( + ConsentRequired, InvalidRequestError, LoginRequired, +) + +log = logging.getLogger(__name__) + + +class GrantTypeBase: + + # Just proxy the majority of method calls through to the + # proxy_target grant type handler, which will usually be either + # the standard OAuth2 AuthCode or Implicit grant types. + def __getattr__(self, attr): + return getattr(self.proxy_target, attr) + + def __setattr__(self, attr, value): + proxied_attrs = {'refresh_token', 'response_types'} + if attr in proxied_attrs: + setattr(self.proxy_target, attr, value) + else: + super(OpenIDConnectBase, self).__setattr__(attr, value) + + def validate_authorization_request(self, request): + """Validates the OpenID Connect authorization request parameters. + + :returns: (list of scopes, dict of request info) + """ + return self.proxy_target.validate_authorization_request(request) + + def _inflate_claims(self, request): + # this may be called multiple times in a single request so make sure we only de-serialize the claims once + if request.claims and not isinstance(request.claims, dict): + # specific claims are requested during the Authorization Request and may be requested for inclusion + # in either the id_token or the UserInfo endpoint response + # see http://openid.net/specs/openid-connect-core-1_0.html#ClaimsParameter + try: + request.claims = loads(request.claims) + except Exception as ex: + raise InvalidRequestError(description="Malformed claims parameter", + uri="http://openid.net/specs/openid-connect-core-1_0.html#ClaimsParameter") + + def id_token_hash(self, value, hashfunc=hashlib.sha256): + """ + Its value is the base64url encoding of the left-most half of the + hash of the octets of the ASCII representation of the access_token + value, where the hash algorithm used is the hash algorithm used in + the alg Header Parameter of the ID Token's JOSE Header. + + For instance, if the alg is RS256, hash the access_token value + with SHA-256, then take the left-most 128 bits and + base64url-encode them. + For instance, if the alg is HS512, hash the code value with + SHA-512, then take the left-most 256 bits and base64url-encode + them. The c_hash value is a case-sensitive string. + + Example of hash from OIDC specification (bound to a JWS using RS256): + + code: + Qcb0Orv1zh30vL1MPRsbm-diHiMwcLyZvn1arpZv-Jxf_11jnpEX3Tgfvk + + c_hash: + LDktKdoQak3Pk0cnXxCltA + """ + digest = hashfunc(value.encode()).digest() + left_most = len(digest) // 2 + return base64.urlsafe_b64encode(digest[:left_most]).decode().rstrip("=") + + def add_id_token(self, token, token_handler, request, nonce=None): + """ + Construct an initial version of id_token, and let the + request_validator sign or encrypt it. + + The initial version can contain the fields below, accordingly + to the spec: + - aud + - iat + - nonce + - at_hash + - c_hash + """ + # Treat it as normal OAuth 2 auth code request if openid is not present + if not request.scopes or 'openid' not in request.scopes: + return token + + # Only add an id token on auth/token step if asked for. + if request.response_type and 'id_token' not in request.response_type: + return token + + # Implementation mint its own id_token without help. + id_token = self.request_validator.get_id_token(token, token_handler, request) + if id_token: + token['id_token'] = id_token + return token + + # Fallback for asking some help from oauthlib framework. + # Start with technicals fields bound to the specification. + id_token = {} + id_token['aud'] = request.client_id + id_token['iat'] = int(time.time()) + + # nonce is REQUIRED when response_type value is: + # - id_token token (Implicit) + # - id_token (Implicit) + # - code id_token (Hybrid) + # - code id_token token (Hybrid) + # + # nonce is OPTIONAL when response_type value is: + # - code (Authorization Code) + # - code token (Hybrid) + if nonce is not None: + id_token["nonce"] = nonce + + # at_hash is REQUIRED when response_type value is: + # - id_token token (Implicit) + # - code id_token token (Hybrid) + # + # at_hash is OPTIONAL when: + # - code (Authorization code) + # - code id_token (Hybrid) + # - code token (Hybrid) + # + # at_hash MAY NOT be used when: + # - id_token (Implicit) + if "access_token" in token: + id_token["at_hash"] = self.id_token_hash(token["access_token"]) + + # c_hash is REQUIRED when response_type value is: + # - code id_token (Hybrid) + # - code id_token token (Hybrid) + # + # c_hash is OPTIONAL for others. + if "code" in token: + id_token["c_hash"] = self.id_token_hash(token["code"]) + + # Call request_validator to complete/sign/encrypt id_token + token['id_token'] = self.request_validator.finalize_id_token(id_token, token, token_handler, request) + + return token + + def openid_authorization_validator(self, request): + """Perform OpenID Connect specific authorization request validation. + + nonce + OPTIONAL. String value used to associate a Client session with + an ID Token, and to mitigate replay attacks. The value is + passed through unmodified from the Authentication Request to + the ID Token. Sufficient entropy MUST be present in the nonce + values used to prevent attackers from guessing values + + display + OPTIONAL. ASCII string value that specifies how the + Authorization Server displays the authentication and consent + user interface pages to the End-User. The defined values are: + + page - The Authorization Server SHOULD display the + authentication and consent UI consistent with a full User + Agent page view. If the display parameter is not specified, + this is the default display mode. + + popup - The Authorization Server SHOULD display the + authentication and consent UI consistent with a popup User + Agent window. The popup User Agent window should be of an + appropriate size for a login-focused dialog and should not + obscure the entire window that it is popping up over. + + touch - The Authorization Server SHOULD display the + authentication and consent UI consistent with a device that + leverages a touch interface. + + wap - The Authorization Server SHOULD display the + authentication and consent UI consistent with a "feature + phone" type display. + + The Authorization Server MAY also attempt to detect the + capabilities of the User Agent and present an appropriate + display. + + prompt + OPTIONAL. Space delimited, case sensitive list of ASCII string + values that specifies whether the Authorization Server prompts + the End-User for reauthentication and consent. The defined + values are: + + none - The Authorization Server MUST NOT display any + authentication or consent user interface pages. An error is + returned if an End-User is not already authenticated or the + Client does not have pre-configured consent for the + requested Claims or does not fulfill other conditions for + processing the request. The error code will typically be + login_required, interaction_required, or another code + defined in Section 3.1.2.6. This can be used as a method to + check for existing authentication and/or consent. + + login - The Authorization Server SHOULD prompt the End-User + for reauthentication. If it cannot reauthenticate the + End-User, it MUST return an error, typically + login_required. + + consent - The Authorization Server SHOULD prompt the + End-User for consent before returning information to the + Client. If it cannot obtain consent, it MUST return an + error, typically consent_required. + + select_account - The Authorization Server SHOULD prompt the + End-User to select a user account. This enables an End-User + who has multiple accounts at the Authorization Server to + select amongst the multiple accounts that they might have + current sessions for. If it cannot obtain an account + selection choice made by the End-User, it MUST return an + error, typically account_selection_required. + + The prompt parameter can be used by the Client to make sure + that the End-User is still present for the current session or + to bring attention to the request. If this parameter contains + none with any other value, an error is returned. + + max_age + OPTIONAL. Maximum Authentication Age. Specifies the allowable + elapsed time in seconds since the last time the End-User was + actively authenticated by the OP. If the elapsed time is + greater than this value, the OP MUST attempt to actively + re-authenticate the End-User. (The max_age request parameter + corresponds to the OpenID 2.0 PAPE [OpenID.PAPE] max_auth_age + request parameter.) When max_age is used, the ID Token returned + MUST include an auth_time Claim Value. + + ui_locales + OPTIONAL. End-User's preferred languages and scripts for the + user interface, represented as a space-separated list of BCP47 + [RFC5646] language tag values, ordered by preference. For + instance, the value "fr-CA fr en" represents a preference for + French as spoken in Canada, then French (without a region + designation), followed by English (without a region + designation). An error SHOULD NOT result if some or all of the + requested locales are not supported by the OpenID Provider. + + id_token_hint + OPTIONAL. ID Token previously issued by the Authorization + Server being passed as a hint about the End-User's current or + past authenticated session with the Client. If the End-User + identified by the ID Token is logged in or is logged in by the + request, then the Authorization Server returns a positive + response; otherwise, it SHOULD return an error, such as + login_required. When possible, an id_token_hint SHOULD be + present when prompt=none is used and an invalid_request error + MAY be returned if it is not; however, the server SHOULD + respond successfully when possible, even if it is not present. + The Authorization Server need not be listed as an audience of + the ID Token when it is used as an id_token_hint value. If the + ID Token received by the RP from the OP is encrypted, to use it + as an id_token_hint, the Client MUST decrypt the signed ID + Token contained within the encrypted ID Token. The Client MAY + re-encrypt the signed ID token to the Authentication Server + using a key that enables the server to decrypt the ID Token, + and use the re-encrypted ID token as the id_token_hint value. + + login_hint + OPTIONAL. Hint to the Authorization Server about the login + identifier the End-User might use to log in (if necessary). + This hint can be used by an RP if it first asks the End-User + for their e-mail address (or other identifier) and then wants + to pass that value as a hint to the discovered authorization + service. It is RECOMMENDED that the hint value match the value + used for discovery. This value MAY also be a phone number in + the format specified for the phone_number Claim. The use of + this parameter is left to the OP's discretion. + + acr_values + OPTIONAL. Requested Authentication Context Class Reference + values. Space-separated string that specifies the acr values + that the Authorization Server is being requested to use for + processing this Authentication Request, with the values + appearing in order of preference. The Authentication Context + Class satisfied by the authentication performed is returned as + the acr Claim Value, as specified in Section 2. The acr Claim + is requested as a Voluntary Claim by this parameter. + """ + + # Treat it as normal OAuth 2 auth code request if openid is not present + if not request.scopes or 'openid' not in request.scopes: + return {} + + prompt = request.prompt if request.prompt else [] + if hasattr(prompt, 'split'): + prompt = prompt.strip().split() + prompt = set(prompt) + + if 'none' in prompt: + + if len(prompt) > 1: + msg = "Prompt none is mutually exclusive with other values." + raise InvalidRequestError(request=request, description=msg) + + if not self.request_validator.validate_silent_login(request): + raise LoginRequired(request=request) + + if not self.request_validator.validate_silent_authorization(request): + raise ConsentRequired(request=request) + + self._inflate_claims(request) + + if not self.request_validator.validate_user_match( + request.id_token_hint, request.scopes, request.claims, request): + msg = "Session user does not match client supplied user." + raise LoginRequired(request=request, description=msg) + + ui_locales = request.ui_locales if request.ui_locales else [] + if hasattr(ui_locales, 'split'): + ui_locales = ui_locales.strip().split() + + request_info = { + 'display': request.display, + 'nonce': request.nonce, + 'prompt': prompt, + 'ui_locales': ui_locales, + 'id_token_hint': request.id_token_hint, + 'login_hint': request.login_hint, + 'claims': request.claims + } + + return request_info + + +OpenIDConnectBase = GrantTypeBase diff --git a/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/grant_types/dispatchers.py b/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/grant_types/dispatchers.py new file mode 100644 index 0000000000000000000000000000000000000000..7e0739684f107801ff094f98190efcd17ae438c1 --- /dev/null +++ b/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/grant_types/dispatchers.py @@ -0,0 +1,101 @@ +import logging + +log = logging.getLogger(__name__) + + +class Dispatcher: + default_grant = None + oidc_grant = None + + +class AuthorizationCodeGrantDispatcher(Dispatcher): + """ + This is an adapter class that will route simple Authorization Code + requests, those that have `response_type=code` and a scope including + `openid` to either the `default_grant` or the `oidc_grant` based on + the scopes requested. + """ + def __init__(self, default_grant=None, oidc_grant=None): + self.default_grant = default_grant + self.oidc_grant = oidc_grant + + def _handler_for_request(self, request): + handler = self.default_grant + + if request.scopes and "openid" in request.scopes: + handler = self.oidc_grant + + log.debug('Selecting handler for request %r.', handler) + return handler + + def create_authorization_response(self, request, token_handler): + """Read scope and route to the designated handler.""" + return self._handler_for_request(request).create_authorization_response(request, token_handler) + + def validate_authorization_request(self, request): + """Read scope and route to the designated handler.""" + return self._handler_for_request(request).validate_authorization_request(request) + + +class ImplicitTokenGrantDispatcher(Dispatcher): + """ + This is an adapter class that will route simple Authorization + requests, those that have `id_token` in `response_type` and a scope + including `openid` to either the `default_grant` or the `oidc_grant` + based on the scopes requested. + """ + def __init__(self, default_grant=None, oidc_grant=None): + self.default_grant = default_grant + self.oidc_grant = oidc_grant + + def _handler_for_request(self, request): + handler = self.default_grant + + if request.scopes and "openid" in request.scopes and 'id_token' in request.response_type: + handler = self.oidc_grant + + log.debug('Selecting handler for request %r.', handler) + return handler + + def create_authorization_response(self, request, token_handler): + """Read scope and route to the designated handler.""" + return self._handler_for_request(request).create_authorization_response(request, token_handler) + + def validate_authorization_request(self, request): + """Read scope and route to the designated handler.""" + return self._handler_for_request(request).validate_authorization_request(request) + + +class AuthorizationTokenGrantDispatcher(Dispatcher): + """ + This is an adapter class that will route simple Token requests, those that authorization_code have a scope + including 'openid' to either the default_grant or the oidc_grant based on the scopes requested. + """ + def __init__(self, request_validator, default_grant=None, oidc_grant=None): + self.default_grant = default_grant + self.oidc_grant = oidc_grant + self.request_validator = request_validator + + def _handler_for_request(self, request): + handler = self.default_grant + scopes = () + parameters = dict(request.decoded_body) + client_id = parameters.get('client_id') + code = parameters.get('code') + redirect_uri = parameters.get('redirect_uri') + + # If code is not present fallback to `default_grant` which will + # raise an error for the missing `code` in `create_token_response` step. + if code: + scopes = self.request_validator.get_authorization_code_scopes(client_id, code, redirect_uri, request) + + if 'openid' in scopes: + handler = self.oidc_grant + + log.debug('Selecting handler for request %r.', handler) + return handler + + def create_token_response(self, request, token_handler): + """Read scope and route to the designated handler.""" + handler = self._handler_for_request(request) + return handler.create_token_response(request, token_handler) diff --git a/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/grant_types/hybrid.py b/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/grant_types/hybrid.py new file mode 100644 index 0000000000000000000000000000000000000000..9c1fc702f9496c592b06437e774c5d492c1b7de3 --- /dev/null +++ b/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/grant_types/hybrid.py @@ -0,0 +1,62 @@ +""" +oauthlib.openid.connect.core.grant_types +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +""" +import logging + +from oauthlib.oauth2.rfc6749.errors import InvalidRequestError +from oauthlib.oauth2.rfc6749.grant_types.authorization_code import ( + AuthorizationCodeGrant as OAuth2AuthorizationCodeGrant, +) + +from ..request_validator import RequestValidator +from .base import GrantTypeBase + +log = logging.getLogger(__name__) + + +class HybridGrant(GrantTypeBase): + + def __init__(self, request_validator=None, **kwargs): + self.request_validator = request_validator or RequestValidator() + + self.proxy_target = OAuth2AuthorizationCodeGrant( + request_validator=request_validator, **kwargs) + # All hybrid response types should be fragment-encoded. + self.proxy_target.default_response_mode = "fragment" + self.register_response_type('code id_token') + self.register_response_type('code token') + self.register_response_type('code id_token token') + self.custom_validators.post_auth.append( + self.openid_authorization_validator) + # Hybrid flows can return the id_token from the authorization + # endpoint as part of the 'code' response + self.register_code_modifier(self.add_token) + self.register_code_modifier(self.add_id_token) + self.register_token_modifier(self.add_id_token) + + def add_id_token(self, token, token_handler, request): + return super().add_id_token(token, token_handler, request, nonce=request.nonce) + + def openid_authorization_validator(self, request): + """Additional validation when following the Authorization Code flow. + """ + request_info = super().openid_authorization_validator(request) + if not request_info: # returns immediately if OAuth2.0 + return request_info + + # REQUIRED if the Response Type of the request is `code + # id_token` or `code id_token token` and OPTIONAL when the + # Response Type of the request is `code token`. It is a string + # value used to associate a Client session with an ID Token, + # and to mitigate replay attacks. The value is passed through + # unmodified from the Authentication Request to the ID + # Token. Sufficient entropy MUST be present in the `nonce` + # values used to prevent attackers from guessing values. For + # implementation notes, see Section 15.5.2. + if request.response_type in ["code id_token", "code id_token token"] and not request.nonce: + raise InvalidRequestError( + request=request, + description='Request is missing mandatory nonce parameter.' + ) + return request_info diff --git a/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/grant_types/implicit.py b/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/grant_types/implicit.py new file mode 100644 index 0000000000000000000000000000000000000000..a4fe6049bc29a8d9b202b9e0244a1b6c559d99d6 --- /dev/null +++ b/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/grant_types/implicit.py @@ -0,0 +1,51 @@ +""" +oauthlib.openid.connect.core.grant_types +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +""" +import logging + +from oauthlib.oauth2.rfc6749.errors import InvalidRequestError +from oauthlib.oauth2.rfc6749.grant_types.implicit import ( + ImplicitGrant as OAuth2ImplicitGrant, +) + +from .base import GrantTypeBase + +log = logging.getLogger(__name__) + + +class ImplicitGrant(GrantTypeBase): + + def __init__(self, request_validator=None, **kwargs): + self.proxy_target = OAuth2ImplicitGrant( + request_validator=request_validator, **kwargs) + self.register_response_type('id_token') + self.register_response_type('id_token token') + self.custom_validators.post_auth.append( + self.openid_authorization_validator) + self.register_token_modifier(self.add_id_token) + + def add_id_token(self, token, token_handler, request): + if 'state' not in token and request.state: + token['state'] = request.state + return super().add_id_token(token, token_handler, request, nonce=request.nonce) + + def openid_authorization_validator(self, request): + """Additional validation when following the implicit flow. + """ + request_info = super().openid_authorization_validator(request) + if not request_info: # returns immediately if OAuth2.0 + return request_info + + # REQUIRED. String value used to associate a Client session with an ID + # Token, and to mitigate replay attacks. The value is passed through + # unmodified from the Authentication Request to the ID Token. + # Sufficient entropy MUST be present in the nonce values used to + # prevent attackers from guessing values. For implementation notes, see + # Section 15.5.2. + if not request.nonce: + raise InvalidRequestError( + request=request, + description='Request is missing mandatory nonce parameter.' + ) + return request_info diff --git a/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/grant_types/refresh_token.py b/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/grant_types/refresh_token.py new file mode 100644 index 0000000000000000000000000000000000000000..43e4499c53c77a7f1486981f84e7fe49cf71f545 --- /dev/null +++ b/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/grant_types/refresh_token.py @@ -0,0 +1,34 @@ +""" +oauthlib.openid.connect.core.grant_types +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +""" +import logging + +from oauthlib.oauth2.rfc6749.grant_types.refresh_token import ( + RefreshTokenGrant as OAuth2RefreshTokenGrant, +) + +from .base import GrantTypeBase + +log = logging.getLogger(__name__) + + +class RefreshTokenGrant(GrantTypeBase): + + def __init__(self, request_validator=None, **kwargs): + self.proxy_target = OAuth2RefreshTokenGrant( + request_validator=request_validator, **kwargs) + self.register_token_modifier(self.add_id_token) + + def add_id_token(self, token, token_handler, request): + """ + Construct an initial version of id_token, and let the + request_validator sign or encrypt it. + + The authorization_code version of this method is used to + retrieve the nonce accordingly to the code storage. + """ + if not self.request_validator.refresh_id_token(request): + return token + + return super().add_id_token(token, token_handler, request) diff --git a/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/request_validator.py b/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/request_validator.py new file mode 100644 index 0000000000000000000000000000000000000000..e3cea79b774d58cae6cc99be28334f76e1d67b56 --- /dev/null +++ b/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/request_validator.py @@ -0,0 +1,320 @@ +""" +oauthlib.openid.connect.core.request_validator +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +""" +import logging + +from oauthlib.oauth2.rfc6749.request_validator import ( + RequestValidator as OAuth2RequestValidator, +) + +log = logging.getLogger(__name__) + + +class RequestValidator(OAuth2RequestValidator): + + def get_authorization_code_scopes(self, client_id, code, redirect_uri, request): + """ Extracts scopes from saved authorization code. + + The scopes returned by this method is used to route token requests + based on scopes passed to Authorization Code requests. + + With that the token endpoint knows when to include OpenIDConnect + id_token in token response only based on authorization code scopes. + + Only code param should be sufficient to retrieve grant code from + any storage you are using, `client_id` and `redirect_uri` can have a + blank value `""` don't forget to check it before using those values + in a select query if a database is used. + + :param client_id: Unicode client identifier + :param code: Unicode authorization code grant + :param redirect_uri: Unicode absolute URI + :return: A list of scope + + Method is used by: + - Authorization Token Grant Dispatcher + """ + raise NotImplementedError('Subclasses must implement this method.') + + def get_authorization_code_nonce(self, client_id, code, redirect_uri, request): + """ Extracts nonce from saved authorization code. + + If present in the Authentication Request, Authorization + Servers MUST include a nonce Claim in the ID Token with the + Claim Value being the nonce value sent in the Authentication + Request. Authorization Servers SHOULD perform no other + processing on nonce values used. The nonce value is a + case-sensitive string. + + Only code param should be sufficient to retrieve grant code from + any storage you are using. However, `client_id` and `redirect_uri` + have been validated and can be used also. + + :param client_id: Unicode client identifier + :param code: Unicode authorization code grant + :param redirect_uri: Unicode absolute URI + :return: Unicode nonce + + Method is used by: + - Authorization Token Grant Dispatcher + """ + raise NotImplementedError('Subclasses must implement this method.') + + def get_jwt_bearer_token(self, token, token_handler, request): + """Get JWT Bearer token or OpenID Connect ID token + + If using OpenID Connect this SHOULD call `oauthlib.oauth2.RequestValidator.get_id_token` + + :param token: A Bearer token dict + :param token_handler: the token handler (BearerToken class) + :param request: OAuthlib request. + :type request: oauthlib.common.Request + :return: The JWT Bearer token or OpenID Connect ID token (a JWS signed JWT) + + Method is used by JWT Bearer and OpenID Connect tokens: + - JWTToken.create_token + """ + raise NotImplementedError('Subclasses must implement this method.') + + def get_id_token(self, token, token_handler, request): + """Get OpenID Connect ID token + + This method is OPTIONAL and is NOT RECOMMENDED. + `finalize_id_token` SHOULD be implemented instead. However, if you + want a full control over the minting of the `id_token`, you + MAY want to override `get_id_token` instead of using + `finalize_id_token`. + + In the OpenID Connect workflows when an ID Token is requested this method is called. + Subclasses should implement the construction, signing and optional encryption of the + ID Token as described in the OpenID Connect spec. + + In addition to the standard OAuth2 request properties, the request may also contain + these OIDC specific properties which are useful to this method: + + - nonce, if workflow is implicit or hybrid and it was provided + - claims, if provided to the original Authorization Code request + + The token parameter is a dict which may contain an ``access_token`` entry, in which + case the resulting ID Token *should* include a calculated ``at_hash`` claim. + + Similarly, when the request parameter has a ``code`` property defined, the ID Token + *should* include a calculated ``c_hash`` claim. + + http://openid.net/specs/openid-connect-core-1_0.html (sections `3.1.3.6`_, `3.2.2.10`_, `3.3.2.11`_) + + .. _`3.1.3.6`: http://openid.net/specs/openid-connect-core-1_0.html#CodeIDToken + .. _`3.2.2.10`: http://openid.net/specs/openid-connect-core-1_0.html#ImplicitIDToken + .. _`3.3.2.11`: http://openid.net/specs/openid-connect-core-1_0.html#HybridIDToken + + :param token: A Bearer token dict + :param token_handler: the token handler (BearerToken class) + :param request: OAuthlib request. + :type request: oauthlib.common.Request + :return: The ID Token (a JWS signed JWT) + """ + return None + + def finalize_id_token(self, id_token, token, token_handler, request): + """Finalize OpenID Connect ID token & Sign or Encrypt. + + In the OpenID Connect workflows when an ID Token is requested + this method is called. Subclasses should implement the + construction, signing and optional encryption of the ID Token + as described in the OpenID Connect spec. + + The `id_token` parameter is a dict containing a couple of OIDC + technical fields related to the specification. Prepopulated + attributes are: + + - `aud`, equals to `request.client_id`. + - `iat`, equals to current time. + - `nonce`, if present, is equals to the `nonce` from the + authorization request. + - `at_hash`, hash of `access_token`, if relevant. + - `c_hash`, hash of `code`, if relevant. + + This method MUST provide required fields as below: + + - `iss`, REQUIRED. Issuer Identifier for the Issuer of the response. + - `sub`, REQUIRED. Subject Identifier + - `exp`, REQUIRED. Expiration time on or after which the ID + Token MUST NOT be accepted by the RP when performing + authentication with the OP. + + Additional claims must be added, note that `request.scope` + should be used to determine the list of claims. + + More information can be found at `OpenID Connect Core#Claims`_ + + .. _`OpenID Connect Core#Claims`: https://openid.net/specs/openid-connect-core-1_0.html#Claims + + :param id_token: A dict containing technical fields of id_token + :param token: A Bearer token dict + :param token_handler: the token handler (BearerToken class) + :param request: OAuthlib request. + :type request: oauthlib.common.Request + :return: The ID Token (a JWS signed JWT or JWE encrypted JWT) + """ + raise NotImplementedError('Subclasses must implement this method.') + + def validate_jwt_bearer_token(self, token, scopes, request): + """Ensure the JWT Bearer token or OpenID Connect ID token are valids and authorized access to scopes. + + If using OpenID Connect this SHOULD call `oauthlib.oauth2.RequestValidator.get_id_token` + + If not using OpenID Connect this can `return None` to avoid 5xx rather 401/3 response. + + OpenID connect core 1.0 describe how to validate an id_token: + - http://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation + - http://openid.net/specs/openid-connect-core-1_0.html#ImplicitIDTValidation + - http://openid.net/specs/openid-connect-core-1_0.html#HybridIDTValidation + - http://openid.net/specs/openid-connect-core-1_0.html#HybridIDTValidation2 + + :param token: Unicode Bearer token + :param scopes: List of scopes (defined by you) + :param request: OAuthlib request. + :type request: oauthlib.common.Request + :rtype: True or False + + Method is indirectly used by all core OpenID connect JWT token issuing grant types: + - Authorization Code Grant + - Implicit Grant + - Hybrid Grant + """ + raise NotImplementedError('Subclasses must implement this method.') + + def validate_id_token(self, token, scopes, request): + """Ensure the id token is valid and authorized access to scopes. + + OpenID connect core 1.0 describe how to validate an id_token: + - http://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation + - http://openid.net/specs/openid-connect-core-1_0.html#ImplicitIDTValidation + - http://openid.net/specs/openid-connect-core-1_0.html#HybridIDTValidation + - http://openid.net/specs/openid-connect-core-1_0.html#HybridIDTValidation2 + + :param token: Unicode Bearer token + :param scopes: List of scopes (defined by you) + :param request: OAuthlib request. + :type request: oauthlib.common.Request + :rtype: True or False + + Method is indirectly used by all core OpenID connect JWT token issuing grant types: + - Authorization Code Grant + - Implicit Grant + - Hybrid Grant + """ + raise NotImplementedError('Subclasses must implement this method.') + + def validate_silent_authorization(self, request): + """Ensure the logged in user has authorized silent OpenID authorization. + + Silent OpenID authorization allows access tokens and id tokens to be + granted to clients without any user prompt or interaction. + + :param request: OAuthlib request. + :type request: oauthlib.common.Request + :rtype: True or False + + Method is used by: + - OpenIDConnectAuthCode + - OpenIDConnectImplicit + - OpenIDConnectHybrid + """ + raise NotImplementedError('Subclasses must implement this method.') + + def validate_silent_login(self, request): + """Ensure session user has authorized silent OpenID login. + + If no user is logged in or has not authorized silent login, this + method should return False. + + If the user is logged in but associated with multiple accounts and + not selected which one to link to the token then this method should + raise an oauthlib.oauth2.AccountSelectionRequired error. + + :param request: OAuthlib request. + :type request: oauthlib.common.Request + :rtype: True or False + + Method is used by: + - OpenIDConnectAuthCode + - OpenIDConnectImplicit + - OpenIDConnectHybrid + """ + raise NotImplementedError('Subclasses must implement this method.') + + def validate_user_match(self, id_token_hint, scopes, claims, request): + """Ensure client supplied user id hint matches session user. + + If the sub claim or id_token_hint is supplied then the session + user must match the given ID. + + :param id_token_hint: User identifier string. + :param scopes: List of OAuth 2 scopes and OpenID claims (strings). + :param claims: OpenID Connect claims dict. + :param request: OAuthlib request. + :type request: oauthlib.common.Request + :rtype: True or False + + Method is used by: + - OpenIDConnectAuthCode + - OpenIDConnectImplicit + - OpenIDConnectHybrid + """ + raise NotImplementedError('Subclasses must implement this method.') + + def get_userinfo_claims(self, request): + """Return the UserInfo claims in JSON or Signed or Encrypted. + + The UserInfo Claims MUST be returned as the members of a JSON object + unless a signed or encrypted response was requested during Client + Registration. The Claims defined in Section 5.1 can be returned, as can + additional Claims not specified there. + + For privacy reasons, OpenID Providers MAY elect to not return values for + some requested Claims. + + If a Claim is not returned, that Claim Name SHOULD be omitted from the + JSON object representing the Claims; it SHOULD NOT be present with a + null or empty string value. + + The sub (subject) Claim MUST always be returned in the UserInfo + Response. + + Upon receipt of the UserInfo Request, the UserInfo Endpoint MUST return + the JSON Serialization of the UserInfo Response as in Section 13.3 in + the HTTP response body unless a different format was specified during + Registration [OpenID.Registration]. + + If the UserInfo Response is signed and/or encrypted, then the Claims are + returned in a JWT and the content-type MUST be application/jwt. The + response MAY be encrypted without also being signed. If both signing and + encryption are requested, the response MUST be signed then encrypted, + with the result being a Nested JWT, as defined in [JWT]. + + If signed, the UserInfo Response SHOULD contain the Claims iss (issuer) + and aud (audience) as members. The iss value SHOULD be the OP's Issuer + Identifier URL. The aud value SHOULD be or include the RP's Client ID + value. + + :param request: OAuthlib request. + :type request: oauthlib.common.Request + :rtype: Claims as a dict OR JWT/JWS/JWE as a string + + Method is used by: + UserInfoEndpoint + """ + + def refresh_id_token(self, request): + """Whether the id token should be refreshed. Default, True + + :param request: OAuthlib request. + :type request: oauthlib.common.Request + :rtype: True or False + + Method is used by: + RefreshTokenGrant + """ + return True diff --git a/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/tokens.py b/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/tokens.py new file mode 100644 index 0000000000000000000000000000000000000000..3ab35492434d31f1f45741233b9ceb31eb54b96a --- /dev/null +++ b/python/user_packages/Python313/site-packages/oauthlib/openid/connect/core/tokens.py @@ -0,0 +1,45 @@ +""" +authlib.openid.connect.core.tokens +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +This module contains methods for adding JWT tokens to requests. +""" +from oauthlib.oauth2.rfc6749.tokens import ( + TokenBase, get_token_from_header, random_token_generator, +) + + +class JWTToken(TokenBase): + __slots__ = ( + 'request_validator', 'token_generator', + 'refresh_token_generator', 'expires_in' + ) + + def __init__(self, request_validator=None, token_generator=None, + expires_in=None, refresh_token_generator=None): + self.request_validator = request_validator + self.token_generator = token_generator or random_token_generator + self.refresh_token_generator = ( + refresh_token_generator or self.token_generator + ) + self.expires_in = expires_in or 3600 + + def create_token(self, request, refresh_token=False): + """Create a JWT Token, using requestvalidator method.""" + + expires_in = self.expires_in(request) if callable(self.expires_in) else self.expires_in + + request.expires_in = expires_in + + return self.request_validator.get_jwt_bearer_token(None, None, request) + + def validate_request(self, request): + token = get_token_from_header(request) + return self.request_validator.validate_jwt_bearer_token( + token, request.scopes, request) + + def estimate_type(self, request): + token = get_token_from_header(request) + if token and token.startswith('ey') and token.count('.') in (2, 4): + return 10 + return 0 diff --git a/python/user_packages/Python313/site-packages/onnxruntime/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e6c617f8fe32ccb73462035e933f01f9bc2825d9 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/backend/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/backend/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a69b913242fc1a30730195daa97d19163b460e66 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/backend/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/backend/__pycache__/backend.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/backend/__pycache__/backend.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eb7e79e2d6c12348fbd305b034ff00fdfec3b659 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/backend/__pycache__/backend.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/backend/__pycache__/backend_rep.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/backend/__pycache__/backend_rep.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..975bfab345f6bf57bd9cc59b8c69283f025156df Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/backend/__pycache__/backend_rep.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/capi/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/capi/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cdf476e5b9d422313de923b923a29c8742719d2e Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/capi/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/capi/__pycache__/_ld_preload.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/capi/__pycache__/_ld_preload.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4e1765c441bc3c8f59add699dc9ecafbafd3ad62 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/capi/__pycache__/_ld_preload.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/capi/__pycache__/_pybind_state.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/capi/__pycache__/_pybind_state.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..04702d2aebe8e1c191f4e13f28ea7074b7ec9d96 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/capi/__pycache__/_pybind_state.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/capi/__pycache__/build_and_package_info.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/capi/__pycache__/build_and_package_info.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..070084352c2b7e39b86dc22a72fb57220605eca8 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/capi/__pycache__/build_and_package_info.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/capi/__pycache__/convert_npz_to_onnx_adapter.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/capi/__pycache__/convert_npz_to_onnx_adapter.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..19a163896a935ddec590b0a88c7ad0ccdbc584a9 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/capi/__pycache__/convert_npz_to_onnx_adapter.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/capi/__pycache__/onnxruntime_collect_build_info.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/capi/__pycache__/onnxruntime_collect_build_info.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..23c8765fc22a21ee347bca72f62732bea6185094 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/capi/__pycache__/onnxruntime_collect_build_info.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/capi/__pycache__/onnxruntime_inference_collection.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/capi/__pycache__/onnxruntime_inference_collection.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f0c0cc9e95b9f5a1d597dfaa1491d3ed36358c7d Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/capi/__pycache__/onnxruntime_inference_collection.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/capi/__pycache__/onnxruntime_validation.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/capi/__pycache__/onnxruntime_validation.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c85d4d0e3adc309f6193623d1413ba7c284bda95 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/capi/__pycache__/onnxruntime_validation.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/capi/__pycache__/version_info.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/capi/__pycache__/version_info.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e6eb39e71cacee4b96d5e884e48a5e991817ee57 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/capi/__pycache__/version_info.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/datasets/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/datasets/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..234e325be414cc62574cf6af367acd82a5ff1508 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/datasets/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/CalTableFlatBuffers/KeyValue.py b/python/user_packages/Python313/site-packages/onnxruntime/quantization/CalTableFlatBuffers/KeyValue.py new file mode 100644 index 0000000000000000000000000000000000000000..b97c226892b1109e1817080bdf13684f7929b098 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/quantization/CalTableFlatBuffers/KeyValue.py @@ -0,0 +1,78 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: CalTableFlatBuffers + +import flatbuffers +from flatbuffers.compat import import_numpy + +np = import_numpy() + + +class KeyValue: + __slots__ = ["_tab"] + + @classmethod + def GetRootAs(cls, buf, offset=0): # noqa: N802 + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = KeyValue() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsKeyValue(cls, buf, offset=0): # noqa: N802 + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + + # KeyValue + def Init(self, buf, pos): # noqa: N802 + self._tab = flatbuffers.table.Table(buf, pos) + + # KeyValue + def Key(self): # noqa: N802 + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.String(o + self._tab.Pos) + return None + + # KeyValue + def Value(self): # noqa: N802 + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.String(o + self._tab.Pos) + return None + + +def Start(builder): # noqa: N802 + builder.StartObject(2) + + +def KeyValueStart(builder): # noqa: N802 + """This method is deprecated. Please switch to Start.""" + return Start(builder) + + +def AddKey(builder, key): # noqa: N802 + builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(key), 0) + + +def KeyValueAddKey(builder, key): # noqa: N802 + """This method is deprecated. Please switch to AddKey.""" + return AddKey(builder, key) + + +def AddValue(builder, value): # noqa: N802 + builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(value), 0) + + +def KeyValueAddValue(builder, value): # noqa: N802 + """This method is deprecated. Please switch to AddValue.""" + return AddValue(builder, value) + + +def End(builder): # noqa: N802 + return builder.EndObject() + + +def KeyValueEnd(builder): # noqa: N802 + """This method is deprecated. Please switch to End.""" + return End(builder) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/CalTableFlatBuffers/TrtTable.py b/python/user_packages/Python313/site-packages/onnxruntime/quantization/CalTableFlatBuffers/TrtTable.py new file mode 100644 index 0000000000000000000000000000000000000000..9b57c84c4485049e9f5c1ef6257b5c55eace6006 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/quantization/CalTableFlatBuffers/TrtTable.py @@ -0,0 +1,90 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: CalTableFlatBuffers + +import flatbuffers +from flatbuffers.compat import import_numpy + +np = import_numpy() + + +class TrtTable: + __slots__ = ["_tab"] + + @classmethod + def GetRootAs(cls, buf, offset=0): # noqa: N802 + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = TrtTable() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsTrtTable(cls, buf, offset=0): # noqa: N802 + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + + # TrtTable + def Init(self, buf, pos): # noqa: N802 + self._tab = flatbuffers.table.Table(buf, pos) + + # TrtTable + def Dict(self, j): # noqa: N802 + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + x = self._tab.Vector(o) + x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4 + x = self._tab.Indirect(x) + from onnxruntime.quantization.CalTableFlatBuffers.KeyValue import KeyValue # noqa: PLC0415 + + obj = KeyValue() + obj.Init(self._tab.Bytes, x) + return obj + return None + + # TrtTable + def DictLength(self): # noqa: N802 + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # TrtTable + def DictIsNone(self): # noqa: N802 + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + return o == 0 + + +def Start(builder): # noqa: N802 + builder.StartObject(1) + + +def TrtTableStart(builder): # noqa: N802 + """This method is deprecated. Please switch to Start.""" + return Start(builder) + + +def AddDict(builder, dict): # noqa: N802 + builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(dict), 0) + + +def TrtTableAddDict(builder, dict): # noqa: N802 + """This method is deprecated. Please switch to AddDict.""" + return AddDict(builder, dict) + + +def StartDictVector(builder, numElems): # noqa: N802 + return builder.StartVector(4, numElems, 4) + + +def TrtTableStartDictVector(builder, numElems): # noqa: N802 + """This method is deprecated. Please switch to Start.""" + return StartDictVector(builder, numElems) + + +def End(builder): # noqa: N802 + return builder.EndObject() + + +def TrtTableEnd(builder): # noqa: N802 + """This method is deprecated. Please switch to End.""" + return End(builder) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/CalTableFlatBuffers/__init__.py b/python/user_packages/Python313/site-packages/onnxruntime/quantization/CalTableFlatBuffers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/CalTableFlatBuffers/__pycache__/KeyValue.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/quantization/CalTableFlatBuffers/__pycache__/KeyValue.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6f0f1136a5f82ef7790b0ebfd504ca1252006c0b Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/quantization/CalTableFlatBuffers/__pycache__/KeyValue.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/CalTableFlatBuffers/__pycache__/TrtTable.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/quantization/CalTableFlatBuffers/__pycache__/TrtTable.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c25acfc0fff2c1977485384a4f00e3d6e12043f5 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/quantization/CalTableFlatBuffers/__pycache__/TrtTable.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/CalTableFlatBuffers/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/quantization/CalTableFlatBuffers/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a1cfbee0858478f3ff7e26d3a458862e989cb645 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/quantization/CalTableFlatBuffers/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/quantization/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3427f261525fef39c0fa7fd6399c7a01fac3f37d Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/quantization/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/__pycache__/base_quantizer.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/quantization/__pycache__/base_quantizer.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7cd9393082f0cb96c928271ccff6881fe50cec00 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/quantization/__pycache__/base_quantizer.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/__pycache__/calibrate.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/quantization/__pycache__/calibrate.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4ccb1aab5a73cd40bada3d16ad598d6a83d1c309 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/quantization/__pycache__/calibrate.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/__pycache__/matmul_bnb4_quantizer.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/quantization/__pycache__/matmul_bnb4_quantizer.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e667fea6df4070409899a9d6dc7a035b007d34cd Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/quantization/__pycache__/matmul_bnb4_quantizer.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/__pycache__/matmul_nbits_quantizer.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/quantization/__pycache__/matmul_nbits_quantizer.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..caa6ed51cd5905c4525211f4e2969befc88400a5 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/quantization/__pycache__/matmul_nbits_quantizer.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/__pycache__/onnx_model.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/quantization/__pycache__/onnx_model.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..38cf1bde69ce1a9ff8b5828b256f1fea4fedaa7b Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/quantization/__pycache__/onnx_model.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/__pycache__/onnx_quantizer.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/quantization/__pycache__/onnx_quantizer.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4d8bb53541939ce65d905e50008c87b07a46d308 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/quantization/__pycache__/onnx_quantizer.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/__pycache__/preprocess.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/quantization/__pycache__/preprocess.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cfa50b93da8eda2df70c8c0e62dc8ecf52f35429 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/quantization/__pycache__/preprocess.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/__pycache__/qdq_loss_debug.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/quantization/__pycache__/qdq_loss_debug.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d7885e2a511e1bb3f00e1973901c7deb13ca2506 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/quantization/__pycache__/qdq_loss_debug.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/__pycache__/qdq_quantizer.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/quantization/__pycache__/qdq_quantizer.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9205eaac6b7eb9cd9f2da28e35522e3a3b81a0e8 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/quantization/__pycache__/qdq_quantizer.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/__pycache__/quant_utils.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/quantization/__pycache__/quant_utils.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4efbb8c8b01e09c6641f9397e343c83f53762ce4 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/quantization/__pycache__/quant_utils.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/__pycache__/quantize.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/quantization/__pycache__/quantize.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e37df9466ca52aa569be85ad6b6b807d345e3ea3 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/quantization/__pycache__/quantize.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/__pycache__/registry.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/quantization/__pycache__/registry.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bffb78a59b2f156997dea592d8f0ed1bcf09a501 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/quantization/__pycache__/registry.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/__pycache__/shape_inference.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/quantization/__pycache__/shape_inference.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..02559d8a76913b5fbc8e3776680bb21d9aaab71d Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/quantization/__pycache__/shape_inference.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/__pycache__/static_quantize_runner.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/quantization/__pycache__/static_quantize_runner.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..269da1780ba77544633d02c76f7eaf82f0160aa0 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/quantization/__pycache__/static_quantize_runner.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/__pycache__/tensor_quant_overrides.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/quantization/__pycache__/tensor_quant_overrides.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b05e99680757cd9af0fe0b1ccf946ac2a08cdecb Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/quantization/__pycache__/tensor_quant_overrides.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/execution_providers/qnn/__init__.py b/python/user_packages/Python313/site-packages/onnxruntime/quantization/execution_providers/qnn/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c861e1332269018fd9a863ed31aa5cb80573309a --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/quantization/execution_providers/qnn/__init__.py @@ -0,0 +1,2 @@ +from .preprocess import qnn_preprocess_model # noqa: F401 +from .quant_config import get_qnn_qdq_config # noqa: F401 diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/execution_providers/qnn/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/quantization/execution_providers/qnn/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..471f85b00c2e68fb97807e35a8c27425b989cf67 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/quantization/execution_providers/qnn/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/execution_providers/qnn/__pycache__/fusion_lpnorm.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/quantization/execution_providers/qnn/__pycache__/fusion_lpnorm.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1432f7d82d743c28318a69a7f0c5995e74353dda Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/quantization/execution_providers/qnn/__pycache__/fusion_lpnorm.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/execution_providers/qnn/__pycache__/fusion_spacetodepth.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/quantization/execution_providers/qnn/__pycache__/fusion_spacetodepth.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cfa990eee6e0f95325f99848a5c3de771516855f Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/quantization/execution_providers/qnn/__pycache__/fusion_spacetodepth.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/execution_providers/qnn/__pycache__/mixed_precision_overrides_utils.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/quantization/execution_providers/qnn/__pycache__/mixed_precision_overrides_utils.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0d637e8dbb157e3fbb825f65a9b0f3a7152f333d Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/quantization/execution_providers/qnn/__pycache__/mixed_precision_overrides_utils.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/execution_providers/qnn/__pycache__/preprocess.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/quantization/execution_providers/qnn/__pycache__/preprocess.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fcd413a8b475b302113c8e8c5a742a42bb7b765a Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/quantization/execution_providers/qnn/__pycache__/preprocess.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/execution_providers/qnn/__pycache__/quant_config.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/quantization/execution_providers/qnn/__pycache__/quant_config.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7077c3b962d87aaf03f177ae5df1b5e49920a306 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/quantization/execution_providers/qnn/__pycache__/quant_config.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/execution_providers/qnn/fusion_lpnorm.py b/python/user_packages/Python313/site-packages/onnxruntime/quantization/execution_providers/qnn/fusion_lpnorm.py new file mode 100644 index 0000000000000000000000000000000000000000..0eb140f892f330c8414664cb2fc7921041fd99cf --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/quantization/execution_providers/qnn/fusion_lpnorm.py @@ -0,0 +1,132 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- +from __future__ import annotations + +import onnx + +from ...fusions import Fusion +from ...onnx_model import ONNXModel + + +class FusionLpNormalization(Fusion): + def __init__(self, model: ONNXModel, epsilon: float = 1e-12): + super().__init__(model, "LpNormalization", "ReduceL2") + self.epsilon = epsilon + + def fuse( + self, + reduce_node: onnx.NodeProto, + input_name_to_nodes: dict[str, list[onnx.NodeProto]], + output_name_to_node: dict[str, onnx.NodeProto], + ): + """ + Interface function that tries to fuse a node sequence containing a ReduceL2 node into a single + LpNormalization node. + + Pattern 1: + [root] --> ReduceL2 -----> Clip --> Expand ----> Div --> + | (axis=-1) (min=epsilon) (shape=root) ^ + | (keepdims=True) | + | | + +-----------------------------------------------+ + Notes: + - ReduceL2 must use the last axis, and keepdims == True + - Clip must only have a min attribute that is ~1e-12 + - Expand must restore the shape to root.shape + - The output of Expand must be the second input to Div. + """ + if reduce_node.output[0] not in input_name_to_nodes: + return + + # ReduceL2 must have one Clip child + children = input_name_to_nodes[reduce_node.output[0]] + if len(children) != 1 or children[0].op_type != "Clip": + return + + # ReduceL2 must have keepdims == True + keepdims = self.get_node_attribute(reduce_node, "keepdims") + if not keepdims: + return + + # ReduceL2 axes must refer only to the last dimension. + # Axes became an input in opset 18. Before then, axes was an attribute + reduce_input_ttype = self.model.get_tensor_type(reduce_node.input[0]) + if not reduce_input_ttype: + return + + reduce_input_shape = self.tensor_shape_to_list(reduce_input_ttype) + if not reduce_input_shape: + return + + axes = self.get_node_attribute(reduce_node, "axes") + if not axes and len(reduce_node.input) > 1: + axes = self.model.get_constant_value(reduce_node.input[1]) + + if not axes or len(axes) != 1: + return + + last_dim = len(reduce_input_shape) - 1 + if axes[0] != -1 and axes[0] != last_dim: + return + + # Clip node must have a min attribute approximately equal to 1e-12 + clip_node = children[0] + clip_min = self.get_node_attribute(clip_node, "min") + if clip_min is None and len(clip_node.input) > 1: + clip_min = self.model.get_constant_value(clip_node.input[1]) + + clip_max = self.get_node_attribute(clip_node, "max") # TODO: clip_max could be FLOAT_MAX + if clip_max is None and len(clip_node.input) > 2: + clip_max = self.model.get_constant_value(clip_node.input[2]) + + if not (clip_max is None and clip_min is not None and clip_min > 0 and abs(clip_min - self.epsilon) < 1e-13): + return + + if clip_node.output[0] not in input_name_to_nodes: + return + + # Clip must have a single Expand child. + children = input_name_to_nodes[clip_node.output[0]] + if len(children) != 1 or children[0].op_type != "Expand": + return + + expand_node = children[0] + if expand_node.output[0] not in input_name_to_nodes: + return + + # Expand must have a single Div child + children = input_name_to_nodes[expand_node.output[0]] + if len(children) != 1 or children[0].op_type != "Div": + return + + div_node = children[0] + + # The first input to Div must be the root of the subgraph (i.e., reduce_node.input[0]) + # The second input to Div must be the output of the Expand. + # As long as these two inputs go to the same Div node, then ONNX validation will ensure that + # their shapes match. + if div_node.input[0] != reduce_node.input[0]: + return + if div_node.input[1] != expand_node.output[0]: + return + + subgraph_input = reduce_node.input[0] + subgraph_output = div_node.output[0] + + subgraph_nodes = [reduce_node, clip_node, expand_node, div_node] + if not self.is_safe_to_fuse_nodes(subgraph_nodes, [subgraph_output], input_name_to_nodes, output_name_to_node): + return + + self.nodes_to_remove.extend(subgraph_nodes) + fused_node = onnx.helper.make_node( + self.fused_op_type, + name=self.create_unique_node_name(), + inputs=[subgraph_input], + outputs=[subgraph_output], + p=2, + axis=-1, + ) + self.nodes_to_add.append(fused_node) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/execution_providers/qnn/fusion_spacetodepth.py b/python/user_packages/Python313/site-packages/onnxruntime/quantization/execution_providers/qnn/fusion_spacetodepth.py new file mode 100644 index 0000000000000000000000000000000000000000..6ea9f6eee5a51f38ca4d1a8ec3e3a8416b6bdfaf --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/quantization/execution_providers/qnn/fusion_spacetodepth.py @@ -0,0 +1,162 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- +"""Define SpaceToDepth fusion.""" + +import onnx + +from ... import fusions, onnx_model + + +class FusionSpaceToDepth(fusions.Fusion): + """Fusion for SpaceToDepth.""" + + def __init__(self, model: onnx_model.ONNXModel): + """Initialize. + + Args: + model: An onnx_model.ONNXModel instance. + """ + super().__init__(model, "SpaceToDepth", "Reshape") + + def _fuse_yolo( + self, + node: onnx.NodeProto, + input_name_to_nodes: dict[str, list[onnx.NodeProto]], + output_name_to_node: dict[str, onnx.NodeProto], + ): + """Fuse for early version of YOLO. + + Pattern: + + | [N, C, H, W] + Reshape + | [N, C, H/blk, blk, W/blk, blk] + Transpose + | [N, C, H/blk, W/blk, blk, blk] + Reshape + | [N, C, H/blk * W/blk, blk * blk] + Transpose + | [N, C, blk * blk, H/blk * W/blk] + Reshape + | [N, C, blk * blk, H/blk, W/blk] + Transpose + | [N, blk * blk, C, H/blk, W/blk] + Reshape + | [N, blk * blk * C, H/blk, W/blk] + + This sequence can be fused into a single SpaceToDepth with blocksize `blk`. Note that unlike DepthToSpace + supporting DCR or CRD mode, SpaceToDepth only supports DCR mode in its latest opset version (13), which matches + the pattern here. + """ + reshape_node1 = node + + def get_target_child(parent_node, target_op_type): + """Get target child of given node.""" + if parent_node.output[0] not in input_name_to_nodes: + return None + + children = input_name_to_nodes[parent_node.output[0]] + if len(children) > 1 or children[0].op_type != target_op_type: + return None + + return children[0] + + if ( + (transpose_node1 := get_target_child(reshape_node1, "Transpose")) is None + or (reshape_node2 := get_target_child(transpose_node1, "Reshape")) is None + or (transpose_node2 := get_target_child(reshape_node2, "Transpose")) is None + or (reshape_node3 := get_target_child(transpose_node2, "Reshape")) is None + or (transpose_node3 := get_target_child(reshape_node3, "Transpose")) is None + or (reshape_node4 := get_target_child(transpose_node3, "Reshape")) is None + ): + return False + + def get_tensor_shape(tensor_name): + """Get shape for given tensor name.""" + tensor_type = self.model.get_tensor_type(tensor_name) + if not tensor_type: + return None + + tensor_shape = self.tensor_shape_to_list(tensor_type) + if not tensor_shape: + return None + + return tensor_shape + + if ( + (input_shape := get_tensor_shape(reshape_node1.input[0])) is None + or (reshape_shape1 := get_tensor_shape(reshape_node1.output[0])) is None + or (reshape_shape2 := get_tensor_shape(reshape_node2.output[0])) is None + or (reshape_shape3 := get_tensor_shape(reshape_node3.output[0])) is None + or (reshape_shape4 := get_tensor_shape(reshape_node4.output[0])) is None + ): + return False + + transpose_perm1 = self.get_node_attribute(transpose_node1, "perm") + transpose_perm2 = self.get_node_attribute(transpose_node2, "perm") + transpose_perm3 = self.get_node_attribute(transpose_node3, "perm") + + # Check rank. + if ( + len(input_shape) != 4 + or len(reshape_shape1) != 6 + or len(reshape_shape2) != 4 + or len(reshape_shape3) != 5 + or len(reshape_shape4) != 4 + ): + return False + + # Check shape and perm. + batch, channel, height, width = input_shape + blocksize = reshape_shape1[3] + if ( + reshape_shape1 != [batch, channel, height // blocksize, blocksize, width // blocksize, blocksize] + or transpose_perm1 != [0, 1, 2, 4, 3, 5] + or reshape_shape2 != [batch, channel, (height // blocksize) * (width // blocksize), blocksize**2] + or transpose_perm2 != [0, 1, 3, 2] + or reshape_shape3 != [batch, channel, blocksize**2, height // blocksize, width // blocksize] + or transpose_perm3 != [0, 2, 1, 3, 4] + or reshape_shape4 != [batch, blocksize**2 * channel, height // blocksize, width // blocksize] + ): + return False + + self.nodes_to_remove.extend( + [ + reshape_node1, + transpose_node1, + reshape_node2, + transpose_node2, + reshape_node3, + transpose_node3, + reshape_node4, + ] + ) + + s2d_node = onnx.helper.make_node( + self.fused_op_type, + name=self.create_unique_node_name(), + inputs=[reshape_node1.input[0]], + outputs=[reshape_node4.output[0]], + blocksize=blocksize, + ) + self.nodes_to_add.append(s2d_node) + + return True + + def fuse( + self, + node: onnx.NodeProto, + input_name_to_nodes: dict[str, list[onnx.NodeProto]], + output_name_to_node: dict[str, onnx.NodeProto], + ): + """Fuse a sequence of Reshape and Transpose nodes into a single SpaceToDepth node. + + Args: + node: An onnx.NodeProto matching the specified search type (i.e., Reshape). + input_name_to_nodes: A dict mapping tensor name to consumed nodes. + output_name_to_node: A dict mapping tensor name to produced node. + """ + self._fuse_yolo(node, input_name_to_nodes, output_name_to_node) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/execution_providers/qnn/mixed_precision_overrides_utils.py b/python/user_packages/Python313/site-packages/onnxruntime/quantization/execution_providers/qnn/mixed_precision_overrides_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..5757a302cbce5a4a8bd260af0017fb152e95f994 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/quantization/execution_providers/qnn/mixed_precision_overrides_utils.py @@ -0,0 +1,413 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- +from __future__ import annotations + +import logging +from dataclasses import dataclass + +import onnx + +from ...quant_utils import QuantType +from ...tensor_quant_overrides import QuantTypeInfo, TensorQuantOverridesHelper + + +@dataclass +class TensorTypeRequest: + """ + Bundles desired quantization type requests for a tensor. A distinction is made between the + produced type and the consumed type. + """ + + # The tensor's quant type at the producer end. If None, assumed to be the default activation quant type. + producer: QuantTypeInfo | None + + # The tensor's quant type received by a set of consumer nodes. + # If None, assumed to be the default activation quant type for all consumers. + # consumers[1] is a set of consumer node names. + consumers: tuple[QuantTypeInfo, set[str]] | None + + +class MixedPrecisionTensorQuantOverridesFixer: + """ + Helper that generates tensor quantization overrides for mixed-precision QDQ models. + + Specifically, this helper fixes an initial set of quantization overrides that assign a non-default + activation quantization type to one or more tensors by doing the following: + - Inferring which other tensors need to be overridden to the non-default activation quantization type. + - Inserting quantization data type conversions. + + Example: + -------- + + Float model: + + input_0 --> Op1 --> Op3 --> Op5 --> Op6 --> output_0 + ^ + | + input_1 --> Op2 -+-> Op4 ----+ + | + +-> Op7 --> output_1 + | + +-> Op8 --> output_2 + + If we'd like to quantize this model to uint8 precision, but would like to make sure tensor "Op4_out" + is quantized to 16-bit, then we would specify the following initial tensor quantization overrides: + + ``` + init_overrides = {"Op4_out": [{"quant_type": QuantType.QUInt16}]} + ``` + + These initial overrides may not create a valid model because Op4 and Op5 may require both the input and output + to be the same type (e.g., uint16). This helper fixes the overrides so that input/output data types + are valid: + + ``` + overrides = TensorQuantOverridesHelper(init_overrides) + + fixer = MixedPrecisionTensorQuantOverridesFixer.create_from_model(overrides, model, QuantType.QUInt8) + fixer.apply( + default_activation_qtype=QuantType.QUInt8, + default_activation_symmetric=False, + ) + ``` + + The above snippet generates the following "fixed" overrides (get via overrides.get_dict()): + + { + "Op2_out": [{"quant_type": QUInt8, "convert": {"quant_type": QUInt16, "recv_nodes": {"Op4"}}}], + "Op3_out": [{"quant_type": QUInt8, "convert": {"quant_type": QUInt16, "recv_nodes": {"Op5"}}}], + "Op4_out": [{"quant_type": QUInt16}], + "Op5_out": [{"quant_type": QUInt16, "convert": {"quant_type": QUInt8, "recv_nodes": {"Op6"}}}] + } + + How to interpret the fixed overrides: + - Op2's output is consumed by Op4, Op7, and Op8. Op4 consumes the converted u16 type, + but Op7 and Op8 consume the original u8 type. + - Op3's output is converted from u8 to u16. Op5 consumes the converted u16 type. + - Op4's output is just u16 (not converted). All consumers of Op4_out get the u16 type. + - Op5's output is converted from u16 to u8. Op6 consumes the u8 type. + """ + + def __init__( + self, + overrides: TensorQuantOverridesHelper, + producers: dict[str, onnx.NodeProto], + consumers: dict[str, list[onnx.NodeProto]], + value_infos: dict[str, onnx.ValueInfoProto], + initializers: dict[str, onnx.TensorProto], + ): + """ + Params: + overrides: The initial tensor quantization overrides to fix. + producers: Dictionary that maps a tensor name to the producer node that generates the tensor. + consumers: Dictionary that maps a tensor name to the consumer nodes that take the tensor as input. + value_infos: Dictionary that maps a tensor name to its onnx.ValueInfoProto. + initializers: Dictionary that maps an initializer name to its onnx.TensorProto. + """ + self.overrides = overrides + self.consumers = consumers + self.producers = producers + self.value_infos = value_infos + self.initializers = initializers + + @staticmethod + def create_from_model( + overrides: TensorQuantOverridesHelper, model: onnx.ModelProto, default_activation_qtype: QuantType + ) -> MixedPrecisionTensorQuantOverridesFixer: + """ + Helper function that creates an instance of this class from a loaded ONNX model. + + Params: + overrides: The initial tensor quantization overrides to fix. + model: Loaded ONNX model + default_activation_qtype: The intended default activation quantization type. + Used to validate the initial overrides. + + Returns: + Initialized MixedPrecisionTensorQuantOverridesFixer object + """ + model = onnx.shape_inference.infer_shapes(model) # Need to infer shapes to get value_infos + + # Build dictionaries that enable convenient lookups of initializers and value_infos by name. + initializers = {initializer.name: initializer for initializer in model.graph.initializer} + value_infos = {vi.name: vi for vi in model.graph.value_info} + value_infos.update({ot.name: ot for ot in model.graph.output}) + value_infos.update({it.name: it for it in model.graph.input}) + + # Ensure that the user-provided initial overrides are actually valid. + valid, err = overrides.is_valid(initializers, set(value_infos), default_activation_qtype) + if not valid: + pprint_overrides = overrides.pprint_str(indent=4) + logging.error(f"Provided invalid tensor quantization overrides:\n{pprint_overrides}") + raise ValueError(err) + + consumers = {} + producers = {} + + # Build dictionaries that map a tensor name to the consumer or producer nodes. + for node in model.graph.node: + for input_name in node.input: + if input_name: + if input_name not in consumers: + consumers[input_name] = [] + + consumers[input_name].append(node) + + for output_name in node.output: + producers[output_name] = node + + return MixedPrecisionTensorQuantOverridesFixer(overrides, producers, consumers, value_infos, initializers) + + def apply( + self, + default_activation_qtype: QuantType, + default_activation_symmetric: bool, + ): + """ + Fixes the initial tensor quantization overrides (in-place) for use in mixed-precision QDQ models. + + Params: + default_activation_qtype: The intended default activation quantization type. + default_activation_symmetric: The intended default symmetry used to quantize activations. + """ + type_requests = self.get_desired_tensor_types(default_activation_qtype, default_activation_symmetric) + + # Use type requests to "fix" tensor quantization overrides by adding + # quantization type conversions where necessary. + for tensor_name, type_req in type_requests.items(): + all_consumers = {node.name for node in self.consumers.get(tensor_name, [])} + has_producer_req = type_req.producer is not None + has_consumer_req = bool(type_req.consumers) + + # Only producer type: Add conversion back to default activation type + if has_producer_req and not has_consumer_req: + self._update_converted_tensor( + tensor_name, type_req.producer, QuantTypeInfo(default_activation_qtype), all_consumers + ) + # Only consumers + elif not has_producer_req and has_consumer_req: + prod_type_info = self.overrides.get_node_output_qtype_info(tensor_name, default_activation_qtype) + consumer_type_info = type_req.consumers[0] + + if prod_type_info != consumer_type_info: + self._update_converted_tensor( + tensor_name, prod_type_info, consumer_type_info, type_req.consumers[1] + ) + else: + if not self._check_nodes_are_not_convert_consumers(tensor_name, type_req.consumers[1]): + raise ValueError( + f"Tensor override for '{tensor_name}' converts the type for consumers that need the original type." + ) + # Both producer and consumers + elif has_producer_req and has_consumer_req: + prod_type_info = type_req.producer + consumer_type_info = type_req.consumers[0] + + if prod_type_info != consumer_type_info: + self._update_converted_tensor( + tensor_name, prod_type_info, consumer_type_info, type_req.consumers[1] + ) + else: + consumers_for_original_type = all_consumers.difference(type_req.consumers[1]) + + if len(consumers_for_original_type) == 0: + # All consumers want the overridden type, so no need for convert nodes! + # Just add the override to the new new if not already present. + if tensor_name not in self.overrides: + self.overrides[tensor_name] = [{}] + prod_type_info.save_to_dict(self.overrides[tensor_name][0]) + + assert "convert" not in self.overrides[tensor_name][0] + else: + # Some consumers don't want the overridden type. + self._update_converted_tensor( + tensor_name, + prod_type_info, + QuantTypeInfo(default_activation_qtype), + consumers_for_original_type, + ) + else: + raise ValueError(f"TypeRequest for tensor {tensor_name} has no producer or consumers.") + + # Done. Check if the overrides are valid. + valid, err = self.overrides.is_valid(self.initializers, set(self.value_infos), default_activation_qtype) + if not valid: + pprint_overrides = self.overrides.pprint_str(indent=4) + logging.error( + f"Generated invalid tensor quantization overrides for mixed-precision QDQ model:\n{pprint_overrides}" + ) + raise ValueError(err) + + def get_desired_tensor_types( + self, + default_activation_qtype: QuantType, + default_activation_symmetric: bool, + ) -> dict[str, TensorTypeRequest]: + """ + Iterates through the initial tensor quantization overrides and builds a set of TensorTypeRequests objects + that describe the quantization types required at each tensor. These TensorTypeRequests objects are ultimately + used to generated the "fixed" overrides. + + Params: + default_activation_qtype: The intended default activation quantization type. + default_activation_symmetric: The intended default symmetry used to quantize activations. + + Returns: + TensorTypeRequest objects as a dict that maps a tensor name to its requested types. + """ + type_requests = {} + default_activation_type_info = QuantTypeInfo(default_activation_qtype, default_activation_symmetric) + + # Scan tensor overrides for type conversion requests. + for tensor_name, override_list in self.overrides.items(): + if not self.__is_tensor_quantizable(tensor_name): + continue # Skip non-quantizable tensors (e.g., not a float) + + if tensor_name in self.initializers: + continue # Skip initializers + + if not override_list or len(override_list) > 1: + continue # Skip per-channel stuff + + override_dict = override_list[0] + quant_type_info = QuantTypeInfo.load_from_dict(override_dict, default_activation_type_info.quant_type) + producer_node = self.producers.get(tensor_name) # None if this is a model input + + if quant_type_info != default_activation_type_info and "convert" not in override_dict: + if producer_node is not None: + self._add_type_requests_for_node(type_requests, quant_type_info, producer_node) + + # Find all consumer nodes of `tensor_name` and update their inputs/outputs to the new type. + for consumer_node in self.consumers.get(tensor_name, []): + self._add_type_requests_for_node(type_requests, quant_type_info, consumer_node) + + return type_requests + + def _add_type_requests_for_node( + self, + type_requests: dict[str, TensorTypeRequest], + quant_type_info: QuantTypeInfo, + node: onnx.NodeProto, + ): + """ + Adds TensorTypeRequest objects for a given node, assuming that we want all its inputs and outputs + to have the same quantization type (as specified by the `quant_type_info` parameter). + + Params: + type_requests: Dictionary of type requests to append to for this node. + quant_type_info: The quantization type to use for inputs and outputs. + node: The node for which the TensorTypeRequest objects are created and added to type_requests. + """ + # Add output side + for output_name in node.output: + if not self.__is_tensor_quantizable(output_name): + continue + + if output_name not in type_requests: + type_requests[output_name] = TensorTypeRequest(quant_type_info, None) + else: + if ( + type_requests[output_name].producer is not None + and type_requests[output_name].producer != quant_type_info + ): + raise ValueError(f"Tensor {output_name} has multiple types.") + + type_requests[output_name].producer = quant_type_info + + # Add the consumer side + for input_name in node.input: + if input_name and input_name not in self.initializers and self.__is_tensor_quantizable(input_name): + if input_name not in type_requests: + type_requests[input_name] = TensorTypeRequest(None, None) + + if type_requests[input_name].consumers is None: + type_requests[input_name].consumers = (quant_type_info, set()) + + if type_requests[input_name].consumers[0] != quant_type_info: + raise ValueError(f"Tensor {input_name} has consumers requesting different types.") + + if not node.name: + raise ValueError( + f"Node of type {node.op_type} with output 0 {node.output[0]} does not have a name!" + ) + + type_requests[input_name].consumers[1].add(node.name) + + def _update_converted_tensor( + self, + tensor_name: str, + producer_type_info: QuantTypeInfo, + consumer_type_info: QuantTypeInfo, + consumer_names: set[str], + ): + """ + Updates the tensor quantization overrides for a tensor that is converted from one type to another. + + Params: + tensor_name: The name of the tensor for which to update overrides. + producer_type_info: Info for the tensor's produced type. + consumer_type_info: Info for the tensor's consumed (i.e., converted) type. + consumer_names: Nodes names of consumers that consume the converted type. + """ + if tensor_name not in self.overrides or not self.overrides[tensor_name]: + self.overrides[tensor_name] = [{}] + producer_type_info.save_to_dict(self.overrides[tensor_name][0]) + + overrides = self.overrides[tensor_name][0] + if producer_type_info != QuantTypeInfo.load_from_dict(overrides): + raise ValueError(f"Desired producer quant_type for {tensor_name} doesn't match existing type.") + + if consumer_names: + if "convert" not in overrides: + overrides["convert"] = {} + consumer_type_info.save_to_dict(overrides["convert"]) + + convert_dict = overrides["convert"] + if consumer_type_info != QuantTypeInfo.load_from_dict(convert_dict): + raise ValueError(f"Desired consumer quant_type for {tensor_name} doesn't match existing type.") + + if "recv_nodes" not in convert_dict: + convert_dict["recv_nodes"] = set() + + convert_dict["recv_nodes"].update(consumer_names) + + def _check_nodes_are_not_convert_consumers(self, tensor_name: str, node_names: set[str]): + """ + Returns true if the given nodes do not consume/receive a converted quantization type. + + Params: + tensor_name: The name of the tensor to check. + node_names: Set of node names that should not be consumers of the converted type. + """ + if tensor_name not in self.overrides or not self.overrides[tensor_name]: + return True + + overrides = self.overrides[tensor_name][0] + + if "convert" not in overrides: + return True + + convert_dict = overrides["convert"] + + if "recv_nodes" not in convert_dict: + return False + + return not convert_dict["recv_nodes"].intersection(node_names) + + def __is_tensor_quantizable(self, tensor_name): + weight = self.initializers.get(tensor_name) + if weight is not None: + if weight.data_type in (onnx.TensorProto.FLOAT, onnx.TensorProto.FLOAT16): + return True + elif tensor_name in self.value_infos: + vi = self.value_infos[tensor_name] + if vi.type.HasField("tensor_type") and vi.type.tensor_type.elem_type in ( + onnx.TensorProto.FLOAT, + onnx.TensorProto.FLOAT16, + ): + return True + + return False diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/execution_providers/qnn/preprocess.py b/python/user_packages/Python313/site-packages/onnxruntime/quantization/execution_providers/qnn/preprocess.py new file mode 100644 index 0000000000000000000000000000000000000000..ff7b8d3d2abc07fb7ecdc9966a5c9a102b550e8e --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/quantization/execution_providers/qnn/preprocess.py @@ -0,0 +1,353 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- +from __future__ import annotations + +import logging +import tempfile +from pathlib import Path + +import onnx + +from ....tools.onnx_model_utils import fix_output_shapes, make_input_shape_fixed, optimize_model +from ....tools.remove_initializer_from_input import remove_initializer_from_input +from ...fusions import FusionGelu, FusionLayerNormalization +from ...onnx_model import ONNXModel +from .fusion_lpnorm import FusionLpNormalization +from .fusion_spacetodepth import FusionSpaceToDepth + + +def qnn_preprocess_model( + model_input: str | Path | onnx.ModelProto, + model_output: str | Path, + exclude_initializer_from_input: bool = False, + fuse_layernorm: bool = False, + save_as_external_data: bool = False, + all_tensors_to_one_file: bool = False, + external_data_location: str | None = None, + external_data_size_threshold: int = 1024, + external_data_convert_attribute: bool = False, + inputs_to_make_channel_last: list[str] | None = None, + outputs_to_make_channel_last: list[str] | None = None, + dynamic_input_shapes: list[tuple[str, str]] | None = None, +) -> bool: + """ + If necessary, this method creates a new "pre-processed" model in preparation for + quantization of a model to be used in QNN EP. Returns true if a new model was created. + + This method perfoms the following operations: + - Fuse Erf sequence into a single Gelu node. + - Fuse ReduceL2 sequence into a single LpNormalization node (p == 2). + - (Optional) Fuse ReduceMean sequence into a single LayerNormalization node. + + Args: + model_input: Path to the input model file or ModelProto. + model_output: Path the output model file, which is only created if this method returns True. + exclude_initializer_from_input: A bool specifying whether to exclude initializer from input. + Defaults to False. + fuse_layernorm: True if ReduceMean sequences should be fused into LayerNormalization nodes. + Defaults to False. + save_as_external_data: True if output model should be saved with external data. Defaults to false. + all_tensors_to_one_file: Effective only if save_as_external_data is true. Defaults to false. + If true, save all tensors to one external file specified by external_data_location. + If false, save each tensor to a file named with the tensor name. + external_data_location: Effective only if save_as_external_data is true. Defaults to None. + Specify the external file to which all tensors are saved. Path is relative + to the model path. If not specified, the model's name is used. + external_data_size_threshold: Effective only if save_as_external_data is true. Defaults to 1024. + Tensors with a data size >= external_data_size_threshold are converted to external data. + To convert every tensor with raw data to external data, set to 0. + external_data_convert_attribute: Effective only if save_as_external_data is true. Defaults to false. + If true, convert all tensors to external data. + If false, convert only non-attribute tensors to external data. + inputs_to_make_channel_last: List of graph input names to transpose to be "channel-last". For example, + if "input0" originally has the shape (N, C, D1, D2, ..., Dn), the resulting model will change input0's + shape to (N, D1, D2, ..., Dn, C) and add a transpose node after it. + + Original: + input0 (N, C, D1, D2, ..., Dn) --> + + Updated: + input0 (N, D1, D2, ..., Dn, C) --> Transpose --> input0_chanfirst (N, C, D1, D2, ..., Dn) --> + + This can potentially improve inference latency for QDQ models running on QNN EP because the + additional transpose node may allow other transpose nodes inserted during ORT layout transformation + to cancel out. + outputs_to_make_channel_last: List of graph output names to transpose to be "channel-last". For example, + if "output0" originally has the shape (N, C, D1, D2, ..., Dn), the resulting model will change output0's + shape to (N, D1, D2, ..., Dn, C) and add a transpose node before it. + + Original: + --> output0 (N, C, D1, D2, ..., Dn) + + Updated: + --> output0_chanfirst (N, C, D1, D2, ..., Dn) --> Transpose --> output0 (N, D1, D2, ..., Dn, C) + + This can potentially improve inference latency for QDQ models running on QNN EP because the + additional transpose node may allow other transpose nodes inserted during ORT layout transformation + to cancel out. + dynamic_input_shapes: A list of tuples specifying model input name to and its static shape in comma seprated + format, for example: [('input', '1,3,256,256')]. Defaults to None. + """ + modified = False + model = model_input if isinstance(model_input, onnx.ModelProto) else onnx.load_model(model_input) + model = save_and_reload_optimize_model(model, shape_infer=True) + onnx_model = ONNXModel(model) + + # Optionally, fix the dynamic input shapes. + if dynamic_input_shapes: + for input_name, input_shape_str in dynamic_input_shapes: + input_shape = [int(i) for i in input_shape_str.split(",")] + make_input_shape_fixed(onnx_model.graph(), input_name, input_shape) + fix_output_shapes(onnx_model.model) + modified = True + + # Exclude initializer from input if model.ir_version >= 4 + if exclude_initializer_from_input: + modified |= remove_initializer_from_input(onnx_model.model) + + # Fuse Erf sequence into a single Gelu + fusion_gelu = FusionGelu(onnx_model) + if fusion_gelu.apply(): + modified = True + + # Fuse ReduceL2 sequence into a single LpNormalization node with p == 2. + fusion_lpnorm = FusionLpNormalization(onnx_model) + if fusion_lpnorm.apply(): + modified = True + + # Fuse Reshape/Transpose sequence into a single SpaceToDepth. + fusion_s2d = FusionSpaceToDepth(onnx_model) + if fusion_s2d.apply(): + modified = True + + # Optionally, fuse ReduceMean sequence into a single LayerNormalization node. + if fuse_layernorm: + onnx_opset = next(x for x in model.opset_import if x.domain == "" or x.domain == "ai.onnx") + + # Need opset >= 17 to use LayerNormalization. + if onnx_opset.version < 17: + logging.warning( + "Unable to fuse ReduceMean sequence into a LayerNormalization node. " + "ONNX model must use an opset >= 17 in order to use LayerNormalization, " + f"but found version {onnx_opset.version}. Please use onnx.version_converter to update your model." + ) + else: + fusion_layernorm = FusionLayerNormalization(onnx_model) + if fusion_layernorm.apply(): + modified = True + + # Optionally, transpose inputs and/or outputs to make them "channel-last". + if inputs_to_make_channel_last or outputs_to_make_channel_last: + transpose_node_prefix = "Transpose_channel_" + transpose_node_suffix: int = onnx_model.get_largest_node_name_suffix(transpose_node_prefix) + 1 + update_io_to_channel_last( + onnx_model.model, + inputs_to_make_channel_last, + outputs_to_make_channel_last, + transpose_node_name_prefix=transpose_node_prefix, + transpose_node_name_start_suffix=transpose_node_suffix, + ) + modified = True + + # Make sure all nodes have a name. + unnamed_node_prefix = "qnn_preproc_node_" + available_suffix = onnx_model.get_largest_node_name_suffix(unnamed_node_prefix) + 1 + for node in onnx_model.model.graph.node: + if node.op_type != "Constant" and not node.name: + new_node_name = f"{unnamed_node_prefix}{available_suffix!s}" + available_suffix += 1 + node.name = new_node_name + modified = True + logging.warning(f"Node of type {node.op_type} does not have a name. Renamed to {new_node_name}.") + + if modified: + onnx_model.topological_sort() + onnx.save_model( + model, + model_output, + save_as_external_data=save_as_external_data, + all_tensors_to_one_file=all_tensors_to_one_file, + location=external_data_location, + size_threshold=external_data_size_threshold, + convert_attribute=external_data_convert_attribute, + ) + + return modified + + +def save_and_reload_optimize_model(model: onnx.ModelProto, shape_infer: bool) -> onnx.ModelProto: + with tempfile.TemporaryDirectory(prefix="ort.qnn_preproc.") as qnn_preproc_tmp_dir: + model_in_path = Path(qnn_preproc_tmp_dir).joinpath("qnn_proc_input.onnx") + onnx.save_model(model, model_in_path, save_as_external_data=True) + if shape_infer: + model_infer_path = Path(qnn_preproc_tmp_dir).joinpath("qnn_proc_infer.onnx") + onnx.shape_inference.infer_shapes_path(str(model_in_path), str(model_infer_path)) + model_in_path = model_infer_path + model_out_path = Path(qnn_preproc_tmp_dir).joinpath("qnn_proc_output.onnx") + optimize_model(model_in_path, model_out_path) + ret_model = onnx.load_model(model_out_path) + ret_metaprops = {"onnx.infer": "onnxruntime.tools.qnn.preprocess"} + if ret_model.metadata_props: + ret_metaprops.update(ret_model.metadata_props) + onnx.helper.set_model_props(ret_model, ret_metaprops) + return ret_model + + +class InputOutputNameMap: + def __init__( + self, + orig_tensor_names: set[str], + orig_graph_inputs: dict[str, onnx.ValueInfoProto], + orig_graph_outputs: dict[str, onnx.ValueInfoProto], + ): + self.orig_tensor_names = orig_tensor_names + self.orig_graph_inputs = orig_graph_inputs + self.orig_graph_outputs = orig_graph_outputs + self.updated_io_names = {} + self.new_value_infos = [] + + def get_new_name(self, orig_name: str): + if orig_name in self.updated_io_names: + return self.updated_io_names[orig_name] + + # Make a new tensor name that is unique among all tensors in the graph. + prefix: str = f"{orig_name}_channel_first_" + suffix: int = -1 + for tensor_name in self.orig_tensor_names: + if tensor_name.startswith(prefix) and tensor_name[len(prefix) :].isdigit(): + index = int(tensor_name[len(prefix) :]) + suffix = max(suffix, index) + + suffix += 1 # This is the first available suffix. + new_name = f"{prefix}{suffix!s}" + + # Add new value_info objects for these new tensors. + orig_value_info = self.orig_graph_inputs.get(orig_name) or self.orig_graph_outputs[orig_name] + value_info_proto = onnx.ValueInfoProto() + value_info_proto.CopyFrom(orig_value_info) + value_info_proto.name = new_name + self.new_value_infos.append(value_info_proto) + + self.updated_io_names[orig_name] = new_name + return self.updated_io_names[orig_name] + + +def update_io_to_channel_last( + model: onnx.ModelProto, + inputs_to_update: list[str] | None, + outputs_to_update: list[str] | None, + transpose_node_name_prefix: str = "Transpose_channel_", + transpose_node_name_start_suffix: int = 0, +): + inputs_to_update = set(inputs_to_update or []) + outputs_to_update = set(outputs_to_update or []) + + if not inputs_to_update and not outputs_to_update: + return + + graph = model.graph + orig_graph_inputs = {ginput.name: ginput for ginput in graph.input} + orig_graph_outputs = {goutput.name: goutput for goutput in graph.output} + + # Check that the user passed in actual input and output names. + for input_name in inputs_to_update: + if input_name not in orig_graph_inputs: + raise ValueError(f"{input_name} is not a graph input") + + for output_name in outputs_to_update: + if output_name not in orig_graph_outputs: + raise ValueError(f"{output_name} is not a graph output") + + orig_tensor_names = set() + orig_tensor_names.update(set(orig_graph_inputs)) + orig_tensor_names.update(set(orig_graph_outputs)) + orig_tensor_names.update(input_name for node in graph.node for input_name in node.input if input_name) + + # Maps original input (or output) name to its updated name used within the graph. + io_map = InputOutputNameMap(orig_tensor_names, orig_graph_inputs, orig_graph_outputs) + + # Update each node's inputs/outputs to use the transposed versions. + for node in graph.node: + for i in range(len(node.input)): + if node.input[i] and node.input[i] in inputs_to_update: + node.input[i] = io_map.get_new_name(node.input[i]) + elif node.input[i] and node.input[i] in outputs_to_update: + node.input[i] = io_map.get_new_name(node.input[i]) + + for i in range(len(node.output)): + if node.output[i] in outputs_to_update: + node.output[i] = io_map.get_new_name(node.output[i]) + + # Update graph inputs to channel-last and a Transpose (to channel-first) after each. + for g_input_name in inputs_to_update: + g_input = orig_graph_inputs[g_input_name] + + if not g_input.type.HasField("tensor_type") or not g_input.type.tensor_type.HasField("shape"): + raise ValueError(f"Expected input {g_input.name} to have a tensor_type with a shape") + + input_shape = g_input.type.tensor_type.shape + input_rank = len(input_shape.dim) + + if input_rank < 3: + raise ValueError(f"Expected input {g_input.name} to be of rank >= 3") + + channel_dim = onnx.TensorShapeProto.Dimension() + channel_dim.CopyFrom(input_shape.dim[1]) + for i in range(1, input_rank - 1): + input_shape.dim[i].CopyFrom(input_shape.dim[i + 1]) + input_shape.dim[input_rank - 1].CopyFrom(channel_dim) + + transpose_perm = list(range(input_rank)) + for i in range(input_rank): + transpose_perm[i] = i if i < 1 else i - 1 + transpose_perm[1] = input_rank - 1 + + transpose_node = onnx.helper.make_node( + "Transpose", + name=f"{transpose_node_name_prefix}{transpose_node_name_start_suffix!s}", + inputs=[g_input.name], + outputs=[io_map.get_new_name(g_input.name)], + perm=transpose_perm, + ) + transpose_node_name_start_suffix += 1 + + graph.node.extend([transpose_node]) + + # Update graph outputs to channel-last and a Transpose (from channel-first) before each. + for g_output_name in outputs_to_update: + g_output = orig_graph_outputs[g_output_name] + if not g_output.type.HasField("tensor_type") or not g_output.type.tensor_type.HasField("shape"): + raise ValueError(f"Expected output {g_output.name} to have a tensor_type with a shape") + + output_shape = g_output.type.tensor_type.shape + output_rank = len(output_shape.dim) + + if output_rank < 3: + raise ValueError(f"Expected output {g_output.name} to be of rank >= 3") + + channel_dim = onnx.TensorShapeProto.Dimension() + channel_dim.CopyFrom(output_shape.dim[1]) + for i in range(1, output_rank - 1): + output_shape.dim[i].CopyFrom(output_shape.dim[i + 1]) + output_shape.dim[output_rank - 1].CopyFrom(channel_dim) + + transpose_perm = list(range(output_rank)) + for i in range(output_rank): + transpose_perm[i] = i if i == 0 else i + 1 + transpose_perm[output_rank - 1] = 1 + + transpose_node = onnx.helper.make_node( + "Transpose", + name=f"{transpose_node_name_prefix}{transpose_node_name_start_suffix!s}", + inputs=[io_map.get_new_name(g_output.name)], + outputs=[g_output.name], + perm=transpose_perm, + ) + transpose_node_name_start_suffix += 1 + + graph.node.extend([transpose_node]) + + graph.value_info.extend(io_map.new_value_infos) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/execution_providers/qnn/quant_config.py b/python/user_packages/Python313/site-packages/onnxruntime/quantization/execution_providers/qnn/quant_config.py new file mode 100644 index 0000000000000000000000000000000000000000..0a23a263555920bdac3b10bb016ebc49438715ca --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/quantization/execution_providers/qnn/quant_config.py @@ -0,0 +1,389 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- +from __future__ import annotations + +import copy +import logging +from pathlib import Path +from typing import Any + +import numpy as np +import onnx + +from ...calibrate import CalibrationDataReader, CalibrationMethod +from ...quant_utils import QuantType +from ...quantize import StaticQuantConfig +from ...tensor_quant_overrides import TensorQuantOverridesHelper +from .mixed_precision_overrides_utils import MixedPrecisionTensorQuantOverridesFixer + +Q16_TYPES = {QuantType.QInt16, QuantType.QUInt16} +Q8_TYPES = {QuantType.QInt8, QuantType.QUInt8} +Q4_TYPES = {QuantType.QInt4, QuantType.QUInt4} +OP_TYPES_TO_EXCLUDE = {"Cast"} +MODEL_SIZE_THRESHOLD = 2147483648 # Quant model should use external data if >= 2GB + + +def warn_unable_to_override( + node: onnx.NodeProto, + what_str: str, + tensor_name: str, + io_kind: str, +): + logging.warning( + f"Unable to override {what_str} for {node.op_type} node's {io_kind} " + "because it has already been overridden! Check the initial quantization overrides provided " + "to get_qnn_qdq_config() if the generated QDQ model does not run on QNN EP. " + f"Node name: {node.name}, {io_kind} name: {tensor_name}" + ) + + +def get_qnn_qdq_config( + model_input: str | Path | onnx.ModelProto, + calibration_data_reader: CalibrationDataReader, + calibrate_method: CalibrationMethod = CalibrationMethod.MinMax, + activation_type: QuantType = QuantType.QUInt8, + weight_type: QuantType = QuantType.QUInt8, + per_channel: bool = False, + init_overrides: dict[str, list[dict[str, Any]]] | None = None, + add_qtype_converts: bool = True, + activation_symmetric: bool = False, + weight_symmetric: bool | None = None, + keep_removable_activations: bool = False, + stride: int | None = None, + calibration_providers: list[str] | None = None, + op_types_to_quantize: list[str] | None = None, + nodes_to_exclude: list[str] | None = None, +) -> StaticQuantConfig: + """ + Returns a static quantization configuration suitable for running QDQ models on QNN EP. + This is done primarily by setting tensor-level quantization overrides. + + Params: + model_input: Path to the input model file or ModelProto. + calibration_data_reader: Calibration data reader. + calibrate_methode: The calibration method. Defaults to MinMax. + activation_type: The default activation quantization type. Defaults to QUInt8. + weight_type: The default weight quantization type. Defaults to QUInt8. + per_channel: Global option that determines if a fixed set of operator types should be quantized per-channel. + Defaults to false. Alternatively, use the tensor-level `init_overrides` to select individual operators + and their quantization axes. + + If set, the quantization tool uses per-channel quantization for the following operator types and inputs: + - Conv: + - input[1] on axis 0 + - input[2] (bias) on axis 0 + - ConvTranspose: + - input[1] on axis 1 + - input[2] (bias) on axis 0 + init_overrides: Initial tensor-level quantization overrides. Defaults to None. This function updates of a copy + of these overrides with any necessary adjustments and includes them in the returned + configuration object (i.e., config.extra_options['TensorQuantOverrides']). + + The key is a tensor name and the value is a list of dictionaries. For per-tensor quantization, the list + contains a single dictionary. For per-channel quantization, the list contains either a dictionary for + each channel in the tensor or a single dictionary that is assumed to apply to all channels. An 'axis' + key must be present in the first dictionary for per-channel quantization. + + Each dictionary contains optional overrides with the following keys and values. + 'quant_type' = QuantType : The tensor's quantization data type. + 'axis' = Int : The per-channel axis. Must be present for per-channel weights. + 'scale' = Float : The scale value to use. Must also specify `zero_point` if set. + 'zero_point' = Int : The zero-point value to use. Must also specify `scale` is set. + 'symmetric' = Bool : If the tensor should use symmetric quantization. Invalid if also + set `scale` or `zero_point`. + 'reduce_range' = Bool : If the quantization range should be reduced. Invalid if also + set `scale` or `zero_point`. Only valid for initializers. + 'rmax' = Float : Override the maximum real tensor value in calibration data. + Invalid if also set `scale` or `zero_point`. + 'rmin' = Float : Override the minimum real tensor value in calibration data. + Invalid if also set `scale` or `zero_point`. + 'convert' = Dict : A nested dictionary with the same keys for an activation + tensor that should be converted to another quantization type. + 'convert["recv_nodes"] = Set : Set of node names that consume the converted activation, + other nodes get the original type. If not specified, + assume all consumer nodes get the converted type. + add_qtype_converts: True if this function should automatically add "convert" entries to the provided + `init_overrides` to ensure that operators use valid input/output types (activations only). + Ex: if you override the output of an Add to 16-bit, this option ensures that the activation inputs + of the Add are also up-converted to 16-bit and that data types for surrounding ops are converted + appropriately. Refer to the documentation in mixed_precision_overrides_utils.py for additional details. + activation_symmetric: True if activations should be quantized symmetrically (i.e, rmax == -rmin) by default. + Defaults to false. For int8 and int16, this results in zero-point values of 0. For uint8 and uin16, + the zero-point values are 128 and 32,768, respectively. + weight_symmetric: True if weights should be quantized symmetrically (i.e., rmax == -rmin) by default. + Defaults to None. If set to None, weight_symmetric is assumed true if the weight_type is a signed int. + keep_removable_activations: Defaults to false. If true, "removable" activations (e.g., Clip or Relu) will not + be removed, and will be explicitly represented in the QDQ model. If false, these activations + are automatically removed if activations are asymmetrically quantized. Keeping these activations + is necessary if optimizations or EP transformations will later remove + QuantizeLinear/DequantizeLinear operators from the model. + calibration_providers: Execution providers to run the session during calibration. Default is None which uses + [ "CPUExecutionProvider" ]. + op_types_to_quantize: If set to None, all operator types will be quantized except for OP_TYPES_TO_EXCLUDE + nodes_to_exclude: List of nodes names to exclude from quantization. The nodes in this list will be excluded from + quantization when it is not None. + + Returns: + A StaticQuantConfig object + """ + if weight_symmetric is None: + weight_symmetric = weight_type in {QuantType.QInt8, QuantType.QInt16} + + model = ( + model_input + if isinstance(model_input, onnx.ModelProto) + else onnx.load_model(model_input, load_external_data=False) + ) + + op_types = set() + model_has_external_data = False + name_to_initializer = {} + + # Build map of initializers (name -> initializer) and + # check if the model has external data. + for initializer in model.graph.initializer: + name_to_initializer[initializer.name] = initializer + if onnx.external_data_helper.uses_external_data(initializer): + model_has_external_data = True + + overrides_helper = TensorQuantOverridesHelper(copy.deepcopy(init_overrides) if init_overrides else {}) + + if not overrides_helper.empty() and add_qtype_converts: + # Fix mixed-precision overrides. + overrides_fixer = MixedPrecisionTensorQuantOverridesFixer.create_from_model( + overrides_helper, model, activation_type + ) + overrides_fixer.apply(activation_type, activation_symmetric) + + # Setup quantization overrides for specific operator types to ensure compatibility with QNN EP. + qnn_compat = QnnCompatibilityOverrides( + activation_type, + weight_type, + activation_symmetric, + weight_symmetric, + per_channel, + overrides_helper, + name_to_initializer, + ) + + op_types_to_quantize_set = set(op_types_to_quantize) if op_types_to_quantize else None + nodes_to_exclude_set = set(nodes_to_exclude) if nodes_to_exclude else None + + for node in model.graph.node: + if op_types_to_quantize_set and node.op_type not in op_types_to_quantize_set: + continue + if nodes_to_exclude_set and node.name in nodes_to_exclude_set: + continue + op_types.add(node.op_type) + qnn_compat.process_node(node) + + extra_options = { + "MinimumRealRange": 0.0001, + "DedicatedQDQPair": False, # Let ORT optimizer duplicate DQ nodes + "QDQKeepRemovableActivations": keep_removable_activations, + "TensorQuantOverrides": overrides_helper.get_dict(), + "ActivationSymmetric": activation_symmetric, + "WeightSymmetric": weight_symmetric, + "CalibStridedMinMax": stride, + } + + # ONNX opset < 21 does not support 16-bit quantization, so must use 'com.microsoft' domain + # on Q/DQ operators if using 16-bit or 4-bit quantization. + onnx_opset = next(x for x in model.opset_import if x.domain == "" or x.domain == "ai.onnx") + if onnx_opset.version < 21: + opset21_types = Q16_TYPES.union(Q4_TYPES) + overrides_have_opset21_types = any(t in opset21_types for t in overrides_helper.get_quant_types()) + if activation_type in opset21_types or weight_type in opset21_types or overrides_have_opset21_types: + extra_options["UseQDQContribOps"] = True + + return StaticQuantConfig( + calibration_data_reader, + calibrate_method=calibrate_method, + activation_type=activation_type, + weight_type=weight_type, + op_types_to_quantize=( + op_types_to_quantize if op_types_to_quantize else list(op_types.difference(OP_TYPES_TO_EXCLUDE)) + ), + nodes_to_exclude=nodes_to_exclude, + per_channel=per_channel, + use_external_data_format=(model_has_external_data or model.ByteSize() >= MODEL_SIZE_THRESHOLD), + calibration_providers=calibration_providers, + extra_options=extra_options, + ) + + +class QnnCompatibilityOverrides: + """ + Helper that processes nodes to generate quantization overrides that make the resulting QDQ model + compatible with QNN EP. + """ + + def __init__( + self, + default_activation_qtype: QuantType, + default_weight_qtype: QuantType, + activation_symmetric: bool, + weight_symmetric: bool, + per_channel: bool, + overrides: TensorQuantOverridesHelper, + initializers: dict[str, onnx.TensorProto], + ): + self.default_activation_qtype = default_activation_qtype + self.default_weight_qtype = default_weight_qtype + self.activation_symmetric = activation_symmetric + self.weight_symmetric = weight_symmetric + self.per_channel = per_channel + self.overrides = overrides + self.initializers = initializers + + self.process_fns = { + "MatMul": self._process_matmul, + "LayerNormalization": self._process_layernorm, + "Sigmoid": self._process_sigmoid, + "Tanh": self._process_tanh, + } + + def process_node(self, node: onnx.NodeProto): + process_fn = self.process_fns.get(node.op_type) + + if process_fn is not None: + process_fn(node) + + def _make_static_inputs_use_default_weight_type(self, node: onnx.NodeProto): + """ + Overrides initializer input(s) to use the default weight type if: + - The default weight type is 8-bit + - One of the inputs is a 16-bit activation + - The other input is an initializer (per-tensor quantized) + + This is necessary because the quantization tool does not assign MatMul or LayerNorm initializer + inputs the default weight type. Instead, it assigns the default activation type. + """ + if self.default_weight_qtype not in Q8_TYPES: + return + + input_16bit_act_name = None + input_weight_name = None + + # Loop through first 2 inputs to find a 16-bit activation and a (per-tensor) weight. + for i in range(2): + input_name = node.input[i] + if not input_name: + continue + + is_weight = input_name in self.initializers + qtype_info = self.overrides.get_node_input_qtype_info( + input_name, + node.name, + default_qtype=None if is_weight else self.default_activation_qtype, + ) + + if qtype_info.axis is not None: + return # Don't process MatMul with a per-channel quantized input. + + if ( + is_weight + and qtype_info.quant_type == self.default_weight_qtype + and qtype_info.symmetric == self.weight_symmetric + ): + return # Return. Weight is already overridden to use the desired weight type. + + if is_weight: + input_weight_name = input_name + elif qtype_info.quant_type in Q16_TYPES: + input_16bit_act_name = input_name + + # Override initializer input to use the default weight type. + if input_16bit_act_name and input_weight_name: + did_update = self.overrides.update_tensor_overrides( + input_weight_name, + {"quant_type": self.default_weight_qtype, "symmetric": self.weight_symmetric}, + overwrite=False, + ) + + if not did_update: + warn_unable_to_override(node, "quant_type/symmetric", input_weight_name, "input weight") + + def _process_matmul(self, node: onnx.NodeProto): + assert node.op_type == "MatMul", f"Expected MatMul, but got {node.op_type}" + + if not self.per_channel: + self._make_static_inputs_use_default_weight_type(node) + return + + # QNN does not support per-channel MatMul. However, the ORT quantization tool attempts to use per-channel + # quantization for MatMul by default *if* the global per_channel setting is enabled. So, we need to + # provide explicit per-tensor quantization overrides for MatMul if per_channel is enabled and + # the user did not provide any other overrides. + for input_name in node.input: + is_weight_no_overrides = input_name in self.initializers and input_name not in self.overrides + if is_weight_no_overrides: + self.overrides.update_tensor_overrides( + input_name, + {"quant_type": self.default_weight_qtype, "symmetric": self.weight_symmetric}, + ) + + def _process_layernorm(self, node: onnx.NodeProto): + assert node.op_type == "LayerNormalization", f"Expected LayerNormalization, but got {node.op_type}" + + if not self.per_channel: + self._make_static_inputs_use_default_weight_type(node) + + def _process_sigmoid(self, node: onnx.NodeProto): + """ + Overrides 16-bit Sigmoid's output scale and zero-point as per QNN requirements. + """ + assert node.op_type == "Sigmoid", f"Expected Sigmoid, but got {node.op_type}" + output_type = self.overrides.get_node_output_qtype_info( + node.output[0], self.default_activation_qtype + ).quant_type + + if output_type == QuantType.QUInt16: + self.overrides.update_tensor_overrides( + node.output[0], + { + "quant_type": output_type, + "scale": np.array(1.0 / 65536.0, dtype=np.float32), + "zero_point": np.array(0, dtype=np.uint16), + }, + ) + elif output_type == QuantType.QInt16: + self.overrides.update_tensor_overrides( + node.output[0], + { + "quant_type": output_type, + "scale": np.array(1.0 / 32768.0, dtype=np.float32), + "zero_point": np.array(0, dtype=np.int16), + }, + ) + + def _process_tanh(self, node: onnx.NodeProto): + """ + Overrides 16-bit Tanh's output scale and zero-point as per QNN requirements. + """ + assert node.op_type == "Tanh", f"Expected Tanh, but got {node.op_type}" + output_type = self.overrides.get_node_output_qtype_info( + node.output[0], self.default_activation_qtype + ).quant_type + + if output_type == QuantType.QUInt16: + self.overrides.update_tensor_overrides( + node.output[0], + { + "quant_type": output_type, + "scale": np.array(1.0 / 32768.0, dtype=np.float32), + "zero_point": np.array(32768, dtype=np.uint16), + }, + ) + elif output_type == QuantType.QInt16: + self.overrides.update_tensor_overrides( + node.output[0], + { + "quant_type": output_type, + "scale": np.array(1.0 / 32768.0, dtype=np.float32), + "zero_point": np.array(0, dtype=np.int16), + }, + ) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/fusions/__init__.py b/python/user_packages/Python313/site-packages/onnxruntime/quantization/fusions/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9b5299c8377a5496e45271a081740740d170122e --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/quantization/fusions/__init__.py @@ -0,0 +1,4 @@ +from .fusion import Fusion # noqa: F401 +from .fusion_gelu import FusionGelu # noqa: F401 +from .fusion_layernorm import FusionLayerNormalization # noqa: F401 +from .replace_upsample_with_resize import ReplaceUpsampleWithResize # noqa: F401 diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/fusions/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/quantization/fusions/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9d04a1a5a285cf9d232b6aff7eea8fc8adc62790 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/quantization/fusions/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/fusions/__pycache__/fusion.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/quantization/fusions/__pycache__/fusion.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8897dbfb8fe1ba74f6ef09030c0176f2c1efb4e8 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/quantization/fusions/__pycache__/fusion.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/fusions/__pycache__/fusion_gelu.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/quantization/fusions/__pycache__/fusion_gelu.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9b5195ef31428c21ebcd0a5e6a8bd1e38c051d81 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/quantization/fusions/__pycache__/fusion_gelu.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/fusions/__pycache__/fusion_layernorm.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/quantization/fusions/__pycache__/fusion_layernorm.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..babb8186965fe876cc19fcb1447174edb6f77542 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/quantization/fusions/__pycache__/fusion_layernorm.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/fusions/__pycache__/replace_upsample_with_resize.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/quantization/fusions/__pycache__/replace_upsample_with_resize.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aba84661f0686f04a89eb7281932106adcd0bf17 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/quantization/fusions/__pycache__/replace_upsample_with_resize.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/fusions/fusion.py b/python/user_packages/Python313/site-packages/onnxruntime/quantization/fusions/fusion.py new file mode 100644 index 0000000000000000000000000000000000000000..6c7e04fc7f46593bbc4f4d271062878f3d250f1f --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/quantization/fusions/fusion.py @@ -0,0 +1,311 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- +from __future__ import annotations + +from collections import deque + +import onnx + +from ..onnx_model import ONNXModel + + +class Fusion: + """ + Base class for fusions. + """ + + def __init__(self, model: ONNXModel, fused_op_type: str, search_op_type: str): + self.search_op_type: str = search_op_type + self.fused_op_type: str = fused_op_type + self.model: ONNXModel = model + self.nodes_to_remove: list = [] + self.nodes_to_add: list = [] + + self._new_node_name_prefix = self.fused_op_type + "_fused_" + self.search_op_type + "_" + self._new_node_name_suffix = None # int|None used to create unique node names for the fused ops. + + def fuse( + self, + node: onnx.NodeProto, + input_name_to_nodes: dict[str, list[onnx.NodeProto]], + output_name_to_node: dict[str, onnx.NodeProto], + ): + """ + Interface function for derived fusion classes. Tries to fuse a node sequence containing + the specified node. + """ + raise NotImplementedError + + def apply(self) -> bool: + """ + Apply graph fusion on the entire model graph. + """ + input_name_to_nodes = self.model.input_name_to_nodes() + output_name_to_node = self.model.output_name_to_node() + + for node in self.model.nodes(): + if node.op_type == self.search_op_type: + self.fuse(node, input_name_to_nodes, output_name_to_node) + + self.model.remove_nodes(self.nodes_to_remove) + self.model.add_nodes(self.nodes_to_add) + + graph_updated = bool(self.nodes_to_remove or self.nodes_to_add) + + if graph_updated: + self.model.remove_unused_constant() + + return graph_updated + + def create_unique_node_name(self): + prefix = self._new_node_name_prefix + + if self._new_node_name_suffix is None: + largest_suffix: int = self.model.get_largest_node_name_suffix(prefix) + self._new_node_name_suffix = largest_suffix + 1 + + new_name = f"{prefix}{self._new_node_name_suffix!s}" + self._new_node_name_suffix += 1 + + return new_name + + @staticmethod + def is_safe_to_fuse_nodes( + nodes_to_remove: list[onnx.NodeProto], + keep_outputs: list[str], + input_name_to_nodes: dict[str, list[onnx.NodeProto]], + output_name_to_node: dict[str, onnx.NodeProto], + ) -> bool: + for node_to_remove in nodes_to_remove: + for output_to_remove in node_to_remove.output: + if output_to_remove in keep_outputs: + continue + + if output_to_remove in input_name_to_nodes: + for impacted_node in input_name_to_nodes[output_to_remove]: + if impacted_node not in nodes_to_remove: + # Not safe to remove nodes since output is used by impacted_node + return False + return True + + @staticmethod + def get_node_attribute(node: onnx.NodeProto, attribute_name: str): + for attr in node.attribute: + if attr.name == attribute_name: + value = onnx.helper.get_attribute_value(attr) + return value + return None + + @staticmethod + def input_index(node_output: str, child_node: onnx.NodeProto) -> int: + for index, input_name in enumerate(child_node.input): + if input_name == node_output: + return index + return -1 + + @staticmethod + def tensor_shape_to_list(tensor_type) -> list[int]: + shape_list = [] + for d in tensor_type.shape.dim: + if d.HasField("dim_value"): + shape_list.append(d.dim_value) # known dimension + elif d.HasField("dim_param"): + shape_list.append(d.dim_param) # unknown dimension with symbolic name + else: + shape_list.append("?") # shall not happen + return shape_list + + def get_constant_input(self, node: onnx.NodeProto): + for i, inp in enumerate(node.input): + value = self.model.get_constant_value(inp) + if value is not None: + return i, value + + return None, None + + def find_constant_input(self, node: onnx.NodeProto, expected_value: float, delta: float = 0.000001) -> int: + i, value = self.get_constant_input(node) + if value is not None and value.size == 1 and abs(value - expected_value) < delta: + return i + + return -1 + + def has_constant_input(self, node: onnx.NodeProto, expected_value: float, delta: float = 0.000001) -> bool: + return self.find_constant_input(node, expected_value, delta) >= 0 + + def is_constant_with_specified_rank(self, output_name: str, rank: int) -> bool: + value = self.model.get_constant_value(output_name) + if value is None: + return False # Not an initializer + + if len(value.shape) != rank: + return False # Wrong dimensions + + return True + + def match_first_parent( + self, + node: onnx.NodeProto, + parent_op_type: str, + output_name_to_node: dict[str, onnx.NodeProto] | None = None, + exclude: list[onnx.NodeProto] = [], # noqa: B006 + ) -> tuple[onnx.NodeProto | None, int | None]: + """ + Find parent node based on constraints on op_type. + + Args: + node: current node. + parent_op_type (str): constraint of parent node op_type. + output_name_to_node (dict): dictionary with output name as key, and node as value. + exclude (list): list of nodes that are excluded (not allowed to match as parent). + + Returns: + parent: The matched parent node. None if not found. + index: The input index of matched parent node. None if not found. + """ + if output_name_to_node is None: + output_name_to_node = self.model.output_name_to_node() + + for i, inp in enumerate(node.input): + if inp in output_name_to_node: + parent = output_name_to_node[inp] + if parent.op_type == parent_op_type and parent not in exclude: + return parent, i + + return None, None + + def match_parent( + self, + node: onnx.NodeProto, + parent_op_type: str, + input_index: int | None = None, + output_name_to_node: dict[str, onnx.NodeProto] | None = None, + exclude: list[onnx.NodeProto] = [], # noqa: B006 + return_indice: list[int] | None = None, + ) -> onnx.NodeProto | None: + """ + Find parent node based on constraints on op_type and index. + When input_index is None, we will find the first parent node based on constraints, + and return_indice will be appended the corresponding input index. + + Args: + node (str): current node name. + parent_op_type (str): constraint of parent node op_type. + input_index (int or None): only check the parent given input index of current node. + output_name_to_node (dict): dictionary with output name as key, and node as value. + exclude (list): list of nodes that are excluded (not allowed to match as parent). + return_indice (list): a list to append the input index when input_index is None. + + Returns: + parent: The matched parent node. + """ + assert node is not None + assert input_index is None or input_index >= 0 + + if output_name_to_node is None: + output_name_to_node = self.model.output_name_to_node() + + if input_index is None: + parent, index = self.match_first_parent(node, parent_op_type, output_name_to_node, exclude) + if return_indice is not None: + return_indice.append(index) + return parent + + if input_index >= len(node.input): + # Input index out of bounds. + return None + + parent = self.model.get_parent(node, input_index, output_name_to_node) + if parent is not None and parent.op_type == parent_op_type and parent not in exclude: + return parent + + return None + + def match_parent_path( + self, + node: onnx.NodeProto, + parent_op_types: list[str], + parent_input_index: list[int] | None = None, + output_name_to_node: dict[str, onnx.NodeProto] | None = None, + return_indice: list[int] | None = None, + ) -> list[onnx.NodeProto] | None: + """ + Find a sequence of input edges based on constraints on parent op_type and index. + When input_index is None, we will find the first parent node based on constraints, + and return_indice will be appended the corresponding input index. + + Args: + node (str): current node name. + parent_op_types (str): constraint of parent node op_type of each input edge. + parent_input_index (list): constraint of input index of each input edge. None means no constraint. + output_name_to_node (dict): dictionary with output name as key, and node as value. + return_indice (list): a list to append the input index + When there is no constraint on input index of an edge. + + Returns: + parents: a list of matched parent node. + """ + if parent_input_index is not None: + assert len(parent_input_index) == len(parent_op_types) + + if output_name_to_node is None: + output_name_to_node = self.model.output_name_to_node() + + current_node = node + matched_parents = [] + for i, op_type in enumerate(parent_op_types): + matched_parent = self.match_parent( + current_node, + op_type, + parent_input_index[i] if parent_input_index is not None else None, + output_name_to_node, + exclude=[], + return_indice=return_indice, + ) + if matched_parent is None: + return None + + matched_parents.append(matched_parent) + current_node = matched_parent + + return matched_parents + + def match_parent_paths( + self, + node: onnx.NodeProto, + paths: list[tuple[list[str], list[int]]], + output_name_to_node: dict[str, onnx.NodeProto], + ) -> tuple[int, list[onnx.NodeProto] | None, list[int] | None]: + """ + Find a matching parent path to the given node. + """ + for i, path in enumerate(paths): + return_indice = [] + matched = self.match_parent_path(node, path[0], path[1], output_name_to_node, return_indice) + if matched: + return i, matched, return_indice + return -1, None, None + + def find_first_child_by_type( + self, + node: onnx.NodeProto, + child_type: str, + input_name_to_nodes: dict[str, list[onnx.NodeProto]] | None = None, + recursive: bool = True, + ) -> onnx.NodeProto | None: + children = self.model.get_children(node, input_name_to_nodes) + dq = deque(children) + while len(dq) > 0: + current_node = dq.pop() + if current_node.op_type == child_type: + return current_node + + if recursive: + children = self.model.get_children(current_node, input_name_to_nodes) + for child in children: + dq.appendleft(child) + + return None diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/fusions/fusion_gelu.py b/python/user_packages/Python313/site-packages/onnxruntime/quantization/fusions/fusion_gelu.py new file mode 100644 index 0000000000000000000000000000000000000000..8507454a5ab910a800f5d5632b2d1bf79b01fa93 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/quantization/fusions/fusion_gelu.py @@ -0,0 +1,272 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- +from __future__ import annotations + +import onnx + +from ..onnx_model import ONNXModel +from .fusion import Fusion + + +class FusionGelu(Fusion): + def __init__(self, model: ONNXModel): + super().__init__(model, "Gelu", "Erf") + + def fuse( + self, + erf_node: onnx.NodeProto, + input_name_to_nodes: dict[str, list[onnx.NodeProto]], + output_name_to_node: dict[str, onnx.NodeProto], + ): + """ + Interface function that tries to fuse a node sequence containing an Erf node into a single + Gelu node. + """ + if ( + self.fuse_1(erf_node, input_name_to_nodes, output_name_to_node) + or self.fuse_2(erf_node, input_name_to_nodes, output_name_to_node) + or self.fuse_3(erf_node, input_name_to_nodes, output_name_to_node) + ): + self.model.set_opset_import("com.microsoft", 1) + + def fuse_1( + self, + erf_node: onnx.NodeProto, + input_name_to_nodes: dict[str, list[onnx.NodeProto]], + output_name_to_node: dict[str, onnx.NodeProto], + ) -> bool: + """ + This pattern is from PyTorch model + Fuse Gelu with Erf into one node: + Pattern 1: + +-------Mul(0.5)---------------------+ + | | + | v + [root] --> Div -----> Erf --> Add --> Mul --> + (B=1.4142...) (1) + + Pattern 2: + +------------------------------------+ + | | + | v + [root] --> Div -----> Erf --> Add --> Mul -->Mul --> + (B=1.4142...) (1) (0.5) + + Note that constant input for Add and Mul could be first or second input: like either A=0.5 or B=0.5 is fine. + """ + if erf_node.output[0] not in input_name_to_nodes: + return False + children = input_name_to_nodes[erf_node.output[0]] + if len(children) != 1 or children[0].op_type != "Add": + return False + add_after_erf = children[0] + + if not self.has_constant_input(add_after_erf, 1): + return False + + if add_after_erf.output[0] not in input_name_to_nodes: + return False + + children = input_name_to_nodes[add_after_erf.output[0]] + if len(children) != 1 or children[0].op_type != "Mul": + return False + + mul_after_erf = children[0] + + div = self.match_parent(erf_node, "Div", 0, output_name_to_node) + if div is None: + return False + + if self.find_constant_input(div, 1.4142, delta=0.001) != 1: + return False + + subgraph_input = div.input[0] + + another = 1 if mul_after_erf.input[0] == add_after_erf.output[0] else 0 + if subgraph_input == mul_after_erf.input[another]: # pattern 2 + children = input_name_to_nodes[mul_after_erf.output[0]] + if len(children) != 1 or children[0].op_type != "Mul": + return False + mul_half = children[0] + if not self.has_constant_input(mul_half, 0.5): + return False + subgraph_output = mul_half.output[0] + else: # pattern 1 + mul_half = self.match_parent(mul_after_erf, "Mul", another, output_name_to_node) + if mul_half is None: + return False + + if not self.has_constant_input(mul_half, 0.5): + return False + + if subgraph_input not in mul_half.input: + return False + + subgraph_output = mul_after_erf.output[0] + + subgraph_nodes = [div, erf_node, add_after_erf, mul_after_erf, mul_half] + if not self.is_safe_to_fuse_nodes(subgraph_nodes, [subgraph_output], input_name_to_nodes, output_name_to_node): + return False + + self.nodes_to_remove.extend(subgraph_nodes) + fused_node = onnx.helper.make_node( + "Gelu", name=self.create_unique_node_name(), inputs=[subgraph_input], outputs=[subgraph_output] + ) + fused_node.domain = "com.microsoft" + self.nodes_to_add.append(fused_node) + return True + + def fuse_2( + self, + erf_node: onnx.NodeProto, + input_name_to_nodes: dict[str, list[onnx.NodeProto]], + output_name_to_node: dict[str, onnx.NodeProto], + ) -> bool: + """ + This pattern is from Keras model + Fuse Gelu with Erf into one node: + +------------------------------------------+ + | | + | v + [root] --> Div -----> Erf --> Add --> Mul -->Mul + (B=1.4142...) (A=1) (A=0.5) + + Note that constant input for Add and Mul could be first or second input: like either A=0.5 or B=0.5 is fine. + """ + if erf_node.output[0] not in input_name_to_nodes: + return False + children = input_name_to_nodes[erf_node.output[0]] + if len(children) != 1 or children[0].op_type != "Add": + return False + add_after_erf = children[0] + + if not self.has_constant_input(add_after_erf, 1): + return False + + if add_after_erf.output[0] not in input_name_to_nodes: + return False + children = input_name_to_nodes[add_after_erf.output[0]] + if len(children) != 1 or children[0].op_type != "Mul": + return False + mul_after_erf = children[0] + + if not self.has_constant_input(mul_after_erf, 0.5): + return False + + if mul_after_erf.output[0] not in input_name_to_nodes: + return False + children = input_name_to_nodes[mul_after_erf.output[0]] + if len(children) != 1 or children[0].op_type != "Mul": + return False + mul = children[0] + + div = self.match_parent(erf_node, "Div", 0, output_name_to_node) + if div is None: + return False + + sqrt_node = None + if self.find_constant_input(div, 1.4142, delta=0.001) != 1: + sqrt_node = self.match_parent(div, "Sqrt", 1, output_name_to_node) + if sqrt_node is None: + return False + if not self.has_constant_input(sqrt_node, 2.0): + return False + + subgraph_input = div.input[0] + + if subgraph_input not in mul.input: + return False + + subgraph_nodes = [div, erf_node, add_after_erf, mul_after_erf, mul] + if sqrt_node: + subgraph_nodes.append(sqrt_node) + + if not self.is_safe_to_fuse_nodes(subgraph_nodes, [mul.output[0]], input_name_to_nodes, output_name_to_node): + return False + + self.nodes_to_remove.extend(subgraph_nodes) + fused_node = onnx.helper.make_node( + "Gelu", name=self.create_unique_node_name(), inputs=[subgraph_input], outputs=[mul.output[0]] + ) + fused_node.domain = "com.microsoft" + self.nodes_to_add.append(fused_node) + return True + + def fuse_3( + self, + erf_node: onnx.NodeProto, + input_name_to_nodes: dict[str, list[onnx.NodeProto]], + output_name_to_node: dict[str, onnx.NodeProto], + ) -> bool: + """ + This pattern is from TensorFlow model + Fuse Gelu with Erf into one node: + +----------------------------------------------+ + | | + | v + [root] --> Mul -----> Erf --> Add --> Mul -->Mul + (A=0.7071067690849304) (B=1) (B=0.5) + + Note that constant input for Add and Mul could be first or second input: like either A=0.5 or B=0.5 is fine. + """ + + if erf_node.output[0] not in input_name_to_nodes: + return False + children = input_name_to_nodes[erf_node.output[0]] + if len(children) != 1 or children[0].op_type != "Add": + return False + add_after_erf = children[0] + + if not self.has_constant_input(add_after_erf, 1): + return False + + if add_after_erf.output[0] not in input_name_to_nodes: + return False + children = input_name_to_nodes[add_after_erf.output[0]] + if len(children) != 1 or children[0].op_type != "Mul": + return False + mul_half = children[0] + + if not self.has_constant_input(mul_half, 0.5): + return False + + first_mul = self.match_parent(erf_node, "Mul", 0, output_name_to_node) + if first_mul is None: + return False + + i = self.find_constant_input(first_mul, 0.7071067690849304, delta=0.001) + if i < 0: + return False + + root_input_index = 1 - i + subgraph_input = first_mul.input[root_input_index] + + if mul_half.output[0] not in input_name_to_nodes: + return False + children = input_name_to_nodes[mul_half.output[0]] + if len(children) != 1 or children[0].op_type != "Mul": + return False + last_mul = children[0] + + if not (last_mul.input[0] == subgraph_input or last_mul.input[1] == subgraph_input): + return False + + subgraph_nodes = [first_mul, erf_node, add_after_erf, mul_half, last_mul] + if not self.is_safe_to_fuse_nodes( + subgraph_nodes, + [last_mul.output[0]], + input_name_to_nodes, + output_name_to_node, + ): + return False + + self.nodes_to_remove.extend(subgraph_nodes) + fused_node = onnx.helper.make_node( + "Gelu", name=self.create_unique_node_name(), inputs=[subgraph_input], outputs=[last_mul.output[0]] + ) + fused_node.domain = "com.microsoft" + self.nodes_to_add.append(fused_node) + return True diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/fusions/fusion_layernorm.py b/python/user_packages/Python313/site-packages/onnxruntime/quantization/fusions/fusion_layernorm.py new file mode 100644 index 0000000000000000000000000000000000000000..e0ef02ca0862d22b04ac8a401345d1c0a8d9202e --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/quantization/fusions/fusion_layernorm.py @@ -0,0 +1,146 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- +from __future__ import annotations + +import onnx + +from ..onnx_model import ONNXModel +from .fusion import Fusion + + +class FusionLayerNormalization(Fusion): + def __init__(self, model: ONNXModel): + super().__init__(model, "LayerNormalization", "ReduceMean") + + def fuse( + self, + reduce_mean_node: onnx.NodeProto, + input_name_to_nodes: dict[str, list[onnx.NodeProto]], + output_name_to_node: dict[str, onnx.NodeProto], + ): + """ + Interface function that tries to fuse a node sequence containing a ReduceMean node into a single + LayerNormalization node. + + +----------------------+ + | | + | v + [Root] --> ReduceMean --> Sub --> Pow --> ReduceMean --> Add --> Sqrt --> Div --> Mul --> Add + (axis=2 or -1) | (Y=2) (axis=2 or -1) (E-6 or E-12 or 0) ^ + | | + +-------------------------------------------------+ + + Or, using Mul instead of Pow: + + +----------------------+ + | | + | v + [Root] --> ReduceMean --> Sub --> Mul --> ReduceMean --> Add --> Sqrt --> Div --> Mul --> Add + (axis=2 or -1) | (in0=in1) (axis=2 or -1) (E-6 or E-12 or 0) ^ + | | + +-------------------------------------------------+ + + It also handles cases of duplicated sub nodes exported from older version of PyTorch: + + +----------------------+ + | v + | +-------> Sub-----------------------------------------------+ + | | | + | | v + [Root] --> ReduceMean --> Sub --> (Pow or Mul) --> ReduceMean --> Add --> Sqrt --> Div --> Mul --> Add + | ^ + | | + +----------------------+ + """ + children = self.model.get_children(reduce_mean_node, input_name_to_nodes) + if len(children) == 0 or len(children) > 2: + return + + root_input = reduce_mean_node.input[0] + + if children[0].op_type != "Sub" or children[0].input[0] != root_input: + return + + if len(children) == 2: + if children[1].op_type != "Sub" or children[1].input[0] != root_input: + return + + div_node = None + for child in children: + div_node = self.find_first_child_by_type(child, "Div", input_name_to_nodes, recursive=False) + if div_node is not None: + break + if div_node is None: + return + + path_id, parent_nodes, _ = self.match_parent_paths( + div_node, + [ + (["Sqrt", "Add", "ReduceMean", "Pow", "Sub"], [1, 0, 0, 0, 0]), + (["Sqrt", "Add", "ReduceMean", "Pow", "Cast", "Sub"], [1, 0, 0, 0, 0, 0]), + (["Sqrt", "Add", "ReduceMean", "Mul", "Sub"], [1, 0, 0, 0, 0]), + (["Sqrt", "Add", "ReduceMean", "Mul", "Cast", "Sub"], [1, 0, 0, 0, 0, 0]), + ], + output_name_to_node, + ) + if path_id < 0: + return + + sub_node = parent_nodes[-1] + if sub_node not in children: + return + + second_add_node = parent_nodes[1] + i, add_weight = self.get_constant_input(second_add_node) + if add_weight is None or add_weight <= 0 or add_weight > 1.0e-4: + # Skip fusion since epsilon value is not expected. + return + + pow_or_mul_node = parent_nodes[3] + if pow_or_mul_node.op_type == "Pow" and self.find_constant_input(pow_or_mul_node, 2.0) != 1: + return + elif pow_or_mul_node.op_type == "Mul" and pow_or_mul_node.input[0] != pow_or_mul_node.input[1]: + return + + mul_node = input_name_to_nodes[div_node.output[0]][0] + if mul_node.op_type != "Mul": + return + + last_add_node = input_name_to_nodes[mul_node.output[0]][0] + if last_add_node.op_type != "Add": + return + + subgraph_nodes = [reduce_mean_node] + subgraph_nodes.extend(children) + subgraph_nodes.extend(parent_nodes[:-1]) + + subgraph_nodes.extend([last_add_node, mul_node, div_node]) + if not self.is_safe_to_fuse_nodes( + subgraph_nodes, + last_add_node.output, + input_name_to_nodes, + output_name_to_node, + ): + return + + weight_input = mul_node.input[1 - self.input_index(div_node.output[0], mul_node)] + if not self.is_constant_with_specified_rank(weight_input, 1): + return + + bias_input = last_add_node.input[1 - self.input_index(mul_node.output[0], last_add_node)] + if not self.is_constant_with_specified_rank(bias_input, 1): + return + + self.nodes_to_remove.extend(subgraph_nodes) + + normalize_node = onnx.helper.make_node( + "LayerNormalization", + name=self.create_unique_node_name(), + inputs=[reduce_mean_node.input[0], weight_input, bias_input], + outputs=[last_add_node.output[0]], + ) + normalize_node.attribute.extend([onnx.helper.make_attribute("epsilon", float(add_weight))]) + self.nodes_to_add.append(normalize_node) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/fusions/replace_upsample_with_resize.py b/python/user_packages/Python313/site-packages/onnxruntime/quantization/fusions/replace_upsample_with_resize.py new file mode 100644 index 0000000000000000000000000000000000000000..323bed9dd1eb669b821020d0b1791ec4b94d9c0a --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/quantization/fusions/replace_upsample_with_resize.py @@ -0,0 +1,96 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- +from __future__ import annotations + +import numpy as np +import onnx + +from ..onnx_model import ONNXModel +from .fusion import Fusion + + +class ReplaceUpsampleWithResize(Fusion): + """Replace Upsample with Resize.""" + + def __init__(self, model: ONNXModel, opset): + """Initialize.""" + super().__init__(model, "Resize", "Upsample") + self.opset = opset + + def fuse( + self, + node: onnx.NodeProto, + input_name_to_nodes: dict[str, list[onnx.NodeProto]], + output_name_to_node: dict[str, onnx.NodeProto], + ): + """Replace Upsample with Resize.""" + mode = None + for attr in node.attribute: + if attr.name == "mode": + mode = attr.s.decode("utf-8") + break + + scales_input = None + if self.opset > 7: + scales_input = node.input[1] if len(node.input) > 1 else "" + resize_inputs = [node.input[0], node.name + "_roi", scales_input] + else: + if self.opset == 7: + for attr in node.attribute: + if attr.name == "scales": + scales_input = attr.floats + break + + scales_input = np.array(list(scales_input), np.float32) + else: + h_scale = 1 + w_scale = 1 + for attr in node.attribute: + if attr.name == "height_scale": + h_scale = attr.float + elif attr.name == "width_scale": + w_scale = attr.float + + scales_input = np.array([1, 1, h_scale, w_scale], np.float32) + + scales_tensor = onnx.helper.make_tensor( + name=node.name + "_scales", + data_type=onnx.TensorProto.FLOAT, + dims=scales_input.shape, + vals=scales_input.flatten().tolist(), + ) + + scales_node = onnx.helper.make_node( + "Constant", inputs=[], outputs=[node.name + "_scales"], value=scales_tensor + ) + + self.nodes_to_add.append(scales_node) + + resize_inputs = [node.input[0], node.name + "_roi", node.name + "_scales"] + + roi_tensor = onnx.helper.make_tensor( + name=node.name + "_roi", + data_type=onnx.TensorProto.FLOAT, + dims=(len(scales_input) * 2,), + vals=[0] * len(scales_input) + [1] * len(scales_input), + ) + + roi_node = onnx.helper.make_node("Constant", inputs=[], outputs=[node.name + "_roi"], value=roi_tensor) + + resize_node = onnx.helper.make_node( + op_type="Resize", inputs=resize_inputs, outputs=node.output, mode=mode, nearest_mode="floor" + ) + + self.nodes_to_remove.append(node) + self.nodes_to_add.append(roi_node) + self.nodes_to_add.append(resize_node) + + def apply(self) -> bool: + """Apply.""" + if super().apply(): + self.model.topological_sort() + return True + return False diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/neural_compressor/__init__.py b/python/user_packages/Python313/site-packages/onnxruntime/quantization/neural_compressor/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..cd64b471046035200143b3ed126312d78f0f8e3f --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/quantization/neural_compressor/__init__.py @@ -0,0 +1 @@ +from .weight_only import gptq_quantize, rtn_quantize # noqa: F401 diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/neural_compressor/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/quantization/neural_compressor/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..972b864ef1d543b4209962d7c28dfe6696012bcd Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/quantization/neural_compressor/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/neural_compressor/__pycache__/onnx_model.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/quantization/neural_compressor/__pycache__/onnx_model.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d4f98a39f1f3e1a9a278f09bfd9b56b9b33e48ec Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/quantization/neural_compressor/__pycache__/onnx_model.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/neural_compressor/__pycache__/util.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/quantization/neural_compressor/__pycache__/util.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..243d421da986fb5fa00cc43ca68e970da906c86e Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/quantization/neural_compressor/__pycache__/util.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/neural_compressor/__pycache__/weight_only.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/quantization/neural_compressor/__pycache__/weight_only.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b1ba79a4fe58c9f837f07aef4fe2fe735fb289be Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/quantization/neural_compressor/__pycache__/weight_only.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/neural_compressor/onnx_model.py b/python/user_packages/Python313/site-packages/onnxruntime/quantization/neural_compressor/onnx_model.py new file mode 100644 index 0000000000000000000000000000000000000000..75e5332cfa254ec6c96e5d2292e5a5e9807519d0 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/quantization/neural_compressor/onnx_model.py @@ -0,0 +1,1236 @@ +# +# The implementation of this file is based on: +# https://github.com/intel/neural-compressor/tree/master/neural_compressor +# +# Copyright (c) 2023 Intel Corporation +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Class for ONNX model.""" + +import copy +import logging +import os +from collections import deque +from pathlib import Path + +import onnx +import onnx.external_data_helper +import onnx_ir as ir + +from .util import MAXIMUM_PROTOBUF, find_by_name + +logger = logging.getLogger("neural_compressor") + +# TODO: Check https://github.com/microsoft/onnxruntime/blob/main/onnxruntime/python/tools/quantization/onnx_model.py to see if we can integrate with it. + + +class ONNXModel: + """Build ONNX model.""" + + def __init__(self, model, **kwargs): + """Initialize an ONNX model. + + Args: + model (str or ModelProto): path to onnx model or loaded ModelProto model object. + ignore_warning (bool): ignore large model warning. Default is False. + load_external_data (bool): load external data for large model. Default is True. + """ + self._model = model if not isinstance(model, str) else onnx.load(model, load_external_data=False) + self._model_path = None if not isinstance(model, str) else model + + self.check_is_large_model() + if self._is_large_model and self._model_path is None and not kwargs.get("ignore_warning", False): + logger.warning("Model size > 2GB. Please use model path instead of onnx model object to quantize") + + if self._is_large_model and isinstance(model, str) and kwargs.get("load_external_data", True): + onnx.external_data_helper.load_external_data_for_model(self._model, os.path.dirname(self._model_path)) + + self._config = None + if isinstance(model, str) and os.path.exists(Path(model).parent.joinpath("config.json").as_posix()): + from transformers import AutoConfig # noqa: PLC0415 + + self._config = AutoConfig.from_pretrained(Path(model).parent.as_posix()) + + self.node_name_counter = {} + self._output_name_to_node = {} + self._input_name_to_nodes = {} + self._get_input_name_to_nodes(self._model.graph.node) + self._get_output_name_to_node(self._model.graph.node) + self._graph_info = {} + self._get_graph_info() + self._q_config = None + + def check_is_large_model(self): + """Check model > 2GB.""" + ir_graph = ir.from_proto(self._model.graph) + initializer_size = sum( + v.const_value.nbytes for v in ir_graph.initializers.values() if v.const_value is not None + ) + self._is_large_model = initializer_size > MAXIMUM_PROTOBUF + + @property + def is_large_model(self): + """Check the onnx model is over 2GB.""" + return self._is_large_model + + @property + def model_path(self): + """Return model path.""" + return self._model_path + + @model_path.setter + def model_path(self, path): + """Set model path.""" + self._model_path = path + + def framework(self): + """Return framework.""" + return "onnxruntime" + + @property + def q_config(self): + """Return q_config.""" + return self._q_config + + @q_config.setter + def q_config(self, q_config): + """Set q_config.""" + self._q_config = q_config + + @property + def hf_config(self): + """Return huggingface config if model is Transformer-based.""" + return self._config + + @property + def model(self): + """Return model itself.""" + return self._model + + @model.setter + def model(self, model): + """Set model itself.""" + self._model = model + self._graph_info = {} + self._get_graph_info() + self._output_name_to_node = {} + self._input_name_to_nodes = {} + self._get_input_name_to_nodes(self._model.graph.node) + self._get_output_name_to_node(self._model.graph.node) + + def input(self): + """Return input of model.""" + return [i.name for i in self._model.graph.input] + + def output(self): + """Return output of model.""" + return [i.name for i in self._model.graph.output] + + def update(self): + """Update model info.""" + self._graph_info = {} + self._get_graph_info() + self._output_name_to_node = {} + self._input_name_to_nodes = {} + self._get_input_name_to_nodes(self._model.graph.node) + self._get_output_name_to_node(self._model.graph.node) + + @property + def graph_info(self): + """Return ORT Graph Info object holding information about backend graph.""" + return self._graph_info + + def _get_graph_info(self): + """Update graph info.""" + for node in self._model.graph.node: + self.graph_info.update({node.name: node.op_type}) + + def save(self, root): + """Save ONNX model.""" + if os.path.split(root)[0] != "" and not os.path.exists(os.path.split(root)[0]): + raise ValueError('"root" directory does not exists.') + if self.is_large_model: + onnx.external_data_helper.load_external_data_for_model(self._model, os.path.split(self._model_path)[0]) + onnx.save_model( + self._model, + root, + save_as_external_data=True, + all_tensors_to_one_file=True, + location=root.split("/")[-1] + "_data", + size_threshold=1024, + convert_attribute=False, + ) + else: + onnx.save(self._model, root) + + if self._config is not None: + model_type = "" if not hasattr(self._config, "model_type") else self._config.model_type + self._config.__class__.model_type = model_type + output_config_file = Path(root).parent.joinpath("config.json").as_posix() + self._config.to_json_file(output_config_file, use_diff=False) + + def nodes(self): + """Return model nodes.""" + return self._model.graph.node + + def initializer(self): + """Return model initializer.""" + return self._model.graph.initializer + + def graph(self): + """Return model graph.""" + return self._model.graph + + def ir_version(self): + """Return model ir_version.""" + return self._model.ir_version + + def opset_import(self): + """Return model opset_import.""" + return self._model.opset_import + + def remove_node(self, node): + """Remove a node from model.""" + if node in self._model.graph.node: + self._model.graph.node.remove(node) + + def remove_nodes(self, nodes_to_remove): + """Remove nodes from model.""" + for node in nodes_to_remove: + self.remove_node(node) + + def add_node(self, node): + """Add a node to model.""" + self._model.graph.node.extend([node]) + + def add_nodes(self, nodes_to_add): + """Add nodes to model.""" + self._model.graph.node.extend(nodes_to_add) + + def add_initializer(self, tensor): + """Add a initializer to model.""" + if find_by_name(tensor.name, self._model.graph.initializer) is None: + self._model.graph.initializer.extend([tensor]) + + def add_initializers(self, tensors): + """Add initializers to model.""" + for tensor in tensors: + self.add_initializer(tensor) + + def get_initializer(self, name): + """Get an initializer by name.""" + for tensor in self._model.graph.initializer: + if tensor.name == name: + return tensor + return None + + def get_initializer_share_num(self, name): + """Get the number of shares of initializer.""" + num = 0 + if self.get_initializer(name) is None: + return num + + for node in self.nodes(): + if name in node.input: + num += 1 + return num + + def get_node(self, name): + """Get a node by name.""" + for node in self._model.graph.node: + if node.name == name: + return node + return None + + def remove_initializer(self, tensor): + """Remove an initializer from model.""" + if tensor in self._model.graph.initializer: + self._model.graph.initializer.remove(tensor) + + def remove_initializers(self, init_to_remove): + """Remove initializers from model.""" + for initializer in init_to_remove: + self.remove_initializer(initializer) + + def set_initializer(self, tensor, array, raw=False): + """Update initializer.""" + old_tensor = self.get_initializer(tensor) + self.remove_initializer(old_tensor) + dims = old_tensor.dims + data_type = old_tensor.data_type + new_tensor = ( + onnx.helper.make_tensor(tensor, data_type, dims, array.flatten().tolist()) + if not raw + else onnx.helper.make_tensor(tensor, data_type, dims, array.tostring(), raw=raw) + ) + self.add_initializer(new_tensor) + + @property + def input_name_to_nodes(self): + """Return input names of nodes.""" + return self._input_name_to_nodes + + def _get_input_name_to_nodes(self, nodes): + """Get input names of nodes.""" + for node in nodes: + attrs = [ + attr + for attr in node.attribute + if attr.type == onnx.AttributeProto.GRAPH or attr.type == onnx.AttributeProto.GRAPHS + ] + if len(attrs) > 0: + for attr in attrs: + self._get_input_name_to_nodes(attr.g.node) + for input_name in node.input: + if len(input_name.strip()) != 0: + if input_name not in self._input_name_to_nodes: + self._input_name_to_nodes[input_name] = [node] + else: + self._input_name_to_nodes[input_name].append(node) + + @property + def output_name_to_node(self): + """Return output names of nodes.""" + return self._output_name_to_node + + def _get_output_name_to_node(self, nodes): + """Get output names of nodes.""" + for node in nodes: + attrs = [ + attr + for attr in node.attribute + if attr.type == onnx.AttributeProto.GRAPH or attr.type == onnx.AttributeProto.GRAPHS + ] + if len(attrs) > 0: + for attr in attrs: + self._get_output_name_to_node(attr.g.node) + for output_name in node.output: + if len(output_name.strip()) != 0: + self._output_name_to_node[output_name] = node + + def get_siblings(self, node): + """Get siblings nodes.""" + siblings = [] + for parent in self.get_parents(node): + for child in self.get_children(parent): + if child.name != node.name: + siblings.append(child) + return siblings + + def get_children(self, node, input_name_to_nodes=None): + """Get children nodes.""" + if input_name_to_nodes is None: + input_name_to_nodes = self._input_name_to_nodes + + children = [] + for output in node.output: + if output in input_name_to_nodes: + for child in input_name_to_nodes[output]: + children.append(child) # noqa: PERF402 + return children + + def get_parents(self, node, output_name_to_node=None): + """Get parents nodes.""" + if output_name_to_node is None: + output_name_to_node = self._output_name_to_node + + parents = [] + for input in node.input: + if input in output_name_to_node: + parents.append(output_name_to_node[input]) + return parents + + def get_parent(self, node, idx, output_name_to_node=None): + """Get parent node by idx.""" + if output_name_to_node is None: + output_name_to_node = self._output_name_to_node + + if len(node.input) <= idx: + return None + + input = node.input[idx] + if input not in output_name_to_node: + return None + + return output_name_to_node[input] + + def find_node_by_name(self, node_name, new_nodes_list, graph): + """Find out node by name.""" + graph_nodes_list = list(graph.node) # deep copy + graph_nodes_list.extend(new_nodes_list) + node = find_by_name(node_name, graph_nodes_list) + return node + + def find_nodes_by_initializer(self, graph, initializer): + """Find all nodes with given initializer as an input.""" + nodes = [] + for node in graph.node: + for node_input in node.input: + if node_input == initializer.name: + nodes.append(node) + return nodes + + def get_scale_zero(self, tensor): + """Help function to get scale and zero_point.""" + if not tensor.endswith("_quantized"): + logger.debug(f"Find {tensor} in the quantized graph is not quantized.") + return None, None + + def _searcher(tensor_name): + """Search scale and zero point tensor recursively.""" + node = self._input_name_to_nodes[tensor_name][0] + parent = self._output_name_to_node.get(tensor_name, None) + direct_int8 = ["Reshape", "Transpose", "Squeeze", "Unsqueeze", "MaxPool", "Pad", "Split"] + if parent is not None and parent.op_type in direct_int8: + fp32_tensor_name = ( + parent.input[0] + .replace("_quantized", "") + .replace("_QuantizeLinear", "") + .replace("_QuantizeInput", "") + ) + elif node.op_type in ["Gather"]: # pragma: no cover + fp32_tensor_name = ( + node.output[0] + .replace("_quantized", "") + .replace("_QuantizeLinear", "") + .replace("_QuantizeInput", "") + ) + else: + fp32_tensor_name = ( + tensor_name.replace("_quantized", "").replace("_QuantizeLinear", "").replace("_QuantizeInput", "") + ) + scale = fp32_tensor_name + "_scale" + scale_tensor = self.get_initializer(scale) + zo = fp32_tensor_name + "_zero_point" + zo_tensor = self.get_initializer(zo) + + if scale_tensor is None or zo_tensor is None: + if parent is not None: + scale_tensor, zo_tensor = _searcher(parent.input[0]) + return scale_tensor, zo_tensor + + node = self._input_name_to_nodes[tensor][0] + # TODO check if scale_tensor and zero_point is needed + # for bias of qlinearconv, scale and zero_point is not needed + if (node.op_type == "QLinearConv" and tensor == node.input[-1]) or ( + node.op_type == "QGemm" and tensor == node.input[-3] + ): + return None, None + else: + scale_tensor, zo_tensor = _searcher(tensor) + assert scale_tensor, f"missing scale for tensor {tensor}" + assert zo_tensor, f"missing zero point for tensor {tensor}" + return scale_tensor, zo_tensor + + def save_model_to_file(self, output_path, use_external_data_format=False): + """Save model to external data, which is needed for model size > 2GB.""" + if use_external_data_format: + onnx.external_data_helper.convert_model_to_external_data( + self._model, all_tensors_to_one_file=True, location=Path(output_path).name + ".data" + ) + onnx.save_model(self._model, output_path) + + @staticmethod + def replace_node_input(node, old_input_name, new_input_name): + """Replace input of a node.""" + assert isinstance(old_input_name, str) and isinstance(new_input_name, str) + for j in range(len(node.input)): + if node.input[j] == old_input_name: + node.input[j] = new_input_name + + def replace_input_of_all_nodes(self, old_input_name, new_input_name, white_optype=None, black_optype=None): + """Replace inputs of all nodes.""" + if white_optype is None: + white_optype = [] + if black_optype is None: + black_optype = [] + if len(white_optype) > 0: + for node in self.model.graph.node: + if node.op_type in white_optype: + ONNXModel.replace_node_input(node, old_input_name, new_input_name) + else: + for node in self.model.graph.node: + if node.op_type not in black_optype: + ONNXModel.replace_node_input(node, old_input_name, new_input_name) + + @staticmethod + def replace_node_output(node, old_output_name, new_output_name): + """Replace output of a node.""" + assert isinstance(old_output_name, str) and isinstance(new_output_name, str) + for j in range(len(node.output)): + if node.output[j] == old_output_name: + node.output[j] = new_output_name + + def replace_output_of_all_nodes(self, old_output_name, new_output_name, white_optype=None, black_optype=None): + """Replace outputs of all nodes.""" + if white_optype is None: + white_optype = [] + if black_optype is None: + black_optype = [] + if len(white_optype) > 0: + for node in self.model.graph.node: + if node.op_type in white_optype: + ONNXModel.replace_node_output(node, old_output_name, new_output_name) + else: + for node in self.model.graph.node: + if node.op_type not in black_optype: + ONNXModel.replace_node_output(node, old_output_name, new_output_name) + + def remove_unused_nodes(self): + """Remove unused nodes.""" + unused_nodes = [] + nodes = self.nodes() + for node in nodes: + if ( + node.op_type == "Constant" + and node.output[0] not in self._model.graph.output + and node.output[0] not in self._input_name_to_nodes + ): + unused_nodes.append(node) + elif ( + node.op_type == "QuantizeLinear" + and len(self.get_children(node)) == 1 + and self.get_children(node)[0].op_type == "DequantizeLinear" + and node.input[0] not in self._output_name_to_node + and self.get_children(node)[0].output[0] not in self._input_name_to_nodes + ): + unused_nodes.append(node) + unused_nodes.extend(self.get_children(node)) + else: + # remove the node if it does not serve as the input or output of any other nodes + unused = True + for output in node.output: + if output in self._input_name_to_nodes or output in self.output(): + unused = False + break + for input in node.input: + if self.get_initializer(input) is not None: + continue + elif input in self._output_name_to_node or input in self.input(): + unused = False + break + if unused: + unused_nodes.append(node) + self.remove_nodes(unused_nodes) + + ununsed_weights = [] + for w in self._model.graph.initializer: + if w.name not in self._input_name_to_nodes and w.name not in self._model.graph.output: + ununsed_weights.append(w) + # Remove from graph.input + for graph_input in self.graph().input: + if graph_input.name == w.name: + self.graph().input.remove(graph_input) + + self.remove_initializers(ununsed_weights) + self.update() + + def topological_sort(self, enable_subgraph=False): + """Topological sort the model.""" + + if not enable_subgraph: + input_name_to_nodes = {} + output_name_to_node = {} + for node in self.model.graph.node: + for input_name in node.input: + if len(input_name.strip()) != 0: + if input_name not in input_name_to_nodes: + input_name_to_nodes[input_name] = [node] + else: + input_name_to_nodes[input_name].append(node) + for output_name in node.output: + if len(output_name.strip()) != 0: + output_name_to_node[output_name] = node + else: # pragma: no cover + input_name_to_nodes = self._input_name_to_nodes + output_name_to_node = self._output_name_to_node + + all_nodes = {} + q = deque() + wait = deque() + for inp in self.model.graph.input: + q.extend(input_name_to_nodes[inp.name]) + for n in self.model.graph.node: + if all(i not in output_name_to_node and i not in self.input() for i in n.input): + q.append(n) + + while q: + n = q.popleft() + if not all(output_name_to_node[i].name in all_nodes for i in n.input if i in output_name_to_node): + if n not in wait: + wait.append(n) + continue + + all_nodes[n.name] = n + for out in n.output: + if out in input_name_to_nodes: + q.extend([i for i in input_name_to_nodes[out] if i.name not in all_nodes and i not in q]) + if len(q) == 0 and len(wait) != 0: + q = copy.deepcopy(wait) + wait.clear() + nodes = [i[1] for i in all_nodes.items()] + assert len(list({n.name for n in nodes})) == len(list({n.name for n in self.model.graph.node})) + self.model.graph.ClearField("node") + self.model.graph.node.extend(nodes) + + def get_nodes_chain(self, start, stop, result_chain=None): + """Get nodes chain with given start node and stop node.""" + if result_chain is None: + result_chain = [] + # process start node list + start_node = deque() + for node in start: + if isinstance(node, str): + start_node.append(node) + elif isinstance(node, onnx.NodeProto): + start_node.append(node.name) + else: + assert False, "'get_nodes_chain' function only support list[string]or list[NodeProto] params" # noqa: B011 + + # process stop node list + stop_node = [] + for node in stop: + if isinstance(node, str): + stop_node.append(node) + elif isinstance(node, onnx.NodeProto): + stop_node.append(node.name) + else: + assert False, "'get_nodes_chain' function only support list[string]or list[NodeProto] params" # noqa: B011 + + while start_node: + node_name = start_node.popleft() + if node_name in stop_node: + continue + if node_name not in result_chain: + result_chain.append(node_name) + else: + continue + + node = find_by_name(node_name, list(self.model.graph.node)) + for parent in self.get_parents(node): + start_node.append(parent.name) + + return result_chain + + def find_split_node_for_layer_wise_quantization(self): + """Find split node for layer wise quantization.""" + # find split nodes of decoder blocks + # embed -> decoder.0 -(split_node)-> ... -(split_node)-> decoder.n -(split_node)-> norm -> head + # after split: embed -> decoder.0, + # decoder.1, + # decoder.2, + # ..., + # decoder.n, + # norm -> head + start_nodes = [] + for node in self._model.graph.node: + start_node, qkv_nodes_list = None, None + if node.op_type == "SkipLayerNormalization": + start_node = node + qkv_nodes_list = [ + self.match_parent_path( + start_node, + ["MatMul", "Reshape", "Transpose", "Reshape", "MatMul"], + [None, 0, 0, 0, 0], + ), + self.match_parent_path( + start_node, + ["Add", "MatMul", "Reshape", "Transpose", "MatMul"], + [1, 1, 0, 0, 0], + ), + ] + if node.op_type == "Add": + start_node = node + qkv_nodes_list = [ + # match base attention structure + self.match_parent_path( + start_node, + ["Add", "MatMul", "Reshape", "Transpose", "MatMul"], + [0, None, 0, 0, 0], + ), + self.match_parent_path( + start_node, ["Add", "MatMul", "Reshape", "Transpose", "MatMul"], [1, None, 0, 0, 0] + ), + # match gpt attention no past structure + self.match_parent_path( + start_node, + ["Reshape", "Gemm", "Reshape", "Reshape", "Transpose", "MatMul"], + [None, 0, 0, 0, 0, 0], + output_name_to_node=self.output_name_to_node, + return_indice=[], + ), + # match bart attention structure + self.match_parent_path( + start_node, + ["Add", "MatMul", "Reshape", "Transpose", "Reshape", "MatMul"], + [0, None, 0, 0, 0, 0], + ), + self.match_parent_path( + start_node, + ["Add", "MatMul", "Reshape", "Transpose", "Reshape", "MatMul"], + [1, None, 0, 0, 0, 0], + ), + self.match_parent_path( + start_node, + ["MatMul", "Mul", "MatMul", "Mul", "Div", "Add"], + [None, 0, None, 0, None, 0], + ), + self.match_parent_path( + start_node, + ["MatMul", "Mul", "MatMul", "SimplifiedLayerNormalization", "Add"], + [None, 0, None, 0, 0], + ), + ] + if not start_node: + continue + if not any(qkv_nodes_list): + continue + start_nodes.append(start_node) + return start_nodes + + def find_qkv_in_attention(self, find_all=False): + """Find qkv MatMul in Attention. + + Args: + find_all (bool, optional): find all qkv MatMul. Defaults to False + + Returns: + qkv (list): qkv MatMul list + """ + qkv = [] + for node in self._model.graph.node: + if node.op_type == "Attention": + qkv.append([node.name]) + continue + start_node, qkv_nodes_list = None, None + if node.op_type == "SkipLayerNormalization": + start_node = node + qkv_nodes_list = [ + self.match_parent_path( + start_node, + ["MatMul", "Reshape", "Transpose", "Reshape", "MatMul"], + [None, 0, 0, 0, 0], + ), + self.match_parent_path( + start_node, + ["Add", "MatMul", "Reshape", "Transpose", "MatMul"], + [1, 1, 0, 0, 0], + ), + ] + if node.op_type == "Add": + start_node = node + qkv_nodes_list = [ + # match base attention structure + self.match_parent_path( + start_node, + ["Add", "MatMul", "Reshape", "Transpose", "MatMul"], + [0, None, 0, 0, 0], + ), + self.match_parent_path( + start_node, ["Add", "MatMul", "Reshape", "Transpose", "MatMul"], [1, None, 0, 0, 0] + ), + # match gpt attention no past structure + self.match_parent_path( + start_node, + ["Reshape", "Gemm", "Reshape", "Reshape", "Transpose", "MatMul"], + [None, 0, 0, 0, 0, 0], + output_name_to_node=self.output_name_to_node, + return_indice=[], + ), + # match bart attention structure + self.match_parent_path( + start_node, + ["Add", "MatMul", "Reshape", "Transpose", "Reshape", "MatMul"], + [0, None, 0, 0, 0, 0], + ), + self.match_parent_path( + start_node, + ["Add", "MatMul", "Reshape", "Transpose", "Reshape", "MatMul"], + [1, None, 0, 0, 0, 0], + ), + ] + if not start_node: + continue + if not any(qkv_nodes_list): + continue + qkv_nodes = [qkv for qkv in qkv_nodes_list if qkv is not None][-1] + other_inputs = [] + for input in start_node.input: + if input not in self.output_name_to_node: + continue + if input == qkv_nodes[0].output[0]: + continue + other_inputs.append(input) + if len(other_inputs) != 1: + continue + root_input = other_inputs[0] + input_name_to_nodes = self.input_name_to_nodes + children = input_name_to_nodes[root_input] + children_types = [child.op_type for child in children] + if children_types.count("MatMul") == 3: + qkv.append([child.name for child in children if child.op_type == "MatMul"]) + if not find_all: + break + return qkv + + def find_ffn_matmul(self, attention_index, attention_matmul_list, block_len): + """Find MatMul in FFN. + + Args: + attention_index (list): index of Attention + attention_matmul_list (list): list of Attention and MatMul nodes + block_len (int): block length + + Returns: + list: list of MatMul in FFN + """ + ffn_matmul = [] + for idx in range(len(attention_index)): + if idx != len(attention_index) - 1: + index = attention_index[idx + 1] + if index - 2 >= 0: + ffn_matmul.append([attention_matmul_list[index - 2], attention_matmul_list[index - 1]]) + else: + index = attention_index[idx] + if index + block_len - 1 < len(attention_matmul_list): + ffn_matmul.append( + [attention_matmul_list[index + block_len - 2], attention_matmul_list[index + block_len - 1]] + ) + return ffn_matmul + + def export(self, save_path, conf): + """Export Qlinear to QDQ model.""" + from neural_compressor.config import ONNXQlinear2QDQConfig # noqa: PLC0415 + from neural_compressor.utils.export import onnx_qlinear_to_qdq # noqa: PLC0415 + + if isinstance(conf, ONNXQlinear2QDQConfig): + add_nodes, remove_nodes, inits = onnx_qlinear_to_qdq(self._model, self._input_name_to_nodes) + self.add_nodes(add_nodes) + self.remove_nodes(remove_nodes) + self.add_initializers(inits) + self.update() + self.remove_unused_nodes() + self.topological_sort() + self.save(save_path) + else: + logger.warning("Unsupported config for export, only ONNXQlinear2QDQConfig is supported!") + exit(0) + + def add_tensors_to_outputs(self, tensor_names): + """Add the tensors to the model outputs to gets their values. + + Args: + tensor_names: The names of tensors to be dumped. + """ + added_outputs = [] + for tensor in tensor_names: + if tensor not in self.output(): + added_tensor = onnx.helper.ValueInfoProto() + added_tensor.name = tensor + added_outputs.append(added_tensor) + self._model.graph.output.extend(added_outputs) # pylint: disable=no-member + + def remove_tensors_from_outputs(self, tensor_names): + """Remove the tensors from the model outputs. + + Args: + tensor_names: The names of tensors to be removed. + """ + removed_outputs = [] + for tensor in tensor_names: + if tensor in self.output(): + removed_outputs.append(self._model.graph.output[self.output().index(tensor)]) + for output in removed_outputs: + self._model.graph.output.remove(output) + + def match_first_parent(self, node, parent_op_type, output_name_to_node, exclude=None): + """Find parent node based on constraints on op_type. + + Args: + node (str): current node name. + parent_op_type (str): constraint of parent node op_type. + output_name_to_node (dict): dictionary with output name as key, and node as value. + exclude (list): list of nodes that are excluded (not allowed to match as parent). + + Returns: + parent: The matched parent node. None if not found. + index: The input index of matched parent node. None if not found. + """ + if exclude is None: + exclude = [] + for i, input in enumerate(node.input): + if input in output_name_to_node: + parent = output_name_to_node[input] + if parent.op_type == parent_op_type and parent not in exclude: + return parent, i + return None, None + + def match_parent( + self, + node, + parent_op_type, + input_index=None, + output_name_to_node=None, + exclude=None, + return_indice=None, + ): + """Find parent node based on constraints on op_type and index. + + Args: + node (str): current node name. + parent_op_type (str): constraint of parent node op_type. + input_index (int or None): only check the parent given input index of current node. + output_name_to_node (dict): dictionary with output name as key, and node as value. + exclude (list): list of nodes that are excluded (not allowed to match as parent). + return_indice (list): a list to append the input index when input_index is None. + + Returns: + parent: The matched parent node. + """ + assert node is not None + assert input_index is None or input_index >= 0 + if exclude is None: + exclude = [] + if output_name_to_node is None: + output_name_to_node = self._output_name_to_node + + if input_index is None: + parent, index = self.match_first_parent(node, parent_op_type, output_name_to_node, exclude) + if return_indice is not None: + return_indice.append(index) + return parent + + if input_index >= len(node.input): + return None + + parent = self.get_parent(node, input_index, output_name_to_node) + if parent is not None and parent.op_type == parent_op_type and parent not in exclude: + return parent + + return None + + def match_parent_path( + self, + node, + parent_op_types, + parent_input_index, + output_name_to_node=None, + return_indice=None, + ): + """Find a sequence of input edges based on constraints on parent op_type and index. + + Args: + node (str): current node name. + parent_op_types (str): constraint of parent node op_type of each input edge. + parent_input_index (list): constraint of input index of each input edge. + None means no constraint. + output_name_to_node (dict): dictionary with output name as key, and node as value. + return_indice (list): a list to append the input index when there is + no constraint on input index of an edge. + + Returns: + parents: a list of matched parent node. + """ + assert len(parent_input_index) == len(parent_op_types) + + if output_name_to_node is None: + output_name_to_node = self._output_name_to_node + + current_node = node + matched_parents = [] + for i, op_type in enumerate(parent_op_types): + matched_parent = self.match_parent( + current_node, + op_type, + parent_input_index[i], + output_name_to_node, + exclude=[], + return_indice=return_indice, + ) + if matched_parent is None: + return None + + matched_parents.append(matched_parent) + current_node = matched_parent + + return matched_parents + + def is_smoothquant_model(self): + """Check the model is smooth quantized or not. + + Returns: + bool: the model is smooth quantized or not. + """ + for init in self.model.graph.initializer: # noqa: SIM110 + if "_smooth_scale" in init.name: + return True + return False + + def find_split_nodes(self): + """Find split nodes for layer-wise quantization.""" + split_nodes = self.find_split_node_for_layer_wise_quantization() + return split_nodes + + def split_model_with_node( + self, split_node_name, path_of_model_to_split, shape_infer=True, save_both_split_models=True + ): + """Split model into two parts at a given node. + + Args: + split_node_name (str): name of the node where the model is split at> + path_of_model_to_split (str): path of model to be split. + shape_infer (bool): do shape inference. Default is True. + save_both_split_models (bool): whether to save the two split models. + False means only save the first split model. + True means save both the two split models. + Default id True. + + Returns: + tuple: the first split model, the second split model + """ + # origin model : ... -> node_1 -> split_node -> node_2 -> ... + # split model 1: ... -> node_1 -> split_node + # split model 2: node_2 -> ... + + split_model_part_1 = onnx.ModelProto() + split_model_part_1.CopyFrom(self._model) + split_model_part_1.graph.ClearField("node") + + split_model_part_2 = onnx.ModelProto() + split_model_part_2.CopyFrom(self._model) + split_model_part_2.graph.ClearField("node") + + split_node_output = None + part_idx = 1 + for node in self._model.graph.node: + if part_idx == 1: + split_model_part_1.graph.node.append(node) + elif part_idx == 2: + split_model_part_2.graph.node.append(node) + + if node.name == split_node_name: + split_node_output = node.output + part_idx = 2 + + assert len(split_node_output) == 1, ( + f"Only support split at node with 1 output tensor, while current split node {split_node_name} has {len(split_node_output)} output tensors" + ) + split_tensor_name = split_node_output[0] + + # infer shape of the model to be split + if shape_infer: + try: + from neural_compressor.adaptor.ox_utils.util import infer_shapes # noqa: PLC0415 + + self._model = infer_shapes(self._model, auto_merge=True, base_dir=os.path.dirname(self._model_path)) + except Exception as e: # pragma: no cover + logger.error( + "Shape infer fails for layer-wise quantization. " + "We would recommend checking the graph optimization level of your model " + "and setting it to 'DISABLE_ALL' or 'ENABLE_BASIC', " + "as this may help avoid this error." + ) + raise e + + split_tensor_type, split_tensor_shape = self._get_output_type_shape_by_tensor_name(split_tensor_name) + split_tensor = onnx.helper.make_tensor_value_info(split_tensor_name, split_tensor_type, split_tensor_shape) + + split_model_part_1 = ONNXModel(split_model_part_1, ignore_warning=True) + split_model_part_2 = ONNXModel(split_model_part_2, ignore_warning=True) + + # remove unused input & output + split_model_part_1._remove_unused_input_output() + split_model_part_2._remove_unused_input_output() + + split_model_part_1.model.graph.output.append(split_tensor) + split_model_part_2.model.graph.input.append(split_tensor) + + insert_output_for_model_1 = [] + insert_input_for_model_2 = [] + for output in split_model_part_1.output_name_to_node: + if output in split_model_part_2.input_name_to_nodes: + output_type, output_shape = self._get_output_type_shape_by_tensor_name(output) + output_tensor = onnx.helper.make_tensor_value_info(output, output_type, output_shape) + if output_tensor not in split_model_part_1.model.graph.output: + insert_output_for_model_1.append(output_tensor) + if output_tensor not in split_model_part_2.model.graph.input: + insert_input_for_model_2.append(output_tensor) + + # insert model 1 output + for output in insert_output_for_model_1: + split_model_part_1.model.graph.output.append(output) + + # insert model 2 input + for input in insert_input_for_model_2: + split_model_part_2.model.graph.input.append(input) + + # remove unused init + split_model_part_1.remove_unused_init() + split_model_part_2.remove_unused_init() + + split_model_part_1.update() + split_model_part_2.update() + + dir_of_model_to_split = os.path.dirname(path_of_model_to_split) + + split_model_part_1.load_model_initializer_by_tensor(dir_of_model_to_split) + split_model_part_1_path = os.path.join(dir_of_model_to_split, "split_model_part_1.onnx") + split_model_part_1.model_path = split_model_part_1_path + split_model_part_1._save_split_model(split_model_part_1_path) + split_model_part_1.check_is_large_model() + logger.debug(f"save split model part 1 to {split_model_part_1_path} for layer wise quantization") + + if save_both_split_models: + split_model_part_2.load_model_initializer_by_tensor(dir_of_model_to_split) + split_model_part_2_path = os.path.join(dir_of_model_to_split, "split_model_part_2.onnx") + split_model_part_2.model_path = split_model_part_2_path + split_model_part_2._save_split_model(split_model_part_2_path) + split_model_part_2.check_is_large_model() + logger.debug(f"save split model part 2 to {split_model_part_2_path} for layer wise quantization") + return split_model_part_1, split_model_part_2 + else: + return split_model_part_1, split_model_part_2 + + def _save_split_model(self, save_path): + """Save split model as external data for layer wise quantization. + + Args: + save_path (str): the path to save the split model + """ + if os.path.exists(save_path + "_data"): + os.remove(save_path + "_data") + onnx.save_model( + self._model, + save_path, + save_as_external_data=True, + all_tensors_to_one_file=True, + location=save_path.split("/")[-1] + "_data", + size_threshold=1024, + convert_attribute=False, + ) + + def _get_output_type_shape_by_tensor_name(self, tensor_name): + """Get output type and shape with a tensor name. + + Args: + tensor_name (str): name of a tensor + + Returns: + tuple: output type and shape + """ + elem_type = onnx.TensorProto.FLOAT + shape = None + for output in self._model.graph.value_info: + if output.name == tensor_name: + elem_type = output.type.tensor_type.elem_type + shape = [ + dim.dim_value if dim.HasField("dim_value") else -1 for dim in output.type.tensor_type.shape.dim + ] + break + return elem_type, shape + + def _remove_unused_input_output(self): + """Remove unused input & output for split model.""" + remove_outputs = [] + remove_inputs = [] + for output in self._model.graph.output: + if output.name not in self.output_name_to_node: + remove_outputs.append(output) + + for input in self._model.graph.input: + if input.name not in self.input_name_to_nodes: + remove_inputs.append(input) + + for output in remove_outputs: + self._model.graph.output.remove(output) + for input in remove_inputs: + self._model.graph.input.remove(input) + + def remove_unused_init(self): + """Remove unused init.""" + remov_inits = [] + for init in self._model.graph.initializer: + if init.name not in self.input_name_to_nodes: + remov_inits.append(init) + self.remove_initializers(remov_inits) + + def load_model_initializer_by_tensor(self, data_path=None): + """Load model initializer by tensor. + + Args: + data_path (str, optional): the directory of saved initializer. Defaults to None. + """ + if data_path is None: + data_path = os.path.dirname(self._model_path) + for init in self._model.graph.initializer: + if init.HasField("data_location") and init.data_location == onnx.TensorProto.EXTERNAL: + onnx.external_data_helper.load_external_data_for_tensor(init, data_path) + + def write_external_data_to_new_location(self, external_data_location="external.data", overwrite=False): + """Write external data of merged quantized model to new location to save memory. + + Args: + external_data_location (str, optional): external data location of merged quantized model. + Defaults to "external.data". + overwrite (bool, optional): if True, remove existed externa data. Defaults to False. + """ + if overwrite and os.path.exists(os.path.join(os.path.dirname(self._model_path), external_data_location)): + os.remove(os.path.join(os.path.dirname(self._model_path), external_data_location)) + self.load_model_initializer_by_tensor() + onnx.external_data_helper.convert_model_to_external_data(self._model, location=external_data_location) + # TODO : if init is already saved, skip write it + onnx.external_data_helper.write_external_data_tensors(self._model, filepath=os.path.dirname(self._model_path)) + + def merge_split_models(self, to_merge_model): + """Merge two split model into final model.""" + to_merge_model.write_external_data_to_new_location() + self.add_nodes(list(to_merge_model.nodes())) + self.add_initializers(list(to_merge_model.initializer())) + self.update() + + # add new output + for output in to_merge_model.graph().output: + if output.name not in self.output(): + self._model.graph.output.append(output) + + # remove unused output + remove_output = [] + for output in self._model.graph.output: + if output.name in to_merge_model.input(): + remove_output.append(output) + for output in remove_output: + self._model.graph.output.remove(output) + + # add new input + for input in to_merge_model.graph().input: + if ( + input.name not in self.input() + and input.name not in self.output() + and input.name not in self.output_name_to_node + ): + self._model.graph.input.append(input) + + def re_org_output(self, origin_output): + """Re-org output of merged model for layer-wise quantization.""" + outputs = {} + tmp_remove = [] + for output in self._model.graph.output: + outputs[output.name] = output + tmp_remove.append(output) + + for output in tmp_remove: + self._model.graph.output.remove(output) + + for out_name in origin_output: + self._model.graph.output.append(outputs[out_name]) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/neural_compressor/util.py b/python/user_packages/Python313/site-packages/onnxruntime/quantization/neural_compressor/util.py new file mode 100644 index 0000000000000000000000000000000000000000..341e13dc067c95a2eea667b9ea2b874da551e28a --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/quantization/neural_compressor/util.py @@ -0,0 +1,80 @@ +# +# The implementation of this file is based on: +# https://github.com/intel/neural-compressor/tree/master/neural_compressor +# +# Copyright (c) 2023 Intel Corporation +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Helper classes or functions for onnxrt adaptor.""" + +import importlib +import logging + +import numpy as np + +logger = logging.getLogger("neural_compressor") + + +MAXIMUM_PROTOBUF = 2147483648 + + +def simple_progress_bar(total, i): + """Progress bar for cases where tqdm can't be used.""" + progress = i / total + bar_length = 20 + bar = "#" * int(bar_length * progress) + spaces = " " * (bar_length - len(bar)) + percentage = progress * 100 + print(f"\rProgress: [{bar}{spaces}] {percentage:.2f}%", end="") + + +def find_by_name(name, item_list): + """Helper function to find item by name in a list.""" + items = [] + for item in item_list: + assert hasattr(item, "name"), f"{item} should have a 'name' attribute defined" # pragma: no cover + if item.name == name: + items.append(item) + if len(items) > 0: + return items[0] + else: + return None + + +def to_numpy(data): + """Convert to numpy ndarrays.""" + import torch # noqa: PLC0415 + + if not isinstance(data, np.ndarray): + if not importlib.util.find_spec("torch"): + logger.error( + "Please install torch to enable subsequent data type check and conversion, " + "or reorganize your data format to numpy array." + ) + exit(0) + if isinstance(data, torch.Tensor): + if data.dtype is torch.bfloat16: # pragma: no cover + return data.detach().cpu().to(torch.float32).numpy() + if data.dtype is torch.chalf: # pragma: no cover + return data.detach().cpu().to(torch.cfloat).numpy() + return data.detach().cpu().numpy() + else: + try: + return np.array(data) + except Exception: + assert False, ( # noqa: B011 + f"The input data for onnx model is {type(data)}, which is not supported to convert to numpy ndarrays." + ) + else: + return data diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/neural_compressor/weight_only.py b/python/user_packages/Python313/site-packages/onnxruntime/quantization/neural_compressor/weight_only.py new file mode 100644 index 0000000000000000000000000000000000000000..080d77ad0871a70a5522e69d703a29210e50866b --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/quantization/neural_compressor/weight_only.py @@ -0,0 +1,932 @@ +# +# The implementation of this file is based on: +# https://github.com/intel/neural-compressor/tree/master/neural_compressor +# +# Copyright (c) 2023 Intel Corporation +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Modifications: +# Add k-quant quantization method. +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. + +"""WeightOnly for onnxrt adaptor.""" + +import copy +import logging +import os +import sys + +import numpy as np +import onnx +from onnx import numpy_helper +from onnx.helper import np_dtype_to_tensor_dtype + +import onnxruntime as ort + +from .onnx_model import ONNXModel +from .util import simple_progress_bar + +logger = logging.getLogger("neural_compressor") + + +def make_matmul_weight_only_node( + node, + weight_shape, + num_bits, + group_size, + k_blocks, + q_weight, + scale, + zero_point, + accuracy_level=0, +): # pragma: no cover + """Build MatMulNBits node. + + Args: + node: original matmul node + weight_shape: original weight shape + num_bits (int): num_bits + group_size (int): how many elements share one scale/zp + k_blocks (int): block number + q_weight (array): quantized weight + scale (array): scale + zero_point (array): zero point + accuracy_level (int): accuracy level. Support 0 (unset), 1(fp32), 2(fp16), 3(bf16), or 4(int8). + + Returns: + matmul_weight_only_node: MatMulNBits node + new_inits: initializers of the new node + """ + blob_size = group_size * num_bits // 8 + packed = np.zeros((q_weight.shape[0], blob_size), dtype="uint8") + q_weight_name = node.input[1] + f"_Q{num_bits!s}G{group_size!s}" + input_names = [node.input[0], q_weight_name] + new_inits = [] + kwargs = {} + + op_type = "MatMulNBits" + + # pack quantized weight + if num_bits == 4: + q_weight_pairs = q_weight[:, ::2] | q_weight[:, 1::2] << 4 + packed[:, :] = q_weight_pairs[:, :blob_size] + elif num_bits == 8: + packed = q_weight + else: + logger.error(f"MatMulNBits does not have kernel support for num_bits = {num_bits}.") + + packed = np.reshape(packed, (-1, k_blocks, blob_size)) + + # build scale tensor + scale = np.reshape(scale, (-1, k_blocks)) + assert scale.dtype == np.float32 or scale.dtype == np.float16 + scale_tensor = onnx.helper.make_tensor( + name=node.input[1] + "_scale", + data_type=np_dtype_to_tensor_dtype(scale.dtype), + dims=scale.shape, + vals=scale.tobytes(), + raw=True, + ) + input_names.append(scale_tensor.name) + new_inits.append(scale_tensor) + + # build zero_point tensor + if zero_point is not None: + if num_bits == 8: + packed_zp = zero_point.astype("uint8") + elif num_bits == 4: + # For 4-bit case, the default zeros is 0x8. So it is 0x88 = 136 if we fill lower/higher 4 bits with 0x8. + packed_zp = np.full((zero_point.shape[0] + 1) // 2, 136, dtype="uint8") + # create an index array + idx = np.arange(zero_point.shape[0] // k_blocks * k_blocks).reshape(-1) + # separate odd and even indices + even_idx = idx[::2] + odd_idx = idx[1::2] + # vectorized operation for even and odd indices + packed_zp[even_idx // 2] = (packed_zp[even_idx // 2] & 0xF0) | zero_point[even_idx].ravel() + packed_zp[odd_idx // 2] = (packed_zp[odd_idx // 2] & 0x0F) | (zero_point[odd_idx].ravel() << 4) + else: + raise ValueError(f"MatMulNBits does not have kernel support for num_bits = {num_bits}.") + + packed_zp = np.reshape(packed_zp, (weight_shape[1], -1)) + zp_tensor = onnx.helper.make_tensor( + name=node.input[1] + "_zp", data_type=2, dims=packed_zp.shape, vals=packed_zp.tobytes(), raw=True + ) + input_names.append(zp_tensor.name) + new_inits.append(zp_tensor) + + # set kwargs + kwargs["K"] = weight_shape[0] + kwargs["N"] = weight_shape[1] + kwargs["bits"] = num_bits + kwargs["block_size"] = group_size + if accuracy_level > 0: + # require onnxruntime > 1.16.3 + kwargs["accuracy_level"] = accuracy_level + + q_weight_tensor = onnx.helper.make_tensor( + name=q_weight_name, + data_type=2, + dims=packed.shape, + vals=packed.tobytes(), + raw=True, + ) + new_inits.append(q_weight_tensor) + + matmul_weight_only_node = onnx.helper.make_node( + op_type, + inputs=input_names, + outputs=node.output, + name=node.name + "_Q" + str(num_bits) if node.name else "_Q" + str(num_bits), + domain="com.microsoft", + **kwargs, + ) + return matmul_weight_only_node, new_inits + + +def quant_tensor(data, num_bits=4, group_size=32, scheme="asym", dtype="int", ratio=1.0): + """Quantize tensor per group. + + Args: + data : input weight + num_bits (int, optional): num_bits. Defaults to 4. + group_size (int, optional): how many elements share one scale/zp. Defaults to 4. + scheme (str, optional): quantization scheme. Defaults to "asym". + dtype (str, optional): data type. Defaults to "int". + ratio (float, optional): percentile of clip. Defaults to 1.0. + + Returns: + output: quantized weight + scale: scale + zero_point: zero point + """ + data = np.reshape(data, (-1, group_size)) + if scheme == "asym" or dtype == "uint": + maxq = 2**num_bits - 1 + minq = 0 + elif scheme == "sym": + maxq = 2 ** (num_bits - 1) - 1 if num_bits != 1 else 0 + minq = -(2 ** (num_bits - 1)) if num_bits != 1 else -1 + + rmin = np.min(data, axis=1, keepdims=True) * ratio + rmax = np.max(data, axis=1, keepdims=True) * ratio + if scheme == "sym": + max_range = np.maximum(np.abs(rmin), np.abs(rmax)) + scale = np.ones(rmax.shape) + mask = max_range > 0 + scale[mask] = (max_range[mask] * 2.0).astype(np.float64) / (maxq - minq) + zero_point = ( + np.zeros(scale.shape) if dtype == "int" else np.ones(rmax.shape, dtype="uint8") * (1 << (num_bits - 1)) + ) + else: + scale = np.ones(rmax.shape) + scale[rmin != rmax] = np.array( + [float(i) / (maxq - minq) for i in (rmax - rmin)[rmin != rmax].flatten().tolist()] + ) + zero_point = ( + ((np.zeros(scale.shape) - rmin) / scale).round() + if dtype == "int" + else np.maximum(0, np.minimum(maxq, ((np.zeros(scale.shape) - rmin) / scale).round())).astype("uint8") + ) + + q_weight = np.empty_like(data, dtype=scale.dtype) + np.divide(data, scale, out=q_weight) + np.add(q_weight, zero_point, out=q_weight) + np.round(q_weight, out=q_weight) + np.clip(q_weight, minq, maxq, out=q_weight) + + return q_weight, scale, zero_point + + +def quant_tensor_k_quant_cpu(data, num_bits=4, group_size=32): + """Quantize tensor per group based on k quant. + + Ref: https://github.com/ggml-org/llama.cpp/blob/64eda5deb9859e87a020e56bab5d2f9ca956f1de/ggml/src/ggml-quants.c + + Args: + data : input weight + num_bits (int, optional): num_bits. Defaults to 4. + group_size (int, optional): how many elements share one scale/zp. Defaults to 32. + + Returns: + output: quantized weight + scale: scale + zero_point: zero point + """ + data = np.reshape(data, (-1, group_size)).astype(np.float32) # nb = data.shape[0], (nb, group_size) + maxq = 2**num_bits - 1 + minq = 0 + sum_x2 = np.sum(data**2, axis=1, keepdims=True) # (nb, 1) + av_x = np.sqrt(sum_x2 / group_size) # (nb, 1) + weights = np.add(av_x, np.abs(data)) # (nb, group_size) + rmin = np.min(data, axis=1, keepdims=True) # (nb, 1) + rmax = np.max(data, axis=1, keepdims=True) # (nb, 1) + sum_w = np.sum(weights, axis=1, keepdims=True) # (nb, 1) + sum_x = np.sum(weights * data, axis=1, keepdims=True) # (nb, group_size) + iscale = np.ones(rmax.shape, dtype=data.dtype) # (nb, 1) + mask = rmin != rmax + iscale[mask] = (maxq - minq) / (rmax[mask] - rmin[mask]) + scale = 1 / iscale + quant_data = np.clip(np.round(iscale * (data - rmin)), minq, maxq) # (nb, group_size) + diff = scale * quant_data + rmin - data # (nb, group_size) + best_mad = np.sum(weights * diff**2, axis=1, keepdims=True) # (nb, 1) + nstep = 20 + rdelta = 0.1 + # nstep * rdelta = -2 * rrmin, maxq - minq = 2**num_bits - 1 + rrmin = -1 + for is_ in range(nstep): + iscale_new = np.ones(rmax.shape, dtype=data.dtype) # (nb, 1) + factor = np.array([rrmin + rdelta * is_ + maxq - minq]).astype(data.dtype)[0] + mask = rmin != rmax + iscale_new[mask] = factor / (rmax[mask] - rmin[mask]) + quant_data_new = np.clip(np.round(iscale_new * (data - rmin)), minq, maxq) # (nb, group_size) + mul_weights_quant_data_new = weights * quant_data_new + sum_l = np.sum(mul_weights_quant_data_new, axis=1, keepdims=True) # (nb, 1) + sum_l2 = np.sum(mul_weights_quant_data_new * quant_data_new, axis=1, keepdims=True) # (nb, 1) + sum_xl = np.sum(mul_weights_quant_data_new * data, axis=1, keepdims=True) # (nb, 1) + D = np.subtract(sum_w * sum_l2, sum_l**2) # noqa: N806 + + this_scale = (sum_w * sum_xl - sum_x * sum_l) / D # (nb, 1) + this_min = (sum_l2 * sum_x - sum_l * sum_xl) / D # (nb, 1) + + diff = this_scale * quant_data_new + this_min - data # (nb, group_size) + mad = np.sum(weights * diff**2, axis=1, keepdims=True) # (nb, 1) + + mad_1 = np.array(mad) + best_mad_1 = np.array(best_mad) + idx_to_replace = np.where(mad_1 < best_mad_1)[0] + quant_data[idx_to_replace, :] = quant_data_new[idx_to_replace, :] + best_mad[idx_to_replace] = mad[idx_to_replace] + scale[idx_to_replace] = this_scale[idx_to_replace] + rmin[idx_to_replace] = this_min[idx_to_replace] + + zero_point = np.clip(((-rmin) / scale).round(), 0, maxq).astype("uint8") + scale = scale.astype(np.float64) + q_weight = np.empty_like(data, dtype=scale.dtype) + np.divide(data, scale, out=q_weight) + np.add(q_weight, zero_point, out=q_weight) + np.round(q_weight, out=q_weight) + np.clip(q_weight, minq, maxq, out=q_weight) + + return q_weight, scale, zero_point + + +def quant_tensor_k_quant_cuda(data, num_bits=4, group_size=32): + """Quantize tensor per group based on k quant. + + Ref: https://github.com/ggml-org/llama.cpp/blob/64eda5deb9859e87a020e56bab5d2f9ca956f1de/ggml/src/ggml-quants.c + + Args: + data : input weight + num_bits (int, optional): num_bits. Defaults to 4. + group_size (int, optional): how many elements share one scale/zp. Defaults to 4. + + Returns: + output: quantized weight + scale: scale + zero_point: zero point + """ + try: + import cupy as cp # noqa: PLC0415 + import torch # noqa: PLC0415 + + if torch.cuda.is_available(): + data = cp.asarray(data) + data = data.reshape((-1, group_size)).astype(cp.float32) # nb = data.shape[0], (nb, group_size) + maxq = 2**num_bits - 1 + minq = 0 + sum_x2 = cp.sum(data**2, axis=1, keepdims=True) # (nb, 1) + av_x = cp.sqrt(sum_x2 / group_size) # (nb, 1) + weights = cp.add(av_x, cp.abs(data)) # (nb, group_size) + rmin = cp.min(data, axis=1, keepdims=True) # (nb, 1) + rmax = cp.max(data, axis=1, keepdims=True) # (nb, 1) + sum_w = cp.sum(weights, axis=1, keepdims=True) # (nb, 1) + sum_x = cp.sum(weights * data, axis=1, keepdims=True) # (nb, group_size) + iscale = cp.ones(rmax.shape, dtype=data.dtype) # (nb, 1) + mask = rmin != rmax + iscale[mask] = (maxq - minq) / (rmax[mask] - rmin[mask]) + scale = 1 / iscale + quant_data = cp.clip(cp.round(iscale * (data - rmin)), minq, maxq) # (nb, group_size) + diff = scale * quant_data + rmin - data # (nb, group_size) + best_mad = cp.sum(weights * diff**2, axis=1, keepdims=True) # (nb, 1) + nstep = 20 + rdelta = 0.1 + rrmin = -1 + for is_ in range(nstep): + iscale_new = cp.ones(rmax.shape, dtype=data.dtype) # (nb, 1) + factor = cp.array([rrmin + rdelta * is_ + maxq - minq]).astype(data.dtype)[0] + mask = rmin != rmax + iscale_new[mask] = factor / (rmax[mask] - rmin[mask]) + quant_data_new = cp.clip(cp.round(iscale_new * (data - rmin)), minq, maxq) # (nb, group_size) + mul_weights_quant_data_new = weights * quant_data_new + sum_l = cp.sum(mul_weights_quant_data_new, axis=1, keepdims=True) # (nb, 1) + sum_l2 = cp.sum(mul_weights_quant_data_new * quant_data_new, axis=1, keepdims=True) # (nb, 1) + sum_xl = cp.sum(mul_weights_quant_data_new * data, axis=1, keepdims=True) # (nb, 1) + D = cp.subtract(sum_w * sum_l2, sum_l**2) # noqa: N806 + + this_scale = (sum_w * sum_xl - sum_x * sum_l) / D # (nb, 1) + this_min = (sum_l2 * sum_x - sum_l * sum_xl) / D # (nb, 1) + + diff = this_scale * quant_data_new + this_min - data # (nb, group_size) + mad = cp.sum(weights * diff**2, axis=1, keepdims=True) # (nb, 1) + + mad_1 = cp.array(mad) + best_mad_1 = cp.array(best_mad) + idx_to_replace = cp.where(mad_1 < best_mad_1)[0] + quant_data[idx_to_replace, :] = quant_data_new[idx_to_replace, :] + best_mad[idx_to_replace] = mad[idx_to_replace] + scale[idx_to_replace] = this_scale[idx_to_replace] + rmin[idx_to_replace] = this_min[idx_to_replace] + + zero_point = cp.clip(((-rmin) / scale).round(), 0, maxq).astype("uint8") + scale = scale.astype(cp.float64) + q_weight = cp.empty_like(data, dtype=scale.dtype) + cp.divide(data, scale, out=q_weight) + cp.add(q_weight, zero_point, out=q_weight) + cp.round(q_weight, out=q_weight) + cp.clip(q_weight, minq, maxq, out=q_weight) + + return q_weight.get(), scale.get(), zero_point.get() + else: + logger.warning( + "Try to use k-quant quantization on CUDA. However, CUDA is not available." + "Fall back to k-quant quantization on CPU." + ) + return quant_tensor_k_quant_cpu(data, num_bits, group_size) + except ImportError: + logger.info( + "Now we are using k-quant quantization on cpu, which is time consuming." + "Please consider install cupy to speed up on CUDA. See https://cupy.dev/" + "Please also install torch to check CUDA availability." + ) + return quant_tensor_k_quant_cpu(data, num_bits, group_size) + + +def qdq_tensor(data, num_bits=4, group_size=32, scheme="asym", dtype="int", ratio=1.0): + """Quant dequant tensor per group. + + Args: + data : input weight + num_bits (int, optional): num_bits. Defaults to 4. + group_size (int, optional): how many elements share one scale/zp. Defaults to 4. + scheme (str, optional): quantization scheme. Defaults to "asym". + dtype (str, optional): data type. Defaults to "int". + ratio (float, optional): percentile of clip. Defaults to 1.0. + + Returns: + output: quant-dequant weight + """ + org_shape = data.shape + weight, scale, zp = quant_tensor(data, num_bits, group_size, scheme, dtype, ratio) + return np.reshape(scale * (weight - zp), org_shape) + + +def pad_tensor(weight, group_size, k_blocks): + """Pad tensor rowi so that it can be is divisible by group_size. + + Args: + weight (array): weight + group_size (int): how many elements share one scale/zp + k_blocks (int): the number of block + + Returns: + weight: paded weight + """ + if group_size == -1: + return weight + + org_w_shape = weight.shape + padded_rows = k_blocks * group_size + pad_len = padded_rows - org_w_shape[0] + + if pad_len > 0: + weight = np.pad(weight, ((0, pad_len), (0, 0)), "constant") + + return weight + + +def rtn_quantize( + model, + weight_config={}, # noqa: B006 + num_bits=4, + group_size=32, + scheme="asym", + ratios={}, # noqa: B006 + accuracy_level=0, + providers=["CPUExecutionProvider"], # noqa: B006 + algorithm="k_quant", +): + """Quant the model with round to nearst method. + + Args: + model (ModelProto or ONNXModel): onnx model + weight_config (dict): quantization config + For example, + weight_config = { + 'fc2': + { + 'bits': 4, + 'group_size': 32, + 'scheme': 'sym', + 'algorithm': 'RTN' + } + } + num_bits (int, optional): num_bits. Default is 4. + group_size (int, optional): how many elements share one scale/zp. Default is 32. + scheme (str, optional): sym or asym. Defaults to "asym". + ratios (dict, optional): percentile of clip. Defaults to {}. + accuracy_level (int): accuracy level. Support 0 (unset),1(fp32), 2(fp16), 3(bf16), or 4(int8). + providers (list): providers to use + + Returns: + model: fake quantized ONNXModel + """ + model = ONNXModel(model) + base_dir = os.path.dirname(model.model_path) if model.model_path is not None else "" + new_nodes = [] + remove_nodes = [] + total_num = len([i for i in model.nodes() if i.op_type in ["MatMul"]]) + curr_id = 0 + for node in model.nodes(): + if node.op_type in ["MatMul"]: + curr_id += 1 + simple_progress_bar(total_num, curr_id) + if ( + node.op_type in ["MatMul"] + and model.get_initializer(node.input[1]) is not None + and weight_config.get(node.name, {}) != "fp32" + ): + weight_tensor = model.get_initializer(node.input[1]) + weight = numpy_helper.to_array(weight_tensor, base_dir=base_dir).copy() + if len(weight.shape) != 2: + continue + + dtype = weight.dtype + + if node.name in weight_config: + num_bits = weight_config[node.name]["bits"] + group_size = weight_config[node.name]["group_size"] + scheme = weight_config[node.name]["scheme"] + + org_w_shape = weight.shape # ic, oc + group_size = group_size if group_size != -1 else org_w_shape[0] + + k_blocks = (org_w_shape[0] - 1) // group_size + 1 + init_share_num = model.get_initializer_share_num(node.input[1]) + + weight = pad_tensor(weight, group_size, k_blocks) + + satisfy_MatMulNBits_condition = num_bits == 4 or num_bits == 8 # noqa: N806 + + if satisfy_MatMulNBits_condition: # pragma: no cover + if algorithm == "k_quant": + q_weight, scale, zp = quant_tensor_k_quant_cuda(weight.T, num_bits, group_size) + else: + q_weight, scale, zp = quant_tensor( + weight.T, num_bits, group_size, scheme, "uint", ratios.get(node.input[1], 1) + ) + + q_matmul_node, new_inits = make_matmul_weight_only_node( + node=node, + weight_shape=org_w_shape, + num_bits=num_bits, + group_size=group_size, + k_blocks=k_blocks, + q_weight=q_weight.astype("uint8"), + scale=scale.astype(dtype), + zero_point=zp if scheme == "asym" or algorithm == "k_quant" else None, + accuracy_level=accuracy_level, + ) + + model.add_initializers(new_inits) + remove_nodes.append(node) + new_nodes.append(q_matmul_node) + else: + q_weight = qdq_tensor(weight.T, num_bits, group_size, scheme, "int", ratios.get(node.input[1], 1)) + q_weight = np.reshape(q_weight, (org_w_shape[1], -1)) + q_weight = np.transpose(q_weight) + q_weight = q_weight[: org_w_shape[0], :].astype(dtype) + q_weight_tensor = onnx.helper.make_tensor( + name=node.input[1] + f"_Q{num_bits!s}G{group_size!s}", + data_type=np_dtype_to_tensor_dtype(dtype), + dims=weight.shape, + vals=q_weight.tobytes(), + raw=True, + ) + model.add_initializer(q_weight_tensor) + node.input[1] = q_weight_tensor.name + if init_share_num == 1: + model.remove_initializer(weight_tensor) + + model.add_nodes(new_nodes) + model.remove_nodes(remove_nodes) + model.topological_sort() + return model + + +def get_weight_scale(weight, group_size): + """Get the scale of weight.""" + org_shape = weight.shape + weight = np.reshape(weight, (-1, group_size)) if group_size != -1 else weight + scale = np.mean(np.reshape(np.abs(weight) / np.max(np.abs(weight), axis=1, keepdims=True), org_shape), axis=0) + return scale + + +def prepare_inputs(model, n_samples, dataloader, providers): + """Prepare inputs for weight only quantization. + + Args: + model (ModelProto or ONNXModel): onnx model + n_samples (int, optional): calibration sample number. -1 means all samples. + dataloader (object): dataloader for calibration. + providers (list): providers to use + + Returns: + inputs: prepared inputs. + so: session options + """ + from importlib.util import find_spec # noqa: PLC0415 + + from .util import to_numpy # noqa: PLC0415 + + so = ort.SessionOptions() + if sys.version_info < (3, 11) and find_spec("onnxruntime_extensions"): # pragma: no cover + from onnxruntime_extensions import get_library_path # noqa: PLC0415 + + so.register_custom_ops_library(get_library_path()) + if model.is_large_model: + onnx.save_model( + model.model, + model.model_path + "_augment.onnx", + save_as_external_data=True, + all_tensors_to_one_file=True, + convert_attribute=False, + ) + + session = ( + ort.InferenceSession(model.model.SerializeToString(), so, providers=providers) + if not model.is_large_model + else ort.InferenceSession(model.model_path + "_augment.onnx", so, providers=providers) + ) + inputs_names = [i.name for i in session.get_inputs()] + del session + + inputs = [] + for i, data in enumerate(dataloader): + if n_samples != -1 and ((i + 1) * dataloader.batch_size) > n_samples: + break + if len(inputs_names) != 1 or isinstance(data[0], dict): + assert len(data[0]) == len(inputs_names), ( + f"Input number mismatch, require {len(inputs_names)} but get {len(data[0])}" + ) + + if isinstance(data[0], dict): + inputs.append(dict([(name, to_numpy(inp_data)) for name, inp_data in data[0].items()])) # noqa: C404 + elif isinstance(data[0], np.ndarray): # pragma: no cover + inputs.append(dict([(name, inp) for name, inp in zip(inputs_names, [data[0]], strict=False)])) # noqa: C404 + else: # pragma: no cover + inputs.append(dict([(name, to_numpy(inp)) for name, inp in zip(inputs_names, data[0], strict=False)])) # noqa: C404 + return inputs, so + + +def gptq( + W, + H, + num_bits=4, + group_size=32, + scheme="asym", + blocksize=128, + percdamp=0.01, + actorder=False, + mse=False, + perchannel=True, +): + """Quant the weight with GPTQ method. + + Args: + W (array): weight. + H (array): Hessian matrix. + num_bits (int, optional): num_bits. Default is 4. + group_size (int, optional): how many elements share one scale/zp. Default is 32. + scheme (str, optional): sym or asym. Defaults to "asym". + blocksize (int, optional): blocksize to quantize weight. + percdamp (float, optional): percent of the average Hessian diagonal to use for dampening. + actorder (bool, optional): whether rearrange Hessian matrix considering the diag's value. + mse (bool, optional): whether get scale and zero point with mse error. + perchannel (bool, optional): whether quantize weight per-channel. + + Returns: + Q: fake quantized weight + """ + maxq = 2**num_bits - 1 + grid = 100 + maxshrink = 0.8 + norm = 2.4 + + def find_params(weight): + org_shape = weight.shape + # find zp, scale + if not perchannel: + weight = np.expand_dims(weight.flatten(), axis=1) + tmp = np.zeros(weight.shape[1]) + xmin = np.minimum(np.min(weight, axis=0), tmp) + xmax = np.maximum(np.max(weight, axis=0), tmp) + if scheme == "sym": + xmax = np.maximum(np.abs(xmin), xmax) + tmp = xmin < 0 + if np.any(tmp): + xmin[tmp] = -xmax[tmp] + tmp = (xmin == 0) & (xmax == 0) + xmin[tmp] = -1 + xmax[tmp] = +1 + + scale = (xmax - xmin) / maxq + if scheme == "sym": + zero = np.ones(scale.shape) * (maxq + 1) / 2 + else: + zero = np.round(-xmin / scale) + if mse: + best = np.ones([weight.shape[1]]) * float("inf") + for i in range(int(maxshrink * grid)): + p = 1 - i / grid + xmin1 = p * xmin + xmax1 = p * xmax + scale1 = (xmax1 - xmin1) / maxq + zero1 = np.round(-xmin1 / scale1) if scheme != "sym" else zero + q = np.clip(np.round(weight / scale1) + zero1, 0, maxq) + q -= weight + q = np.power(np.abs(q), norm) + err = np.sum(q, 0) + tmp = err < best + if np.any(tmp): + best[tmp] = err[tmp] + scale[tmp] = scale1[tmp] + zero[tmp] = zero1[tmp] + if not perchannel: + tmp = org_shape[1] + scale = np.repeat(scale, tmp) + zero = np.repeat(zero, tmp) + shape = [-1] + [1] * (len(org_shape) - 1) + scale = np.reshape(scale, shape) + zero = np.reshape(zero, shape) + return scale, zero + + shape = W.shape + scale, zp = find_params(W) + dead = np.diag(H) == 0 + H[dead, dead] = 1 + W[dead, :] = 0 # such channel makes no contribution to quantization computation + + # rearrange considering the diag's value + if actorder: + perm = np.argsort(np.diag(H))[::-1] + W = W[perm, :] # noqa: N806 + H = H[perm, :][:, perm] # noqa: N806 + Losses = np.zeros_like(W) # noqa: N806 + Q = np.zeros_like(W) # noqa: N806 + damp = percdamp * np.mean(np.diag(H)) + diag = np.arange(shape[0]) + H[diag, diag] += damp # add a average value of + H = np.linalg.cholesky(np.linalg.inv(H)).T # noqa: N806 + Hinv = H # noqa: N806 + for i1 in range(0, shape[0], blocksize): + i2 = min(i1 + blocksize, shape[0]) + count = i2 - i1 + + W1 = copy.deepcopy(W[i1:i2, :]) # noqa: N806 + Q1 = np.zeros_like(W1) # noqa: N806 + Err1 = np.zeros_like(W1) # noqa: N806 + Losses1 = np.zeros_like(W1) # noqa: N806 + Hinv1 = Hinv[i1:i2, i1:i2] # noqa: N806 + + for i in range(count): # within a block, channel wise + w = W1[i, :] + d = Hinv1[i, i] + + if group_size != -1: + if (i1 + i) % group_size == 0: + scale, zp = find_params(W[(i1 + i) : (i1 + i + group_size), :]) + + q = (scale * (np.clip(np.round(w[:, np.newaxis] / scale) + zp, 0, maxq) - zp)).flatten() + Q1[i, :] = q + Losses1[i, :] = (w - q) ** 2 / d**2 + + err1 = (w - q) / d + W1[i:, :] -= np.matmul(np.expand_dims(Hinv1[i:, i], axis=1), np.expand_dims(err1, axis=0)) + Err1[i, :] = err1 + + Q[i1:i2, :] = Q1 + Losses[i1:i2, :] = Losses1 / 2 + + W[i2:, :] -= np.matmul(Hinv[i2:, i1:i2], Err1) + + if actorder: + invperm = np.argsort(perm) + Q = Q[invperm, :] # noqa: N806 + + Q = np.reshape(Q, W.shape) # noqa: N806 + del W + return Q + + +def gptq_quantize( + model, + dataloader, + weight_config={}, # noqa: B006 + num_bits=4, + group_size=32, + scheme="asym", + n_samples=128, + percdamp=0.01, + blocksize=128, + actorder=False, + mse=False, + perchannel=True, + accuracy_level=0, + providers=["CPUExecutionProvider"], # noqa: B006 +): + """Quant the model with GPTQ method. + + Args: + model (ModelProto or ONNXModel): onnx model + dataloader (object): dataloader for calibration. + weight_config (dict): quantization config + For example, + weight_config = { + 'fc2': + { + 'bits': 4, + 'group_size': 32, + 'scheme': 'sym', + 'algorithm': 'GPTQ' + } + } + num_bits (int, optional): num_bits. Default is 4. + group_size (int, optional): how many elements share one scale/zp. Default is 32. + scheme (str, optional): sym or asym. Defaults to "asym". + n_samples (int, optional): calibration sample number. + percdamp (float, optional): percent of the average Hessian diagonal to use for dampening. + blocksize (int, optional): blocksize to quantize weight. + actorder (bool, optional): whether rearrange Hessian matrix considering the diag's value. + mse (bool, optional): whether get scale and zero point with mse error. + perchannel (bool, optional): whether quantize weight per-channel. + accuracy_level (int): accuracy level. Support 0 (unset), 1(fp32), 2(fp16), 3(bf16), or 4(int8). + providers (list): providers to use + + Returns: + model: fake quantized ONNXModel + """ + model = ONNXModel(model) + base_dir = os.path.dirname(model.model_path) if model.model_path is not None else "" + + inputs, so = prepare_inputs(model, n_samples, dataloader, providers) + del dataloader + org_output = copy.deepcopy(model.model.graph.output) + model.remove_tensors_from_outputs([i.name for i in org_output]) + output_names = [] + for node in model.nodes(): + if ( + node.op_type in ["MatMul"] + and weight_config.get(node.name, {}) != "fp32" + and weight_config.get(node.name, {}).get("algorithm", "GPTQ") == "GPTQ" + ): + output_names.append(node.input[0]) + output_names = list(set(output_names)) + model.add_tensors_to_outputs(output_names) + if model.is_large_model: + onnx.save_model( + model.model, + model.model_path + "_augment.onnx", + save_as_external_data=True, + all_tensors_to_one_file=True, + convert_attribute=False, + ) + + session = ( + ort.InferenceSession(model.model.SerializeToString(), so, providers=providers) + if not model.is_large_model + else ort.InferenceSession(model.model_path + "_augment.onnx", so, providers=providers) + ) + + for idx, input_name in enumerate(output_names): + simple_progress_bar(len(output_names), idx + 1) + node_list = [] + weights = [] + + for node in model.input_name_to_nodes[input_name]: + if ( + node.op_type in ["MatMul"] + and weight_config.get(node.name, {}) != "fp32" + and weight_config.get(node.name, {}).get("algorithm", "GPTQ") == "GPTQ" + and model.get_initializer(node.input[1]) is not None + ): + weight = numpy_helper.to_array( + model.get_initializer(model.get_node(node.name).input[1]), base_dir + ).copy() + if len(weight.shape) != 2: + continue + + weights.append(weight) + node_list.append(model.get_node(node.name)) + + if len(weights) == 0: + continue + + Hs = [np.zeros((i.shape[0], i.shape[0])) for i in weights] # noqa: N806 + nsamples = 0 + for data in inputs: + inp = session.run([input_name], data)[0] + tmp = inp.shape[0] + inp = np.reshape(inp, (-1, inp.shape[-1])) + Hs = [i * (nsamples / (nsamples + tmp)) for i in Hs] # noqa: N806 + nsamples += tmp + inp = np.sqrt(2 / nsamples) * inp + Hs = [i + np.matmul(inp.T, inp) for i in Hs] # noqa: N806 + + for ( + node, + weight, + H, # noqa: N806 + ) in zip(node_list, weights, Hs, strict=False): + if node.name in weight_config: + num_bits = weight_config[node.name]["bits"] + group_size = weight_config[node.name]["group_size"] + scheme = weight_config[node.name]["scheme"] + group_size = group_size if group_size != -1 else weight.shape[0] + dtype = weight.dtype + + q_weight = gptq( + weight, + H, + num_bits=num_bits, + group_size=group_size, + scheme=scheme, + blocksize=blocksize, + percdamp=percdamp, + actorder=actorder, + mse=mse, + perchannel=perchannel, + ) + + weight_tensor = model.get_initializer(node.input[1]) + init_share_num = model.get_initializer_share_num(node.input[1]) + + satisfy_MatMulNBits_condition = num_bits == 4 # noqa: N806 + + if satisfy_MatMulNBits_condition: # pragma: no cover + org_shape = weight.shape + k_blocks = (org_shape[0] + group_size - 1) // group_size + q_weight = pad_tensor(q_weight, group_size, k_blocks) + q_weight, scale, zp = quant_tensor(q_weight.T, num_bits, group_size, scheme, "uint") + q_matmul_node, new_inits = make_matmul_weight_only_node( + node=node, + weight_shape=org_shape, + num_bits=num_bits, + group_size=group_size, + k_blocks=k_blocks, + q_weight=q_weight.astype("uint8"), + scale=scale.astype(dtype), + zero_point=zp if scheme == "asym" else None, + accuracy_level=accuracy_level, + ) + + model.add_initializers(new_inits) + model.remove_node(node) + model.add_node(q_matmul_node) + else: + q_weight_tensor = onnx.helper.make_tensor( + name=node.input[1] + f"_Q{num_bits!s}G{group_size!s}", + data_type=np_dtype_to_tensor_dtype(dtype), + dims=q_weight.shape, + vals=q_weight.astype(dtype).tobytes(), + raw=True, + ) + model.add_initializer(q_weight_tensor) + node.input[1] = q_weight_tensor.name + if init_share_num == 1: + model.remove_initializer(weight_tensor) + + model.remove_tensors_from_outputs(output_names) + model.model.graph.output.MergeFrom(org_output) + + model.topological_sort() + + # reload external data to prevent external data file path errors + if model.is_large_model: + from onnx.external_data_helper import load_external_data_for_model # noqa: PLC0415 + + load_external_data_for_model(model.model, os.path.split(model.model_path)[0]) + + return model diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/__init__.py b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..52f9d0d0a02fce26760fe5f59da58edfadb5ca52 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/__init__.py @@ -0,0 +1,2 @@ +# from .base_operator import QuantOperatorBase +# from .matmul import MatMulInteger diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5685c9fbc0b3abb3b0207486592d03f347ca0b2e Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/__pycache__/activation.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/__pycache__/activation.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..86499795bb92089e61988af9c9c2f6b4142e5b3e Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/__pycache__/activation.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/__pycache__/argmax.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/__pycache__/argmax.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cc6ba0d48e369ec968c53e2b9b9efc0509657a3f Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/__pycache__/argmax.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/__pycache__/attention.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/__pycache__/attention.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dad8416e9078c8f3fd68c2a00075fa46ff897665 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/__pycache__/attention.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/__pycache__/base_operator.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/__pycache__/base_operator.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..93dac64b36955d0f9e66133dea33fe4dc261ffe6 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/__pycache__/base_operator.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/__pycache__/binary_op.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/__pycache__/binary_op.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..538aa0a53812268bbb3f1abbddf9bf9f8897729e Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/__pycache__/binary_op.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/__pycache__/concat.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/__pycache__/concat.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..171c5fb58ed76d226d6bbbb5a9cbafb36af4514f Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/__pycache__/concat.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/__pycache__/conv.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/__pycache__/conv.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..442c3bb6715363da50cd2370cf7f8228c3cc514d Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/__pycache__/conv.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/__pycache__/direct_q8.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/__pycache__/direct_q8.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..50eb23f99ef909fe46c07598aff4d3b02eab9ff5 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/__pycache__/direct_q8.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/__pycache__/embed_layernorm.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/__pycache__/embed_layernorm.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..749780055e2a913cd28b0ccb843f1876f664b78a Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/__pycache__/embed_layernorm.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/__pycache__/gather.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/__pycache__/gather.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..89727ab253273d846a9c28ce267b81e5f50a7ba6 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/__pycache__/gather.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/__pycache__/gavgpool.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/__pycache__/gavgpool.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..665273a7a5c9d26987ae05489282b82396d629c4 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/__pycache__/gavgpool.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/__pycache__/gemm.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/__pycache__/gemm.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7925cd5b431a0de8e5006239f05b595125f44aeb Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/__pycache__/gemm.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/__pycache__/lstm.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/__pycache__/lstm.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ffec2fde9d2fcb8eef494468f2856c2bbab2d786 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/__pycache__/lstm.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/__pycache__/matmul.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/__pycache__/matmul.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..06709b3422b8038bee1598f0478eda2c7fb28d04 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/__pycache__/matmul.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/__pycache__/maxpool.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/__pycache__/maxpool.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5220de9288f488dc962eaf11de84cd77c46cd981 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/__pycache__/maxpool.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/__pycache__/norm.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/__pycache__/norm.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..550b8200f2fd8ba0279d3ecd418b77c6b179225e Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/__pycache__/norm.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/__pycache__/pad.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/__pycache__/pad.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8bdd1ae39955e7d2172452efc51f54c2ec543dc3 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/__pycache__/pad.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/__pycache__/pooling.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/__pycache__/pooling.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..da55e6f17ce749e464aca910cfc8d8de42078db2 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/__pycache__/pooling.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/__pycache__/qdq_base_operator.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/__pycache__/qdq_base_operator.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cd090cc7e3a6e924c30f2918cda52b384fb48018 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/__pycache__/qdq_base_operator.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/__pycache__/resize.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/__pycache__/resize.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b4c3c4b75279b0f2d95f8ecf21d750f50f42de40 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/__pycache__/resize.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/__pycache__/softmax.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/__pycache__/softmax.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..af509b401d716738d39b094be010dba683f4699c Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/__pycache__/softmax.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/__pycache__/split.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/__pycache__/split.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5ae82222c9b90a63b8762b321b777cd1d98a623a Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/__pycache__/split.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/__pycache__/where.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/__pycache__/where.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..05d2143524bf2c8d6a54f1f79f62ff2eec602433 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/__pycache__/where.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/activation.py b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/activation.py new file mode 100644 index 0000000000000000000000000000000000000000..81927f0390414593cc550329f050c20dff407b50 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/activation.py @@ -0,0 +1,119 @@ +import onnx + +from ..quant_utils import TENSOR_NAME_QUANT_SUFFIX, QuantizedValue, QuantizedValueType, attribute_to_kwarg, ms_domain +from .base_operator import QuantOperatorBase +from .qdq_base_operator import QDQOperatorBase + + +class QLinearActivation(QuantOperatorBase): + def __init__(self, onnx_quantizer, onnx_node): + super().__init__(onnx_quantizer, onnx_node) + + def QuantizeClipRelu(self): # noqa: N802 + node = self.node + assert node.op_type == "Relu" or node.op_type == "Clip" + + # When mode is QLinearOps, the output quantization params are calculated based on outputs from + # activation nodes, therefore these nodes can be removed from the graph if they follow a quantized op. + # If input to this node is not quantized then keep this node + # If activation is symmetric, not quantize the op and simply return + if node.input[0] not in self.quantizer.quantized_value_map or self.quantizer.is_activation_symmetric: + return super().quantize() + + quantized_value = self.quantizer.quantized_value_map[node.input[0]] + self.quantizer.quantized_value_map[node.output[0]] = quantized_value + + def quantize(self): + node = self.node + if node.op_type == "Relu" or node.op_type == "Clip": + self.QuantizeClipRelu() + return + + nnapi_sigmoid_option = "extra.Sigmoid.nnapi" + sigmoid_nnapi_mode = ( + node.op_type == "Sigmoid" + and nnapi_sigmoid_option in self.quantizer.extra_options + and self.quantizer.extra_options[nnapi_sigmoid_option] + ) + use_scale = 1 / 256.0 if sigmoid_nnapi_mode else None + use_zeropoint = 0 if sigmoid_nnapi_mode else None + + # No assert on op_type as it is controlled by registry + # only try to quantize when given quantization parameters for it + ( + data_found, + output_scale_name, + output_zp_name, + _, + _, + ) = self.quantizer._get_quantization_params(node.output[0], use_scale, use_zeropoint) + ( + quantized_input_names, + zero_point_names, + scale_names, + nodes, + ) = self.quantizer.quantize_activation(node, [0]) + if not data_found or quantized_input_names is None: + return super().quantize() + + qlinear_activation_output = node.output[0] + TENSOR_NAME_QUANT_SUFFIX + qlinear_activation_name = "" + if node.name: + qlinear_activation_name = node.name + "_quant" + kwargs = {} + for attribute in node.attribute: + kwargs.update(attribute_to_kwarg(attribute)) + kwargs["domain"] = ms_domain + + qlinear_activation_inputs = [ + quantized_input_names[0], + scale_names[0], + zero_point_names[0], + output_scale_name, + output_zp_name, + ] + + qlinear_activation_node = onnx.helper.make_node( + "QLinear" + node.op_type, + qlinear_activation_inputs, + [qlinear_activation_output], + qlinear_activation_name, + **kwargs, + ) + + # Create an entry for this quantized value + q_output = QuantizedValue( + node.output[0], + qlinear_activation_output, + output_scale_name, + output_zp_name, + QuantizedValueType.Input, + ) + self.quantizer.quantized_value_map[node.output[0]] = q_output + + nodes.append(qlinear_activation_node) + self.quantizer.new_nodes += nodes + + +class QDQRemovableActivation(QDQOperatorBase): + def __init__(self, onnx_quantizer, onnx_node): + super().__init__(onnx_quantizer, onnx_node) + + def quantize(self): + node = self.node + + # If input to this node is not quantized then keep this node + if not self.quantizer.is_tensor_quantized(node.input[0]): + return + + if ( + not self.quantizer.is_activation_symmetric + and not self.quantizer.qdq_keep_removable_activations + and self.quantizer.try_replacing_upstream_output(node.input[0], node.output[0]) + ): + self.quantizer.remove_node(self.node) + else: + self.quantizer.quantize_activation_tensor(node.input[0]) + + if not self.disable_qdq_for_node_output: + self.quantizer.quantize_activation_tensor(node.output[0]) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/argmax.py b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/argmax.py new file mode 100644 index 0000000000000000000000000000000000000000..6a3484f867a59ddc1f02b6b8bb45118d244956b3 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/argmax.py @@ -0,0 +1,18 @@ +from .base_operator import QuantOperatorBase + + +# Use the quantized tensor as input without DQ. +class QArgMax(QuantOperatorBase): + def __init__(self, onnx_quantizer, onnx_node): + super().__init__(onnx_quantizer, onnx_node) + + def quantize(self): + node = self.node + + quantized_input_value = self.quantizer.find_quantized_value(node.input[0]) + if quantized_input_value is None: + self.quantizer.new_nodes += [node] + return + + node.input[0] = quantized_input_value.q_name + self.quantizer.new_nodes += [node] diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/attention.py b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/attention.py new file mode 100644 index 0000000000000000000000000000000000000000..4220a4e15bc45161fc0f41a5331e9c39003ebbc2 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/attention.py @@ -0,0 +1,73 @@ +import onnx +from onnx import onnx_pb as onnx_proto # noqa: F401 + +from ..quant_utils import attribute_to_kwarg, ms_domain +from .base_operator import QuantOperatorBase + +""" + Quantize Attention +""" + + +class AttentionQuant(QuantOperatorBase): + def __init__(self, onnx_quantizer, onnx_node): + super().__init__(onnx_quantizer, onnx_node) + + def should_quantize(self): + return self.quantizer.should_quantize_node(self.node) + + def quantize(self): + """ + parameter node: Attention node. + parameter new_nodes_list: List of new nodes created before processing this node. + return: a list of nodes in topological order that represents quantized Attention node. + """ + node = self.node + assert node.op_type == "Attention" + + # TODO This is a temporary fix to stop exporting QAttention with qkv_hidden_sizes + # attribute. This needs to be removed once the QAttention for varied q,k,v sizes + # is implemented + for attr in node.attribute: + if attr.name == "qkv_hidden_sizes": + return super().quantize() + + ( + quantized_input_names, + zero_point_names, + scale_names, + nodes, + ) = self.quantizer.quantize_activation(node, [0]) + + ( + quantized_input_names_weight, + zero_point_names_weight, + scale_names_weight, + nodes_weight, + ) = self.quantizer.quantize_weight(node, [1], reduce_range=True, op_level_per_channel=True) + quantized_input_names.extend(quantized_input_names_weight) + zero_point_names.extend(zero_point_names_weight) + scale_names.extend(scale_names_weight) + nodes.extend(nodes_weight) + + if quantized_input_names is None: + return super().quantize() + + qattention_name = "" if not node.name else node.name + "_quant" + + inputs = [] + inputs.extend(quantized_input_names) + inputs.extend([node.input[2]]) + inputs.extend(scale_names) + inputs.extend([node.input[3] if len(node.input) > 3 else ""]) + inputs.extend(zero_point_names) + inputs.extend([node.input[4] if len(node.input) > 4 else ""]) + + kwargs = {} + for attribute in node.attribute: + kwargs.update(attribute_to_kwarg(attribute)) + kwargs["domain"] = ms_domain + qattention_node = onnx.helper.make_node("QAttention", inputs, node.output, qattention_name, **kwargs) + nodes.append(qattention_node) + + self.quantizer.new_nodes += nodes diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/base_operator.py b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/base_operator.py new file mode 100644 index 0000000000000000000000000000000000000000..e4895bd807a37a52fc8b1c465909575f3f7b25e2 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/base_operator.py @@ -0,0 +1,26 @@ +class QuantOperatorBase: + def __init__(self, onnx_quantizer, onnx_node): + self.quantizer = onnx_quantizer + self.node = onnx_node + + def should_quantize(self): + if not self.quantizer.should_quantize_node(self.node): + return False + + return self.quantizer.is_float_tensor(self.node.input[0]) + + def quantize(self): + """ + Given a node which does not support quantization, this method checks whether the input to + this node is quantized and adds a DequantizeLinear node to dequantize this input back to FP32 + parameter node: Current node + parameter new_nodes_list: List of new nodes created before processing current node + return: List of new nodes created + """ + for _, node_input in enumerate(self.node.input): + dequantize_node = self.quantizer._dequantize_value(node_input) + if dequantize_node is not None: + self.quantizer.new_nodes.append(dequantize_node) + + # Append the original node + self.quantizer.new_nodes.append(self.node) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/binary_op.py b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/binary_op.py new file mode 100644 index 0000000000000000000000000000000000000000..85da759750b41d722c26645999294ef46c3a4773 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/binary_op.py @@ -0,0 +1,72 @@ +import onnx +from onnx import onnx_pb as onnx_proto # noqa: F401 + +from ..quant_utils import TENSOR_NAME_QUANT_SUFFIX, QuantizedValue, QuantizedValueType, attribute_to_kwarg, ms_domain +from .base_operator import QuantOperatorBase + + +class QLinearBinaryOp(QuantOperatorBase): + def __init__(self, onnx_quantizer, onnx_node): + super().__init__(onnx_quantizer, onnx_node) + + def quantize(self): + node = self.node + + ( + data_found, + output_scale_name, + output_zp_name, + _, + _, + ) = self.quantizer._get_quantization_params(node.output[0]) + ( + quantized_input_names, + zero_point_names, + scale_names, + nodes, + ) = self.quantizer.quantize_activation(node, [0, 1]) + if not data_found or quantized_input_names is None: + return super().quantize() + + qlinear_binary_math_output = node.output[0] + TENSOR_NAME_QUANT_SUFFIX + qlinear_binary_math_name = node.name + "_quant" if node.name else "" + + kwargs = {} + for attribute in node.attribute: + kwargs.update(attribute_to_kwarg(attribute)) + kwargs["domain"] = ms_domain + + qlinear_binary_math_inputs = [] + # Input 0 + qlinear_binary_math_inputs.append(quantized_input_names[0]) + qlinear_binary_math_inputs.append(scale_names[0]) + qlinear_binary_math_inputs.append(zero_point_names[0]) + # Input 1 + qlinear_binary_math_inputs.append(quantized_input_names[1]) + qlinear_binary_math_inputs.append(scale_names[1]) + qlinear_binary_math_inputs.append(zero_point_names[1]) + + # Output + qlinear_binary_math_inputs.append(output_scale_name) + qlinear_binary_math_inputs.append(output_zp_name) + + qlinear_binary_math_node = onnx.helper.make_node( + "QLinear" + node.op_type, + qlinear_binary_math_inputs, + [qlinear_binary_math_output], + qlinear_binary_math_name, + **kwargs, + ) + nodes.append(qlinear_binary_math_node) + + # Create an entry for this quantized value + q_output = QuantizedValue( + node.output[0], + qlinear_binary_math_output, + output_scale_name, + output_zp_name, + QuantizedValueType.Input, + ) + self.quantizer.quantized_value_map[node.output[0]] = q_output + + self.quantizer.new_nodes += nodes diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/concat.py b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/concat.py new file mode 100644 index 0000000000000000000000000000000000000000..523eef72018209d8aad07e9bebddd2284fb82297 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/concat.py @@ -0,0 +1,62 @@ +import onnx + +from ..quant_utils import ( # noqa: F401 + TENSOR_NAME_QUANT_SUFFIX, + QuantizedValue, + QuantizedValueType, + attribute_to_kwarg, + ms_domain, +) +from .base_operator import QuantOperatorBase +from .qdq_base_operator import QDQOperatorBase # noqa: F401 + + +class QLinearConcat(QuantOperatorBase): + def __init__(self, onnx_quantizer, onnx_node): + super().__init__(onnx_quantizer, onnx_node) + + def quantize(self): + node = self.node + + ( + data_found, + output_scale_name, + output_zp_name, + _, + _, + ) = self.quantizer._get_quantization_params(node.output[0]) + ( + q_input_names, + zero_point_names, + scale_names, + nodes, + ) = self.quantizer.quantize_activation(node, [*range(len(node.input))]) + if not data_found or q_input_names is None: + return super().quantize() + + # Create an entry for output quantized value + quantized_input_value = self.quantizer.quantized_value_map[node.input[0]] + quantized_output_value = QuantizedValue( + node.output[0], + node.output[0] + TENSOR_NAME_QUANT_SUFFIX, + output_scale_name, + output_zp_name, + quantized_input_value.value_type, + ) + self.quantizer.quantized_value_map[node.output[0]] = quantized_output_value + + kwargs = {} + for attribute in node.attribute: + kwargs.update(attribute_to_kwarg(attribute)) + kwargs["domain"] = ms_domain + qnode_name = node.name + "_quant" if node.name else "" + + qlconcat_inputs = [output_scale_name, output_zp_name] + for i in range(len(q_input_names)): + qlconcat_inputs.extend([q_input_names[i], scale_names[i], zero_point_names[i]]) + qlconcat_node = onnx.helper.make_node( + "QLinearConcat", qlconcat_inputs, [quantized_output_value.q_name], qnode_name, **kwargs + ) + + self.quantizer.new_nodes += nodes + self.quantizer.new_nodes += [qlconcat_node] diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/conv.py b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/conv.py new file mode 100644 index 0000000000000000000000000000000000000000..61b5e37c66823ea9d8ac448a0233567d43c0d722 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/conv.py @@ -0,0 +1,260 @@ +import numpy as np +import onnx +from onnx import onnx_pb as onnx_proto + +from ..quant_utils import ( + TENSOR_NAME_QUANT_SUFFIX, + QuantizedValue, + QuantizedValueType, + attribute_to_kwarg, + find_by_name, + get_mul_node, +) +from .base_operator import QuantOperatorBase +from .qdq_base_operator import QDQOperatorBase + + +class ConvInteger(QuantOperatorBase): + def __init__(self, onnx_quantizer, onnx_node): + super().__init__(onnx_quantizer, onnx_node) + + def add_bias(self, nodes, scaled_output): + """ + Given a node, this function handles bias add by adding a "reshape" node on bias and an "add" node + parameter nodes: new nodes would be appended into nodes + parameter node: current node (Conv) + parameter scaled_output: output of quant conv without bias + parameter output: output of Conv + parameter bias_name: bias of Conv + return: the name of output + """ + node = self.node + model = self.quantizer.model + # Add tensors for the shape to be reshaped to + weight = find_by_name(node.input[1], model.initializer()) + if weight is None: + raise ValueError(f"Expected {node.input[1]} to be an initializer") + + # Add reshape for correct broadcase + output = node.output[0] + reshape_input_data = node.input[2] # bias of Conv + reshape_input_shape = output + "_bias_reshape_shape" + reshape_output = output + "_bias_reshape_output" + + shape = np.ones((len(weight.dims)), dtype=np.int64) + shape[1] = -1 + init_shape = onnx.helper.make_tensor( + reshape_input_shape, onnx_proto.TensorProto.INT64, [len(weight.dims)], shape + ) + model.add_initializer(init_shape) + + reshape_node = onnx.helper.make_node("Reshape", [reshape_input_data, reshape_input_shape], [reshape_output]) + nodes.append(reshape_node) + + # Add an Add operation for bias + add_node = onnx.helper.make_node("Add", [scaled_output, reshape_output], [output], output + "_bias_add") + nodes.append(add_node) + + def quantize(self): + node = self.node + assert node.op_type == "Conv" + # Get Quantized from both activation(input[0]) and weight(input[1]) + ( + quantized_input_names, + zero_point_names, + scale_names, + nodes, + ) = self.quantizer.quantize_activation(node, [0]) + + ( + quantized_input_names_weight, + zero_point_names_weight, + scale_names_weight, + nodes_weight, + ) = self.quantizer.quantize_weight(node, [1], reduce_range=self.quantizer.reduce_range) + quantized_input_names.extend(quantized_input_names_weight) + zero_point_names.extend(zero_point_names_weight) + scale_names.extend(scale_names_weight) + nodes.extend(nodes_weight) + + conv_integer_output = node.output[0] + "_output_quantized" + conv_integer_name = node.name + "_quant" if node.name else "" + + kwargs = {} + for attribute in node.attribute: + kwargs.update(attribute_to_kwarg(attribute)) + conv_integer_node = onnx.helper.make_node( + "ConvInteger", quantized_input_names + zero_point_names, [conv_integer_output], conv_integer_name, **kwargs + ) + nodes.append(conv_integer_node) + + # Add cast operation to cast convInteger output to float. + onnx_type = self.quantizer.get_tensor_type(node.output[0], mandatory=True) + cast_op_output = conv_integer_output + "_cast_output" + cast_node = onnx.helper.make_node( + "Cast", + [conv_integer_output], + [cast_op_output], + conv_integer_output + "_cast", + to=onnx_type, # TODO: FLOAT ot FLOAT16 + ) + nodes.append(cast_node) + + # Add mul operation to multiply scales of two inputs. + assert len(scale_names) == 2 + if conv_integer_name: + scales_mul_op = conv_integer_name + "_scales_mul" + else: + scales_mul_op = scale_names[0] + "_" + scale_names[1] + "_mul" + + scales_mul_node = find_by_name(scales_mul_op, self.quantizer.new_nodes) + if scales_mul_node is None: + scales_mul_node = get_mul_node(scale_names, scales_mul_op + ":0", scales_mul_op) + nodes.append(scales_mul_node) + + scales_mul_op_output = scales_mul_node.output[0] + + has_bias = len(node.input) == 3 + scaled_output_name = node.output[0] if not has_bias else node.output[0] + "quant_scaled_output" + + # Add mul operation to multiply mul_scales_op result with output of ConvInteger + # and make the output of this node the same as output of original conv node. + output_scale_mul_op = conv_integer_name + "_output_scale_mul" if conv_integer_name else "" + nodes.append( + get_mul_node( + [cast_op_output, scales_mul_op_output], + scaled_output_name, + output_scale_mul_op, + ) + ) + + if has_bias: + self.add_bias(nodes, scaled_output_name) + + self.quantizer.new_nodes += nodes + + +class QLinearConv(QuantOperatorBase): + def __init__(self, onnx_quantizer, onnx_node): + super().__init__(onnx_quantizer, onnx_node) + + def quantize(self): + node = self.node + assert node.op_type == "Conv" + + ( + data_found, + output_scale_name, + output_zp_name, + _, + _, + ) = self.quantizer._get_quantization_params(node.output[0]) + + if self.quantizer.is_input_a_initializer(node.input[1]) and self.quantizer.is_per_channel(): + ( + quantized_input_names, + zero_point_names, + scale_names, + nodes, + ) = self.quantizer.quantize_activation(node, [0]) + quant_weight_tuple = self.quantizer.quantize_weight_per_channel( + node.input[1], + onnx_proto.TensorProto.INT8, + 0, # self.quantizer.weight_qType? + ) + quantized_input_names.append(quant_weight_tuple[0]) + zero_point_names.append(quant_weight_tuple[1]) + scale_names.append(quant_weight_tuple[2]) + else: + ( + quantized_input_names, + zero_point_names, + scale_names, + nodes, + ) = self.quantizer.quantize_activation(node, [0]) + + ( + quantized_input_names_weight, + zero_point_names_weight, + scale_names_weight, + nodes_weight, + ) = self.quantizer.quantize_weight(node, [1], reduce_range=self.quantizer.reduce_range) + quantized_input_names.extend(quantized_input_names_weight) + zero_point_names.extend(zero_point_names_weight) + scale_names.extend(scale_names_weight) + nodes.extend(nodes_weight) + + if not data_found or quantized_input_names is None: + return super().quantize() + + quantized_bias_name = "" + bias_present = False + if len(node.input) == 3: + if self.quantizer.weight_qType == onnx_proto.TensorProto.FLOAT8E4M3FN: + raise RuntimeError("Quantization to FLOAT8E4M3FN for operator Conv is not supported.") + quantized_bias_name = self.quantizer.quantize_bias_static(node.input[2], node.input[0], node.input[1]) + bias_present = True + + qlinear_conv_output = node.output[0] + TENSOR_NAME_QUANT_SUFFIX + qlinear_conv_name = node.name + "_quant" if node.name else "" + + kwargs = {} + for attribute in node.attribute: + kwargs.update(attribute_to_kwarg(attribute)) + qlinear_conv_inputs = [] + # Input 0 + qlinear_conv_inputs.append(quantized_input_names[0]) + qlinear_conv_inputs.append(scale_names[0]) + qlinear_conv_inputs.append(zero_point_names[0]) + # Input 1 + qlinear_conv_inputs.append(quantized_input_names[1]) + qlinear_conv_inputs.append(scale_names[1]) + qlinear_conv_inputs.append(zero_point_names[1]) + + # Output + qlinear_conv_inputs.append(output_scale_name) + qlinear_conv_inputs.append(output_zp_name) + + if bias_present: + qlinear_conv_inputs.append(quantized_bias_name) + + qlinear_conv_node = onnx.helper.make_node( + "QLinearConv", qlinear_conv_inputs, [qlinear_conv_output], qlinear_conv_name, **kwargs + ) + nodes.append(qlinear_conv_node) + + # Create an entry for this quantized value + q_output = QuantizedValue( + node.output[0], + qlinear_conv_output, + output_scale_name, + output_zp_name, + QuantizedValueType.Input, + ) + self.quantizer.quantized_value_map[node.output[0]] = q_output + + self.quantizer.new_nodes += nodes + + +class QDQConv(QDQOperatorBase): + def __init__(self, onnx_quantizer, onnx_node): + super().__init__(onnx_quantizer, onnx_node) + + def quantize(self): + node = self.node + assert node.op_type == "Conv" or node.op_type == "ConvTranspose" + + self.quantizer.quantize_activation_tensor(node.input[0]) + if not self.disable_qdq_for_node_output: + self.quantizer.quantize_activation_tensor(node.output[0]) + + is_weight_per_channel, weight_axis = self.quantizer.is_tensor_per_channel( + node.input[1], default_axis=0 if node.op_type == "Conv" else 1 + ) + if is_weight_per_channel: + self.quantizer.quantize_weight_tensor_per_channel(node.input[1], weight_axis) + else: + self.quantizer.quantize_weight_tensor(node.input[1]) + + if len(node.input) == 3: + self.quantizer.quantize_bias_tensor(node.name, node.input[2], node.input[0], node.input[1]) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/direct_q8.py b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/direct_q8.py new file mode 100644 index 0000000000000000000000000000000000000000..33dcc8ac9b784736c76569610143f3f95866997c --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/direct_q8.py @@ -0,0 +1,78 @@ +from ..quant_utils import TENSOR_NAME_QUANT_SUFFIX, QuantizedValue, QuantizedValueType +from .base_operator import QuantOperatorBase +from .qdq_base_operator import QDQOperatorBase + + +# For operators that support 8bits operations directly, and output could +# reuse input[0]'s type, zeropoint, scale; For example,Transpose, Reshape, etc. +class Direct8BitOp(QuantOperatorBase): + def __init__(self, onnx_quantizer, onnx_node): + super().__init__(onnx_quantizer, onnx_node) + + def quantize(self): + node = self.node + + if not self.quantizer.force_quantize_no_input_check: + # Keep backward compatibility + # Quantize when input[0] is quantized already. Otherwise keep it. + quantized_input_value = self.quantizer.find_quantized_value(node.input[0]) + if quantized_input_value is None: + self.quantizer.new_nodes += [node] + return + + quantized_output_value = QuantizedValue( + node.output[0], + node.output[0] + TENSOR_NAME_QUANT_SUFFIX, + quantized_input_value.scale_name, + quantized_input_value.zp_name, + quantized_input_value.value_type, + ) + self.quantizer.quantized_value_map[node.output[0]] = quantized_output_value + + node.input[0] = quantized_input_value.q_name + node.output[0] = quantized_output_value.q_name + self.quantizer.new_nodes += [node] + + else: + # Force quantize those ops if possible, use exclude node list if this is not you want + if not self.quantizer.is_valid_quantize_weight(node.input[0]): + super().quantize() + return + + ( + quantized_input_names, + zero_point_names, + scale_names, + nodes, + ) = self.quantizer.quantize_activation(node, [0]) + if quantized_input_names is None: + return super().quantize() + + # Create an entry for output quantized value + quantized_output_value = QuantizedValue( + node.output[0], + node.output[0] + TENSOR_NAME_QUANT_SUFFIX, + scale_names[0], + zero_point_names[0], + QuantizedValueType.Input, + ) + self.quantizer.quantized_value_map[node.output[0]] = quantized_output_value + + node.input[0] = quantized_input_names[0] + node.output[0] = quantized_output_value.q_name + nodes.append(node) + + self.quantizer.new_nodes += nodes + + +class QDQDirect8BitOp(QDQOperatorBase): + def __init__(self, onnx_quantizer, onnx_node): + super().__init__(onnx_quantizer, onnx_node) + + def quantize(self): + if self.quantizer.force_quantize_no_input_check: + self.quantizer.quantize_activation_tensor(self.node.input[0]) + if not self.disable_qdq_for_node_output: + self.quantizer.quantize_output_same_as_input(self.node.output[0], self.node.input[0], self.node.name) + elif self.quantizer.is_tensor_quantized(self.node.input[0]) and not self.disable_qdq_for_node_output: + self.quantizer.quantize_output_same_as_input(self.node.output[0], self.node.input[0], self.node.name) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/embed_layernorm.py b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/embed_layernorm.py new file mode 100644 index 0000000000000000000000000000000000000000..074cf2e72fbd5b2a2a2af6a8e007ef4484ecfa25 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/embed_layernorm.py @@ -0,0 +1,121 @@ +import logging + +import onnx +from onnx import onnx_pb as onnx_proto # noqa: F401 + +from ..quant_utils import attribute_to_kwarg, ms_domain +from .base_operator import QuantOperatorBase + +""" +Quantizes the EmbedLayerNorm fused ONNXRuntime Op. + +This Quant operator keeps the input and segment IDs at int32 but will quantize all initializer and +weight inputs associated with the node to uint8. +""" + + +class EmbedLayerNormalizationQuant(QuantOperatorBase): + def __init__(self, onnx_quantizer, onnx_node): + super().__init__(onnx_quantizer, onnx_node) + + def should_quantize(self): + return self.quantizer.should_quantize_node(self.node) + + def quantize(self): + node = self.node + assert node.op_type == "EmbedLayerNormalization" + + if len(node.output) > 2: + logging.info(f"Quantization is not applied to {node.name} since it has 3 outputs") + return super().quantize() + + """ + Pre-quantization EmbedLayerNorm inputs: + [0] input_ids (int32) + [1] segment_ids (int32) + [2] word_embedding (float32) + [3] position_embedding (float32) + [4] segment_embedding (float32) + [5] gamma (float32) + [6] beta (float32) + [7] mask (int32) (optional) + """ + ( + quantized_input_names, + zero_point_names, + scale_names, + nodes, + ) = self.quantizer.quantize_activation(node, [2, 3, 4, 5, 6]) + if quantized_input_names is None: + return super().quantize() + + qembed_layer_norm_name = "" if not node.name else node.name + "_quant" + + """ + Quantized Input Tensor List + [0] input_ids (int32) + [1] segment_ids (int32) + [2] word_embedding (uint8) + [3] position_embedding (uint8) + [4] segment_embedding (uint8) + [5] gamma (uint8) + [6] beta (uint8) + [7] mask (int32) (optional) + [8] word_embedding_scale (float) + [9] position_embedding_scale (float) + [10] segment_embedding_scale (float) + [11] gamma_scale (float) + [12] beta_scale (float) + [13] word_embedding_zero_point (uint8) + [14] position_embedding_zero_point (uint8) + [15] segment_embedding_zero_point (uint8) + [16] gamma_zero_point (uint8) + [17] beta_zero_point (uint8) + """ + inputs = [] + # 'input_ids' + inputs.extend([node.input[0]]) + # 'segment_ids' + inputs.extend([node.input[1]]) + # 'word_embedding_quant' + inputs.extend([quantized_input_names[0]]) + # 'position_embedding_quant' + inputs.extend([quantized_input_names[1]]) + # 'segment_embedding_quant' + inputs.extend([quantized_input_names[2]]) + # 'gamma_quant' + inputs.extend([quantized_input_names[3]]) + # 'beta_quant' + inputs.extend([quantized_input_names[4]]) + # 'mask' (optional) + inputs.extend([node.input[7] if len(node.input) > 7 else ""]) + + # Add all scales: + inputs.extend([scale_names[0]]) + inputs.extend([scale_names[1]]) + inputs.extend([scale_names[2]]) + inputs.extend([scale_names[3]]) + inputs.extend([scale_names[4]]) + + # Add all zero points: + inputs.extend([zero_point_names[0]]) + inputs.extend([zero_point_names[1]]) + inputs.extend([zero_point_names[2]]) + inputs.extend([zero_point_names[3]]) + inputs.extend([zero_point_names[4]]) + + kwargs = {} + for attribute in node.attribute: + kwargs.update(attribute_to_kwarg(attribute)) + kwargs["domain"] = ms_domain + + qembed_layer_norm_node = onnx.helper.make_node( + "QEmbedLayerNormalization", + inputs, + node.output, + qembed_layer_norm_name, + **kwargs, + ) + nodes.append(qembed_layer_norm_node) + + self.quantizer.new_nodes += nodes diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/gather.py b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/gather.py new file mode 100644 index 0000000000000000000000000000000000000000..5b0e97c43bdf1220f6cb8bc3bd34306f131a1cae --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/gather.py @@ -0,0 +1,64 @@ +from ..quant_utils import TENSOR_NAME_QUANT_SUFFIX, QuantizedValue, QuantizedValueType +from .base_operator import QuantOperatorBase +from .qdq_base_operator import QDQOperatorBase + +""" + Quantize Gather +""" + + +class GatherQuant(QuantOperatorBase): + def __init__(self, onnx_quantizer, onnx_node): + super().__init__(onnx_quantizer, onnx_node) + + def should_quantize(self): + if not self.quantizer.should_quantize_node(self.node): + return False + + return self.quantizer.is_valid_quantize_weight(self.node.input[0]) + + def quantize(self): + node = self.node + assert node.op_type == "Gather" + + ( + quantized_input_names, + zero_point_names, + scale_names, + nodes, + ) = self.quantizer.quantize_activation(node, [0]) + if quantized_input_names is None: + return super().quantize() + + gather_new_output = node.output[0] + TENSOR_NAME_QUANT_SUFFIX + + # Create an entry for this quantized value + q_output = QuantizedValue( + node.output[0], + gather_new_output, + scale_names[0], + zero_point_names[0], + QuantizedValueType.Input, + ) + self.quantizer.quantized_value_map[node.output[0]] = q_output + + node.output[0] = gather_new_output + node.input[0] = quantized_input_names[0] + nodes.append(node) + + self.quantizer.new_nodes += nodes + + +class QDQGather(QDQOperatorBase): + def __init__(self, onnx_quantizer, onnx_node): + super().__init__(onnx_quantizer, onnx_node) + + def quantize(self): + node = self.node + assert node.op_type == "Gather" or node.op_type == "GatherElements" + + if self.quantizer.is_valid_quantize_weight(node.input[0]) or self.quantizer.force_quantize_no_input_check: + self.quantizer.quantize_activation_tensor(node.input[0]) + self.quantizer.quantize_output_same_as_input(node.output[0], node.input[0], node.name) + elif self.quantizer.is_tensor_quantized(node.input[0]): + self.quantizer.quantize_output_same_as_input(node.output[0], node.input[0], node.name) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/gavgpool.py b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/gavgpool.py new file mode 100644 index 0000000000000000000000000000000000000000..49f139d74fe76790f280f0ab7c220a3527144422 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/gavgpool.py @@ -0,0 +1,62 @@ +import onnx + +from ..quant_utils import TENSOR_NAME_QUANT_SUFFIX, QuantizedValue, QuantizedValueType, attribute_to_kwarg, ms_domain +from .base_operator import QuantOperatorBase + + +class QGlobalAveragePool(QuantOperatorBase): + def __init__(self, onnx_quantizer, onnx_node): + super().__init__(onnx_quantizer, onnx_node) + + def quantize(self): + node = self.node + assert node.op_type == "GlobalAveragePool" + + # If input to this node is not quantized then keep this node. + if node.input[0] not in self.quantizer.quantized_value_map: + return super().quantize() + + quantized_input_value = self.quantizer.quantized_value_map[node.input[0]] + + # Create an entry for output quantized value. + quantized_input_value = self.quantizer.quantized_value_map[node.input[0]] + ( + data_found, + output_scale_name_from_parameter, + output_zp_name_from_parameter, + _, + _, + ) = self.quantizer._get_quantization_params(node.output[0]) + # Just use input scale and zp if parameters for output is not specified. + output_scale_name = output_scale_name_from_parameter if data_found else quantized_input_value.scale_name + output_zp_name = output_zp_name_from_parameter if data_found else quantized_input_value.zp_name + quantized_output_value = QuantizedValue( + node.output[0], + node.output[0] + TENSOR_NAME_QUANT_SUFFIX, + output_scale_name, + output_zp_name, + QuantizedValueType.Input, + ) + self.quantizer.quantized_value_map[node.output[0]] = quantized_output_value + + kwargs = {} + for attribute in node.attribute: + kwargs.update(attribute_to_kwarg(attribute)) + kwargs["domain"] = ms_domain + kwargs["channels_last"] = 0 + qnode_name = node.name + "_quant" if node.name else "" + + qnode = onnx.helper.make_node( + "QLinear" + node.op_type, + [ + quantized_input_value.q_name, + quantized_input_value.scale_name, + quantized_input_value.zp_name, + output_scale_name, + output_zp_name, + ], + [quantized_output_value.q_name], + qnode_name, + **kwargs, + ) + self.quantizer.new_nodes += [qnode] diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/gemm.py b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/gemm.py new file mode 100644 index 0000000000000000000000000000000000000000..a4bd293af5e0afc9c99036213337635e86528cc7 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/gemm.py @@ -0,0 +1,172 @@ +import logging + +import numpy as np # noqa: F401 +import onnx + +from ..quant_utils import ( + TENSOR_NAME_QUANT_SUFFIX, + QuantizedValue, + QuantizedValueType, + attribute_to_kwarg, + find_by_name, # noqa: F401 + get_mul_node, # noqa: F401 + ms_domain, +) +from .base_operator import QuantOperatorBase # noqa: F401 +from .matmul import QOpMatMul +from .qdq_base_operator import QDQOperatorBase + + +def is_B_transposed(gemm_node): # noqa: N802 + transB_attribute = [attr for attr in gemm_node.attribute if attr.name == "transB"] # noqa: N806 + if transB_attribute: + return onnx.helper.get_attribute_value(transB_attribute[0]) > 0 + + return False + + +def get_beta(gemm_node): + beta_attribute = [attr for attr in gemm_node.attribute if attr.name == "beta"] + if beta_attribute: + return onnx.helper.get_attribute_value(beta_attribute[0]) + + return 1.0 + + +def set_default_beta(gemm_node): + beta_attribute = [attr for attr in gemm_node.attribute if attr.name == "beta"] + if beta_attribute: + beta_attribute[0].f = 1.0 + + return 1.0 + + +class QLinearGemm(QOpMatMul): + def __init__(self, onnx_quantizer, onnx_node): + super().__init__(onnx_quantizer, onnx_node) + + def quantize(self): + node = self.node + assert node.op_type == "Gemm" + + ( + data_found, + output_scale_name, + output_zp_name, + _, + _, + ) = self.quantizer._get_quantization_params(node.output[0]) + + if self.quantizer.is_input_a_initializer(node.input[1]) and self.quantizer.is_per_channel(): + ( + quantized_input_names, + zero_point_names, + scale_names, + nodes, + ) = self.quantizer.quantize_activation(node, [0]) + quant_weight_tuple = self.quantizer.quantize_weight_per_channel( + node.input[1], + self.quantizer.weight_qType, + 0 if is_B_transposed(node) else 1, + ) + quantized_input_names.append(quant_weight_tuple[0]) + zero_point_names.append(quant_weight_tuple[1]) + scale_names.append(quant_weight_tuple[2]) + else: + # Get Quantized from both activation(input[0]) and weight(input[1]) + ( + quantized_input_names, + zero_point_names, + scale_names, + nodes, + ) = self.quantizer.quantize_activation(node, [0]) + + ( + quantized_input_names_weight, + zero_point_names_weight, + scale_names_weight, + nodes_weight, + ) = self.quantizer.quantize_weight(node, [1], reduce_range=self.quantizer.reduce_range) + quantized_input_names.extend(quantized_input_names_weight) + zero_point_names.extend(zero_point_names_weight) + scale_names.extend(scale_names_weight) + nodes.extend(nodes_weight) + + if not data_found or quantized_input_names is None: + return super().quantize() + + quantized_bias_name = "" + if len(node.input) == 3: + if not self.quantizer.is_input_a_initializer(node.input[2]): + return super().quantize() + + # Note: if the quantized type is float 8, the bias is converted into float 16. + # cublasLtMatMul only supports (b)float16 or float32 bias. + quantized_bias_name = self.quantizer.quantize_bias_static( + node.input[2], node.input[0], node.input[1], get_beta(self.node) + ) + + qgemm_output = node.output[0] + TENSOR_NAME_QUANT_SUFFIX + qgemm_name = node.name + "_quant" if node.name else "" + + kwargs = {} + for attribute in node.attribute: + if attribute.name != "beta": + kwargs.update(attribute_to_kwarg(attribute)) + kwargs["domain"] = ms_domain + + # generate input + qgemm_inputs = [] + for i in range(2): + qgemm_inputs.extend([quantized_input_names[i], scale_names[i], zero_point_names[i]]) + + qgemm_inputs.extend([quantized_bias_name, output_scale_name, output_zp_name]) + + qgemm_node = onnx.helper.make_node("QGemm", qgemm_inputs, [qgemm_output], qgemm_name, **kwargs) + nodes.append(qgemm_node) + + # Create an entry for this quantized value + q_output = QuantizedValue( + node.output[0], + qgemm_output, + output_scale_name, + output_zp_name, + QuantizedValueType.Input, + node_type=node.op_type, + node_qtype=self.quantizer.weight_qType, + ) + self.quantizer.quantized_value_map[node.output[0]] = q_output + + self.quantizer.new_nodes += nodes + + +class QDQGemm(QDQOperatorBase): + def __init__(self, onnx_quantizer, onnx_node): + super().__init__(onnx_quantizer, onnx_node) + + def quantize(self): + node = self.node + assert node.op_type == "Gemm" + + self.quantizer.quantize_activation_tensor(node.input[0]) + if not self.disable_qdq_for_node_output: + self.quantizer.quantize_activation_tensor(node.output[0]) + + is_weight_per_channel, weight_axis = self.quantizer.is_tensor_per_channel( + node.input[1], default_axis=0 if is_B_transposed(node) else 1 + ) + if is_weight_per_channel: + self.quantizer.quantize_weight_tensor_per_channel(node.input[1], weight_axis) + else: + self.quantizer.quantize_weight_tensor(node.input[1]) + + if len(node.input) == 3: + if self.quantizer.is_input_a_initializer(node.input[2]): + self.quantizer.quantize_bias_tensor( + node.name, node.input[2], node.input[0], node.input[1], get_beta(self.node) + ) + set_default_beta(self.node) + else: + logging.warning( + f"Bias of Gemm node '{self.node.name}' is not constant. Please exclude this node for better performance." + ) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/lstm.py b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/lstm.py new file mode 100644 index 0000000000000000000000000000000000000000..1de80fc1ecd20e2a005e0abb1a3d2e934219f1ee --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/lstm.py @@ -0,0 +1,121 @@ +import numpy +import onnx +from onnx import onnx_pb as onnx_proto + +from ..quant_utils import QuantType, attribute_to_kwarg, ms_domain # noqa: F401 +from .base_operator import QuantOperatorBase + +""" + Quantize LSTM +""" + + +class LSTMQuant(QuantOperatorBase): + def __init__(self, onnx_quantizer, onnx_node): + super().__init__(onnx_quantizer, onnx_node) + + def quantize(self): + """ + parameter node: LSTM node. + parameter new_nodes_list: List of new nodes created before processing this node. + return: a list of nodes in topological order that represents quantized Attention node. + """ + node = self.node + assert node.op_type == "LSTM" + + if not self.quantizer.is_valid_quantize_weight(node.input[1]) or not self.quantizer.is_valid_quantize_weight( + node.input[2] + ): + super().quantize() + return + + model = self.quantizer.model + W = model.get_initializer(node.input[1]) # noqa: N806 + R = model.get_initializer(node.input[2]) # noqa: N806 + + if len(W.dims) != 3 or len(R.dims) != 3: + super().quantize() + return + + [W_num_dir, W_4_hidden_size, W_input_size] = W.dims # noqa: N806 + [R_num_dir, R_4_hidden_size, R_hidden_size] = R.dims # noqa: N806 + + if self.quantizer.is_per_channel(): + del W.dims[0] + del R.dims[0] + W.dims[0] = W_num_dir * W_4_hidden_size + R.dims[0] = R_num_dir * R_4_hidden_size + + quant_input_weight_tuple = self.quantizer.quantize_weight_per_channel( + node.input[1], + onnx_proto.TensorProto.INT8, + 0, # self.quantizer.weight_qType? + ) + quant_recurrent_weight_tuple = self.quantizer.quantize_weight_per_channel( + node.input[2], + onnx_proto.TensorProto.INT8, + 0, # self.quantizer.weight_qType? + ) + + W_quant_weight = model.get_initializer(quant_input_weight_tuple[0]) # noqa: N806 + R_quant_weight = model.get_initializer(quant_recurrent_weight_tuple[0]) # noqa: N806 + + W_quant_array = onnx.numpy_helper.to_array(W_quant_weight) # noqa: N806 + R_quant_array = onnx.numpy_helper.to_array(R_quant_weight) # noqa: N806 + + W_quant_array = numpy.reshape(W_quant_array, (W_num_dir, W_4_hidden_size, W_input_size)) # noqa: N806 + R_quant_array = numpy.reshape(R_quant_array, (R_num_dir, R_4_hidden_size, R_hidden_size)) # noqa: N806 + + W_quant_array = numpy.transpose(W_quant_array, (0, 2, 1)) # noqa: N806 + R_quant_array = numpy.transpose(R_quant_array, (0, 2, 1)) # noqa: N806 + + W_quant_tranposed = onnx.numpy_helper.from_array(W_quant_array, quant_input_weight_tuple[0]) # noqa: N806 + R_quant_tranposed = onnx.numpy_helper.from_array(R_quant_array, quant_recurrent_weight_tuple[0]) # noqa: N806 + + model.remove_initializers([W_quant_weight, R_quant_weight]) + model.add_initializer(W_quant_tranposed) + model.add_initializer(R_quant_tranposed) + + W_quant_zp = model.get_initializer(quant_input_weight_tuple[1]) # noqa: N806 + R_quant_zp = model.get_initializer(quant_recurrent_weight_tuple[1]) # noqa: N806 + W_quant_scale = model.get_initializer(quant_input_weight_tuple[2]) # noqa: N806 + R_quant_scale = model.get_initializer(quant_recurrent_weight_tuple[2]) # noqa: N806 + + if self.quantizer.is_per_channel(): + W_quant_zp.dims[:] = [W_num_dir, W_4_hidden_size] + R_quant_zp.dims[:] = [R_num_dir, R_4_hidden_size] + W_quant_scale.dims[:] = [W_num_dir, W_4_hidden_size] + R_quant_scale.dims[:] = [R_num_dir, R_4_hidden_size] + + inputs = [] + input_len = len(node.input) + inputs.extend([node.input[0]]) + inputs.extend([quant_input_weight_tuple[0], quant_recurrent_weight_tuple[0]]) + inputs.extend([node.input[3] if input_len > 3 else ""]) + inputs.extend([node.input[4] if input_len > 4 else ""]) + inputs.extend([node.input[5] if input_len > 5 else ""]) + inputs.extend([node.input[6] if input_len > 6 else ""]) + inputs.extend([node.input[7] if input_len > 7 else ""]) + inputs.extend( + [ + quant_input_weight_tuple[2], + quant_input_weight_tuple[1], + quant_recurrent_weight_tuple[2], + quant_recurrent_weight_tuple[1], + ] + ) + + kwargs = {} + for attribute in node.attribute: + if attribute.name == "layout": + continue + kwargs.update(attribute_to_kwarg(attribute)) + kwargs["domain"] = ms_domain + + quant_lstm_name = "" if not node.name else node.name + "_quant" + quant_lstm_node = onnx.helper.make_node("DynamicQuantizeLSTM", inputs, node.output, quant_lstm_name, **kwargs) + self.quantizer.new_nodes.append(quant_lstm_node) + + dequantize_node = self.quantizer._dequantize_value(node.input[0]) + if dequantize_node is not None: + self.quantizer.new_nodes.append(dequantize_node) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/matmul.py b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/matmul.py new file mode 100644 index 0000000000000000000000000000000000000000..591cb2bbdbf307225ed7a66fd9c9224a55895b01 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/matmul.py @@ -0,0 +1,231 @@ +import itertools +import logging + +import onnx +from onnx import onnx_pb as onnx_proto + +from ..quant_utils import TENSOR_NAME_QUANT_SUFFIX, QuantizedValue, QuantizedValueType, find_by_name, get_mul_node +from .base_operator import QuantOperatorBase +from .qdq_base_operator import QDQOperatorBase + + +class QOpMatMul(QuantOperatorBase): + def __init__(self, onnx_quantizer, onnx_node): + super().__init__(onnx_quantizer, onnx_node) + + def should_quantize(self): + if not self.quantizer.should_quantize_node(self.node): + logging.debug(f"Ignore MatMul {self.node.name}]") + return False + + if (not self.quantizer.is_float_tensor(self.node.input[1])) and ( + not self.quantizer.is_float_tensor(self.node.input[0]) + ): + logging.info(f"Ignore MatMul due to non float inputs {self.node.name}]") + return False + + # do not quantize non-constant B matrices for matmul + if self.quantizer.q_matmul_const_b_only: + if not self.quantizer.find_initializer_in_path(self.node.input[1]): + logging.info(f"Ignore MatMul due to non constant B: {self.quantizer.graph_scope}[{self.node.name}]") + return False + return True + + +""" + Used when quantize mode is QuantizationMode.IntegerOps. +""" + + +class MatMulInteger(QOpMatMul): + def __init__(self, onnx_quantizer, onnx_node): + super().__init__(onnx_quantizer, onnx_node) + + def quantize(self): + node = self.node + assert node.op_type == "MatMul" + # Get Quantized from both activation(input[0]) and weight(input[1]) + ( + quantized_input_names, + zero_point_names, + scale_names, + nodes, + ) = self.quantizer.quantize_activation(node, [0]) + + ( + quantized_input_names_weight, + zero_point_names_weight, + scale_names_weight, + nodes_weight, + ) = self.quantizer.quantize_weight(node, [1], reduce_range=True, op_level_per_channel=True) + quantized_input_names.extend(quantized_input_names_weight) + zero_point_names.extend(zero_point_names_weight) + scale_names.extend(scale_names_weight) + nodes.extend(nodes_weight) + + matmul_integer_output = node.output[0] + "_output_quantized" + matmul_integer_name = node.name + "_quant" if node.name else "" + matmul_integer_node = onnx.helper.make_node( + "MatMulInteger", + quantized_input_names + zero_point_names, + [matmul_integer_output], + matmul_integer_name, + ) + nodes.append(matmul_integer_node) + + # Add cast operation to cast matmulInteger output to float. + cast_op_output = matmul_integer_output + "_cast_output" + otype = self.quantizer.get_tensor_type(node.output[0], mandatory=True) + cast_node = onnx.helper.make_node( + "Cast", + [matmul_integer_output], + [cast_op_output], + matmul_integer_output + "_cast", + to=otype, + ) + nodes.append(cast_node) + + # Add mul operation to multiply scales of two inputs. + assert len(scale_names) == 2 + scales_mul_op = ( + matmul_integer_name + "_scales_mul" + if matmul_integer_name + else scale_names[0] + "_" + scale_names[1] + "_mul" + ) + + scales_mul_node = find_by_name(scales_mul_op, self.quantizer.new_nodes) + if scales_mul_node is None: + scales_mul_node = get_mul_node(scale_names, scales_mul_op + ":0", scales_mul_op) + nodes.append(scales_mul_node) + + scales_mul_op_output = scales_mul_node.output[0] + + # Add mul operation to multiply mul_scales_op result with output of MatMulInteger + # and make the output of this node the same as output of original matmul node. + output_scale_mul_op = "" + if matmul_integer_name: + output_scale_mul_op = matmul_integer_name + "_output_scale_mul" + nodes.append( + get_mul_node( + [cast_op_output, scales_mul_op_output], + node.output[0], + output_scale_mul_op, + ) + ) + self.quantizer.new_nodes += nodes + + +""" + Used when quantize mode is QuantizationMode.QLinearOps +""" + + +class QLinearMatMul(QOpMatMul): + def __init__(self, onnx_quantizer, onnx_node): + super().__init__(onnx_quantizer, onnx_node) + + def quantize(self): + node = self.node + assert node.op_type == "MatMul" + # Get Quantized from both activation(input[0]) and weight(input[1]) + ( + quantized_input_names, + zero_point_names, + scale_names, + nodes, + ) = self.quantizer.quantize_activation(node, [0]) + + ( + quantized_input_names_weight, + zero_point_names_weight, + scale_names_weight, + nodes_weight, + ) = self.quantizer.quantize_weight(node, [1], reduce_range=True, op_level_per_channel=True) + quantized_input_names.extend(quantized_input_names_weight) + zero_point_names.extend(zero_point_names_weight) + scale_names.extend(scale_names_weight) + + nodes.extend(nodes_weight) + ( + data_found, + output_scale_name, + output_zp_name, + _, + _, + ) = self.quantizer._get_quantization_params(node.output[0]) + if not data_found or quantized_input_names is None: + return super().quantize() + + qlinear_matmul_output = node.output[0] + TENSOR_NAME_QUANT_SUFFIX + qlinear_matmul_name = node.name + "_quant" if node.name else "" + + qlinear_matmul_inputs = [] + # Input 0 + qlinear_matmul_inputs.append(quantized_input_names[0]) + qlinear_matmul_inputs.append(scale_names[0]) + qlinear_matmul_inputs.append(zero_point_names[0]) + # Input 1 + qlinear_matmul_inputs.append(quantized_input_names[1]) + qlinear_matmul_inputs.append(scale_names[1]) + qlinear_matmul_inputs.append(zero_point_names[1]) + # Output quantization parameter + qlinear_matmul_inputs.append(output_scale_name) + qlinear_matmul_inputs.append(output_zp_name) + + domain = ( + "com.microsoft" + if self.quantizer.weight_qType + in { + onnx_proto.TensorProto.FLOAT8E4M3FN, + onnx_proto.TensorProto.FLOAT8E4M3FNUZ, + onnx_proto.TensorProto.FLOAT8E5M2, + onnx_proto.TensorProto.FLOAT8E5M2FNUZ, + } + else "" + ) + qlinear_matmul_node = onnx.helper.make_node( + "QLinearMatMul", + qlinear_matmul_inputs, + [qlinear_matmul_output], + qlinear_matmul_name, + domain=domain, + ) + nodes.append(qlinear_matmul_node) + + # Create an entry for this quantized value + q_output = QuantizedValue( + node.output[0], + qlinear_matmul_output, + output_scale_name, + output_zp_name, + QuantizedValueType.Input, + ) + self.quantizer.quantized_value_map[node.output[0]] = q_output + + self.quantizer.new_nodes += nodes + + +class QDQMatMul(QDQOperatorBase): + def __init__(self, onnx_quantizer, onnx_node): + super().__init__(onnx_quantizer, onnx_node) + + def quantize(self): + node = self.node + assert node.op_type == "MatMul" + + if self.disable_qdq_for_node_output: + nodes_to_iterate = node.input + else: + nodes_to_iterate = itertools.chain(node.input, node.output) + + for tensor_name in nodes_to_iterate: + if find_by_name(tensor_name, self.quantizer.model.initializer()): + is_per_channel, channel_axis = self.quantizer.is_tensor_per_channel( + tensor_name, default_axis=1, op_type=node.op_type + ) + if is_per_channel: + self.quantizer.quantize_weight_tensor_per_channel(tensor_name, channel_axis) + else: + self.quantizer.quantize_weight_tensor(tensor_name) + else: + self.quantizer.quantize_activation_tensor(tensor_name) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/maxpool.py b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/maxpool.py new file mode 100644 index 0000000000000000000000000000000000000000..cb689b0aa5d9e8395e2d32f75d57a84a21794074 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/maxpool.py @@ -0,0 +1,34 @@ +from .direct_q8 import Direct8BitOp, QDQDirect8BitOp + + +class QMaxPool(Direct8BitOp): + def __init__(self, onnx_quantizer, onnx_node): + super().__init__(onnx_quantizer, onnx_node) + + def quantize(self): + node = self.node + assert node.op_type == "MaxPool" + + # if version is less than 12, go to normal quantize. + if self.quantizer.opset_version < 12: + super(Direct8BitOp, self).quantize() + return + + # Direct 8bits op + return super().quantize() + + +class QDQMaxPool(QDQDirect8BitOp): + def __init__(self, onnx_quantizer, onnx_node): + super().__init__(onnx_quantizer, onnx_node) + + def quantize(self): + node = self.node + assert node.op_type == "MaxPool" + + # if version is less than 12, just no change + if self.quantizer.opset_version < 12: + return + + # Direct 8bits op + return super().quantize() diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/norm.py b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/norm.py new file mode 100644 index 0000000000000000000000000000000000000000..d2b5147a61654a1a0e1b0ce63318939fd89c6733 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/norm.py @@ -0,0 +1,40 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +# -------------------------------------------------------------------------- + +from .qdq_base_operator import QDQOperatorBase + + +class QDQNormalization(QDQOperatorBase): + def __init__(self, onnx_quantizer, onnx_node): + super().__init__(onnx_quantizer, onnx_node) + + def quantize(self): + node = self.node + assert node.op_type in {"InstanceNormalization", "LayerNormalization", "BatchNormalization"} + + # Input + self.quantizer.quantize_activation_tensor(node.input[0]) + + # Scale + scale_is_initializer = self.quantizer.is_input_a_initializer(node.input[1]) + scale_is_per_channel, scale_channel_axis = self.quantizer.is_tensor_per_channel( + node.input[1], default_axis=1, op_type=node.op_type + ) + + if scale_is_per_channel: + self.quantizer.quantize_weight_tensor_per_channel(node.input[1], axis=scale_channel_axis) + elif scale_is_initializer: + self.quantizer.quantize_weight_tensor(node.input[1]) + else: + self.quantizer.quantize_activation_tensor(node.input[1]) + + # Bias + if len(node.input) > 2 and node.input[2]: + self.quantizer.quantize_bias_tensor(node.name, node.input[2], node.input[0], node.input[1]) + + # Output + if not self.disable_qdq_for_node_output: + for output_name in node.output: + self.quantizer.quantize_activation_tensor(output_name) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/pad.py b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/pad.py new file mode 100644 index 0000000000000000000000000000000000000000..2d5c8344a774c4814c23f2f4c379bbe80f1b5a3e --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/pad.py @@ -0,0 +1,172 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +# -------------------------------------------------------------------------- +from __future__ import annotations + +from typing import Any + +import numpy as np +import onnx + +from ..quant_utils import ( + TENSOR_NAME_QUANT_SUFFIX, + QuantizedValue, + QuantizedValueType, + attribute_to_kwarg, + quantize_nparray, +) +from .base_operator import QuantOperatorBase +from .qdq_base_operator import QDQOperatorBase + + +class QPad(QuantOperatorBase): + def __init__(self, onnx_quantizer, onnx_node): + super().__init__(onnx_quantizer, onnx_node) + + def quantize(self): + node = self.node + assert node.op_type == "Pad" + + # Only after version 11, it has the optional constant_value + # If input[0] is not quantized, do not quanitize this node + if (self.quantizer.opset_version < 11) or (node.input[0] not in self.quantizer.quantized_value_map): + super().quantize() + return + quantized_input_value = self.quantizer.quantized_value_map[node.input[0]] + + kwargs = {} + for attribute in node.attribute: + kv = attribute_to_kwarg(attribute) + kwargs.update(kv) + + if "mode" not in kwargs or kwargs["mode"] == b"constant": + if len(node.input) > 2 and node.input[2] != "": # There is 3rd input 'constant_value' + zp_tensor = self.quantizer.model.get_initializer(quantized_input_value.zp_name) + scale_tensor = self.quantizer.model.get_initializer(quantized_input_value.scale_name) + if zp_tensor is None or scale_tensor is None: + super().quantize() + return + + padding_constant_initializer = self.quantizer.model.get_initializer(node.input[2]) + if padding_constant_initializer is not None: + zp_array = onnx.numpy_helper.to_array(zp_tensor) + zp_value = zp_array.item() if zp_array.ndim == 0 else zp_array[0] + scale_array = onnx.numpy_helper.to_array(scale_tensor) + scale_value = scale_array.item() if scale_array.ndim == 0 else scale_array[0] + padding_constant_array = onnx.numpy_helper.to_array(padding_constant_initializer) + quantized_padding_constant_array = quantize_nparray( + self.quantizer.activation_qType, + padding_constant_array, + scale_value, + zp_value, + ) + quantized_padding_constant_name = node.input[2] + TENSOR_NAME_QUANT_SUFFIX + quantized_padding_constant_initializer = onnx.numpy_helper.from_array( + quantized_padding_constant_array, + quantized_padding_constant_name, + ) + # Suppose this padding constant initializer only used by the node + self.quantizer.model.remove_initializer(padding_constant_initializer) + self.quantizer.model.add_initializer(quantized_padding_constant_initializer) + node.input[2] = quantized_padding_constant_name + else: + # TODO: check quantize_inputs after sub graph is supported + pad_value_qnodes = self.quantizer._get_quantize_input_nodes( + node, + 2, + self.quantizer.activation_qType, + quantized_input_value.scale_name, + quantized_input_value.zp_name, + initial_type=scale_tensor.data_type, + ) + self.quantizer.new_nodes.extend(pad_value_qnodes) + node.input[2] = pad_value_qnodes[0].output[0] + else: + # In quantized format, the `zero` before quantization is mapped + # to quantized_input_value.zp_name. Thus, padding 0 to + # original tensor should become padding zero point to quantized + # tensor. + if len(node.input) == 2: + # Feed quantization's zero point to padding node. + node.input.append(quantized_input_value.zp_name) + else: + # Assign quantization's zero point to padding node. + assert node.input[2] == "" + node.input[2] = quantized_input_value.zp_name + + # Create an entry for output quantized value + quantized_output_value = QuantizedValue( + node.output[0], + node.output[0] + TENSOR_NAME_QUANT_SUFFIX, + quantized_input_value.scale_name, + quantized_input_value.zp_name, + QuantizedValueType.Input, + ) + self.quantizer.quantized_value_map[node.output[0]] = quantized_output_value + + node.input[0] = quantized_input_value.q_name + node.output[0] = quantized_output_value.q_name + self.quantizer.new_nodes += [node] + + +class QDQPad(QDQOperatorBase): + def __init__(self, onnx_quantizer, onnx_node): + super().__init__(onnx_quantizer, onnx_node) + + def _get_pad_const_val(self, attrs_dict: dict[str, Any]) -> np.ndarray | None: + """ + Returns the Pad's constant padding value. Returns `None` if the padding value is + not constant (i.e., comes from a dynamic input). + """ + const_val = None + onnx_tensor_type = self.quantizer.model.get_tensor_type(self.node.input[0]) + if onnx_tensor_type is None: + return None + + np_dtype = onnx.helper.tensor_dtype_to_np_dtype(onnx_tensor_type.elem_type) + if self.quantizer.opset_version < 11: + const_val = np.array(attrs_dict.get("value", 0), dtype=np_dtype) + elif len(self.node.input) >= 3 and self.node.input[2]: + const_val = self.quantizer.model.get_constant_value(self.node.input[2]) + else: + const_val = np.array(0, dtype=np_dtype) + + return const_val + + def _should_quantize_output_same_as_input(self) -> bool: + """ + Returns true if Pad's output should use the same quantization parameters as input[0] + """ + attrs_dict = {} + for attribute in self.node.attribute: + kv = attribute_to_kwarg(attribute) + attrs_dict.update(kv) + + pad_mode = attrs_dict.get("mode", b"constant") + if pad_mode in (b"reflect", b"edge", b"wrap"): + # These modes pad the output with a value that already exists in the input. + # So, we can quantize the output the same as the input. + return True + + # For 'constant' mode, if padding with 0, we can also quantize the output the same as the input + # because our quantization floating-point range always includes 0. + if pad_mode == b"constant": + pad_val = self._get_pad_const_val(attrs_dict) + if pad_val is not None and pad_val.dtype in (np.float32, np.float16): + return float(pad_val.item()) == 0 + + return False + + def quantize(self): + assert self.node.op_type == "Pad" + + for input_name in self.node.input: + if input_name: + self.quantizer.quantize_activation_tensor(input_name) + + if not self.disable_qdq_for_node_output: + if self._should_quantize_output_same_as_input(): + self.quantizer.quantize_output_same_as_input(self.node.output[0], self.node.input[0], self.node.name) + else: + self.quantizer.quantize_activation_tensor(self.node.output[0]) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/pooling.py b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/pooling.py new file mode 100644 index 0000000000000000000000000000000000000000..7595e756eeedbb144fe6ebd954fd09f05ad32516 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/pooling.py @@ -0,0 +1,67 @@ +import onnx + +from ..quant_utils import TENSOR_NAME_QUANT_SUFFIX, QuantizedValue, QuantizedValueType, attribute_to_kwarg, ms_domain +from .base_operator import QuantOperatorBase + + +class QLinearPool(QuantOperatorBase): + def __init__(self, onnx_quantizer, onnx_node): + super().__init__(onnx_quantizer, onnx_node) + + def quantize(self): + node = self.node + + # only try to quantize when given quantization parameters for it + ( + data_found, + output_scale_name, + output_zp_name, + _, + _, + ) = self.quantizer._get_quantization_params(node.output[0]) + + # get quantized input tensor names, quantize input if needed + ( + quantized_input_names, + input_zero_point_names, + input_scale_names, + nodes, + ) = self.quantizer.quantize_activation(node, [0]) + + if not data_found or quantized_input_names is None: + return super().quantize() + + # Create an entry for output quantized value. + qlinear_output_name = node.output[0] + TENSOR_NAME_QUANT_SUFFIX + quantized_output_value = QuantizedValue( + node.output[0], + qlinear_output_name, + output_scale_name, + output_zp_name, + QuantizedValueType.Input, + ) + self.quantizer.quantized_value_map[node.output[0]] = quantized_output_value + + # Create qlinear pool node for given type (AveragePool, etc) + kwargs = {} + for attribute in node.attribute: + kwargs.update(attribute_to_kwarg(attribute)) + kwargs["domain"] = ms_domain + qlinear_node_name = node.name + "_quant" if node.name else "" + qnode = onnx.helper.make_node( + "QLinear" + node.op_type, + [ + quantized_input_names[0], + input_scale_names[0], + input_zero_point_names[0], + output_scale_name, + output_zp_name, + ], + [qlinear_output_name], + qlinear_node_name, + **kwargs, + ) + + # add all newly created nodes + nodes.append(qnode) + self.quantizer.new_nodes += nodes diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/qdq_base_operator.py b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/qdq_base_operator.py new file mode 100644 index 0000000000000000000000000000000000000000..0ad2829b607aa49176375534edc23d877f0b3375 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/qdq_base_operator.py @@ -0,0 +1,22 @@ +import itertools + +from ..quant_utils import QuantizedValue, QuantizedValueType, attribute_to_kwarg, quantize_nparray # noqa: F401 +from .base_operator import QuantOperatorBase # noqa: F401 + + +class QDQOperatorBase: + def __init__(self, onnx_quantizer, onnx_node): + self.quantizer = onnx_quantizer + self.node = onnx_node + self.disable_qdq_for_node_output = onnx_node.op_type in onnx_quantizer.op_types_to_exclude_output_quantization + + def quantize(self): + node = self.node + + if self.disable_qdq_for_node_output: + tensors_to_quantize = node.input + else: + tensors_to_quantize = itertools.chain(node.input, node.output) + + for tensor_name in tensors_to_quantize: + self.quantizer.quantize_activation_tensor(tensor_name) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/resize.py b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/resize.py new file mode 100644 index 0000000000000000000000000000000000000000..1604965025a3035f42a4438d0d971be94eb5305f --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/resize.py @@ -0,0 +1,34 @@ +from .direct_q8 import Direct8BitOp, QDQDirect8BitOp + + +class QResize(Direct8BitOp): + def __init__(self, onnx_quantizer, onnx_node): + super().__init__(onnx_quantizer, onnx_node) + + def quantize(self): + node = self.node + assert node.op_type == "Resize" + + # if version is less than 11, go to normal quantize. + if self.quantizer.opset_version < 11: + super(Direct8BitOp, self).quantize() + return + + # Direct 8bits op + return super().quantize() + + +class QDQResize(QDQDirect8BitOp): + def __init__(self, onnx_quantizer, onnx_node): + super().__init__(onnx_quantizer, onnx_node) + + def quantize(self): + node = self.node + assert node.op_type == "Resize" + + # if version is less than 11, just keep this node + if self.quantizer.opset_version < 11: + return + + # Direct 8bits op + return super().quantize() diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/softmax.py b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/softmax.py new file mode 100644 index 0000000000000000000000000000000000000000..5e34fd742755c41f7ad6508f0e071294beb3b3b5 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/softmax.py @@ -0,0 +1,74 @@ +import onnx +import onnx.helper + +from ..quant_utils import TENSOR_NAME_QUANT_SUFFIX, QuantizedValue, QuantizedValueType, attribute_to_kwarg, ms_domain +from .base_operator import QuantOperatorBase + + +class QLinearSoftmax(QuantOperatorBase): + def quantize(self): + node = self.node + # set limitations for softmax output scale and zp, because the output of softmax is always 0-1 + if self.quantizer.activation_qType == onnx.onnx_pb.TensorProto.UINT8: + out_scale = 1 / 256.0 + out_zero_point = 0 + else: + out_scale = 1 / 256.0 + out_zero_point = -128 + # only try to quantize when given quantization parameters for it + ( + data_found, + output_scale_name, + output_zp_name, + _, + _, + ) = self.quantizer._get_quantization_params(node.output[0], out_scale, out_zero_point) + + # get quantized input tensor names, quantize input if needed + ( + quantized_input_names, + input_zero_point_names, + input_scale_names, + nodes, + ) = self.quantizer.quantize_activation(node, [0]) + + if not data_found or quantized_input_names is None: + return super().quantize() + + # Create an entry for output quantized value. + qlinear_output_name = node.output[0] + TENSOR_NAME_QUANT_SUFFIX + quantized_output_value = QuantizedValue( + node.output[0], + qlinear_output_name, + output_scale_name, + output_zp_name, + QuantizedValueType.Input, + ) + self.quantizer.quantized_value_map[node.output[0]] = quantized_output_value + + # Create qlinear softmax node for given type + kwargs = {} + for attribute in node.attribute: + kwargs.update(attribute_to_kwarg(attribute)) + kwargs["domain"] = ms_domain + # make qlinearsoft has the real opset_version, its default SinceVersion would be 1 + kwargs["opset"] = self.quantizer.opset_version + qlinear_node_name = node.name + "_quant" if node.name else "" + qnode = onnx.helper.make_node( + "QLinear" + node.op_type, + [ + quantized_input_names[0], + input_scale_names[0], + input_zero_point_names[0], + output_scale_name, + output_zp_name, + ], + [qlinear_output_name], + qlinear_node_name, + **kwargs, + ) + + # add all newly created nodes + nodes.append(qnode) + self.quantizer.new_nodes += nodes + return None diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/split.py b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/split.py new file mode 100644 index 0000000000000000000000000000000000000000..2fd8e9f1655a5b69c8385c6c0b115a312dccbe9d --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/split.py @@ -0,0 +1,63 @@ +import onnx + +from ..quant_utils import QuantizedValue, QuantizedValueType, attribute_to_kwarg +from .base_operator import QuantOperatorBase +from .qdq_base_operator import QDQOperatorBase + + +class QSplit(QuantOperatorBase): + def __init__(self, onnx_quantizer, onnx_node): + super().__init__(onnx_quantizer, onnx_node) + + def quantize(self): + node = self.node + ( + quantized_input_names, + zero_point_names, + scale_names, + nodes, + ) = self.quantizer.quantize_activation(node, [0]) + if quantized_input_names is None: + return super().quantize() + + quantized_node_name = "" + if node.name: + quantized_node_name = node.name + "_quant" + kwargs = {} + for attribute in node.attribute: + kwargs.update(attribute_to_kwarg(attribute)) + + # Output just derive the scale/zero from input + quantized_output_names = [] + for output_name in node.output: + quantized_output_name = output_name + "quantized" + quantized_output_names.append(quantized_output_name) + q_output = QuantizedValue( + output_name, + quantized_output_name, + scale_names[0], + zero_point_names[0], + QuantizedValueType.Input, + ) + self.quantizer.quantized_value_map[output_name] = q_output + + if len(node.input) > 1: + quantized_input_names.extend(node.input[1:]) + quantized_node = onnx.helper.make_node( + node.op_type, quantized_input_names, quantized_output_names, quantized_node_name, **kwargs + ) + + nodes.append(quantized_node) + self.quantizer.new_nodes += nodes + + +class QDQSplit(QDQOperatorBase): + def quantize(self): + node = self.node + assert node.op_type == "Split" + + if not self.quantizer.is_tensor_quantized(node.input[0]): + self.quantizer.quantize_activation_tensor(node.input[0]) + if not self.disable_qdq_for_node_output: + for output in node.output: + self.quantizer.quantize_output_same_as_input(output, node.input[0], node.name) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/where.py b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/where.py new file mode 100644 index 0000000000000000000000000000000000000000..993be45ee8cfa99a0f4efd3d712a5c768e2a6fd2 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/quantization/operators/where.py @@ -0,0 +1,87 @@ +import onnx + +from ..quant_utils import TENSOR_NAME_QUANT_SUFFIX, QuantizedValue, QuantizedValueType, attribute_to_kwarg, ms_domain +from .base_operator import QuantOperatorBase +from .qdq_base_operator import QDQOperatorBase + + +class QLinearWhere(QuantOperatorBase): + def should_quantize(self): + return True + + def quantize(self): + node = self.node + assert node.op_type == "Where" + if not self.quantizer.force_quantize_no_input_check: + self.quantizer.new_nodes += [node] + return + ( + data_found, + output_scale_name, + output_zp_name, + _, + _, + ) = self.quantizer._get_quantization_params(node.output[0]) + ( + q_input_names, + zero_point_names, + scale_names, + nodes, + ) = self.quantizer.quantize_activation(node, [1, 2]) + if not data_found or q_input_names is None: + return super().quantize() + qlinear_output = node.output[0] + TENSOR_NAME_QUANT_SUFFIX + qlinear_output_name = node.name + "_quant" if node.name else "" + + q_output = QuantizedValue( + node.output[0], + qlinear_output, + output_scale_name, + output_zp_name, + QuantizedValueType.Input, + ) + self.quantizer.quantized_value_map[node.output[0]] = q_output + + kwargs = {} + for attribute in node.attribute: + kwargs.update(attribute_to_kwarg(attribute)) + kwargs["domain"] = ms_domain + + qlwhere_inputs = [ + node.input[0], + q_input_names[0], + scale_names[0], + zero_point_names[0], + q_input_names[1], + scale_names[1], + zero_point_names[1], + output_scale_name, + output_zp_name, + ] + qlwhere_node = onnx.helper.make_node( + "QLinearWhere", qlwhere_inputs, [qlinear_output], qlinear_output_name, **kwargs + ) + + self.quantizer.new_nodes += nodes + self.quantizer.new_nodes += [qlwhere_node] + + +class QDQWhere(QDQOperatorBase): + def quantize(self): + node = self.node + assert node.op_type == "Where" + if self.quantizer.force_quantize_no_input_check: + if not self.quantizer.is_tensor_quantized(node.input[1]): + self.quantizer.quantize_activation_tensor(node.input[1]) + if not self.quantizer.is_tensor_quantized(node.input[2]): + self.quantizer.quantize_activation_tensor(node.input[2]) + if not self.disable_qdq_for_node_output: + for output in node.output: + self.quantizer.quantize_activation_tensor(output) + elif ( + self.quantizer.is_tensor_quantized(node.input[1]) + and self.quantizer.is_tensor_quantized(node.input[2]) + and not self.disable_qdq_for_node_output + ): + for output in node.output: + self.quantizer.quantize_activation_tensor(output) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/tools/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a7ba72077568695ced9971bcab637f59d4e4559e Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/tools/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/__pycache__/check_onnx_model_mobile_usability.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/tools/__pycache__/check_onnx_model_mobile_usability.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..35ac32351952dad32cba9b51d85eedc386c0773c Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/tools/__pycache__/check_onnx_model_mobile_usability.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/__pycache__/convert_onnx_models_to_ort.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/tools/__pycache__/convert_onnx_models_to_ort.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..01d7c0a5b26401dca002550d958502290781ac79 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/tools/__pycache__/convert_onnx_models_to_ort.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/__pycache__/file_utils.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/tools/__pycache__/file_utils.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f990af87a0aa315e4538cb51814f45b6b4192008 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/tools/__pycache__/file_utils.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/__pycache__/logger.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/tools/__pycache__/logger.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8c9d9f48dec5cefd38a8d146c5bee653fabfb9b6 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/tools/__pycache__/logger.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/__pycache__/make_dynamic_shape_fixed.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/tools/__pycache__/make_dynamic_shape_fixed.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0170bb61aaa023e0e75cb661954fdd40046a4325 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/tools/__pycache__/make_dynamic_shape_fixed.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/__pycache__/offline_tuning.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/tools/__pycache__/offline_tuning.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..79c20ddc0b73f3a2a3d436a3bc28672036884caf Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/tools/__pycache__/offline_tuning.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/__pycache__/onnx_model_utils.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/tools/__pycache__/onnx_model_utils.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..19b284662ba931253074b1cf707ae0e24fa9367a Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/tools/__pycache__/onnx_model_utils.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/__pycache__/onnx_randomizer.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/tools/__pycache__/onnx_randomizer.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f346bd87b9f3f139b14d860bcdac3862f0f2f50c Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/tools/__pycache__/onnx_randomizer.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/__pycache__/onnxruntime_test.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/tools/__pycache__/onnxruntime_test.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6a180156ed58f36bab6a1685e8dd4d3812b0f668 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/tools/__pycache__/onnxruntime_test.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/__pycache__/optimize_onnx_model.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/tools/__pycache__/optimize_onnx_model.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4dca6a3b4b6a4fa8cfa21a43fa6825eca3336bd0 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/tools/__pycache__/optimize_onnx_model.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/__pycache__/pytorch_export_contrib_ops.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/tools/__pycache__/pytorch_export_contrib_ops.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c459b5fe0ec451bfd2fb467def6974296fcae150 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/tools/__pycache__/pytorch_export_contrib_ops.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/__pycache__/pytorch_export_helpers.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/tools/__pycache__/pytorch_export_helpers.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..daacbb46f09d21c94c8df449741e8678b491dd16 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/tools/__pycache__/pytorch_export_helpers.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/__pycache__/reduced_build_config_parser.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/tools/__pycache__/reduced_build_config_parser.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..242e557be9d480660719aad787f6b04f0a13486d Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/tools/__pycache__/reduced_build_config_parser.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/__pycache__/remove_initializer_from_input.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/tools/__pycache__/remove_initializer_from_input.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..452bbe32869967611149a0e520b5e6d23bbbf1a3 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/tools/__pycache__/remove_initializer_from_input.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/__pycache__/update_onnx_opset.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/tools/__pycache__/update_onnx_opset.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d4e76f12c356424e800c42eff556c19cf7b62238 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/tools/__pycache__/update_onnx_opset.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/mobile_helpers/__init__.py b/python/user_packages/Python313/site-packages/onnxruntime/tools/mobile_helpers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/mobile_helpers/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/tools/mobile_helpers/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f04dab8abb900614422915df376a6987adc6f6e3 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/tools/mobile_helpers/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/mobile_helpers/__pycache__/usability_checker.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/tools/mobile_helpers/__pycache__/usability_checker.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7da1597c5e79bf433f8b19703a01777562fc9d35 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/tools/mobile_helpers/__pycache__/usability_checker.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/mobile_helpers/coreml_supported_mlprogram_ops.md b/python/user_packages/Python313/site-packages/onnxruntime/tools/mobile_helpers/coreml_supported_mlprogram_ops.md new file mode 100644 index 0000000000000000000000000000000000000000..f1bd98c4cc89516116461709e29ddcf211eedb66 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/tools/mobile_helpers/coreml_supported_mlprogram_ops.md @@ -0,0 +1,55 @@ + +|Operator|Note| +|--------|------| +|ai.onnx:Add|| +|ai.onnx:Argmax|| +|ai.onnx:AveragePool|Only 2D Pool is supported currently. 3D and 5D support can be added if needed.| +|ai.onnx:Cast|| +|ai.onnx:Clip|| +|ai.onnx:Concat|| +|ai.onnx:Conv|Only 1D/2D Conv is supported.
Bias if provided must be constant.| +|ai.onnx:ConvTranspose|Weight and bias must be constant.
padding_type of SAME_UPPER/SAME_LOWER is not supported.
kernel_shape must have default values.
output_shape is not supported.
output_padding must have default values.| +|ai.onnx:DepthToSpace|If 'mode' is 'CRD' the input must have a fixed shape.| +|ai.onnx:Div|| +|ai.onnx:Elu|| +|ai.onnx:Erf|| +|ai.onnx:Exp|| +|ai.onnx:Gemm|Input B must be constant.| +|ai.onnx:Gelu|| +|ai.onnx:GlobalAveragePool|Only 2D Pool is supported currently. 3D and 5D support can be added if needed.| +|ai.onnx:GlobalMaxPool|Only 2D Pool is supported currently. 3D and 5D support can be added if needed.| +|ai.onnx:GridSample|4D input.
'mode' of 'linear' or 'zeros'.
(mode==linear && padding_mode==reflection && align_corners==0) is not supported.| +|ai.onnx:GroupNormalization|| +|ai.onnx:HardSigmoid|| +|ai.onnx:InstanceNormalization|| +|ai.onnx:LayerNormalization|| +|ai.onnx:LeakyRelu|| +|ai.onnx:MatMul|Only support for transA == 0, alpha == 1.0 and beta == 1.0 is currently implemented.| +|ai.onnx:MaxPool|Only 2D Pool is supported currently. 3D and 5D support can be added if needed.| +|ai.onnx:Max|| +|ai.onnx:Mul|| +|ai.onnx:Pow|Only supports cases when both inputs are fp32.| +|ai.onnx:PRelu|| +|ai.onnx:Reciprocal|this ask for a `epislon` (default 1e-4) where onnx don't provide| +|ai.onnx:ReduceSum|| +|ai.onnx:ReduceMean|| +|ai.onnx:ReduceMax|| +|ai.onnx:Relu|| +|ai.onnx:Reshape|| +|ai.onnx:Resize|See [resize_op_builder.cc](https://github.com/microsoft/onnxruntime/blob/main/onnxruntime/core/providers/coreml/builders/impl/resize_op_builder.cc) implementation. There are too many permutations to describe the valid combinations.| +|ai.onnx:Round|| +|ai.onnx:Shape|| +|ai.onnx:Slice|starts/ends/axes/steps must be constant initializers.| +|ai.onnx:Softplus|| +|ai.onnx:Split|If provided, `splits` must be constant.| +|ai.onnx:Sub|| +|ai.onnx:Sigmoid|| +|ai.onnx:Softmax|| +|ai.onnx:Sqrt|| +|ai.onnx:Squeeze|| +|ai.onnx:Tanh|| +|ai.onnx:Transpose|| +|ai.onnx:Unsqueeze|| +|com.microsoft:QuickGelu|Produced by ORT's `QuickGeluFusion` optimizer pass. Decomposed into `mul` / `sigmoid` / `mul`.| diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/mobile_helpers/coreml_supported_neuralnetwork_ops.md b/python/user_packages/Python313/site-packages/onnxruntime/tools/mobile_helpers/coreml_supported_neuralnetwork_ops.md new file mode 100644 index 0000000000000000000000000000000000000000..d32dcc44011abe55fabbe5414100ee696243fea2 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/tools/mobile_helpers/coreml_supported_neuralnetwork_ops.md @@ -0,0 +1,43 @@ + +|Operator|Note| +|--------|------| +|ai.onnx:Add|| +|ai.onnx:ArgMax|| +|ai.onnx:AveragePool|Only 2D Pool is supported.| +|ai.onnx:BatchNormalization|| +|ai.onnx:Cast|| +|ai.onnx:Clip|| +|ai.onnx:Concat|| +|ai.onnx:Conv|Only 1D/2D Conv is supported.
Weights and bias should be constant.| +|ai.onnx:DepthToSpace|Only DCR mode DepthToSpace is supported.| +|ai.onnx:Div|| +|ai.onnx:Flatten|| +|ai.onnx:Gather|Input `indices` with scalar value is not supported.| +|ai.onnx:Gemm|Input B should be constant.| +|ai.onnx:GlobalAveragePool|Only 2D Pool is supported.| +|ai.onnx:GlobalMaxPool|Only 2D Pool is supported.| +|ai.onnx:LeakyRelu|| +|ai.onnx:LRN|| +|ai.onnx:MatMul|Input B should be constant.| +|ai.onnx:MaxPool|Only 2D Pool is supported.| +|ai.onnx:Mul|| +|ai.onnx:Pad|Only constant mode and last two dim padding is supported.
Input pads and constant_value should be constant.
If provided, axes should be constant.| +|ai.onnx:Pow|Only supports cases when both inputs are fp32.| +|ai.onnx:PRelu|Input slope should be constant.
Input slope should either have shape [C, 1, 1] or have 1 element.| +|ai.onnx:Reciprocal|| +|ai.onnx.ReduceSum|| +|ai.onnx:Relu|| +|ai.onnx:Reshape|| +|ai.onnx:Resize|4D input.
`coordinate_transformation_mode` == `asymmetric`.
`mode` == `linear` or `nearest`.
`nearest_mode` == `floor`.
`exclude_outside` == false
`scales` or `sizes` must be constant.| +|ai.onnx:Shape|Attribute `start` with non-default value is not supported.
Attribute `end` is not supported.| +|ai.onnx:Sigmoid|| +|ai.onnx:Slice|Inputs `starts`, `ends`, `axes`, and `steps` should be constant. Empty slice is not supported.| +|ai.onnx:Softmax|| +|ai.onnx:Split|If provided, `splits` must be constant.| +|ai.onnx:Squeeze|| +|ai.onnx:Sqrt|| +|ai.onnx:Sub|| +|ai.onnx:Tanh|| +|ai.onnx:Transpose|| diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/mobile_helpers/nnapi_supported_ops.md b/python/user_packages/Python313/site-packages/onnxruntime/tools/mobile_helpers/nnapi_supported_ops.md new file mode 100644 index 0000000000000000000000000000000000000000..9c417760bb7a05f167dd7e6963cd09f04410e19f --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/tools/mobile_helpers/nnapi_supported_ops.md @@ -0,0 +1,58 @@ + +|Operator|Note| +|--------|------| +|ai.onnx:Abs|| +|ai.onnx:Add|| +|ai.onnx:AveragePool|Only 2D Pool is supported.| +|ai.onnx:BatchNormalization|| +|ai.onnx:Cast|| +|ai.onnx:Clip|| +|ai.onnx:Concat|| +|ai.onnx:Conv|Only 2D Conv is supported.
Weights and bias should be constant.| +|ai.onnx:DepthToSpace|Only DCR mode DepthToSpace is supported.| +|ai.onnx:DequantizeLinear|All quantization scales and zero points should be constant.| +|ai.onnx:Div|| +|ai.onnx:Elu|| +|ai.onnx:Exp|| +|ai.onnx:Flatten|| +|ai.onnx:Floor|| +|ai.onnx:Gather|Input indices should be constant if not int32 type.| +|ai.onnx:Gemm|If input B is not constant, transB should be 1.| +|ai.onnx:GlobalAveragePool|Only 2D Pool is supported.| +|ai.onnx:GlobalMaxPool|Only 2D Pool is supported.| +|ai.onnx:Identity|| +|ai.onnx:LeakyRelu|| +|ai.onnx:Log|| +|ai.onnx:LRN|| +|ai.onnx:MatMul|| +|ai.onnx:MaxPool|Only 2D Pool is supported.| +|ai.onnx:Max|| +|ai.onnx:Min|| +|ai.onnx:Mul|| +|ai.onnx:Neg|| +|ai.onnx:Pad|Only constant mode Pad is supported.
Input pads and constant_value should be constant.
Input pads values should be non-negative.| +|ai.onnx:Pow|| +|ai.onnx:PRelu|| +|ai.onnx:QLinearConv|Only 2D Conv is supported.
Weights and bias should be constant.
All quantization scales and zero points should be constant.| +|ai.onnx:QLinearMatMul|All quantization scales and zero points should be constant.| +|ai.onnx:QuantizeLinear|All quantization scales and zero points should be constant.| +|ai.onnx:ReduceMean|| +|ai.onnx:Relu|| +|ai.onnx:Reshape|| +|ai.onnx:Resize|Only 2D Resize is supported.| +|ai.onnx:Sigmoid|| +|ai.onnx:Sin|| +|ai.onnx:Slice|| +|ai.onnx:Softmax|| +|ai.onnx:Split|Number of splits must evenly divide split axis size. Input split should be constant if provided.| +|ai.onnx:Sqrt|| +|ai.onnx:Squeeze|Input axes should be constant.| +|ai.onnx:Sub|| +|ai.onnx:Tanh|| +|ai.onnx:Transpose|| +|ai.onnx:Unsqueeze|Input axes should be constant.| +|com.microsoft:QLinearAdd|All quantization scales and zero points should be constant.| +|com.microsoft:QLinearAveragePool|Only 2D Pool is supported.
All quantization scales and zero points should be constant.| +|com.microsoft:QLinearSigmoid|All quantization scales and zero points should be constant.| diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/mobile_helpers/usability_checker.py b/python/user_packages/Python313/site-packages/onnxruntime/tools/mobile_helpers/usability_checker.py new file mode 100644 index 0000000000000000000000000000000000000000..2ac6e776378dc0ce6324fe139b7652181e83e1c2 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/tools/mobile_helpers/usability_checker.py @@ -0,0 +1,738 @@ +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +from __future__ import annotations + +import argparse +import logging +import os +import pathlib +import tempfile +from collections import deque +from enum import IntEnum + +import onnx + +from ..onnx_model_utils import ModelProtoWithShapeInfo, get_producer_consumer_maps, is_fixed_size_tensor, optimize_model + + +class _SupportedOpsChecker: + """ + Class to process the md file with list of supported ops and caveats for an execution provider. + e.g. /tools/ci_build/github/android/nnapi_supported_ops.md + /tools/ci_build/github/apple/coreml_supported_mlprogram_ops.md + /tools/ci_build/github/apple/coreml_supported_neuralnetwork_ops.md + """ + + def __init__(self, filename): + self._filename = filename + self._ops = {} # op to caveats + self._ops_seen = set() + + with open(filename) as f: + for line in f: + # we're looking for a markdown table with 2 columns. first is op name. second is caveats + # op name is domain:op + if line.startswith("|"): + pieces = line.strip().split("|") + if len(pieces) == 4: # pre-first '|'. op, caveat, post-last '|' + domain_op = pieces[1] + caveat = pieces[2] + caveat = caveat.replace("
", " ") # remove some HTML tags + # skip lines that don't have the ':' which separates the domain and op + # e.g. the table header will fail this check + if ":" in domain_op: + self._ops[domain_op] = caveat + + def is_op_supported(self, node): + domain = node.domain if node.domain else "ai.onnx" + domain_op = domain + ":" + node.op_type + + is_supported = domain_op in self._ops + if is_supported: + self._ops_seen.add(domain_op) + + return is_supported + + def get_caveats(self): + caveats = [] + for op in sorted(self._ops_seen): + caveat = self._ops[op] + if caveat: + caveats.append(f"{op}:{caveat}") + + return caveats + + +class PartitioningInfo: + class TryWithEP(IntEnum): + NO = (0,) + MAYBE = (1,) + YES = 2 + + def __init__( + self, + num_nodes: int, + num_supported_nodes: int, + num_partitions: int, + supported_ops_checker: _SupportedOpsChecker, + supported_groups: list[onnx.NodeProto], + unsupported_ops: set[str], + nodes_unsupported_due_to_op: int, + nodes_unsupported_due_to_dynamic_input: int, + num_unsupported_nodes_due_to_rank: int, + ops_with_unsupported_rank: set[str], + ): + self.num_nodes = num_nodes + self.num_supported_nodes = num_supported_nodes + self.num_partitions = num_partitions + self.supported_ops_checker = supported_ops_checker + self.supported_groups = supported_groups + self.unsupported_ops = unsupported_ops + self.nodes_unsupported_due_to_op = nodes_unsupported_due_to_op + self.nodes_unsupported_due_to_dynamic_input = nodes_unsupported_due_to_dynamic_input + self.num_unsupported_nodes_due_to_rank = num_unsupported_nodes_due_to_rank + self.ops_with_unsupported_rank = ops_with_unsupported_rank + + self.num_subgraphs = 0 + self.num_nodes_in_subgraphs = 0 + + def merge(self, other: PartitioningInfo): + """ + Merge the information from another PartitioningInfo instance into this one. + """ + self.num_nodes += other.num_nodes + self.num_supported_nodes += other.num_supported_nodes + self.num_partitions += other.num_partitions + self.supported_groups.extend(other.supported_groups) + self.unsupported_ops.update(other.unsupported_ops) + self.nodes_unsupported_due_to_op += other.nodes_unsupported_due_to_op + self.nodes_unsupported_due_to_dynamic_input += other.nodes_unsupported_due_to_dynamic_input + self.num_unsupported_nodes_due_to_rank += other.num_unsupported_nodes_due_to_rank + self.ops_with_unsupported_rank.update(other.ops_with_unsupported_rank) + + # hard assumption that we merge into the main graph partitioning info + self.num_subgraphs += 1 + self.num_nodes_in_subgraphs += other.num_nodes + + def suitability(self): + # semi-arbitrary choices that err on the side of MAYBE. + # having 1 partition is always preferred, but if that is small it may not be useful. + # having 2 partitions may be okay if they cover most nodes + # more than 2 partitions and the device copy cost is almost guaranteed to outweigh the benefit of using the NPU + # NOTE: This assumes the EP is not CPU based and there is device copy overhead to consider + pct_supported = self.num_supported_nodes / self.num_nodes * 100 + if self.num_partitions == 1: + if pct_supported > 75: + return PartitioningInfo.TryWithEP.YES + elif pct_supported > 50: + return PartitioningInfo.TryWithEP.MAYBE + else: + return PartitioningInfo.TryWithEP.NO + + if self.num_partitions == 2: + if pct_supported > 75: + return PartitioningInfo.TryWithEP.MAYBE + else: + return PartitioningInfo.TryWithEP.NO + + return PartitioningInfo.TryWithEP.NO + + def print_analysis(self, logger: logging.Logger, ep_name: str): + """ + Analyze the partitioning information and log the analysis + :param logger: Logger to use + :param ep_name: Execution provider name to use in the log messages + """ + + logger.info( + f"{self.num_partitions} partitions with a total of {self.num_supported_nodes}/{self.num_nodes} " + f"nodes can be handled by the {ep_name} EP." + ) + + if self.supported_groups: + logger.info( + f"\tPartition sizes: [{', '.join([str(len(partition)) for partition in self.supported_groups])}]" + ) + + # dump full groups if debug output is enabled + for group in self.supported_groups: + logger.debug(f"Nodes in group: {','.join([f'{node.op_type}:{node.name}' for node in group])}") + + logger.info(f"Unsupported nodes due to operator={self.nodes_unsupported_due_to_op}") + if self.unsupported_ops: + logger.info(f"\tUnsupported ops: {','.join(sorted(self.unsupported_ops))}") + + caveats = self.supported_ops_checker.get_caveats() + if caveats: + indent = " " * 5 + logger.info( + "\tCaveats that have not been checked and may result in a node not actually being supported: " + f"{''.join([os.linesep + indent + caveat for caveat in caveats])}" + ) + + if self.nodes_unsupported_due_to_dynamic_input: + logger.info( + "Unsupported nodes due to input having a dynamic shape=%d", + self.nodes_unsupported_due_to_dynamic_input, + ) + + if self.num_unsupported_nodes_due_to_rank: + logger.info(f"Unsupported nodes due to rank of input data={self.num_unsupported_nodes_due_to_rank}") + logger.info(f"\tOps with unsupported rank: {','.join(sorted(self.ops_with_unsupported_rank))}") + + if self.num_subgraphs > 0: + # TODO: CoreML has a flag. NNAPI doesn't. Either should be able to support a subgraph when treated as a + # separate graph (only extra detail would be making sure implicit inputs are handled). + # Merging the subgraph into the parent graph would be more complex. + # e.g. for CoreML we could potentially convert Loop to while_loop and If to cond if the subgraphs in the + # control flow node are fully supported. + # NNAPI also has While and If. + + # It most likely will be necessary to support merging in If nodes with fully supported subgraphs, + # as the subgraphs in those are often very simple, so the performance cost of going to the CPU EP and back + # is high. + logger.info( + f"{self.num_nodes_in_subgraphs} nodes are in {self.num_subgraphs} subgraphs. " + "Check EP as to whether subgraphs are supported." + ) + + pct_nodes_using_ep = self.num_supported_nodes / self.num_nodes * 100 + if self.num_partitions == 0: + logger.info(f"{ep_name} cannot run any nodes in this model.") + elif self.num_partitions == 1: + if pct_nodes_using_ep > 75: + logger.info( + f"{ep_name} should work well for this model as there is one partition " + f"covering {pct_nodes_using_ep:.1f}% of the nodes in the model." + ) + elif pct_nodes_using_ep > 50: + logger.info( + f"{ep_name} may work well for this model, however only {pct_nodes_using_ep:.1f}% of nodes " + "will use it. Performance testing is required to validate." + ) + else: + logger.info( + f"{ep_name} will probably not work will for this model as only {pct_nodes_using_ep:.2f}% " + "of nodes will use it." + ) + + elif self.num_partitions == 2 and pct_nodes_using_ep > 75: + logger.info( + f"{ep_name} can be considered for this model as there are two partitions " + f"covering {pct_nodes_using_ep:.1f}% of the nodes. " + "Performance testing is required to validate." + ) + else: + logger.info( + f"{ep_name} is not recommended with this model as there are {self.num_partitions} partitions " + f"covering {pct_nodes_using_ep:.1f}% of the nodes in the model. " + "This will most likely result in worse performance than just using the CPU EP." + ) + + +def _check_partitioning_for_graph( + graph: onnx.GraphProto, + node_to_producers: dict[onnx.NodeProto, set[onnx.NodeProto]], + node_to_consumers: dict[onnx.NodeProto, set[onnx.NodeProto]], + supported_ops_checker: _SupportedOpsChecker, + outer_scope_initializers: set[str], + require_fixed_input_sizes: bool, + value_info: dict[str, onnx.ValueInfoProto], + max_rank: int = 999, # max rank if EP has a limitation +): + # initializers have fixed sizes. + initializers = [i.name for i in graph.initializer] + + def _is_fixed_shape_value(value): + if value in value_info: + return is_fixed_size_tensor(value_info[value]) + + if value in initializers or value in outer_scope_initializers: + return True + + # if something has an unknown shape (e.g. something downstream of a Reshape with dynamic input for the shape) + # it won't have an entry in value_info + return False + + # + # Replicate logic from /onnxruntime/core/providers/partitioning_utils.cc:CreateSupportedPartitionNodeGroups + # to roughly estimate number of partitions for nodes that is_node_supported_fn returns true for. + # + # We keep the structure and variable names as close as possible to the C++ implementation to simplify keeping them + # in sync if future updates are needed. + # + # NOTE: CreateSupportedPartitionNodeGroups was recently updated to be QDQ aware so that partitions did not split + # QDQ node groups. This code does not need to be QDQ aware as splitting a QDQ node group does not affect the total + # number of partitions or supported nodes. + # + + # we don't currently support a callback for additional group closure checks in the python implementation + on_group_closed_fn = None + + supported_groups = [] + # number of inputs from unprocessed nodes (in-degree) per node + in_degree = {} + # nodes that are ready to process + nodes_to_process = deque() # deque of Node instances + # nodes that will be processed when considering the next partition node group + nodes_to_process_with_next_group = deque() + + # initialize in-degrees and find root nodes + for node in graph.node: + node_input_edge_count = len(node_to_producers[node]) if node in node_to_producers else 0 + in_degree[node] = node_input_edge_count + if node_input_edge_count == 0: + # node is only dependent on graph input or initializers + nodes_to_process.append(node) + + supported_group = [] + # the partition node group's border is the aggregate of its nodes' output nodes + supported_group_border = set() + num_supported_nodes = 0 + num_unsupported_nodes_due_to_op = 0 + num_unsupported_nodes_due_to_dynamic_input = 0 + num_unsupported_nodes_due_to_rank = 0 + unsupported_ops = set() + ops_with_unsupported_rank = set() + + def close_group(): + if supported_group: + keep_partition = not on_group_closed_fn or on_group_closed_fn(supported_group) + + if keep_partition: + supported_groups.append(supported_group.copy()) + + supported_group.clear() + supported_group_border.clear() + + while nodes_to_process or nodes_to_process_with_next_group: + if not nodes_to_process: + close_group() + nodes_to_process = nodes_to_process_with_next_group + nodes_to_process_with_next_group = deque() + continue + + node = nodes_to_process.popleft() + + is_op_supported = supported_ops_checker.is_op_supported(node) + is_input_shape_supported = not require_fixed_input_sizes or all(_is_fixed_shape_value(i) for i in node.input) + + is_rank_supported = True + if value_info: + for node_input in node.input: + if node_input and node_input in value_info and value_info[node_input].type.HasField("tensor_type"): + input_rank = len(value_info[node_input].type.tensor_type.shape.dim) + if input_rank > max_rank: + is_rank_supported = False + break + + # special-case if we can infer the rank from the length of the 'perms' Transpose attribute + # e.g. this works with SegmentAnything where dynamic Reshape operators result in no shape info. + if node.op_type == "Transpose" and len(node.attribute[0].ints) > max_rank: + is_rank_supported = False + + is_node_supported = is_op_supported and is_input_shape_supported and is_rank_supported + + if not is_node_supported: + if node in supported_group_border: + # an unsupported node on the border will be processed after the current partition node group + # so skip any additional processing/counting here + nodes_to_process_with_next_group.append(node) + continue + + if not is_op_supported: + unsupported_ops.add(f"{node.domain if node.domain else 'ai.onnx'}:{node.op_type}") + num_unsupported_nodes_due_to_op += 1 + + if not is_input_shape_supported: + num_unsupported_nodes_due_to_dynamic_input += 1 + + if not is_rank_supported: + num_unsupported_nodes_due_to_rank += 1 + ops_with_unsupported_rank.add(f"{node.domain if node.domain else 'ai.onnx'}:{node.op_type}") + + if is_node_supported: + num_supported_nodes += 1 + + # add node to the partition node group + supported_group.append(node) + + # remove node from the border and add its outputs to the border + if node in supported_group_border: # noqa: FURB132 + supported_group_border.remove(node) + + # for each consumer node add to supported_group_border + if node in node_to_consumers: + for consumer in node_to_consumers[node]: + supported_group_border.add(consumer) + + # adjust in-degrees of the node outputs and add any new nodes to process + if node in node_to_consumers: + for consumer in node_to_consumers[node]: + consumer_node_in_degree = in_degree[consumer] + consumer_node_in_degree -= 1 + if consumer_node_in_degree == 0: + nodes_to_process.append(consumer) + + in_degree[consumer] = consumer_node_in_degree + + close_group() + + num_nodes = len(graph.node) + num_partitions = len(supported_groups) + + info = PartitioningInfo( + num_nodes, + num_supported_nodes, + num_partitions, + supported_ops_checker, + supported_groups, + unsupported_ops, + num_unsupported_nodes_due_to_op, + num_unsupported_nodes_due_to_dynamic_input, + num_unsupported_nodes_due_to_rank, + ops_with_unsupported_rank, + ) + + return info + + +def check_partitioning( + main_graph: onnx.GraphProto, + supported_ops_checker: _SupportedOpsChecker, + require_fixed_input_sizes: bool, + max_rank: int = 999, +) -> PartitioningInfo: + """ + Estimate the partitions the graph will be split into for nodes that is_node_supported_fn returns true for. + + The check on whether a node is supported is purely based on the operator type. Additional limitations + (e.g. NNAPI EP only supports 2D Conv) are not checked, so partitions may not be 100% accurate. The limitations + for operators in the partitions are printed so the user can manually check. + :param main_graph: Graph to process + :param supported_ops_checker: Checker with info on supported ops. + :param require_fixed_input_sizes: If True, require that the inputs to a potentially supported node are fixed size + tensors for it to be considered as supported. This requires + onnx.shape_inference.infer_shapes to have been run on the model to populate the + shape information. + If False, shapes are ignored during the check. + :param max_rank: Set if EP has a limitation on the rank of tensors it supports. + :return PartitioningInfo instance with details + """ + + if require_fixed_input_sizes and len(main_graph.value_info) == 0 and len(main_graph.node) > 1: + raise ValueError("Run onnx.shape_inference.infer_shapes on the model to populate the shape information.") + + # create lookup map from ValueInfo for efficiency + def _update_value_info(graph: onnx.GraphProto, value_to_shape: dict[str, onnx.ValueInfoProto]): + for v in graph.input: + value_to_shape[v.name] = v + for v in graph.output: + value_to_shape[v.name] = v + for v in graph.value_info: + value_to_shape[v.name] = v + + # the producer/consumer maps are for the entire model + node_to_producers, node_to_consumers = get_producer_consumer_maps(main_graph) + + def _check_graph( + graph: onnx.GraphProto, + outer_scope_value_info: dict[str, onnx.ValueInfoProto] | None, + outer_scope_initializers: set[str] | None = None, + partitioning_info: PartitioningInfo | None = None, + ) -> PartitioningInfo: + if outer_scope_value_info is not None: + # extend value info if we're using it. we replace any value shadowed with a local one + value_info = outer_scope_value_info.copy() + _update_value_info(graph, value_info) + else: + value_info = {} + + if outer_scope_initializers is None: + outer_scope_initializers = set() + + info = _check_partitioning_for_graph( + graph, + node_to_producers, + node_to_consumers, + supported_ops_checker, + outer_scope_initializers, + require_fixed_input_sizes, + value_info, + max_rank, + ) + + if partitioning_info: + # merge in subgraph info + partitioning_info.merge(info) + else: + # main graph info + partitioning_info = info + + # setup outer scope initializers. we copy the input set as a model may have multiple subgraphs + # on multiple levels, so we need to keep the set for each descent separate + subgraph_outer_scope_initializers = set(outer_scope_initializers) + for initializer in graph.initializer: + subgraph_outer_scope_initializers.add(initializer.name) + + for node in graph.node: + # recurse into nodes with subgraphs + for attr in node.attribute: + if attr.HasField("g"): + subgraph = attr.g + partitioning_info = _check_graph( + subgraph, value_info, subgraph_outer_scope_initializers, partitioning_info + ) + + return partitioning_info + + aggregated_partitioning_info = _check_graph(main_graph, {} if require_fixed_input_sizes else None) + + return aggregated_partitioning_info + + +def _check_ep_partitioning( + model: onnx.ModelProto, supported_ops_config: pathlib.Path, require_fixed_input_sizes: bool, max_rank: int = 999 +): + supported_ops = _SupportedOpsChecker(supported_ops_config) + partition_info = check_partitioning(model.graph, supported_ops, require_fixed_input_sizes, max_rank) + return partition_info + + +def check_nnapi_partitions(model, require_fixed_input_sizes: bool): + # if we're running in the ORT python package the file should be local. otherwise assume we're running from the + # ORT repo + script_dir = pathlib.Path(__file__).parent + local_config = script_dir / "nnapi_supported_ops.md" + if local_config.exists(): + config_path = local_config + else: + ort_root = script_dir.parents[3] + config_path = ort_root / "tools" / "ci_build" / "github" / "android" / "nnapi_supported_ops.md" + + return _check_ep_partitioning(model, config_path, require_fixed_input_sizes) + + +def check_coreml_partitions(model: onnx.ModelProto, require_fixed_input_sizes: bool, config_filename: str): + # if we're running in the ORT python package the file should be local. otherwise assume we're running from the + # ORT repo + script_dir = pathlib.Path(__file__).parent + local_config = script_dir / config_filename + if local_config.exists(): + config_path = local_config + else: + ort_root = script_dir.parents[3] + config_path = ort_root / "tools" / "ci_build" / "github" / "apple" / config_filename + + max_rank = 5 + return _check_ep_partitioning(model, config_path, require_fixed_input_sizes, max_rank) + + +def check_shapes(graph: onnx.GraphProto, logger: logging.Logger | None = None): + """ + Check the shapes of graph inputs, values and graph outputs to determine if they have static or dynamic sizes. + NNAPI does not support dynamically sized values. CoreML does, but it will most likely cost performance. + :param graph: Graph to check. If shape inferencing has been run the checks on values will be meaningful. + :param logger: Optional logger for diagnostic information. + :return: Tuple of List of inputs with dynamic shapes, Number of dynamic values found + """ + + # it's OK if the input is dynamically sized and we do a Resize early to a fixed size. + # it's not good if lots of ops have dynamic inputs + + num_fixed_values = 0 + num_dynamic_values = 0 + + dynamic_inputs = [] + for i in graph.input: + if not is_fixed_size_tensor(i): + dynamic_inputs.append(i) + # split/join to remove repeated whitespace and newlines from str(i) + if logger: + logger.info(f"Input is not a fixed size tensor: {' '.join(str(i).split())}") + num_dynamic_values += 1 + else: + num_fixed_values += 1 + + dynamic_outputs = [] + for o in graph.output: + if not is_fixed_size_tensor(o): + dynamic_outputs.append(o) + if logger: + logger.info(f"Output is not a fixed size tensor: {' '.join(str(o).split())}") + num_dynamic_values += 1 + else: + num_fixed_values += 1 + + # check we have value info. + # special case some test graphs with a single node which only have graph input and output values, and + # a model where all inputs are dynamic (results in no value_info) + if not graph.value_info and not (len(graph.node) == 1 or len(dynamic_inputs) == len(graph.input)): + logger.warning( + "Unable to check shapes within model. ONNX shape inferencing should be run on the model prior to checking." + ) + + for vi in graph.value_info: + if is_fixed_size_tensor(vi): + num_fixed_values += 1 + else: + num_dynamic_values += 1 + + if logger: + logger.info( + f"Num values with fixed shape={num_fixed_values}. Num values with dynamic shape={num_dynamic_values}" + ) + + if dynamic_inputs: + if dynamic_outputs: + logger.info( + "Model has dynamic inputs and outputs. Consider re-exporting model with fixed sizes " + "if NNAPI or CoreML can be used with this model." + ) + else: + logger.info( + """Model has dynamically sized inputs but fixed sized outputs. + If the sizes become fixed early in the model (e.g. pre-processing of a dynamic input size + results in a fixed input size for the majority of the model) performance with NNAPI and CoreML, + if applicable, should not be significantly impacted.""" + ) + + return dynamic_inputs, num_dynamic_values + + +def checker(model_path: pathlib.Path, logger: logging.Logger): + model_with_shape_info_wrapper = ModelProtoWithShapeInfo(model_path) + model_with_shape_info = model_with_shape_info_wrapper.model_with_shape_info + + dynamic_inputs, num_dynamic_values = check_shapes(model_with_shape_info.graph) + + def check_ep(ep_name, checker_func): + logger.info(f"Checking {ep_name}") + + # check with shape info first so supported nodes takes into account values with dynamic shapes + require_fixed_input_sizes = True + partition_info = checker_func(model_with_shape_info, require_fixed_input_sizes) + if logger.getEffectiveLevel() <= logging.INFO: + partition_info.print_analysis(logger, ep_name) + + suitability = partition_info.suitability() + logger.info(f"Model should perform well with {ep_name} as is: {suitability.name}") + + if suitability != PartitioningInfo.TryWithEP.YES and dynamic_inputs: + logger.info("--------") + logger.info("Checking if model will perform better if the dynamic shapes are fixed...") + require_fixed_input_sizes = False + partition_info_with_fixed_shapes = checker_func(model_with_shape_info, require_fixed_input_sizes) + + if logger.getEffectiveLevel() <= logging.INFO: + # analyze and log detailed info + logger.info("Partition information if the model was updated to make the shapes fixed:") + partition_info_with_fixed_shapes.print_analysis(logger, ep_name) + + fixed_shape_suitability = partition_info_with_fixed_shapes.suitability() + logger.info( + f"Model should perform well with {ep_name} if modified to have fixed input shapes: " + f"{fixed_shape_suitability.name}" + ) + + if fixed_shape_suitability != PartitioningInfo.TryWithEP.NO: + logger.info("Shapes can be altered using python -m onnxruntime.tools.make_dynamic_shape_fixed") + + if fixed_shape_suitability.value > suitability.value: + suitability = fixed_shape_suitability + + logger.info("================") + logger.info("") + + return suitability + + nnapi_suitability = check_ep("NNAPI", check_nnapi_partitions) + + # Check for NeuralNetwork CoreML model + def check_nn_coreml(model: onnx.ModelProto, require_fixed_input_sizes): + return check_coreml_partitions(model, require_fixed_input_sizes, "coreml_supported_neuralnetwork_ops.md") + + # Check for MLProgram CoreML model + def check_mlprogram_coreml(model: onnx.ModelProto, require_fixed_input_sizes): + return check_coreml_partitions(model, require_fixed_input_sizes, "coreml_supported_mlprogram_ops.md") + + coreml_nn_suitability = check_ep("CoreML NeuralNetwork", check_nn_coreml) + coreml_mlprogram_suitability = check_ep("CoreML MLProgram", check_mlprogram_coreml) + + if ( + nnapi_suitability != PartitioningInfo.TryWithEP.YES + or coreml_nn_suitability != PartitioningInfo.TryWithEP.YES + or coreml_mlprogram_suitability != PartitioningInfo.TryWithEP.YES + ) and logger.getEffectiveLevel() > logging.INFO: + logger.info("Re-run with log level of INFO for more details on the NNAPI/CoreML issues.") + + return ( + nnapi_suitability != PartitioningInfo.TryWithEP.NO + or coreml_nn_suitability != PartitioningInfo.TryWithEP.NO + or coreml_mlprogram_suitability != PartitioningInfo.TryWithEP.NO + ) + + +def analyze_model(model_path: pathlib.Path, skip_optimize: bool = False, logger: logging.Logger | None = None): + """ + Analyze the provided model to determine if it's likely to work well with the NNAPI or CoreML Execution Providers + :param model_path: Model to analyze. + :param skip_optimize: Skip optimizing to BASIC level before checking. When exporting to ORT format we will do this + optimization.. + :param logger: Logger for output + :return: True if either the NNAPI or CoreML Execution Providers may work well with this model. + """ + if not logger: + logger = logging.getLogger("usability_checker") + logger.setLevel(logging.INFO) + + logger.info(f"Checking {model_path} for usability with ORT Mobile.") + + with tempfile.TemporaryDirectory() as tmp: + if not skip_optimize: + tmp_path = pathlib.Path(tmp) / model_path.name + optimize_model(model_path, tmp_path, use_external_initializers=True) + model_path = tmp_path + + try_eps = checker(model_path.resolve(strict=True), logger) + + return try_eps + + +def parse_args(): + parser = argparse.ArgumentParser( + os.path.basename(__file__), description="""Analyze an ONNX model for usage with the ORT mobile""" + ) + + parser.add_argument("--log_level", choices=["debug", "info"], default="info", help="Logging level") + parser.add_argument( + "--skip_optimize", + action="store_true", + help="Don't optimize the model to BASIC level prior to analyzing. " + "Optimization will occur when exporting the model to ORT format, so in general " + "should not be skipped unless you have a specific reason to do so.", + ) + parser.add_argument("model_path", type=pathlib.Path, help="Provide path to ONNX model") + + return parser.parse_args() + + +def run_analyze_model(): + args = parse_args() + logger = logging.getLogger("default") + + if args.log_level == "debug": + logger.setLevel(logging.DEBUG) + elif args.log_level == "info": + logger.setLevel(logging.INFO) + elif args.log_level == "warning": + logger.setLevel(logging.WARNING) + else: + logger.setLevel(logging.ERROR) + + model_path = args.model_path.resolve() + analyze_model(model_path, args.skip_optimize, logger) + + +if __name__ == "__main__": + run_analyze_model() diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/__init__.py b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..226ab64e051fc072011180c785df2d95518b7499 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/__init__.py @@ -0,0 +1,27 @@ +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. + +import os +import sys + +# need to add the path to the ORT flatbuffers python module before we import anything else here. +# we also auto-magically adjust to whether we're running from the ORT repo, or from within the ORT python package +script_dir = os.path.dirname(os.path.realpath(__file__)) +fbs_py_schema_dirname = "ort_flatbuffers_py" +if os.path.isdir(os.path.join(script_dir, fbs_py_schema_dirname)): + # fbs bindings are in this directory, so we're running in the ORT python package + ort_fbs_py_parent_dir = script_dir +else: + # running directly from ORT repo, so fbs bindings are under onnxruntime/core/flatbuffers + ort_root = os.path.abspath(os.path.join(script_dir, "..", "..", "..", "..")) + ort_fbs_py_parent_dir = os.path.join(ort_root, "onnxruntime", "core", "flatbuffers") + +sys.path.append(ort_fbs_py_parent_dir) + +from .operator_type_usage_processors import ( # noqa: E402 + GloballyAllowedTypesOpTypeImplFilter, # noqa: F401 + OperatorTypeUsageManager, # noqa: F401 + OpTypeImplFilterInterface, # noqa: F401 +) +from .ort_model_processor import OrtFormatModelProcessor # noqa: E402, F401 +from .utils import create_config_from_models # noqa: E402, F401 diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e08a687d11d92769e2fce2a9909494467257c124 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/__pycache__/operator_type_usage_processors.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/__pycache__/operator_type_usage_processors.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..43b1f00aa68e6b5885dc0a2839777ee2a24ac6a9 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/__pycache__/operator_type_usage_processors.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/__pycache__/ort_model_processor.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/__pycache__/ort_model_processor.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3beb12a8a045d69095bb549b45bde05489148033 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/__pycache__/ort_model_processor.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/__pycache__/types.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/__pycache__/types.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..78c92061a05f4d972004e0a58f605bf9fcbe0082 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/__pycache__/types.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/__pycache__/utils.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/__pycache__/utils.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dfb8160425a6335d4aa5d6ec348d2932d92f925e Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/__pycache__/utils.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/operator_type_usage_processors.py b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/operator_type_usage_processors.py new file mode 100644 index 0000000000000000000000000000000000000000..af259d9b5764f27f4e0c5e01f90724c95f4f2a16 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/operator_type_usage_processors.py @@ -0,0 +1,653 @@ +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +from __future__ import annotations + +import json +from abc import ABC, abstractmethod + +import ort_flatbuffers_py.fbs as fbs + +from .types import FbsTypeInfo, value_name_to_typestr + + +def _create_op_key(domain: str, optype: str): + return f"{domain}:{optype}" + + +def _ort_constant_for_domain(domain: str): + """ + Map a string domain value to the internal ONNX Runtime constant for that domain. + :param domain: Domain string to map. + :return: Internal ONNX Runtime constant + """ + + # constants are defined in /include/onnxruntime/core/graph/constants.h + # This list is limited to just the domains we have processors for + domain_to_constant_map = {"ai.onnx": "kOnnxDomain", "ai.onnx.ml": "kMLDomain", "com.microsoft": "kMSDomain"} + + if domain not in domain_to_constant_map: + raise ValueError(f"Domain {domain} not found in map to ONNX Runtime constant. Please update map.") + + return domain_to_constant_map[domain] + + +def _reg_type_to_cpp_type(reg_type: str): + if reg_type == "string": + return "std::string" + return reg_type + + +def _split_reg_types(reg_types_str: str): + """ + Split on underscores but append "_t" to the previous element. + """ + tokens = reg_types_str.split("_") + reg_types = [] + for token in tokens: + if token == "t" and len(reg_types) > 0: + reg_types[-1] += "_t" + else: + reg_types += [token] + return reg_types + + +class TypeUsageProcessor(ABC): + """ + Abstract base class for processors which implement operator specific logic to determine the type or types required. + """ + + def __init__(self, domain: str, optype: str): + self.domain = domain + self.optype = optype + self.name = _create_op_key(domain, optype) + + @abstractmethod + def process_node(self, node: fbs.Node, value_name_to_typeinfo: dict): + pass + + def is_typed_registration_needed(self, type_in_registration: str, globally_allowed_types: set[str] | None): + """ + Given the string from a kernel registration, determine if the registration is required or not. + :param type_in_registration: Type string from kernel registration + :param globally_allowed_types: Optional set of globally allowed types. If provided, these types take precedence + in determining the required types. + :return: True is required. False if not. + """ + # Not all operators have typed registrations, so this is optionally implemented by derived classes + raise RuntimeError(f"Did not expect processor for {self.name} to have typed registrations.") + + def get_cpp_entry(self): + """ + Get the C++ code that specifies this operator's required types. + :return: List with any applicable C++ code for this operator's required types. One line per entry. + """ + # Not applicable for some ops, so return no lines by default. + return [] + + @abstractmethod + def to_config_entry(self): + """ + Generate a configuration file entry in JSON format with the required types for the operator. + :return: JSON string with required type information. + """ + + @abstractmethod + def from_config_entry(self, entry: str): + """ + Re-create the types required from a configuration file entry created with to_config_entry. + NOTE: Any existing type information should be cleared prior to re-creating from a config file entry. + :param entry: Configuration file entry + """ + + +class DefaultTypeUsageProcessor(TypeUsageProcessor): + """ + Operator processor which tracks the types used for selected input/s and/or output/s. + """ + + def __init__( + self, + domain: str, + optype: str, + inputs: [int] = [0], # noqa: B006 + outputs: [int] = [], # noqa: B006 + required_input_types: dict[int, set[str]] = {}, # noqa: B006 + required_output_types: dict[int, set[str]] = {}, # noqa: B006 + ): + """ + Create DefaultTypeUsageProcessor. Types for one or more inputs and/or outputs can be tracked by the processor. + The default is to track the types required for input 0, as this is the most common use case in ONNX. + + Required input and output types may be specified. These are only applicable to is_typed_registration_needed(). + If a registration type matches a required type, the typed registration is needed. + There is a separate mechanism for specifying required types from C++ for kernels with untyped registration. + + :param domain: Operator domain. + :param optype: Operator name. + :param inputs: Inputs to track. Zero based index. May be empty. + :param outputs: Outputs to track. Zero based index. May be empty. + :param required_input_types: Required input types. May be empty. + :param required_output_types: Required output types. May be empty. + """ + super().__init__(domain, optype) + self._input_types = {} + self._output_types = {} + + for i in inputs: + self._input_types[i] = set() + + for o in outputs: + self._output_types[o] = set() + + if not inputs and not outputs: + raise ValueError("At least one input or output must be tracked") + + self._required_input_types = required_input_types + self._required_output_types = required_output_types + + def _is_type_enabled(self, reg_type, index, required_types, allowed_type_set): + cpp_type = _reg_type_to_cpp_type(reg_type) + return cpp_type in required_types.get(index, set()) or cpp_type in allowed_type_set + + def is_input_type_enabled(self, reg_type, index, allowed_type_set=None): + """Whether input type is enabled based on required and allowed types.""" + if allowed_type_set is None: + allowed_type_set = self._input_types[index] + return self._is_type_enabled(reg_type, index, self._required_input_types, allowed_type_set) + + def is_output_type_enabled(self, reg_type, index, allowed_type_set=None): + """Whether output type is enabled based on required and allowed types.""" + if allowed_type_set is None: + allowed_type_set = self._output_types[index] + return self._is_type_enabled(reg_type, index, self._required_output_types, allowed_type_set) + + def process_node(self, node: fbs.Node, value_name_to_typeinfo: dict): + for i in self._input_types: + if i >= node.InputsLength(): + # Some operators have fewer inputs in earlier versions where data that was as an attribute + # become an input in later versions to allow it to be dynamically provided. Allow for that. + # e.g. Slice-1 had attributes for the indices, and Slice-10 moved those to be inputs + # raise RuntimeError('Node has {} outputs. Tracker for {} incorrectly configured as it requires {}.' + # .format(node.OutputsLength(), self.name, o)) + pass + else: + type_str = value_name_to_typestr(node.Inputs(i), value_name_to_typeinfo) + self._input_types[i].add(type_str) + + for o in self._output_types: + # Don't know of any ops where the number of outputs changed across versions, so require a valid length + if o >= node.OutputsLength(): + raise RuntimeError( + f"Node has {node.OutputsLength()} outputs. Tracker for {self.name} incorrectly configured as it requires {o}." + ) + + type_str = value_name_to_typestr(node.Outputs(o), value_name_to_typeinfo) + self._output_types[o].add(type_str) + + def is_typed_registration_needed(self, type_in_registration: str, globally_allowed_types: set[str] | None): + if 0 not in self._input_types: + # currently all standard typed registrations are for input 0. + # custom registrations can be handled by operator specific processors (e.g. OneHotProcessor below). + raise RuntimeError(f"Expected typed registration to use type from input 0. Node:{self.name}") + + return self.is_input_type_enabled(type_in_registration, 0, globally_allowed_types) + + def get_cpp_entry(self): + entries = [] + domain = _ort_constant_for_domain(self.domain) + for i in sorted(self._input_types.keys()): + if self._input_types[i]: + entries.append( + "ORT_SPECIFY_OP_KERNEL_ARG_ALLOWED_TYPES({}, {}, Input, {}, {});".format( + domain, self.optype, i, ", ".join(sorted(self._input_types[i])) + ) + ) + + for o in sorted(self._output_types.keys()): + if self._output_types[o]: + entries.append( + "ORT_SPECIFY_OP_KERNEL_ARG_ALLOWED_TYPES({}, {}, Output, {}, {});".format( + domain, self.optype, o, ", ".join(sorted(self._output_types[o])) + ) + ) + + return entries + + def to_config_entry(self): + # convert the sets of types to lists so they can easily written out using the json model + aggregate_info = {"inputs": {}, "outputs": {}} + + # filter out empty entries and sort the types + for i in sorted(self._input_types.keys()): + if self._input_types[i]: + aggregate_info["inputs"][i] = sorted(self._input_types[i]) + + for o in sorted(self._output_types.keys()): + if self._output_types[o]: + aggregate_info["outputs"][o] = sorted(self._output_types[o]) + + # remove any empty keys + if not aggregate_info["inputs"]: + aggregate_info.pop("inputs") + if not aggregate_info["outputs"]: + aggregate_info.pop("outputs") + + entry = json.dumps(aggregate_info) if aggregate_info else None + return entry + + def from_config_entry(self, entry: str): + self._input_types.clear() + self._output_types.clear() + + aggregate_info = json.loads(entry) + if "inputs" in aggregate_info: + for i_str, values in aggregate_info["inputs"].items(): + self._input_types[int(i_str)] = set(values) + + if "outputs" in aggregate_info: + for o_str, values in aggregate_info["outputs"].items(): + self._output_types[int(o_str)] = set(values) + + +class Input1TypedRegistrationProcessor(DefaultTypeUsageProcessor): + """ + Processor for operators where the second input type is used in a typed kernel registration. + """ + + def __init__(self, domain: str, optype: str): + # init with tracking of input 1 only. + super().__init__(domain, optype, inputs=[1], outputs=[]) + + def is_typed_registration_needed(self, type_in_registration: str, globally_allowed_types: set[str] | None): + return self.is_input_type_enabled(type_in_registration, 1, globally_allowed_types) + + +class Output0TypedRegistrationProcessor(DefaultTypeUsageProcessor): + """ + Processor for operators where the first output type is used in a typed kernel registration. + """ + + def __init__(self, domain: str, optype: str): + # init with tracking of output 0 only. + super().__init__(domain, optype, inputs=[], outputs=[0]) + + def is_typed_registration_needed(self, type_in_registration: str, globally_allowed_types: set[str] | None): + return self.is_output_type_enabled(type_in_registration, 0, globally_allowed_types) + + +class OneHotProcessor(TypeUsageProcessor): + """ + Processor for the OneHot operator, which requires custom logic as the type registration key is a concatenation of + the three types involved instead of a single type name. + """ + + def __init__(self): + super().__init__("ai.onnx", "OneHot") + self._triples = set() + + def process_node(self, node: fbs.Node, value_name_to_typeinfo: dict): + type0 = value_name_to_typestr(node.Inputs(0), value_name_to_typeinfo) + type1 = value_name_to_typestr(node.Inputs(1), value_name_to_typeinfo) + type2 = value_name_to_typestr(node.Inputs(2), value_name_to_typeinfo) + # types in kernel registration are ordered this way: input (T1), output (T3), depth (T2) + key = (type0, type2, type1) + self._triples.add(key) + + def is_typed_registration_needed(self, type_in_registration: str, globally_allowed_types: set[str] | None): + # the OneHot registration involves a concatenation of the 3 types involved + reg_types = tuple([_reg_type_to_cpp_type(reg_type) for reg_type in _split_reg_types(type_in_registration)]) + if globally_allowed_types is not None: + return all(reg_type in globally_allowed_types for reg_type in reg_types) + else: + return reg_types in self._triples + + def to_config_entry(self): + if not self._triples: + return None + + aggregate_info = {"custom": sorted(self._triples)} + entry = json.dumps(aggregate_info) + return entry + + def from_config_entry(self, entry: str): + self._triples.clear() + aggregate_info = json.loads(entry) + if "custom" in aggregate_info: + self._triples = {tuple(triple) for triple in aggregate_info["custom"]} + + +def _create_operator_type_usage_processors(): + """ + Create a set of processors that determine the required types for all enabled operators. + :return: Dictionary of operator key to processor. Key is 'domain:operator (e.g. ai.onnx:Cast)'. + """ + operator_processors = {} + + def add(processor): + if processor.name in operator_processors: + raise RuntimeError("Duplicate processor for " + processor.name) + + operator_processors[processor.name] = processor + + # Starting with ops from: + # - Priority 1P models + # - Mobilenet + SSD Mobilenet + MobileBert + # - some known large kernels + # + # Ops we are ignoring currently so as not to produce meaningless/unused output: + # - Implementation is type agnostic: + # ai.onnx: If, Loop, Reshape, Scan, Shape, Squeeze, Tile, Unsqueeze + # com.microsoft: DynamicQuantizeMatMul, MatMulIntegerToFloat + # - Only one type supported in the ORT implementation: + # ai.onnx: NonMaxSuppression + # com.microsoft: FusedConv, FusedGemm, FusedMatMul + # - Implementation does not have any significant type specific code: + # ai.onnx: Concat, Flatten, Not, Reshape, Shape, Squeeze, Unsqueeze + # + default_processor_onnx_ops = [ + "Abs", + "ArgMax", + "ArgMin", + "AveragePool", + "BatchNormalization", + "BitShift", + "Ceil", + "Clip", + "Conv", + "CumSum", + "Exp", + "Expand", + "Floor", + "Gemm", + "IsNaN", + "Log", + "LogSoftmax", + "LpNormalization", + "MatMul", + "Max", + "MaxPool", + "Mean", + "Min", + "NonZero", + "Pad", + "QLinearConv", + "QLinearMatMul", + "Range", + "Reciprocal", + "ReduceL1", + "ReduceL2", + "ReduceLogSum", + "ReduceLogSumExp", + "ReduceMax", + "ReduceMean", + "ReduceMin", + "ReduceProd", + "ReduceSum", + "ReduceSumSquare", + "Relu", + "Resize", + "ReverseSequence", + "RoiAlign", + "Round", + "Scatter", + "ScatterElements", + "ScatterND", + "Shrink", + "Sigmoid", + "Sign", + "Sin", + "Softmax", + "Split", + "SplitToSequence", + "Sqrt", + "Sum", + "Tanh", + "TopK", + "Transpose", + "Unique", + ] + + # ops that are used to manipulate shapes or indices so require int32_t and int64_t to be available + default_processor_onnx_ops_requiring_ints_for_input_0 = [ + "Add", + "Concat", + "Div", + "Equal", + "Greater", + "Less", + "Mul", + "Neg", # used in tflite TransposeConv conversion + "Sub", + ] + + # NOTE: QLinearConv has ONNX and internal implementations + internal_ops = ["QLinearAdd", "QLinearMul", "QLinearConv"] + + # TODO - review and add ML ops as needed + # ML Op notes. + # CastMap: Switch on value type of input map type, and output type + # DictVectorizer: Templatized on key+value of input so need to handle like OneHot with custom processor + # LabelEncoder: Implementation switches on input and output types (only supports string and int64 in T1 and T2) + # LinearClassifier: Internal switch on input type and also switch on output type + # SVMClassifier: ditto + # TreeEnsembleClassifier: Templatized on input type and also switch on output type + # ZipMap: Switch on output type (derived from attributes) + default_processor_onnxml_ops = [] + + [add(DefaultTypeUsageProcessor("ai.onnx", op)) for op in default_processor_onnx_ops] + [ + add(DefaultTypeUsageProcessor("ai.onnx", op, required_input_types={0: {"int32_t", "int64_t"}})) + for op in default_processor_onnx_ops_requiring_ints_for_input_0 + ] + [add(DefaultTypeUsageProcessor("ai.onnx.ml", op)) for op in default_processor_onnxml_ops] + [add(DefaultTypeUsageProcessor("com.microsoft", op)) for op in internal_ops] + + # + # Operators that require custom handling + # + + # Cast switches on types of input 0 and output 0 + add(DefaultTypeUsageProcessor("ai.onnx", "Cast", inputs=[0], outputs=[0])) + + # Operators that switch on the type of input 0 and 1 + add(DefaultTypeUsageProcessor("ai.onnx", "Gather", inputs=[0, 1])) + add(DefaultTypeUsageProcessor("ai.onnx", "GatherElements", inputs=[0, 1])) + add(DefaultTypeUsageProcessor("ai.onnx", "Pow", inputs=[0, 1])) + add(DefaultTypeUsageProcessor("ai.onnx", "Slice", inputs=[0, 1])) + + # Operators that switch on output type + add(DefaultTypeUsageProcessor("ai.onnx", "ConstantOfShape", inputs=[], outputs=[0])) + + # Random generator ops produce new data so we track the output type + onnx_random_ops = ["RandomNormal", "RandomNormalLike", "RandomUniform", "RandomUniformLike", "Multinomial"] + [add(DefaultTypeUsageProcessor("ai.onnx", op, inputs=[], outputs=[0])) for op in onnx_random_ops] + + # Where always has a boolean first input so track the second input type for typed registration + add(Input1TypedRegistrationProcessor("ai.onnx", "Where")) + + # we only support 'float' as input for [Dynamic]QuantizeLinear so just track the output type + # as that's what is used in the typed registration + add(Output0TypedRegistrationProcessor("ai.onnx", "QuantizeLinear")) + add(Output0TypedRegistrationProcessor("ai.onnx", "DynamicQuantizeLinear")) + + # make sure all the dequantize types are enabled. we use int32_t for parts of GEMM and Conv so just + # enabling int8 and uint8 is not enough. + # TODO: Only apply required types to the global type list and ignore if it's model based per-op type reduction + add( + DefaultTypeUsageProcessor( + "ai.onnx", "DequantizeLinear", inputs=[0], required_input_types={0: {"int8_t", "uint8_t", "int32_t"}} + ) + ) + + # OneHot concatenates type strings into a triple in the typed registration + # e.g. float_int64_t_int64_t + add(OneHotProcessor()) + + return operator_processors + + +class OpTypeImplFilterInterface(ABC): + """ + Class that filters operator implementations based on type. + """ + + @abstractmethod + def is_typed_registration_needed(self, domain: str, optype: str, type_registration_str: str): + """ + Given the string from a kernel registration, determine if the registration is required or not. + :param domain: Operator domain. + :param optype: Operator type. + :param type_registration_str: Type string from kernel registration + :return: True is required. False if not. + """ + + @abstractmethod + def get_cpp_entries(self): + """ + Get the C++ code that specifies the operator types to enable. + :return: List of strings. One line of C++ code per entry. + """ + + +class OperatorTypeUsageManager: + """ + Class to manage the operator type usage processors. + TODO: Currently the type tracking is not specific to a version of the operator. + It's unclear how/where version specific logic could/should be added, and it would add significant complexity + to track types on a per-version basis. Not clear there's enough benefit from doing so either. + """ + + def __init__(self): + self._all_operator_processors = _create_operator_type_usage_processors() # all possible processors + self._operator_processors = {} # processors we have actually used so we can limit output to be meaningful + + def _get_op_processor(self, key): + "Add the processor to _operator_processors as it is about to be used." + processor = None + if key in self._all_operator_processors: + if key not in self._operator_processors: + self._operator_processors[key] = self._all_operator_processors[key] + + processor = self._operator_processors[key] + + return processor + + def process_node(self, node: fbs.Node, value_name_to_typeinfo: dict): + """ + Process a Node and record info on the types used. + :param node: Node from ORT format model + :param value_name_to_typeinfo: Map of value names to TypeInfo instances + """ + optype = node.OpType().decode() + domain = node.Domain().decode() or "ai.onnx" # empty domain defaults to ai.onnx + + key = _create_op_key(domain, optype) + op_processor = self._get_op_processor(key) + if op_processor: + op_processor.process_node(node, value_name_to_typeinfo) + + def get_config_entry(self, domain: str, optype: str): + """ + Get the config entry specifying the types for this operator. + :param domain: Operator domain. + :param optype: Operator type. + :return: JSON string with type info if available, else None + """ + key = _create_op_key(domain, optype) + config_str = None + if key in self._operator_processors: + config_str = self._operator_processors[key].to_config_entry() + + return config_str + + def restore_from_config_entry(self, domain: str, optype: str, config_entry: str): + """ + Restore the per-operator type information from a configuration file entry. + :param domain: Operator domain. + :param optype: Operator type. + :param config_entry: JSON string with type info as created by get_config_entry + """ + key = _create_op_key(domain, optype) + op_processor = self._get_op_processor(key) + if op_processor: + op_processor.from_config_entry(config_entry) + + def debug_dump(self): + print("C++ code that will be emitted:") + [print(cpp_line) for cpp_line in self.get_cpp_entries()] + + print("Config file type information that will be returned by get_config_entry:") + for key in sorted(self._operator_processors.keys()): + entry = self._operator_processors[key].to_config_entry() + if entry: + print(f"{key} -> {entry}") + + # roundtrip test to validate that we can initialize the processor from the entry and get the + # same values back + self._operator_processors[key].from_config_entry(entry) + assert entry == self._operator_processors[key].to_config_entry() + + class _OpTypeImplFilter(OpTypeImplFilterInterface): + def __init__(self, manager): + self._manager = manager + + def is_typed_registration_needed(self, domain: str, optype: str, type_registration_str: str): + needed = True # we keep the registration unless the per-operator processor says not to + key = _create_op_key(domain, optype) + if key in self._manager._operator_processors: + needed = self._manager._operator_processors[key].is_typed_registration_needed( + type_in_registration=type_registration_str, globally_allowed_types=None + ) + + return needed + + def get_cpp_entries(self): + entries = [] + for key in sorted(self._manager._operator_processors.keys()): + entries.extend(self._manager._operator_processors[key].get_cpp_entry()) + + return entries + + def make_op_type_impl_filter(self): + """ + Creates an OpTypeImplFilterInterface instance from this manager. + Filtering uses the manager's operator type usage processor state. + """ + return OperatorTypeUsageManager._OpTypeImplFilter(self) + + +class GloballyAllowedTypesOpTypeImplFilter(OpTypeImplFilterInterface): + """ + Operator implementation filter which uses globally allowed types. + """ + + _valid_allowed_types = set(FbsTypeInfo.tensordatatype_to_string.values()) # noqa: RUF012 + + def __init__(self, globally_allowed_types: set[str]): + self._operator_processors = _create_operator_type_usage_processors() + + if not globally_allowed_types.issubset(self._valid_allowed_types): + raise ValueError( + f"Globally allowed types must all be valid. Invalid types: {sorted(globally_allowed_types - self._valid_allowed_types)}" + ) + + self._globally_allowed_types = globally_allowed_types + + def is_typed_registration_needed(self, domain: str, optype: str, type_registration_str: str): + key = _create_op_key(domain, optype) + if key in self._operator_processors: + needed = self._operator_processors[key].is_typed_registration_needed( + type_in_registration=type_registration_str, globally_allowed_types=self._globally_allowed_types + ) + else: + needed = _reg_type_to_cpp_type(type_registration_str) in self._globally_allowed_types + + return needed + + def get_cpp_entries(self): + return [ + "ORT_SPECIFY_OP_KERNEL_GLOBAL_ALLOWED_TYPES({});".format(", ".join(sorted(self._globally_allowed_types))) + ] + + def global_type_list(self): + return self._globally_allowed_types diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/__init__.py b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1b8b5f9a6962f7c71150bc1b1b4928cfa0cf7edd Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/ArgType.py b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/ArgType.py new file mode 100644 index 0000000000000000000000000000000000000000..2bdb7f8150bba2509d818a5590a00e0ab565d610 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/ArgType.py @@ -0,0 +1,7 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: fbs + +class ArgType(object): + INPUT = 0 + OUTPUT = 1 diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/ArgTypeAndIndex.py b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/ArgTypeAndIndex.py new file mode 100644 index 0000000000000000000000000000000000000000..b4fc858a8ff97640332c0de28fa2b33c9d2cdfb3 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/ArgTypeAndIndex.py @@ -0,0 +1,67 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: fbs + +import flatbuffers +from flatbuffers.compat import import_numpy +np = import_numpy() + +class ArgTypeAndIndex(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = ArgTypeAndIndex() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsArgTypeAndIndex(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def ArgTypeAndIndexBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x4F\x52\x54\x4D", size_prefixed=size_prefixed) + + # ArgTypeAndIndex + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # ArgTypeAndIndex + def ArgType(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int8Flags, o + self._tab.Pos) + return 0 + + # ArgTypeAndIndex + def Index(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint32Flags, o + self._tab.Pos) + return 0 + +def ArgTypeAndIndexStart(builder): + builder.StartObject(2) + +def Start(builder): + ArgTypeAndIndexStart(builder) + +def ArgTypeAndIndexAddArgType(builder, argType): + builder.PrependInt8Slot(0, argType, 0) + +def AddArgType(builder, argType): + ArgTypeAndIndexAddArgType(builder, argType) + +def ArgTypeAndIndexAddIndex(builder, index): + builder.PrependUint32Slot(1, index, 0) + +def AddIndex(builder, index): + ArgTypeAndIndexAddIndex(builder, index) + +def ArgTypeAndIndexEnd(builder): + return builder.EndObject() + +def End(builder): + return ArgTypeAndIndexEnd(builder) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/Attribute.py b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/Attribute.py new file mode 100644 index 0000000000000000000000000000000000000000..cf6f54d72e42263fa707ca5093c4414d94abe612 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/Attribute.py @@ -0,0 +1,337 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: fbs + +import flatbuffers +from flatbuffers.compat import import_numpy +np = import_numpy() + +class Attribute(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = Attribute() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsAttribute(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def AttributeBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x4F\x52\x54\x4D", size_prefixed=size_prefixed) + + # Attribute + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # Attribute + def Name(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.String(o + self._tab.Pos) + return None + + # Attribute + def DocString(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.String(o + self._tab.Pos) + return None + + # Attribute + def Type(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return 0 + + # Attribute + def F(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Float32Flags, o + self._tab.Pos) + return 0.0 + + # Attribute + def I(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int64Flags, o + self._tab.Pos) + return 0 + + # Attribute + def S(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(14)) + if o != 0: + return self._tab.String(o + self._tab.Pos) + return None + + # Attribute + def T(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(16)) + if o != 0: + x = self._tab.Indirect(o + self._tab.Pos) + from ort_flatbuffers_py.fbs.Tensor import Tensor + obj = Tensor() + obj.Init(self._tab.Bytes, x) + return obj + return None + + # Attribute + def G(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(18)) + if o != 0: + x = self._tab.Indirect(o + self._tab.Pos) + from ort_flatbuffers_py.fbs.Graph import Graph + obj = Graph() + obj.Init(self._tab.Bytes, x) + return obj + return None + + # Attribute + def Floats(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(20)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Float32Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 4)) + return 0 + + # Attribute + def FloatsAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(20)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Float32Flags, o) + return 0 + + # Attribute + def FloatsLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(20)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Attribute + def FloatsIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(20)) + return o == 0 + + # Attribute + def Ints(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(22)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Int64Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 8)) + return 0 + + # Attribute + def IntsAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(22)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Int64Flags, o) + return 0 + + # Attribute + def IntsLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(22)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Attribute + def IntsIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(22)) + return o == 0 + + # Attribute + def Strings(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(24)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.String(a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 4)) + return "" + + # Attribute + def StringsLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(24)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Attribute + def StringsIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(24)) + return o == 0 + + # Attribute + def Tensors(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(26)) + if o != 0: + x = self._tab.Vector(o) + x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4 + x = self._tab.Indirect(x) + from ort_flatbuffers_py.fbs.Tensor import Tensor + obj = Tensor() + obj.Init(self._tab.Bytes, x) + return obj + return None + + # Attribute + def TensorsLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(26)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Attribute + def TensorsIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(26)) + return o == 0 + + # Attribute + def Graphs(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(28)) + if o != 0: + x = self._tab.Vector(o) + x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4 + x = self._tab.Indirect(x) + from ort_flatbuffers_py.fbs.Graph import Graph + obj = Graph() + obj.Init(self._tab.Bytes, x) + return obj + return None + + # Attribute + def GraphsLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(28)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Attribute + def GraphsIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(28)) + return o == 0 + +def AttributeStart(builder): + builder.StartObject(13) + +def Start(builder): + AttributeStart(builder) + +def AttributeAddName(builder, name): + builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(name), 0) + +def AddName(builder, name): + AttributeAddName(builder, name) + +def AttributeAddDocString(builder, docString): + builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(docString), 0) + +def AddDocString(builder, docString): + AttributeAddDocString(builder, docString) + +def AttributeAddType(builder, type): + builder.PrependInt32Slot(2, type, 0) + +def AddType(builder, type): + AttributeAddType(builder, type) + +def AttributeAddF(builder, f): + builder.PrependFloat32Slot(3, f, 0.0) + +def AddF(builder, f): + AttributeAddF(builder, f) + +def AttributeAddI(builder, i): + builder.PrependInt64Slot(4, i, 0) + +def AddI(builder, i): + AttributeAddI(builder, i) + +def AttributeAddS(builder, s): + builder.PrependUOffsetTRelativeSlot(5, flatbuffers.number_types.UOffsetTFlags.py_type(s), 0) + +def AddS(builder, s): + AttributeAddS(builder, s) + +def AttributeAddT(builder, t): + builder.PrependUOffsetTRelativeSlot(6, flatbuffers.number_types.UOffsetTFlags.py_type(t), 0) + +def AddT(builder, t): + AttributeAddT(builder, t) + +def AttributeAddG(builder, g): + builder.PrependUOffsetTRelativeSlot(7, flatbuffers.number_types.UOffsetTFlags.py_type(g), 0) + +def AddG(builder, g): + AttributeAddG(builder, g) + +def AttributeAddFloats(builder, floats): + builder.PrependUOffsetTRelativeSlot(8, flatbuffers.number_types.UOffsetTFlags.py_type(floats), 0) + +def AddFloats(builder, floats): + AttributeAddFloats(builder, floats) + +def AttributeStartFloatsVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def StartFloatsVector(builder, numElems: int) -> int: + return AttributeStartFloatsVector(builder, numElems) + +def AttributeAddInts(builder, ints): + builder.PrependUOffsetTRelativeSlot(9, flatbuffers.number_types.UOffsetTFlags.py_type(ints), 0) + +def AddInts(builder, ints): + AttributeAddInts(builder, ints) + +def AttributeStartIntsVector(builder, numElems): + return builder.StartVector(8, numElems, 8) + +def StartIntsVector(builder, numElems: int) -> int: + return AttributeStartIntsVector(builder, numElems) + +def AttributeAddStrings(builder, strings): + builder.PrependUOffsetTRelativeSlot(10, flatbuffers.number_types.UOffsetTFlags.py_type(strings), 0) + +def AddStrings(builder, strings): + AttributeAddStrings(builder, strings) + +def AttributeStartStringsVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def StartStringsVector(builder, numElems: int) -> int: + return AttributeStartStringsVector(builder, numElems) + +def AttributeAddTensors(builder, tensors): + builder.PrependUOffsetTRelativeSlot(11, flatbuffers.number_types.UOffsetTFlags.py_type(tensors), 0) + +def AddTensors(builder, tensors): + AttributeAddTensors(builder, tensors) + +def AttributeStartTensorsVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def StartTensorsVector(builder, numElems: int) -> int: + return AttributeStartTensorsVector(builder, numElems) + +def AttributeAddGraphs(builder, graphs): + builder.PrependUOffsetTRelativeSlot(12, flatbuffers.number_types.UOffsetTFlags.py_type(graphs), 0) + +def AddGraphs(builder, graphs): + AttributeAddGraphs(builder, graphs) + +def AttributeStartGraphsVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def StartGraphsVector(builder, numElems: int) -> int: + return AttributeStartGraphsVector(builder, numElems) + +def AttributeEnd(builder): + return builder.EndObject() + +def End(builder): + return AttributeEnd(builder) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/AttributeType.py b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/AttributeType.py new file mode 100644 index 0000000000000000000000000000000000000000..a7ee8309fad0fcf6f886aadc8ae08f16c9d8ca58 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/AttributeType.py @@ -0,0 +1,18 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: fbs + +class AttributeType(object): + UNDEFINED = 0 + FLOAT = 1 + INT = 2 + STRING = 3 + TENSOR = 4 + GRAPH = 5 + FLOATS = 6 + INTS = 7 + STRINGS = 8 + TENSORS = 9 + GRAPHS = 10 + SPARSE_TENSOR = 11 + SPARSE_TENSORS = 12 diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/Checkpoint.py b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/Checkpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..b8ace29fdaf79ac4083e1b894e8e9ca007bffd71 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/Checkpoint.py @@ -0,0 +1,125 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: fbs + +import flatbuffers +from flatbuffers.compat import import_numpy +np = import_numpy() + +class Checkpoint(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = Checkpoint() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsCheckpoint(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def CheckpointBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x4F\x44\x54\x43", size_prefixed=size_prefixed) + + # Checkpoint + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # Checkpoint + def Version(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return 0 + + # Checkpoint + def ModuleState(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + x = self._tab.Indirect(o + self._tab.Pos) + from ort_flatbuffers_py.fbs.ModuleState import ModuleState + obj = ModuleState() + obj.Init(self._tab.Bytes, x) + return obj + return None + + # Checkpoint + def OptimizerGroups(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + x = self._tab.Vector(o) + x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4 + x = self._tab.Indirect(x) + from ort_flatbuffers_py.fbs.OptimizerGroup import OptimizerGroup + obj = OptimizerGroup() + obj.Init(self._tab.Bytes, x) + return obj + return None + + # Checkpoint + def OptimizerGroupsLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Checkpoint + def OptimizerGroupsIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + return o == 0 + + # Checkpoint + def PropertyBag(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10)) + if o != 0: + x = self._tab.Indirect(o + self._tab.Pos) + from ort_flatbuffers_py.fbs.PropertyBag import PropertyBag + obj = PropertyBag() + obj.Init(self._tab.Bytes, x) + return obj + return None + +def CheckpointStart(builder): + builder.StartObject(4) + +def Start(builder): + CheckpointStart(builder) + +def CheckpointAddVersion(builder, version): + builder.PrependInt32Slot(0, version, 0) + +def AddVersion(builder, version): + CheckpointAddVersion(builder, version) + +def CheckpointAddModuleState(builder, moduleState): + builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(moduleState), 0) + +def AddModuleState(builder, moduleState): + CheckpointAddModuleState(builder, moduleState) + +def CheckpointAddOptimizerGroups(builder, optimizerGroups): + builder.PrependUOffsetTRelativeSlot(2, flatbuffers.number_types.UOffsetTFlags.py_type(optimizerGroups), 0) + +def AddOptimizerGroups(builder, optimizerGroups): + CheckpointAddOptimizerGroups(builder, optimizerGroups) + +def CheckpointStartOptimizerGroupsVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def StartOptimizerGroupsVector(builder, numElems: int) -> int: + return CheckpointStartOptimizerGroupsVector(builder, numElems) + +def CheckpointAddPropertyBag(builder, propertyBag): + builder.PrependUOffsetTRelativeSlot(3, flatbuffers.number_types.UOffsetTFlags.py_type(propertyBag), 0) + +def AddPropertyBag(builder, propertyBag): + CheckpointAddPropertyBag(builder, propertyBag) + +def CheckpointEnd(builder): + return builder.EndObject() + +def End(builder): + return CheckpointEnd(builder) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/DeprecatedKernelCreateInfos.py b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/DeprecatedKernelCreateInfos.py new file mode 100644 index 0000000000000000000000000000000000000000..e7640b4829893b290988dbff53149267f065cd13 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/DeprecatedKernelCreateInfos.py @@ -0,0 +1,120 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: fbs + +import flatbuffers +from flatbuffers.compat import import_numpy +np = import_numpy() + +# deprecated: no longer using kernel def hashes +class DeprecatedKernelCreateInfos(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = DeprecatedKernelCreateInfos() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsDeprecatedKernelCreateInfos(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def DeprecatedKernelCreateInfosBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x4F\x52\x54\x4D", size_prefixed=size_prefixed) + + # DeprecatedKernelCreateInfos + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # DeprecatedKernelCreateInfos + def NodeIndices(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Uint32Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 4)) + return 0 + + # DeprecatedKernelCreateInfos + def NodeIndicesAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Uint32Flags, o) + return 0 + + # DeprecatedKernelCreateInfos + def NodeIndicesLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # DeprecatedKernelCreateInfos + def NodeIndicesIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + return o == 0 + + # DeprecatedKernelCreateInfos + def KernelDefHashes(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Uint64Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 8)) + return 0 + + # DeprecatedKernelCreateInfos + def KernelDefHashesAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Uint64Flags, o) + return 0 + + # DeprecatedKernelCreateInfos + def KernelDefHashesLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # DeprecatedKernelCreateInfos + def KernelDefHashesIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + return o == 0 + +def DeprecatedKernelCreateInfosStart(builder): + builder.StartObject(2) + +def Start(builder): + DeprecatedKernelCreateInfosStart(builder) + +def DeprecatedKernelCreateInfosAddNodeIndices(builder, nodeIndices): + builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(nodeIndices), 0) + +def AddNodeIndices(builder, nodeIndices): + DeprecatedKernelCreateInfosAddNodeIndices(builder, nodeIndices) + +def DeprecatedKernelCreateInfosStartNodeIndicesVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def StartNodeIndicesVector(builder, numElems: int) -> int: + return DeprecatedKernelCreateInfosStartNodeIndicesVector(builder, numElems) + +def DeprecatedKernelCreateInfosAddKernelDefHashes(builder, kernelDefHashes): + builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(kernelDefHashes), 0) + +def AddKernelDefHashes(builder, kernelDefHashes): + DeprecatedKernelCreateInfosAddKernelDefHashes(builder, kernelDefHashes) + +def DeprecatedKernelCreateInfosStartKernelDefHashesVector(builder, numElems): + return builder.StartVector(8, numElems, 8) + +def StartKernelDefHashesVector(builder, numElems: int) -> int: + return DeprecatedKernelCreateInfosStartKernelDefHashesVector(builder, numElems) + +def DeprecatedKernelCreateInfosEnd(builder): + return builder.EndObject() + +def End(builder): + return DeprecatedKernelCreateInfosEnd(builder) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/DeprecatedNodeIndexAndKernelDefHash.py b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/DeprecatedNodeIndexAndKernelDefHash.py new file mode 100644 index 0000000000000000000000000000000000000000..ca5620aa6ae20e6cbfeb6316670002a95eb73370 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/DeprecatedNodeIndexAndKernelDefHash.py @@ -0,0 +1,68 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: fbs + +import flatbuffers +from flatbuffers.compat import import_numpy +np = import_numpy() + +# deprecated: no longer using kernel def hashes +class DeprecatedNodeIndexAndKernelDefHash(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = DeprecatedNodeIndexAndKernelDefHash() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsDeprecatedNodeIndexAndKernelDefHash(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def DeprecatedNodeIndexAndKernelDefHashBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x4F\x52\x54\x4D", size_prefixed=size_prefixed) + + # DeprecatedNodeIndexAndKernelDefHash + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # DeprecatedNodeIndexAndKernelDefHash + def NodeIndex(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint32Flags, o + self._tab.Pos) + return 0 + + # DeprecatedNodeIndexAndKernelDefHash + def KernelDefHash(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint64Flags, o + self._tab.Pos) + return 0 + +def DeprecatedNodeIndexAndKernelDefHashStart(builder): + builder.StartObject(2) + +def Start(builder): + DeprecatedNodeIndexAndKernelDefHashStart(builder) + +def DeprecatedNodeIndexAndKernelDefHashAddNodeIndex(builder, nodeIndex): + builder.PrependUint32Slot(0, nodeIndex, 0) + +def AddNodeIndex(builder, nodeIndex): + DeprecatedNodeIndexAndKernelDefHashAddNodeIndex(builder, nodeIndex) + +def DeprecatedNodeIndexAndKernelDefHashAddKernelDefHash(builder, kernelDefHash): + builder.PrependUint64Slot(1, kernelDefHash, 0) + +def AddKernelDefHash(builder, kernelDefHash): + DeprecatedNodeIndexAndKernelDefHashAddKernelDefHash(builder, kernelDefHash) + +def DeprecatedNodeIndexAndKernelDefHashEnd(builder): + return builder.EndObject() + +def End(builder): + return DeprecatedNodeIndexAndKernelDefHashEnd(builder) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/DeprecatedSessionState.py b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/DeprecatedSessionState.py new file mode 100644 index 0000000000000000000000000000000000000000..3700cf196b755628a146e7aa69fbce33846d5000 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/DeprecatedSessionState.py @@ -0,0 +1,96 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: fbs + +import flatbuffers +from flatbuffers.compat import import_numpy +np = import_numpy() + +# deprecated: no longer using kernel def hashes +class DeprecatedSessionState(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = DeprecatedSessionState() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsDeprecatedSessionState(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def DeprecatedSessionStateBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x4F\x52\x54\x4D", size_prefixed=size_prefixed) + + # DeprecatedSessionState + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # DeprecatedSessionState + def Kernels(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + x = self._tab.Indirect(o + self._tab.Pos) + from ort_flatbuffers_py.fbs.DeprecatedKernelCreateInfos import DeprecatedKernelCreateInfos + obj = DeprecatedKernelCreateInfos() + obj.Init(self._tab.Bytes, x) + return obj + return None + + # DeprecatedSessionState + def SubGraphSessionStates(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + x = self._tab.Vector(o) + x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4 + x = self._tab.Indirect(x) + from ort_flatbuffers_py.fbs.DeprecatedSubGraphSessionState import DeprecatedSubGraphSessionState + obj = DeprecatedSubGraphSessionState() + obj.Init(self._tab.Bytes, x) + return obj + return None + + # DeprecatedSessionState + def SubGraphSessionStatesLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # DeprecatedSessionState + def SubGraphSessionStatesIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + return o == 0 + +def DeprecatedSessionStateStart(builder): + builder.StartObject(2) + +def Start(builder): + DeprecatedSessionStateStart(builder) + +def DeprecatedSessionStateAddKernels(builder, kernels): + builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(kernels), 0) + +def AddKernels(builder, kernels): + DeprecatedSessionStateAddKernels(builder, kernels) + +def DeprecatedSessionStateAddSubGraphSessionStates(builder, subGraphSessionStates): + builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(subGraphSessionStates), 0) + +def AddSubGraphSessionStates(builder, subGraphSessionStates): + DeprecatedSessionStateAddSubGraphSessionStates(builder, subGraphSessionStates) + +def DeprecatedSessionStateStartSubGraphSessionStatesVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def StartSubGraphSessionStatesVector(builder, numElems: int) -> int: + return DeprecatedSessionStateStartSubGraphSessionStatesVector(builder, numElems) + +def DeprecatedSessionStateEnd(builder): + return builder.EndObject() + +def End(builder): + return DeprecatedSessionStateEnd(builder) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/DeprecatedSubGraphSessionState.py b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/DeprecatedSubGraphSessionState.py new file mode 100644 index 0000000000000000000000000000000000000000..42f2e566b3e5d201f3f75edac52c982767776f76 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/DeprecatedSubGraphSessionState.py @@ -0,0 +1,72 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: fbs + +import flatbuffers +from flatbuffers.compat import import_numpy +np = import_numpy() + +# deprecated: no longer using kernel def hashes +class DeprecatedSubGraphSessionState(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = DeprecatedSubGraphSessionState() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsDeprecatedSubGraphSessionState(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def DeprecatedSubGraphSessionStateBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x4F\x52\x54\x4D", size_prefixed=size_prefixed) + + # DeprecatedSubGraphSessionState + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # DeprecatedSubGraphSessionState + def GraphId(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.String(o + self._tab.Pos) + return None + + # DeprecatedSubGraphSessionState + def SessionState(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + x = self._tab.Indirect(o + self._tab.Pos) + from ort_flatbuffers_py.fbs.DeprecatedSessionState import DeprecatedSessionState + obj = DeprecatedSessionState() + obj.Init(self._tab.Bytes, x) + return obj + return None + +def DeprecatedSubGraphSessionStateStart(builder): + builder.StartObject(2) + +def Start(builder): + DeprecatedSubGraphSessionStateStart(builder) + +def DeprecatedSubGraphSessionStateAddGraphId(builder, graphId): + builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(graphId), 0) + +def AddGraphId(builder, graphId): + DeprecatedSubGraphSessionStateAddGraphId(builder, graphId) + +def DeprecatedSubGraphSessionStateAddSessionState(builder, sessionState): + builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(sessionState), 0) + +def AddSessionState(builder, sessionState): + DeprecatedSubGraphSessionStateAddSessionState(builder, sessionState) + +def DeprecatedSubGraphSessionStateEnd(builder): + return builder.EndObject() + +def End(builder): + return DeprecatedSubGraphSessionStateEnd(builder) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/Dimension.py b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/Dimension.py new file mode 100644 index 0000000000000000000000000000000000000000..275d333d748f2f484f910962f0fc0793c97f8e9f --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/Dimension.py @@ -0,0 +1,71 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: fbs + +import flatbuffers +from flatbuffers.compat import import_numpy +np = import_numpy() + +class Dimension(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = Dimension() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsDimension(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def DimensionBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x4F\x52\x54\x4D", size_prefixed=size_prefixed) + + # Dimension + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # Dimension + def Value(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + x = self._tab.Indirect(o + self._tab.Pos) + from ort_flatbuffers_py.fbs.DimensionValue import DimensionValue + obj = DimensionValue() + obj.Init(self._tab.Bytes, x) + return obj + return None + + # Dimension + def Denotation(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.String(o + self._tab.Pos) + return None + +def DimensionStart(builder): + builder.StartObject(2) + +def Start(builder): + DimensionStart(builder) + +def DimensionAddValue(builder, value): + builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(value), 0) + +def AddValue(builder, value): + DimensionAddValue(builder, value) + +def DimensionAddDenotation(builder, denotation): + builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(denotation), 0) + +def AddDenotation(builder, denotation): + DimensionAddDenotation(builder, denotation) + +def DimensionEnd(builder): + return builder.EndObject() + +def End(builder): + return DimensionEnd(builder) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/DimensionValue.py b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/DimensionValue.py new file mode 100644 index 0000000000000000000000000000000000000000..c49473b58829c247ca12c293cf9fbdf8ad805fac --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/DimensionValue.py @@ -0,0 +1,80 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: fbs + +import flatbuffers +from flatbuffers.compat import import_numpy +np = import_numpy() + +class DimensionValue(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = DimensionValue() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsDimensionValue(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def DimensionValueBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x4F\x52\x54\x4D", size_prefixed=size_prefixed) + + # DimensionValue + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # DimensionValue + def DimType(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int8Flags, o + self._tab.Pos) + return 0 + + # DimensionValue + def DimValue(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int64Flags, o + self._tab.Pos) + return 0 + + # DimensionValue + def DimParam(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + return self._tab.String(o + self._tab.Pos) + return None + +def DimensionValueStart(builder): + builder.StartObject(3) + +def Start(builder): + DimensionValueStart(builder) + +def DimensionValueAddDimType(builder, dimType): + builder.PrependInt8Slot(0, dimType, 0) + +def AddDimType(builder, dimType): + DimensionValueAddDimType(builder, dimType) + +def DimensionValueAddDimValue(builder, dimValue): + builder.PrependInt64Slot(1, dimValue, 0) + +def AddDimValue(builder, dimValue): + DimensionValueAddDimValue(builder, dimValue) + +def DimensionValueAddDimParam(builder, dimParam): + builder.PrependUOffsetTRelativeSlot(2, flatbuffers.number_types.UOffsetTFlags.py_type(dimParam), 0) + +def AddDimParam(builder, dimParam): + DimensionValueAddDimParam(builder, dimParam) + +def DimensionValueEnd(builder): + return builder.EndObject() + +def End(builder): + return DimensionValueEnd(builder) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/DimensionValueType.py b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/DimensionValueType.py new file mode 100644 index 0000000000000000000000000000000000000000..36d33bd9dd6526cc81afd283908b7a38ef96c3a8 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/DimensionValueType.py @@ -0,0 +1,8 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: fbs + +class DimensionValueType(object): + UNKNOWN = 0 + VALUE = 1 + PARAM = 2 diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/EdgeEnd.py b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/EdgeEnd.py new file mode 100644 index 0000000000000000000000000000000000000000..ac3afdf150d5268a3455569a8233b4daf04e0b6b --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/EdgeEnd.py @@ -0,0 +1,32 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: fbs + +import flatbuffers +from flatbuffers.compat import import_numpy +np = import_numpy() + +class EdgeEnd(object): + __slots__ = ['_tab'] + + @classmethod + def SizeOf(cls): + return 12 + + # EdgeEnd + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # EdgeEnd + def NodeIndex(self): return self._tab.Get(flatbuffers.number_types.Uint32Flags, self._tab.Pos + flatbuffers.number_types.UOffsetTFlags.py_type(0)) + # EdgeEnd + def SrcArgIndex(self): return self._tab.Get(flatbuffers.number_types.Int32Flags, self._tab.Pos + flatbuffers.number_types.UOffsetTFlags.py_type(4)) + # EdgeEnd + def DstArgIndex(self): return self._tab.Get(flatbuffers.number_types.Int32Flags, self._tab.Pos + flatbuffers.number_types.UOffsetTFlags.py_type(8)) + +def CreateEdgeEnd(builder, nodeIndex, srcArgIndex, dstArgIndex): + builder.Prep(4, 12) + builder.PrependInt32(dstArgIndex) + builder.PrependInt32(srcArgIndex) + builder.PrependUint32(nodeIndex) + return builder.Offset() diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/FloatProperty.py b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/FloatProperty.py new file mode 100644 index 0000000000000000000000000000000000000000..36976711fcf65e34908f13e7f0bf7849e0589b20 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/FloatProperty.py @@ -0,0 +1,67 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: fbs + +import flatbuffers +from flatbuffers.compat import import_numpy +np = import_numpy() + +class FloatProperty(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = FloatProperty() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsFloatProperty(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def FloatPropertyBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x4F\x44\x54\x43", size_prefixed=size_prefixed) + + # FloatProperty + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # FloatProperty + def Name(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.String(o + self._tab.Pos) + return None + + # FloatProperty + def Value(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Float32Flags, o + self._tab.Pos) + return 0.0 + +def FloatPropertyStart(builder): + builder.StartObject(2) + +def Start(builder): + FloatPropertyStart(builder) + +def FloatPropertyAddName(builder, name): + builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(name), 0) + +def AddName(builder, name): + FloatPropertyAddName(builder, name) + +def FloatPropertyAddValue(builder, value): + builder.PrependFloat32Slot(1, value, 0.0) + +def AddValue(builder, value): + FloatPropertyAddValue(builder, value) + +def FloatPropertyEnd(builder): + return builder.EndObject() + +def End(builder): + return FloatPropertyEnd(builder) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/Graph.py b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/Graph.py new file mode 100644 index 0000000000000000000000000000000000000000..800d3184d0a3e40c35c315400cb1595ce1c61508 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/Graph.py @@ -0,0 +1,320 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: fbs + +import flatbuffers +from flatbuffers.compat import import_numpy +np = import_numpy() + +class Graph(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = Graph() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsGraph(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def GraphBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x4F\x52\x54\x4D", size_prefixed=size_prefixed) + + # Graph + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # Graph + def Initializers(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + x = self._tab.Vector(o) + x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4 + x = self._tab.Indirect(x) + from ort_flatbuffers_py.fbs.Tensor import Tensor + obj = Tensor() + obj.Init(self._tab.Bytes, x) + return obj + return None + + # Graph + def InitializersLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Graph + def InitializersIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + return o == 0 + + # Graph + def NodeArgs(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + x = self._tab.Vector(o) + x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4 + x = self._tab.Indirect(x) + from ort_flatbuffers_py.fbs.ValueInfo import ValueInfo + obj = ValueInfo() + obj.Init(self._tab.Bytes, x) + return obj + return None + + # Graph + def NodeArgsLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Graph + def NodeArgsIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + return o == 0 + + # Graph + def Nodes(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + x = self._tab.Vector(o) + x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4 + x = self._tab.Indirect(x) + from ort_flatbuffers_py.fbs.Node import Node + obj = Node() + obj.Init(self._tab.Bytes, x) + return obj + return None + + # Graph + def NodesLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Graph + def NodesIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + return o == 0 + + # Graph + def MaxNodeIndex(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint32Flags, o + self._tab.Pos) + return 0 + + # Graph + def NodeEdges(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12)) + if o != 0: + x = self._tab.Vector(o) + x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4 + x = self._tab.Indirect(x) + from ort_flatbuffers_py.fbs.NodeEdge import NodeEdge + obj = NodeEdge() + obj.Init(self._tab.Bytes, x) + return obj + return None + + # Graph + def NodeEdgesLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Graph + def NodeEdgesIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12)) + return o == 0 + + # Graph + def Inputs(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(14)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.String(a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 4)) + return "" + + # Graph + def InputsLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(14)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Graph + def InputsIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(14)) + return o == 0 + + # Graph + def Outputs(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(16)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.String(a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 4)) + return "" + + # Graph + def OutputsLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(16)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Graph + def OutputsIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(16)) + return o == 0 + + # Graph + def SparseInitializers(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(18)) + if o != 0: + x = self._tab.Vector(o) + x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4 + x = self._tab.Indirect(x) + from ort_flatbuffers_py.fbs.SparseTensor import SparseTensor + obj = SparseTensor() + obj.Init(self._tab.Bytes, x) + return obj + return None + + # Graph + def SparseInitializersLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(18)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Graph + def SparseInitializersIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(18)) + return o == 0 + + # Graph + def RuntimeOptimizations(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(20)) + if o != 0: + x = self._tab.Indirect(o + self._tab.Pos) + from ort_flatbuffers_py.fbs.RuntimeOptimizations import RuntimeOptimizations + obj = RuntimeOptimizations() + obj.Init(self._tab.Bytes, x) + return obj + return None + +def GraphStart(builder): + builder.StartObject(9) + +def Start(builder): + GraphStart(builder) + +def GraphAddInitializers(builder, initializers): + builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(initializers), 0) + +def AddInitializers(builder, initializers): + GraphAddInitializers(builder, initializers) + +def GraphStartInitializersVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def StartInitializersVector(builder, numElems: int) -> int: + return GraphStartInitializersVector(builder, numElems) + +def GraphAddNodeArgs(builder, nodeArgs): + builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(nodeArgs), 0) + +def AddNodeArgs(builder, nodeArgs): + GraphAddNodeArgs(builder, nodeArgs) + +def GraphStartNodeArgsVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def StartNodeArgsVector(builder, numElems: int) -> int: + return GraphStartNodeArgsVector(builder, numElems) + +def GraphAddNodes(builder, nodes): + builder.PrependUOffsetTRelativeSlot(2, flatbuffers.number_types.UOffsetTFlags.py_type(nodes), 0) + +def AddNodes(builder, nodes): + GraphAddNodes(builder, nodes) + +def GraphStartNodesVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def StartNodesVector(builder, numElems: int) -> int: + return GraphStartNodesVector(builder, numElems) + +def GraphAddMaxNodeIndex(builder, maxNodeIndex): + builder.PrependUint32Slot(3, maxNodeIndex, 0) + +def AddMaxNodeIndex(builder, maxNodeIndex): + GraphAddMaxNodeIndex(builder, maxNodeIndex) + +def GraphAddNodeEdges(builder, nodeEdges): + builder.PrependUOffsetTRelativeSlot(4, flatbuffers.number_types.UOffsetTFlags.py_type(nodeEdges), 0) + +def AddNodeEdges(builder, nodeEdges): + GraphAddNodeEdges(builder, nodeEdges) + +def GraphStartNodeEdgesVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def StartNodeEdgesVector(builder, numElems: int) -> int: + return GraphStartNodeEdgesVector(builder, numElems) + +def GraphAddInputs(builder, inputs): + builder.PrependUOffsetTRelativeSlot(5, flatbuffers.number_types.UOffsetTFlags.py_type(inputs), 0) + +def AddInputs(builder, inputs): + GraphAddInputs(builder, inputs) + +def GraphStartInputsVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def StartInputsVector(builder, numElems: int) -> int: + return GraphStartInputsVector(builder, numElems) + +def GraphAddOutputs(builder, outputs): + builder.PrependUOffsetTRelativeSlot(6, flatbuffers.number_types.UOffsetTFlags.py_type(outputs), 0) + +def AddOutputs(builder, outputs): + GraphAddOutputs(builder, outputs) + +def GraphStartOutputsVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def StartOutputsVector(builder, numElems: int) -> int: + return GraphStartOutputsVector(builder, numElems) + +def GraphAddSparseInitializers(builder, sparseInitializers): + builder.PrependUOffsetTRelativeSlot(7, flatbuffers.number_types.UOffsetTFlags.py_type(sparseInitializers), 0) + +def AddSparseInitializers(builder, sparseInitializers): + GraphAddSparseInitializers(builder, sparseInitializers) + +def GraphStartSparseInitializersVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def StartSparseInitializersVector(builder, numElems: int) -> int: + return GraphStartSparseInitializersVector(builder, numElems) + +def GraphAddRuntimeOptimizations(builder, runtimeOptimizations): + builder.PrependUOffsetTRelativeSlot(8, flatbuffers.number_types.UOffsetTFlags.py_type(runtimeOptimizations), 0) + +def AddRuntimeOptimizations(builder, runtimeOptimizations): + GraphAddRuntimeOptimizations(builder, runtimeOptimizations) + +def GraphEnd(builder): + return builder.EndObject() + +def End(builder): + return GraphEnd(builder) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/InferenceSession.py b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/InferenceSession.py new file mode 100644 index 0000000000000000000000000000000000000000..3ad173a21330aad11fee6b9f69bff743e8e81bd3 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/InferenceSession.py @@ -0,0 +1,88 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: fbs + +import flatbuffers +from flatbuffers.compat import import_numpy +np = import_numpy() + +class InferenceSession(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = InferenceSession() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsInferenceSession(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def InferenceSessionBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x4F\x52\x54\x4D", size_prefixed=size_prefixed) + + # InferenceSession + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # InferenceSession + def OrtVersion(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.String(o + self._tab.Pos) + return None + + # InferenceSession + def Model(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + x = self._tab.Indirect(o + self._tab.Pos) + from ort_flatbuffers_py.fbs.Model import Model + obj = Model() + obj.Init(self._tab.Bytes, x) + return obj + return None + + # InferenceSession + def KernelTypeStrResolver(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10)) + if o != 0: + x = self._tab.Indirect(o + self._tab.Pos) + from ort_flatbuffers_py.fbs.KernelTypeStrResolver import KernelTypeStrResolver + obj = KernelTypeStrResolver() + obj.Init(self._tab.Bytes, x) + return obj + return None + +def InferenceSessionStart(builder): + builder.StartObject(4) + +def Start(builder): + InferenceSessionStart(builder) + +def InferenceSessionAddOrtVersion(builder, ortVersion): + builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(ortVersion), 0) + +def AddOrtVersion(builder, ortVersion): + InferenceSessionAddOrtVersion(builder, ortVersion) + +def InferenceSessionAddModel(builder, model): + builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(model), 0) + +def AddModel(builder, model): + InferenceSessionAddModel(builder, model) + +def InferenceSessionAddKernelTypeStrResolver(builder, kernelTypeStrResolver): + builder.PrependUOffsetTRelativeSlot(3, flatbuffers.number_types.UOffsetTFlags.py_type(kernelTypeStrResolver), 0) + +def AddKernelTypeStrResolver(builder, kernelTypeStrResolver): + InferenceSessionAddKernelTypeStrResolver(builder, kernelTypeStrResolver) + +def InferenceSessionEnd(builder): + return builder.EndObject() + +def End(builder): + return InferenceSessionEnd(builder) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/IntProperty.py b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/IntProperty.py new file mode 100644 index 0000000000000000000000000000000000000000..9fb55c642fb9061f9965ebddae46db4b852a32e3 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/IntProperty.py @@ -0,0 +1,67 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: fbs + +import flatbuffers +from flatbuffers.compat import import_numpy +np = import_numpy() + +class IntProperty(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = IntProperty() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsIntProperty(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def IntPropertyBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x4F\x44\x54\x43", size_prefixed=size_prefixed) + + # IntProperty + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # IntProperty + def Name(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.String(o + self._tab.Pos) + return None + + # IntProperty + def Value(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int64Flags, o + self._tab.Pos) + return 0 + +def IntPropertyStart(builder): + builder.StartObject(2) + +def Start(builder): + IntPropertyStart(builder) + +def IntPropertyAddName(builder, name): + builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(name), 0) + +def AddName(builder, name): + IntPropertyAddName(builder, name) + +def IntPropertyAddValue(builder, value): + builder.PrependInt64Slot(1, value, 0) + +def AddValue(builder, value): + IntPropertyAddValue(builder, value) + +def IntPropertyEnd(builder): + return builder.EndObject() + +def End(builder): + return IntPropertyEnd(builder) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/KernelTypeStrArgsEntry.py b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/KernelTypeStrArgsEntry.py new file mode 100644 index 0000000000000000000000000000000000000000..2279fe444729e98b2eef99ed9c9aef22a1f16b84 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/KernelTypeStrArgsEntry.py @@ -0,0 +1,91 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: fbs + +import flatbuffers +from flatbuffers.compat import import_numpy +np = import_numpy() + +class KernelTypeStrArgsEntry(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = KernelTypeStrArgsEntry() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsKernelTypeStrArgsEntry(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def KernelTypeStrArgsEntryBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x4F\x52\x54\x4D", size_prefixed=size_prefixed) + + # KernelTypeStrArgsEntry + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # KernelTypeStrArgsEntry + def KernelTypeStr(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.String(o + self._tab.Pos) + return None + + # KernelTypeStrArgsEntry + def Args(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + x = self._tab.Vector(o) + x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4 + x = self._tab.Indirect(x) + from ort_flatbuffers_py.fbs.ArgTypeAndIndex import ArgTypeAndIndex + obj = ArgTypeAndIndex() + obj.Init(self._tab.Bytes, x) + return obj + return None + + # KernelTypeStrArgsEntry + def ArgsLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # KernelTypeStrArgsEntry + def ArgsIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + return o == 0 + +def KernelTypeStrArgsEntryStart(builder): + builder.StartObject(2) + +def Start(builder): + KernelTypeStrArgsEntryStart(builder) + +def KernelTypeStrArgsEntryAddKernelTypeStr(builder, kernelTypeStr): + builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(kernelTypeStr), 0) + +def AddKernelTypeStr(builder, kernelTypeStr): + KernelTypeStrArgsEntryAddKernelTypeStr(builder, kernelTypeStr) + +def KernelTypeStrArgsEntryAddArgs(builder, args): + builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(args), 0) + +def AddArgs(builder, args): + KernelTypeStrArgsEntryAddArgs(builder, args) + +def KernelTypeStrArgsEntryStartArgsVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def StartArgsVector(builder, numElems: int) -> int: + return KernelTypeStrArgsEntryStartArgsVector(builder, numElems) + +def KernelTypeStrArgsEntryEnd(builder): + return builder.EndObject() + +def End(builder): + return KernelTypeStrArgsEntryEnd(builder) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/KernelTypeStrResolver.py b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/KernelTypeStrResolver.py new file mode 100644 index 0000000000000000000000000000000000000000..cee565f1ae8b3d5eacfabb47032aa30db188983a --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/KernelTypeStrResolver.py @@ -0,0 +1,78 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: fbs + +import flatbuffers +from flatbuffers.compat import import_numpy +np = import_numpy() + +class KernelTypeStrResolver(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = KernelTypeStrResolver() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsKernelTypeStrResolver(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def KernelTypeStrResolverBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x4F\x52\x54\x4D", size_prefixed=size_prefixed) + + # KernelTypeStrResolver + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # KernelTypeStrResolver + def OpKernelTypeStrArgs(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + x = self._tab.Vector(o) + x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4 + x = self._tab.Indirect(x) + from ort_flatbuffers_py.fbs.OpIdKernelTypeStrArgsEntry import OpIdKernelTypeStrArgsEntry + obj = OpIdKernelTypeStrArgsEntry() + obj.Init(self._tab.Bytes, x) + return obj + return None + + # KernelTypeStrResolver + def OpKernelTypeStrArgsLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # KernelTypeStrResolver + def OpKernelTypeStrArgsIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + return o == 0 + +def KernelTypeStrResolverStart(builder): + builder.StartObject(1) + +def Start(builder): + KernelTypeStrResolverStart(builder) + +def KernelTypeStrResolverAddOpKernelTypeStrArgs(builder, opKernelTypeStrArgs): + builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(opKernelTypeStrArgs), 0) + +def AddOpKernelTypeStrArgs(builder, opKernelTypeStrArgs): + KernelTypeStrResolverAddOpKernelTypeStrArgs(builder, opKernelTypeStrArgs) + +def KernelTypeStrResolverStartOpKernelTypeStrArgsVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def StartOpKernelTypeStrArgsVector(builder, numElems: int) -> int: + return KernelTypeStrResolverStartOpKernelTypeStrArgsVector(builder, numElems) + +def KernelTypeStrResolverEnd(builder): + return builder.EndObject() + +def End(builder): + return KernelTypeStrResolverEnd(builder) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/MapType.py b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/MapType.py new file mode 100644 index 0000000000000000000000000000000000000000..d7ff8fef4d2bd4224d459af504e9e44fe2aa0497 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/MapType.py @@ -0,0 +1,71 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: fbs + +import flatbuffers +from flatbuffers.compat import import_numpy +np = import_numpy() + +class MapType(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = MapType() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsMapType(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def MapTypeBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x4F\x52\x54\x4D", size_prefixed=size_prefixed) + + # MapType + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # MapType + def KeyType(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return 0 + + # MapType + def ValueType(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + x = self._tab.Indirect(o + self._tab.Pos) + from ort_flatbuffers_py.fbs.TypeInfo import TypeInfo + obj = TypeInfo() + obj.Init(self._tab.Bytes, x) + return obj + return None + +def MapTypeStart(builder): + builder.StartObject(2) + +def Start(builder): + MapTypeStart(builder) + +def MapTypeAddKeyType(builder, keyType): + builder.PrependInt32Slot(0, keyType, 0) + +def AddKeyType(builder, keyType): + MapTypeAddKeyType(builder, keyType) + +def MapTypeAddValueType(builder, valueType): + builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(valueType), 0) + +def AddValueType(builder, valueType): + MapTypeAddValueType(builder, valueType) + +def MapTypeEnd(builder): + return builder.EndObject() + +def End(builder): + return MapTypeEnd(builder) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/Model.py b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/Model.py new file mode 100644 index 0000000000000000000000000000000000000000..b1ab985851323f2ebabb28e81cfd97fb5c2179c7 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/Model.py @@ -0,0 +1,223 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: fbs + +import flatbuffers +from flatbuffers.compat import import_numpy +np = import_numpy() + +class Model(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = Model() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsModel(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def ModelBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x4F\x52\x54\x4D", size_prefixed=size_prefixed) + + # Model + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # Model + def IrVersion(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int64Flags, o + self._tab.Pos) + return 0 + + # Model + def OpsetImport(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + x = self._tab.Vector(o) + x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4 + x = self._tab.Indirect(x) + from ort_flatbuffers_py.fbs.OperatorSetId import OperatorSetId + obj = OperatorSetId() + obj.Init(self._tab.Bytes, x) + return obj + return None + + # Model + def OpsetImportLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Model + def OpsetImportIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + return o == 0 + + # Model + def ProducerName(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + return self._tab.String(o + self._tab.Pos) + return None + + # Model + def ProducerVersion(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10)) + if o != 0: + return self._tab.String(o + self._tab.Pos) + return None + + # Model + def Domain(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12)) + if o != 0: + return self._tab.String(o + self._tab.Pos) + return None + + # Model + def ModelVersion(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(14)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int64Flags, o + self._tab.Pos) + return 0 + + # Model + def DocString(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(16)) + if o != 0: + return self._tab.String(o + self._tab.Pos) + return None + + # Model + def Graph(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(18)) + if o != 0: + x = self._tab.Indirect(o + self._tab.Pos) + from ort_flatbuffers_py.fbs.Graph import Graph + obj = Graph() + obj.Init(self._tab.Bytes, x) + return obj + return None + + # Model + def GraphDocString(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(20)) + if o != 0: + return self._tab.String(o + self._tab.Pos) + return None + + # Model + def MetadataProps(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(22)) + if o != 0: + x = self._tab.Vector(o) + x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4 + x = self._tab.Indirect(x) + from ort_flatbuffers_py.fbs.StringStringEntry import StringStringEntry + obj = StringStringEntry() + obj.Init(self._tab.Bytes, x) + return obj + return None + + # Model + def MetadataPropsLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(22)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Model + def MetadataPropsIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(22)) + return o == 0 + +def ModelStart(builder): + builder.StartObject(10) + +def Start(builder): + ModelStart(builder) + +def ModelAddIrVersion(builder, irVersion): + builder.PrependInt64Slot(0, irVersion, 0) + +def AddIrVersion(builder, irVersion): + ModelAddIrVersion(builder, irVersion) + +def ModelAddOpsetImport(builder, opsetImport): + builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(opsetImport), 0) + +def AddOpsetImport(builder, opsetImport): + ModelAddOpsetImport(builder, opsetImport) + +def ModelStartOpsetImportVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def StartOpsetImportVector(builder, numElems: int) -> int: + return ModelStartOpsetImportVector(builder, numElems) + +def ModelAddProducerName(builder, producerName): + builder.PrependUOffsetTRelativeSlot(2, flatbuffers.number_types.UOffsetTFlags.py_type(producerName), 0) + +def AddProducerName(builder, producerName): + ModelAddProducerName(builder, producerName) + +def ModelAddProducerVersion(builder, producerVersion): + builder.PrependUOffsetTRelativeSlot(3, flatbuffers.number_types.UOffsetTFlags.py_type(producerVersion), 0) + +def AddProducerVersion(builder, producerVersion): + ModelAddProducerVersion(builder, producerVersion) + +def ModelAddDomain(builder, domain): + builder.PrependUOffsetTRelativeSlot(4, flatbuffers.number_types.UOffsetTFlags.py_type(domain), 0) + +def AddDomain(builder, domain): + ModelAddDomain(builder, domain) + +def ModelAddModelVersion(builder, modelVersion): + builder.PrependInt64Slot(5, modelVersion, 0) + +def AddModelVersion(builder, modelVersion): + ModelAddModelVersion(builder, modelVersion) + +def ModelAddDocString(builder, docString): + builder.PrependUOffsetTRelativeSlot(6, flatbuffers.number_types.UOffsetTFlags.py_type(docString), 0) + +def AddDocString(builder, docString): + ModelAddDocString(builder, docString) + +def ModelAddGraph(builder, graph): + builder.PrependUOffsetTRelativeSlot(7, flatbuffers.number_types.UOffsetTFlags.py_type(graph), 0) + +def AddGraph(builder, graph): + ModelAddGraph(builder, graph) + +def ModelAddGraphDocString(builder, graphDocString): + builder.PrependUOffsetTRelativeSlot(8, flatbuffers.number_types.UOffsetTFlags.py_type(graphDocString), 0) + +def AddGraphDocString(builder, graphDocString): + ModelAddGraphDocString(builder, graphDocString) + +def ModelAddMetadataProps(builder, metadataProps): + builder.PrependUOffsetTRelativeSlot(9, flatbuffers.number_types.UOffsetTFlags.py_type(metadataProps), 0) + +def AddMetadataProps(builder, metadataProps): + ModelAddMetadataProps(builder, metadataProps) + +def ModelStartMetadataPropsVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def StartMetadataPropsVector(builder, numElems: int) -> int: + return ModelStartMetadataPropsVector(builder, numElems) + +def ModelEnd(builder): + return builder.EndObject() + +def End(builder): + return ModelEnd(builder) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/ModuleState.py b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/ModuleState.py new file mode 100644 index 0000000000000000000000000000000000000000..b3948e94638d1e6aff7203140f3f4acedbd4e3dd --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/ModuleState.py @@ -0,0 +1,141 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: fbs + +import flatbuffers +from flatbuffers.compat import import_numpy +np = import_numpy() + +class ModuleState(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = ModuleState() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsModuleState(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def ModuleStateBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x4F\x44\x54\x43", size_prefixed=size_prefixed) + + # ModuleState + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # ModuleState + def RequiresGradParams(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + x = self._tab.Vector(o) + x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4 + x = self._tab.Indirect(x) + from ort_flatbuffers_py.fbs.Tensor import Tensor + obj = Tensor() + obj.Init(self._tab.Bytes, x) + return obj + return None + + # ModuleState + def RequiresGradParamsLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # ModuleState + def RequiresGradParamsIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + return o == 0 + + # ModuleState + def FrozenParams(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + x = self._tab.Vector(o) + x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4 + x = self._tab.Indirect(x) + from ort_flatbuffers_py.fbs.Tensor import Tensor + obj = Tensor() + obj.Init(self._tab.Bytes, x) + return obj + return None + + # ModuleState + def FrozenParamsLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # ModuleState + def FrozenParamsIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + return o == 0 + + # ModuleState + def IsNominalState(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + return bool(self._tab.Get(flatbuffers.number_types.BoolFlags, o + self._tab.Pos)) + return False + + # ModuleState + def HasExternalData(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10)) + if o != 0: + return bool(self._tab.Get(flatbuffers.number_types.BoolFlags, o + self._tab.Pos)) + return False + +def ModuleStateStart(builder): + builder.StartObject(4) + +def Start(builder): + ModuleStateStart(builder) + +def ModuleStateAddRequiresGradParams(builder, requiresGradParams): + builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(requiresGradParams), 0) + +def AddRequiresGradParams(builder, requiresGradParams): + ModuleStateAddRequiresGradParams(builder, requiresGradParams) + +def ModuleStateStartRequiresGradParamsVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def StartRequiresGradParamsVector(builder, numElems: int) -> int: + return ModuleStateStartRequiresGradParamsVector(builder, numElems) + +def ModuleStateAddFrozenParams(builder, frozenParams): + builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(frozenParams), 0) + +def AddFrozenParams(builder, frozenParams): + ModuleStateAddFrozenParams(builder, frozenParams) + +def ModuleStateStartFrozenParamsVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def StartFrozenParamsVector(builder, numElems: int) -> int: + return ModuleStateStartFrozenParamsVector(builder, numElems) + +def ModuleStateAddIsNominalState(builder, isNominalState): + builder.PrependBoolSlot(2, isNominalState, 0) + +def AddIsNominalState(builder, isNominalState): + ModuleStateAddIsNominalState(builder, isNominalState) + +def ModuleStateAddHasExternalData(builder, hasExternalData): + builder.PrependBoolSlot(3, hasExternalData, 0) + +def AddHasExternalData(builder, hasExternalData): + ModuleStateAddHasExternalData(builder, hasExternalData) + +def ModuleStateEnd(builder): + return builder.EndObject() + +def End(builder): + return ModuleStateEnd(builder) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/Node.py b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/Node.py new file mode 100644 index 0000000000000000000000000000000000000000..c78dd92a14a15efbd94cc6187a4918b1ade30aba --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/Node.py @@ -0,0 +1,317 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: fbs + +import flatbuffers +from flatbuffers.compat import import_numpy +np = import_numpy() + +class Node(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = Node() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsNode(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def NodeBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x4F\x52\x54\x4D", size_prefixed=size_prefixed) + + # Node + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # Node + def Name(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.String(o + self._tab.Pos) + return None + + # Node + def DocString(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.String(o + self._tab.Pos) + return None + + # Node + def Domain(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + return self._tab.String(o + self._tab.Pos) + return None + + # Node + def SinceVersion(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return 0 + + # Node + def Index(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint32Flags, o + self._tab.Pos) + return 0 + + # Node + def OpType(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(14)) + if o != 0: + return self._tab.String(o + self._tab.Pos) + return None + + # Node + def Type(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(16)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return 0 + + # Node + def ExecutionProviderType(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(18)) + if o != 0: + return self._tab.String(o + self._tab.Pos) + return None + + # Node + def Inputs(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(20)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.String(a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 4)) + return "" + + # Node + def InputsLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(20)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Node + def InputsIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(20)) + return o == 0 + + # Node + def Outputs(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(22)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.String(a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 4)) + return "" + + # Node + def OutputsLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(22)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Node + def OutputsIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(22)) + return o == 0 + + # Node + def Attributes(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(24)) + if o != 0: + x = self._tab.Vector(o) + x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4 + x = self._tab.Indirect(x) + from ort_flatbuffers_py.fbs.Attribute import Attribute + obj = Attribute() + obj.Init(self._tab.Bytes, x) + return obj + return None + + # Node + def AttributesLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(24)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Node + def AttributesIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(24)) + return o == 0 + + # Node + def InputArgCounts(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(26)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Int32Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 4)) + return 0 + + # Node + def InputArgCountsAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(26)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Int32Flags, o) + return 0 + + # Node + def InputArgCountsLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(26)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Node + def InputArgCountsIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(26)) + return o == 0 + + # Node + def ImplicitInputs(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(28)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.String(a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 4)) + return "" + + # Node + def ImplicitInputsLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(28)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Node + def ImplicitInputsIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(28)) + return o == 0 + +def NodeStart(builder): + builder.StartObject(13) + +def Start(builder): + NodeStart(builder) + +def NodeAddName(builder, name): + builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(name), 0) + +def AddName(builder, name): + NodeAddName(builder, name) + +def NodeAddDocString(builder, docString): + builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(docString), 0) + +def AddDocString(builder, docString): + NodeAddDocString(builder, docString) + +def NodeAddDomain(builder, domain): + builder.PrependUOffsetTRelativeSlot(2, flatbuffers.number_types.UOffsetTFlags.py_type(domain), 0) + +def AddDomain(builder, domain): + NodeAddDomain(builder, domain) + +def NodeAddSinceVersion(builder, sinceVersion): + builder.PrependInt32Slot(3, sinceVersion, 0) + +def AddSinceVersion(builder, sinceVersion): + NodeAddSinceVersion(builder, sinceVersion) + +def NodeAddIndex(builder, index): + builder.PrependUint32Slot(4, index, 0) + +def AddIndex(builder, index): + NodeAddIndex(builder, index) + +def NodeAddOpType(builder, opType): + builder.PrependUOffsetTRelativeSlot(5, flatbuffers.number_types.UOffsetTFlags.py_type(opType), 0) + +def AddOpType(builder, opType): + NodeAddOpType(builder, opType) + +def NodeAddType(builder, type): + builder.PrependInt32Slot(6, type, 0) + +def AddType(builder, type): + NodeAddType(builder, type) + +def NodeAddExecutionProviderType(builder, executionProviderType): + builder.PrependUOffsetTRelativeSlot(7, flatbuffers.number_types.UOffsetTFlags.py_type(executionProviderType), 0) + +def AddExecutionProviderType(builder, executionProviderType): + NodeAddExecutionProviderType(builder, executionProviderType) + +def NodeAddInputs(builder, inputs): + builder.PrependUOffsetTRelativeSlot(8, flatbuffers.number_types.UOffsetTFlags.py_type(inputs), 0) + +def AddInputs(builder, inputs): + NodeAddInputs(builder, inputs) + +def NodeStartInputsVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def StartInputsVector(builder, numElems: int) -> int: + return NodeStartInputsVector(builder, numElems) + +def NodeAddOutputs(builder, outputs): + builder.PrependUOffsetTRelativeSlot(9, flatbuffers.number_types.UOffsetTFlags.py_type(outputs), 0) + +def AddOutputs(builder, outputs): + NodeAddOutputs(builder, outputs) + +def NodeStartOutputsVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def StartOutputsVector(builder, numElems: int) -> int: + return NodeStartOutputsVector(builder, numElems) + +def NodeAddAttributes(builder, attributes): + builder.PrependUOffsetTRelativeSlot(10, flatbuffers.number_types.UOffsetTFlags.py_type(attributes), 0) + +def AddAttributes(builder, attributes): + NodeAddAttributes(builder, attributes) + +def NodeStartAttributesVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def StartAttributesVector(builder, numElems: int) -> int: + return NodeStartAttributesVector(builder, numElems) + +def NodeAddInputArgCounts(builder, inputArgCounts): + builder.PrependUOffsetTRelativeSlot(11, flatbuffers.number_types.UOffsetTFlags.py_type(inputArgCounts), 0) + +def AddInputArgCounts(builder, inputArgCounts): + NodeAddInputArgCounts(builder, inputArgCounts) + +def NodeStartInputArgCountsVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def StartInputArgCountsVector(builder, numElems: int) -> int: + return NodeStartInputArgCountsVector(builder, numElems) + +def NodeAddImplicitInputs(builder, implicitInputs): + builder.PrependUOffsetTRelativeSlot(12, flatbuffers.number_types.UOffsetTFlags.py_type(implicitInputs), 0) + +def AddImplicitInputs(builder, implicitInputs): + NodeAddImplicitInputs(builder, implicitInputs) + +def NodeStartImplicitInputsVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def StartImplicitInputsVector(builder, numElems: int) -> int: + return NodeStartImplicitInputsVector(builder, numElems) + +def NodeEnd(builder): + return builder.EndObject() + +def End(builder): + return NodeEnd(builder) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/NodeEdge.py b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/NodeEdge.py new file mode 100644 index 0000000000000000000000000000000000000000..de3fb21eab1fcf601a714da4bd77a1363227a537 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/NodeEdge.py @@ -0,0 +1,126 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: fbs + +import flatbuffers +from flatbuffers.compat import import_numpy +np = import_numpy() + +class NodeEdge(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = NodeEdge() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsNodeEdge(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def NodeEdgeBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x4F\x52\x54\x4D", size_prefixed=size_prefixed) + + # NodeEdge + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # NodeEdge + def NodeIndex(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint32Flags, o + self._tab.Pos) + return 0 + + # NodeEdge + def InputEdges(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + x = self._tab.Vector(o) + x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 12 + from ort_flatbuffers_py.fbs.EdgeEnd import EdgeEnd + obj = EdgeEnd() + obj.Init(self._tab.Bytes, x) + return obj + return None + + # NodeEdge + def InputEdgesLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # NodeEdge + def InputEdgesIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + return o == 0 + + # NodeEdge + def OutputEdges(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + x = self._tab.Vector(o) + x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 12 + from ort_flatbuffers_py.fbs.EdgeEnd import EdgeEnd + obj = EdgeEnd() + obj.Init(self._tab.Bytes, x) + return obj + return None + + # NodeEdge + def OutputEdgesLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # NodeEdge + def OutputEdgesIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + return o == 0 + +def NodeEdgeStart(builder): + builder.StartObject(3) + +def Start(builder): + NodeEdgeStart(builder) + +def NodeEdgeAddNodeIndex(builder, nodeIndex): + builder.PrependUint32Slot(0, nodeIndex, 0) + +def AddNodeIndex(builder, nodeIndex): + NodeEdgeAddNodeIndex(builder, nodeIndex) + +def NodeEdgeAddInputEdges(builder, inputEdges): + builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(inputEdges), 0) + +def AddInputEdges(builder, inputEdges): + NodeEdgeAddInputEdges(builder, inputEdges) + +def NodeEdgeStartInputEdgesVector(builder, numElems): + return builder.StartVector(12, numElems, 4) + +def StartInputEdgesVector(builder, numElems: int) -> int: + return NodeEdgeStartInputEdgesVector(builder, numElems) + +def NodeEdgeAddOutputEdges(builder, outputEdges): + builder.PrependUOffsetTRelativeSlot(2, flatbuffers.number_types.UOffsetTFlags.py_type(outputEdges), 0) + +def AddOutputEdges(builder, outputEdges): + NodeEdgeAddOutputEdges(builder, outputEdges) + +def NodeEdgeStartOutputEdgesVector(builder, numElems): + return builder.StartVector(12, numElems, 4) + +def StartOutputEdgesVector(builder, numElems: int) -> int: + return NodeEdgeStartOutputEdgesVector(builder, numElems) + +def NodeEdgeEnd(builder): + return builder.EndObject() + +def End(builder): + return NodeEdgeEnd(builder) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/NodeType.py b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/NodeType.py new file mode 100644 index 0000000000000000000000000000000000000000..031e13dbf0a5d4d957682cdc441e2d82b9306b7c --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/NodeType.py @@ -0,0 +1,7 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: fbs + +class NodeType(object): + Primitive = 0 + Fused = 1 diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/NodesToOptimizeIndices.py b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/NodesToOptimizeIndices.py new file mode 100644 index 0000000000000000000000000000000000000000..b6aebd1cd30ecd1fb6500c1d76142bf80b818af6 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/NodesToOptimizeIndices.py @@ -0,0 +1,160 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: fbs + +import flatbuffers +from flatbuffers.compat import import_numpy +np = import_numpy() + +# nodes to consider for a runtime optimization +# see corresponding type in onnxruntime/core/graph/runtime_optimization_record.h +class NodesToOptimizeIndices(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = NodesToOptimizeIndices() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsNodesToOptimizeIndices(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def NodesToOptimizeIndicesBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x4F\x52\x54\x4D", size_prefixed=size_prefixed) + + # NodesToOptimizeIndices + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # NodesToOptimizeIndices + def NodeIndices(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Uint32Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 4)) + return 0 + + # NodesToOptimizeIndices + def NodeIndicesAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Uint32Flags, o) + return 0 + + # NodesToOptimizeIndices + def NodeIndicesLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # NodesToOptimizeIndices + def NodeIndicesIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + return o == 0 + + # NodesToOptimizeIndices + def NumInputs(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint32Flags, o + self._tab.Pos) + return 0 + + # NodesToOptimizeIndices + def NumOutputs(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint32Flags, o + self._tab.Pos) + return 0 + + # NodesToOptimizeIndices + def HasVariadicInput(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10)) + if o != 0: + return bool(self._tab.Get(flatbuffers.number_types.BoolFlags, o + self._tab.Pos)) + return False + + # NodesToOptimizeIndices + def HasVariadicOutput(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12)) + if o != 0: + return bool(self._tab.Get(flatbuffers.number_types.BoolFlags, o + self._tab.Pos)) + return False + + # NodesToOptimizeIndices + def NumVariadicInputs(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(14)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint32Flags, o + self._tab.Pos) + return 0 + + # NodesToOptimizeIndices + def NumVariadicOutputs(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(16)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint32Flags, o + self._tab.Pos) + return 0 + +def NodesToOptimizeIndicesStart(builder): + builder.StartObject(7) + +def Start(builder): + NodesToOptimizeIndicesStart(builder) + +def NodesToOptimizeIndicesAddNodeIndices(builder, nodeIndices): + builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(nodeIndices), 0) + +def AddNodeIndices(builder, nodeIndices): + NodesToOptimizeIndicesAddNodeIndices(builder, nodeIndices) + +def NodesToOptimizeIndicesStartNodeIndicesVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def StartNodeIndicesVector(builder, numElems: int) -> int: + return NodesToOptimizeIndicesStartNodeIndicesVector(builder, numElems) + +def NodesToOptimizeIndicesAddNumInputs(builder, numInputs): + builder.PrependUint32Slot(1, numInputs, 0) + +def AddNumInputs(builder, numInputs): + NodesToOptimizeIndicesAddNumInputs(builder, numInputs) + +def NodesToOptimizeIndicesAddNumOutputs(builder, numOutputs): + builder.PrependUint32Slot(2, numOutputs, 0) + +def AddNumOutputs(builder, numOutputs): + NodesToOptimizeIndicesAddNumOutputs(builder, numOutputs) + +def NodesToOptimizeIndicesAddHasVariadicInput(builder, hasVariadicInput): + builder.PrependBoolSlot(3, hasVariadicInput, 0) + +def AddHasVariadicInput(builder, hasVariadicInput): + NodesToOptimizeIndicesAddHasVariadicInput(builder, hasVariadicInput) + +def NodesToOptimizeIndicesAddHasVariadicOutput(builder, hasVariadicOutput): + builder.PrependBoolSlot(4, hasVariadicOutput, 0) + +def AddHasVariadicOutput(builder, hasVariadicOutput): + NodesToOptimizeIndicesAddHasVariadicOutput(builder, hasVariadicOutput) + +def NodesToOptimizeIndicesAddNumVariadicInputs(builder, numVariadicInputs): + builder.PrependUint32Slot(5, numVariadicInputs, 0) + +def AddNumVariadicInputs(builder, numVariadicInputs): + NodesToOptimizeIndicesAddNumVariadicInputs(builder, numVariadicInputs) + +def NodesToOptimizeIndicesAddNumVariadicOutputs(builder, numVariadicOutputs): + builder.PrependUint32Slot(6, numVariadicOutputs, 0) + +def AddNumVariadicOutputs(builder, numVariadicOutputs): + NodesToOptimizeIndicesAddNumVariadicOutputs(builder, numVariadicOutputs) + +def NodesToOptimizeIndicesEnd(builder): + return builder.EndObject() + +def End(builder): + return NodesToOptimizeIndicesEnd(builder) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/OpIdKernelTypeStrArgsEntry.py b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/OpIdKernelTypeStrArgsEntry.py new file mode 100644 index 0000000000000000000000000000000000000000..75f2732bc1b266da4d7e6b88fe43dfc42d22ee37 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/OpIdKernelTypeStrArgsEntry.py @@ -0,0 +1,91 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: fbs + +import flatbuffers +from flatbuffers.compat import import_numpy +np = import_numpy() + +class OpIdKernelTypeStrArgsEntry(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = OpIdKernelTypeStrArgsEntry() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsOpIdKernelTypeStrArgsEntry(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def OpIdKernelTypeStrArgsEntryBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x4F\x52\x54\x4D", size_prefixed=size_prefixed) + + # OpIdKernelTypeStrArgsEntry + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # OpIdKernelTypeStrArgsEntry + def OpId(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.String(o + self._tab.Pos) + return None + + # OpIdKernelTypeStrArgsEntry + def KernelTypeStrArgs(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + x = self._tab.Vector(o) + x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4 + x = self._tab.Indirect(x) + from ort_flatbuffers_py.fbs.KernelTypeStrArgsEntry import KernelTypeStrArgsEntry + obj = KernelTypeStrArgsEntry() + obj.Init(self._tab.Bytes, x) + return obj + return None + + # OpIdKernelTypeStrArgsEntry + def KernelTypeStrArgsLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # OpIdKernelTypeStrArgsEntry + def KernelTypeStrArgsIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + return o == 0 + +def OpIdKernelTypeStrArgsEntryStart(builder): + builder.StartObject(2) + +def Start(builder): + OpIdKernelTypeStrArgsEntryStart(builder) + +def OpIdKernelTypeStrArgsEntryAddOpId(builder, opId): + builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(opId), 0) + +def AddOpId(builder, opId): + OpIdKernelTypeStrArgsEntryAddOpId(builder, opId) + +def OpIdKernelTypeStrArgsEntryAddKernelTypeStrArgs(builder, kernelTypeStrArgs): + builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(kernelTypeStrArgs), 0) + +def AddKernelTypeStrArgs(builder, kernelTypeStrArgs): + OpIdKernelTypeStrArgsEntryAddKernelTypeStrArgs(builder, kernelTypeStrArgs) + +def OpIdKernelTypeStrArgsEntryStartKernelTypeStrArgsVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def StartKernelTypeStrArgsVector(builder, numElems: int) -> int: + return OpIdKernelTypeStrArgsEntryStartKernelTypeStrArgsVector(builder, numElems) + +def OpIdKernelTypeStrArgsEntryEnd(builder): + return builder.EndObject() + +def End(builder): + return OpIdKernelTypeStrArgsEntryEnd(builder) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/OperatorSetId.py b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/OperatorSetId.py new file mode 100644 index 0000000000000000000000000000000000000000..1452cfcbf0f8497abd812dc602d138df93efc6fd --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/OperatorSetId.py @@ -0,0 +1,67 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: fbs + +import flatbuffers +from flatbuffers.compat import import_numpy +np = import_numpy() + +class OperatorSetId(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = OperatorSetId() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsOperatorSetId(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def OperatorSetIdBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x4F\x52\x54\x4D", size_prefixed=size_prefixed) + + # OperatorSetId + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # OperatorSetId + def Domain(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.String(o + self._tab.Pos) + return None + + # OperatorSetId + def Version(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int64Flags, o + self._tab.Pos) + return 0 + +def OperatorSetIdStart(builder): + builder.StartObject(2) + +def Start(builder): + OperatorSetIdStart(builder) + +def OperatorSetIdAddDomain(builder, domain): + builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(domain), 0) + +def AddDomain(builder, domain): + OperatorSetIdAddDomain(builder, domain) + +def OperatorSetIdAddVersion(builder, version): + builder.PrependInt64Slot(1, version, 0) + +def AddVersion(builder, version): + OperatorSetIdAddVersion(builder, version) + +def OperatorSetIdEnd(builder): + return builder.EndObject() + +def End(builder): + return OperatorSetIdEnd(builder) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/OptimizerGroup.py b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/OptimizerGroup.py new file mode 100644 index 0000000000000000000000000000000000000000..e86c97984984b6865389da2e44901495be49e876 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/OptimizerGroup.py @@ -0,0 +1,117 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: fbs + +import flatbuffers +from flatbuffers.compat import import_numpy +np = import_numpy() + +class OptimizerGroup(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = OptimizerGroup() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsOptimizerGroup(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def OptimizerGroupBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x4F\x44\x54\x43", size_prefixed=size_prefixed) + + # OptimizerGroup + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # OptimizerGroup + def GroupName(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.String(o + self._tab.Pos) + return None + + # OptimizerGroup + def Step(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int64Flags, o + self._tab.Pos) + return 0 + + # OptimizerGroup + def InitialLearningRate(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Float32Flags, o + self._tab.Pos) + return 0.0 + + # OptimizerGroup + def OptimizerStates(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10)) + if o != 0: + x = self._tab.Vector(o) + x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4 + x = self._tab.Indirect(x) + from ort_flatbuffers_py.fbs.ParameterOptimizerState import ParameterOptimizerState + obj = ParameterOptimizerState() + obj.Init(self._tab.Bytes, x) + return obj + return None + + # OptimizerGroup + def OptimizerStatesLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # OptimizerGroup + def OptimizerStatesIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10)) + return o == 0 + +def OptimizerGroupStart(builder): + builder.StartObject(4) + +def Start(builder): + OptimizerGroupStart(builder) + +def OptimizerGroupAddGroupName(builder, groupName): + builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(groupName), 0) + +def AddGroupName(builder, groupName): + OptimizerGroupAddGroupName(builder, groupName) + +def OptimizerGroupAddStep(builder, step): + builder.PrependInt64Slot(1, step, 0) + +def AddStep(builder, step): + OptimizerGroupAddStep(builder, step) + +def OptimizerGroupAddInitialLearningRate(builder, initialLearningRate): + builder.PrependFloat32Slot(2, initialLearningRate, 0.0) + +def AddInitialLearningRate(builder, initialLearningRate): + OptimizerGroupAddInitialLearningRate(builder, initialLearningRate) + +def OptimizerGroupAddOptimizerStates(builder, optimizerStates): + builder.PrependUOffsetTRelativeSlot(3, flatbuffers.number_types.UOffsetTFlags.py_type(optimizerStates), 0) + +def AddOptimizerStates(builder, optimizerStates): + OptimizerGroupAddOptimizerStates(builder, optimizerStates) + +def OptimizerGroupStartOptimizerStatesVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def StartOptimizerStatesVector(builder, numElems: int) -> int: + return OptimizerGroupStartOptimizerStatesVector(builder, numElems) + +def OptimizerGroupEnd(builder): + return builder.EndObject() + +def End(builder): + return OptimizerGroupEnd(builder) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/ParameterOptimizerState.py b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/ParameterOptimizerState.py new file mode 100644 index 0000000000000000000000000000000000000000..de6efe4e96ccb4c9008a431d7d41ca08b1138777 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/ParameterOptimizerState.py @@ -0,0 +1,91 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: fbs + +import flatbuffers +from flatbuffers.compat import import_numpy +np = import_numpy() + +class ParameterOptimizerState(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = ParameterOptimizerState() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsParameterOptimizerState(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def ParameterOptimizerStateBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x4F\x44\x54\x43", size_prefixed=size_prefixed) + + # ParameterOptimizerState + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # ParameterOptimizerState + def ParamName(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.String(o + self._tab.Pos) + return None + + # ParameterOptimizerState + def Momentums(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + x = self._tab.Vector(o) + x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4 + x = self._tab.Indirect(x) + from ort_flatbuffers_py.fbs.Tensor import Tensor + obj = Tensor() + obj.Init(self._tab.Bytes, x) + return obj + return None + + # ParameterOptimizerState + def MomentumsLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # ParameterOptimizerState + def MomentumsIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + return o == 0 + +def ParameterOptimizerStateStart(builder): + builder.StartObject(2) + +def Start(builder): + ParameterOptimizerStateStart(builder) + +def ParameterOptimizerStateAddParamName(builder, paramName): + builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(paramName), 0) + +def AddParamName(builder, paramName): + ParameterOptimizerStateAddParamName(builder, paramName) + +def ParameterOptimizerStateAddMomentums(builder, momentums): + builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(momentums), 0) + +def AddMomentums(builder, momentums): + ParameterOptimizerStateAddMomentums(builder, momentums) + +def ParameterOptimizerStateStartMomentumsVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def StartMomentumsVector(builder, numElems: int) -> int: + return ParameterOptimizerStateStartMomentumsVector(builder, numElems) + +def ParameterOptimizerStateEnd(builder): + return builder.EndObject() + +def End(builder): + return ParameterOptimizerStateEnd(builder) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/PropertyBag.py b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/PropertyBag.py new file mode 100644 index 0000000000000000000000000000000000000000..05c5829d693c0af2c910d3935ab99667b185a42a --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/PropertyBag.py @@ -0,0 +1,152 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: fbs + +import flatbuffers +from flatbuffers.compat import import_numpy +np = import_numpy() + +class PropertyBag(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = PropertyBag() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsPropertyBag(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def PropertyBagBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x4F\x44\x54\x43", size_prefixed=size_prefixed) + + # PropertyBag + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # PropertyBag + def Ints(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + x = self._tab.Vector(o) + x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4 + x = self._tab.Indirect(x) + from ort_flatbuffers_py.fbs.IntProperty import IntProperty + obj = IntProperty() + obj.Init(self._tab.Bytes, x) + return obj + return None + + # PropertyBag + def IntsLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # PropertyBag + def IntsIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + return o == 0 + + # PropertyBag + def Floats(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + x = self._tab.Vector(o) + x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4 + x = self._tab.Indirect(x) + from ort_flatbuffers_py.fbs.FloatProperty import FloatProperty + obj = FloatProperty() + obj.Init(self._tab.Bytes, x) + return obj + return None + + # PropertyBag + def FloatsLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # PropertyBag + def FloatsIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + return o == 0 + + # PropertyBag + def Strings(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + x = self._tab.Vector(o) + x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4 + x = self._tab.Indirect(x) + from ort_flatbuffers_py.fbs.StringProperty import StringProperty + obj = StringProperty() + obj.Init(self._tab.Bytes, x) + return obj + return None + + # PropertyBag + def StringsLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # PropertyBag + def StringsIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + return o == 0 + +def PropertyBagStart(builder): + builder.StartObject(3) + +def Start(builder): + PropertyBagStart(builder) + +def PropertyBagAddInts(builder, ints): + builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(ints), 0) + +def AddInts(builder, ints): + PropertyBagAddInts(builder, ints) + +def PropertyBagStartIntsVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def StartIntsVector(builder, numElems: int) -> int: + return PropertyBagStartIntsVector(builder, numElems) + +def PropertyBagAddFloats(builder, floats): + builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(floats), 0) + +def AddFloats(builder, floats): + PropertyBagAddFloats(builder, floats) + +def PropertyBagStartFloatsVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def StartFloatsVector(builder, numElems: int) -> int: + return PropertyBagStartFloatsVector(builder, numElems) + +def PropertyBagAddStrings(builder, strings): + builder.PrependUOffsetTRelativeSlot(2, flatbuffers.number_types.UOffsetTFlags.py_type(strings), 0) + +def AddStrings(builder, strings): + PropertyBagAddStrings(builder, strings) + +def PropertyBagStartStringsVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def StartStringsVector(builder, numElems: int) -> int: + return PropertyBagStartStringsVector(builder, numElems) + +def PropertyBagEnd(builder): + return builder.EndObject() + +def End(builder): + return PropertyBagEnd(builder) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/RuntimeOptimizationRecord.py b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/RuntimeOptimizationRecord.py new file mode 100644 index 0000000000000000000000000000000000000000..14defa261b8490116ae29290ee37e06df007d37c --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/RuntimeOptimizationRecord.py @@ -0,0 +1,105 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: fbs + +import flatbuffers +from flatbuffers.compat import import_numpy +np = import_numpy() + +# a single runtime optimization +# see corresponding type in onnxruntime/core/graph/runtime_optimization_record.h +class RuntimeOptimizationRecord(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = RuntimeOptimizationRecord() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsRuntimeOptimizationRecord(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def RuntimeOptimizationRecordBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x4F\x52\x54\x4D", size_prefixed=size_prefixed) + + # RuntimeOptimizationRecord + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # RuntimeOptimizationRecord + def ActionId(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.String(o + self._tab.Pos) + return None + + # RuntimeOptimizationRecord + def NodesToOptimizeIndices(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + x = self._tab.Indirect(o + self._tab.Pos) + from ort_flatbuffers_py.fbs.NodesToOptimizeIndices import NodesToOptimizeIndices + obj = NodesToOptimizeIndices() + obj.Init(self._tab.Bytes, x) + return obj + return None + + # RuntimeOptimizationRecord + def ProducedOpIds(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.String(a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 4)) + return "" + + # RuntimeOptimizationRecord + def ProducedOpIdsLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # RuntimeOptimizationRecord + def ProducedOpIdsIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10)) + return o == 0 + +def RuntimeOptimizationRecordStart(builder): + builder.StartObject(4) + +def Start(builder): + RuntimeOptimizationRecordStart(builder) + +def RuntimeOptimizationRecordAddActionId(builder, actionId): + builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(actionId), 0) + +def AddActionId(builder, actionId): + RuntimeOptimizationRecordAddActionId(builder, actionId) + +def RuntimeOptimizationRecordAddNodesToOptimizeIndices(builder, nodesToOptimizeIndices): + builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(nodesToOptimizeIndices), 0) + +def AddNodesToOptimizeIndices(builder, nodesToOptimizeIndices): + RuntimeOptimizationRecordAddNodesToOptimizeIndices(builder, nodesToOptimizeIndices) + +def RuntimeOptimizationRecordAddProducedOpIds(builder, producedOpIds): + builder.PrependUOffsetTRelativeSlot(3, flatbuffers.number_types.UOffsetTFlags.py_type(producedOpIds), 0) + +def AddProducedOpIds(builder, producedOpIds): + RuntimeOptimizationRecordAddProducedOpIds(builder, producedOpIds) + +def RuntimeOptimizationRecordStartProducedOpIdsVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def StartProducedOpIdsVector(builder, numElems: int) -> int: + return RuntimeOptimizationRecordStartProducedOpIdsVector(builder, numElems) + +def RuntimeOptimizationRecordEnd(builder): + return builder.EndObject() + +def End(builder): + return RuntimeOptimizationRecordEnd(builder) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/RuntimeOptimizationRecordContainerEntry.py b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/RuntimeOptimizationRecordContainerEntry.py new file mode 100644 index 0000000000000000000000000000000000000000..69cda44720a229d19230fd65032e7639c1605f76 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/RuntimeOptimizationRecordContainerEntry.py @@ -0,0 +1,91 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: fbs + +import flatbuffers +from flatbuffers.compat import import_numpy +np = import_numpy() + +class RuntimeOptimizationRecordContainerEntry(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = RuntimeOptimizationRecordContainerEntry() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsRuntimeOptimizationRecordContainerEntry(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def RuntimeOptimizationRecordContainerEntryBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x4F\x52\x54\x4D", size_prefixed=size_prefixed) + + # RuntimeOptimizationRecordContainerEntry + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # RuntimeOptimizationRecordContainerEntry + def OptimizerName(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.String(o + self._tab.Pos) + return None + + # RuntimeOptimizationRecordContainerEntry + def RuntimeOptimizationRecords(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + x = self._tab.Vector(o) + x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4 + x = self._tab.Indirect(x) + from ort_flatbuffers_py.fbs.RuntimeOptimizationRecord import RuntimeOptimizationRecord + obj = RuntimeOptimizationRecord() + obj.Init(self._tab.Bytes, x) + return obj + return None + + # RuntimeOptimizationRecordContainerEntry + def RuntimeOptimizationRecordsLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # RuntimeOptimizationRecordContainerEntry + def RuntimeOptimizationRecordsIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + return o == 0 + +def RuntimeOptimizationRecordContainerEntryStart(builder): + builder.StartObject(2) + +def Start(builder): + RuntimeOptimizationRecordContainerEntryStart(builder) + +def RuntimeOptimizationRecordContainerEntryAddOptimizerName(builder, optimizerName): + builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(optimizerName), 0) + +def AddOptimizerName(builder, optimizerName): + RuntimeOptimizationRecordContainerEntryAddOptimizerName(builder, optimizerName) + +def RuntimeOptimizationRecordContainerEntryAddRuntimeOptimizationRecords(builder, runtimeOptimizationRecords): + builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(runtimeOptimizationRecords), 0) + +def AddRuntimeOptimizationRecords(builder, runtimeOptimizationRecords): + RuntimeOptimizationRecordContainerEntryAddRuntimeOptimizationRecords(builder, runtimeOptimizationRecords) + +def RuntimeOptimizationRecordContainerEntryStartRuntimeOptimizationRecordsVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def StartRuntimeOptimizationRecordsVector(builder, numElems: int) -> int: + return RuntimeOptimizationRecordContainerEntryStartRuntimeOptimizationRecordsVector(builder, numElems) + +def RuntimeOptimizationRecordContainerEntryEnd(builder): + return builder.EndObject() + +def End(builder): + return RuntimeOptimizationRecordContainerEntryEnd(builder) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/RuntimeOptimizations.py b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/RuntimeOptimizations.py new file mode 100644 index 0000000000000000000000000000000000000000..a82143d39a23ac4740d90e628f3ba92e6b15c7bb --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/RuntimeOptimizations.py @@ -0,0 +1,79 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: fbs + +import flatbuffers +from flatbuffers.compat import import_numpy +np = import_numpy() + +class RuntimeOptimizations(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = RuntimeOptimizations() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsRuntimeOptimizations(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def RuntimeOptimizationsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x4F\x52\x54\x4D", size_prefixed=size_prefixed) + + # RuntimeOptimizations + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # mapping from optimizer name to [RuntimeOptimizationRecord] + # RuntimeOptimizations + def Records(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + x = self._tab.Vector(o) + x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4 + x = self._tab.Indirect(x) + from ort_flatbuffers_py.fbs.RuntimeOptimizationRecordContainerEntry import RuntimeOptimizationRecordContainerEntry + obj = RuntimeOptimizationRecordContainerEntry() + obj.Init(self._tab.Bytes, x) + return obj + return None + + # RuntimeOptimizations + def RecordsLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # RuntimeOptimizations + def RecordsIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + return o == 0 + +def RuntimeOptimizationsStart(builder): + builder.StartObject(1) + +def Start(builder): + RuntimeOptimizationsStart(builder) + +def RuntimeOptimizationsAddRecords(builder, records): + builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(records), 0) + +def AddRecords(builder, records): + RuntimeOptimizationsAddRecords(builder, records) + +def RuntimeOptimizationsStartRecordsVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def StartRecordsVector(builder, numElems: int) -> int: + return RuntimeOptimizationsStartRecordsVector(builder, numElems) + +def RuntimeOptimizationsEnd(builder): + return builder.EndObject() + +def End(builder): + return RuntimeOptimizationsEnd(builder) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/SequenceType.py b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/SequenceType.py new file mode 100644 index 0000000000000000000000000000000000000000..604dac0a27402f09ea461b7e55472dc882f06a59 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/SequenceType.py @@ -0,0 +1,58 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: fbs + +import flatbuffers +from flatbuffers.compat import import_numpy +np = import_numpy() + +class SequenceType(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = SequenceType() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsSequenceType(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def SequenceTypeBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x4F\x52\x54\x4D", size_prefixed=size_prefixed) + + # SequenceType + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # SequenceType + def ElemType(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + x = self._tab.Indirect(o + self._tab.Pos) + from ort_flatbuffers_py.fbs.TypeInfo import TypeInfo + obj = TypeInfo() + obj.Init(self._tab.Bytes, x) + return obj + return None + +def SequenceTypeStart(builder): + builder.StartObject(1) + +def Start(builder): + SequenceTypeStart(builder) + +def SequenceTypeAddElemType(builder, elemType): + builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(elemType), 0) + +def AddElemType(builder, elemType): + SequenceTypeAddElemType(builder, elemType) + +def SequenceTypeEnd(builder): + return builder.EndObject() + +def End(builder): + return SequenceTypeEnd(builder) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/Shape.py b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/Shape.py new file mode 100644 index 0000000000000000000000000000000000000000..39e588d94e9019bfdd7eef553d6935552379e7b9 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/Shape.py @@ -0,0 +1,78 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: fbs + +import flatbuffers +from flatbuffers.compat import import_numpy +np = import_numpy() + +class Shape(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = Shape() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsShape(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def ShapeBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x4F\x52\x54\x4D", size_prefixed=size_prefixed) + + # Shape + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # Shape + def Dim(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + x = self._tab.Vector(o) + x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4 + x = self._tab.Indirect(x) + from ort_flatbuffers_py.fbs.Dimension import Dimension + obj = Dimension() + obj.Init(self._tab.Bytes, x) + return obj + return None + + # Shape + def DimLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Shape + def DimIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + return o == 0 + +def ShapeStart(builder): + builder.StartObject(1) + +def Start(builder): + ShapeStart(builder) + +def ShapeAddDim(builder, dim): + builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(dim), 0) + +def AddDim(builder, dim): + ShapeAddDim(builder, dim) + +def ShapeStartDimVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def StartDimVector(builder, numElems: int) -> int: + return ShapeStartDimVector(builder, numElems) + +def ShapeEnd(builder): + return builder.EndObject() + +def End(builder): + return ShapeEnd(builder) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/SparseTensor.py b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/SparseTensor.py new file mode 100644 index 0000000000000000000000000000000000000000..0f90d615d436fc77cca61c2a7e90f18fe41194d2 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/SparseTensor.py @@ -0,0 +1,114 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: fbs + +import flatbuffers +from flatbuffers.compat import import_numpy +np = import_numpy() + +class SparseTensor(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = SparseTensor() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsSparseTensor(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def SparseTensorBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x4F\x52\x54\x4D", size_prefixed=size_prefixed) + + # SparseTensor + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # SparseTensor + def Values(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + x = self._tab.Indirect(o + self._tab.Pos) + from ort_flatbuffers_py.fbs.Tensor import Tensor + obj = Tensor() + obj.Init(self._tab.Bytes, x) + return obj + return None + + # SparseTensor + def Indices(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + x = self._tab.Indirect(o + self._tab.Pos) + from ort_flatbuffers_py.fbs.Tensor import Tensor + obj = Tensor() + obj.Init(self._tab.Bytes, x) + return obj + return None + + # SparseTensor + def Dims(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Int64Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 8)) + return 0 + + # SparseTensor + def DimsAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Int64Flags, o) + return 0 + + # SparseTensor + def DimsLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # SparseTensor + def DimsIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + return o == 0 + +def SparseTensorStart(builder): + builder.StartObject(3) + +def Start(builder): + SparseTensorStart(builder) + +def SparseTensorAddValues(builder, values): + builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(values), 0) + +def AddValues(builder, values): + SparseTensorAddValues(builder, values) + +def SparseTensorAddIndices(builder, indices): + builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(indices), 0) + +def AddIndices(builder, indices): + SparseTensorAddIndices(builder, indices) + +def SparseTensorAddDims(builder, dims): + builder.PrependUOffsetTRelativeSlot(2, flatbuffers.number_types.UOffsetTFlags.py_type(dims), 0) + +def AddDims(builder, dims): + SparseTensorAddDims(builder, dims) + +def SparseTensorStartDimsVector(builder, numElems): + return builder.StartVector(8, numElems, 8) + +def StartDimsVector(builder, numElems: int) -> int: + return SparseTensorStartDimsVector(builder, numElems) + +def SparseTensorEnd(builder): + return builder.EndObject() + +def End(builder): + return SparseTensorEnd(builder) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/StringProperty.py b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/StringProperty.py new file mode 100644 index 0000000000000000000000000000000000000000..f08e0e921c07c92134c75ae8e1d9b76a22511b27 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/StringProperty.py @@ -0,0 +1,67 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: fbs + +import flatbuffers +from flatbuffers.compat import import_numpy +np = import_numpy() + +class StringProperty(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = StringProperty() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsStringProperty(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def StringPropertyBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x4F\x44\x54\x43", size_prefixed=size_prefixed) + + # StringProperty + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # StringProperty + def Name(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.String(o + self._tab.Pos) + return None + + # StringProperty + def Value(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.String(o + self._tab.Pos) + return None + +def StringPropertyStart(builder): + builder.StartObject(2) + +def Start(builder): + StringPropertyStart(builder) + +def StringPropertyAddName(builder, name): + builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(name), 0) + +def AddName(builder, name): + StringPropertyAddName(builder, name) + +def StringPropertyAddValue(builder, value): + builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(value), 0) + +def AddValue(builder, value): + StringPropertyAddValue(builder, value) + +def StringPropertyEnd(builder): + return builder.EndObject() + +def End(builder): + return StringPropertyEnd(builder) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/StringStringEntry.py b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/StringStringEntry.py new file mode 100644 index 0000000000000000000000000000000000000000..7d0961f70a8eacce0c0b83838d9160a2bfe45a40 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/StringStringEntry.py @@ -0,0 +1,67 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: fbs + +import flatbuffers +from flatbuffers.compat import import_numpy +np = import_numpy() + +class StringStringEntry(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = StringStringEntry() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsStringStringEntry(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def StringStringEntryBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x4F\x52\x54\x4D", size_prefixed=size_prefixed) + + # StringStringEntry + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # StringStringEntry + def Key(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.String(o + self._tab.Pos) + return None + + # StringStringEntry + def Value(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.String(o + self._tab.Pos) + return None + +def StringStringEntryStart(builder): + builder.StartObject(2) + +def Start(builder): + StringStringEntryStart(builder) + +def StringStringEntryAddKey(builder, key): + builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(key), 0) + +def AddKey(builder, key): + StringStringEntryAddKey(builder, key) + +def StringStringEntryAddValue(builder, value): + builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(value), 0) + +def AddValue(builder, value): + StringStringEntryAddValue(builder, value) + +def StringStringEntryEnd(builder): + return builder.EndObject() + +def End(builder): + return StringStringEntryEnd(builder) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/Tensor.py b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/Tensor.py new file mode 100644 index 0000000000000000000000000000000000000000..1366b91b93a4c7a1552110dc85b7487c401e6de6 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/Tensor.py @@ -0,0 +1,203 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: fbs + +import flatbuffers +from flatbuffers.compat import import_numpy +np = import_numpy() + +class Tensor(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = Tensor() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsTensor(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def TensorBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x4F\x52\x54\x4D", size_prefixed=size_prefixed) + + # Tensor + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # Tensor + def Name(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.String(o + self._tab.Pos) + return None + + # Tensor + def DocString(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.String(o + self._tab.Pos) + return None + + # Tensor + def Dims(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Int64Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 8)) + return 0 + + # Tensor + def DimsAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Int64Flags, o) + return 0 + + # Tensor + def DimsLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Tensor + def DimsIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + return o == 0 + + # Tensor + def DataType(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return 0 + + # Tensor + def RawData(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Uint8Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 1)) + return 0 + + # Tensor + def RawDataAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Uint8Flags, o) + return 0 + + # Tensor + def RawDataLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Tensor + def RawDataIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12)) + return o == 0 + + # Tensor + def StringData(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(14)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.String(a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 4)) + return "" + + # Tensor + def StringDataLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(14)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Tensor + def StringDataIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(14)) + return o == 0 + + # Tensor + def ExternalDataOffset(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(16)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int64Flags, o + self._tab.Pos) + return -1 + +def TensorStart(builder): + builder.StartObject(7) + +def Start(builder): + TensorStart(builder) + +def TensorAddName(builder, name): + builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(name), 0) + +def AddName(builder, name): + TensorAddName(builder, name) + +def TensorAddDocString(builder, docString): + builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(docString), 0) + +def AddDocString(builder, docString): + TensorAddDocString(builder, docString) + +def TensorAddDims(builder, dims): + builder.PrependUOffsetTRelativeSlot(2, flatbuffers.number_types.UOffsetTFlags.py_type(dims), 0) + +def AddDims(builder, dims): + TensorAddDims(builder, dims) + +def TensorStartDimsVector(builder, numElems): + return builder.StartVector(8, numElems, 8) + +def StartDimsVector(builder, numElems: int) -> int: + return TensorStartDimsVector(builder, numElems) + +def TensorAddDataType(builder, dataType): + builder.PrependInt32Slot(3, dataType, 0) + +def AddDataType(builder, dataType): + TensorAddDataType(builder, dataType) + +def TensorAddRawData(builder, rawData): + builder.PrependUOffsetTRelativeSlot(4, flatbuffers.number_types.UOffsetTFlags.py_type(rawData), 0) + +def AddRawData(builder, rawData): + TensorAddRawData(builder, rawData) + +def TensorStartRawDataVector(builder, numElems): + return builder.StartVector(1, numElems, 1) + +def StartRawDataVector(builder, numElems: int) -> int: + return TensorStartRawDataVector(builder, numElems) + +def TensorAddStringData(builder, stringData): + builder.PrependUOffsetTRelativeSlot(5, flatbuffers.number_types.UOffsetTFlags.py_type(stringData), 0) + +def AddStringData(builder, stringData): + TensorAddStringData(builder, stringData) + +def TensorStartStringDataVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def StartStringDataVector(builder, numElems: int) -> int: + return TensorStartStringDataVector(builder, numElems) + +def TensorAddExternalDataOffset(builder, externalDataOffset): + builder.PrependInt64Slot(6, externalDataOffset, -1) + +def AddExternalDataOffset(builder, externalDataOffset): + TensorAddExternalDataOffset(builder, externalDataOffset) + +def TensorEnd(builder): + return builder.EndObject() + +def End(builder): + return TensorEnd(builder) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/TensorDataType.py b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/TensorDataType.py new file mode 100644 index 0000000000000000000000000000000000000000..903e48747f3b0d7179077757e0a945d0e4c2c464 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/TensorDataType.py @@ -0,0 +1,26 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: fbs + +class TensorDataType(object): + UNDEFINED = 0 + FLOAT = 1 + UINT8 = 2 + INT8 = 3 + UINT16 = 4 + INT16 = 5 + INT32 = 6 + INT64 = 7 + STRING = 8 + BOOL = 9 + FLOAT16 = 10 + DOUBLE = 11 + UINT32 = 12 + UINT64 = 13 + COMPLEX64 = 14 + COMPLEX128 = 15 + BFLOAT16 = 16 + FLOAT8E4M3FN = 17 + FLOAT8E4M3FNUZ = 18 + FLOAT8E5M2 = 19 + FLOAT8E5M2FNUZ = 20 diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/TensorTypeAndShape.py b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/TensorTypeAndShape.py new file mode 100644 index 0000000000000000000000000000000000000000..eedef28266c411c973127b2f9c7aa4d956d6712e --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/TensorTypeAndShape.py @@ -0,0 +1,71 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: fbs + +import flatbuffers +from flatbuffers.compat import import_numpy +np = import_numpy() + +class TensorTypeAndShape(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = TensorTypeAndShape() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsTensorTypeAndShape(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def TensorTypeAndShapeBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x4F\x52\x54\x4D", size_prefixed=size_prefixed) + + # TensorTypeAndShape + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # TensorTypeAndShape + def ElemType(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return 0 + + # TensorTypeAndShape + def Shape(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + x = self._tab.Indirect(o + self._tab.Pos) + from ort_flatbuffers_py.fbs.Shape import Shape + obj = Shape() + obj.Init(self._tab.Bytes, x) + return obj + return None + +def TensorTypeAndShapeStart(builder): + builder.StartObject(2) + +def Start(builder): + TensorTypeAndShapeStart(builder) + +def TensorTypeAndShapeAddElemType(builder, elemType): + builder.PrependInt32Slot(0, elemType, 0) + +def AddElemType(builder, elemType): + TensorTypeAndShapeAddElemType(builder, elemType) + +def TensorTypeAndShapeAddShape(builder, shape): + builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(shape), 0) + +def AddShape(builder, shape): + TensorTypeAndShapeAddShape(builder, shape) + +def TensorTypeAndShapeEnd(builder): + return builder.EndObject() + +def End(builder): + return TensorTypeAndShapeEnd(builder) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/TypeInfo.py b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/TypeInfo.py new file mode 100644 index 0000000000000000000000000000000000000000..db669f78095f4e6a6d2e93ee4e2e7a6dfdbf6fe7 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/TypeInfo.py @@ -0,0 +1,83 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: fbs + +import flatbuffers +from flatbuffers.compat import import_numpy +np = import_numpy() + +class TypeInfo(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = TypeInfo() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsTypeInfo(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def TypeInfoBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x4F\x52\x54\x4D", size_prefixed=size_prefixed) + + # TypeInfo + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # TypeInfo + def Denotation(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.String(o + self._tab.Pos) + return None + + # TypeInfo + def ValueType(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint8Flags, o + self._tab.Pos) + return 0 + + # TypeInfo + def Value(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + from flatbuffers.table import Table + obj = Table(bytearray(), 0) + self._tab.Union(obj, o) + return obj + return None + +def TypeInfoStart(builder): + builder.StartObject(3) + +def Start(builder): + TypeInfoStart(builder) + +def TypeInfoAddDenotation(builder, denotation): + builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(denotation), 0) + +def AddDenotation(builder, denotation): + TypeInfoAddDenotation(builder, denotation) + +def TypeInfoAddValueType(builder, valueType): + builder.PrependUint8Slot(1, valueType, 0) + +def AddValueType(builder, valueType): + TypeInfoAddValueType(builder, valueType) + +def TypeInfoAddValue(builder, value): + builder.PrependUOffsetTRelativeSlot(2, flatbuffers.number_types.UOffsetTFlags.py_type(value), 0) + +def AddValue(builder, value): + TypeInfoAddValue(builder, value) + +def TypeInfoEnd(builder): + return builder.EndObject() + +def End(builder): + return TypeInfoEnd(builder) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/TypeInfoValue.py b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/TypeInfoValue.py new file mode 100644 index 0000000000000000000000000000000000000000..ba76c5f794834ae63324690de3f0fc419a929ec6 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/TypeInfoValue.py @@ -0,0 +1,9 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: fbs + +class TypeInfoValue(object): + NONE = 0 + tensor_type = 1 + sequence_type = 2 + map_type = 3 diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/ValueInfo.py b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/ValueInfo.py new file mode 100644 index 0000000000000000000000000000000000000000..5a4986a66cad2c05281814a740b0cd2de6635e52 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/ValueInfo.py @@ -0,0 +1,84 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: fbs + +import flatbuffers +from flatbuffers.compat import import_numpy +np = import_numpy() + +class ValueInfo(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = ValueInfo() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsValueInfo(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def ValueInfoBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x4F\x52\x54\x4D", size_prefixed=size_prefixed) + + # ValueInfo + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # ValueInfo + def Name(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.String(o + self._tab.Pos) + return None + + # ValueInfo + def DocString(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.String(o + self._tab.Pos) + return None + + # ValueInfo + def Type(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + x = self._tab.Indirect(o + self._tab.Pos) + from ort_flatbuffers_py.fbs.TypeInfo import TypeInfo + obj = TypeInfo() + obj.Init(self._tab.Bytes, x) + return obj + return None + +def ValueInfoStart(builder): + builder.StartObject(3) + +def Start(builder): + ValueInfoStart(builder) + +def ValueInfoAddName(builder, name): + builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(name), 0) + +def AddName(builder, name): + ValueInfoAddName(builder, name) + +def ValueInfoAddDocString(builder, docString): + builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(docString), 0) + +def AddDocString(builder, docString): + ValueInfoAddDocString(builder, docString) + +def ValueInfoAddType(builder, type): + builder.PrependUOffsetTRelativeSlot(2, flatbuffers.number_types.UOffsetTFlags.py_type(type), 0) + +def AddType(builder, type): + ValueInfoAddType(builder, type) + +def ValueInfoEnd(builder): + return builder.EndObject() + +def End(builder): + return ValueInfoEnd(builder) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__init__.py b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6014761347704f0b8af6477ea0c122a1e91b36db --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__init__.py @@ -0,0 +1,6 @@ +from os.path import dirname, basename, isfile, join, splitext +import glob +modules = glob.glob(join(dirname(__file__), "*.py")) +__all__ = [splitext(basename(f))[0] for f in modules if isfile(f) and not f.endswith('__init__.py')] + +from . import * diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/ArgType.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/ArgType.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2478cbe1e4a511f12b0a1d00c6f247630d194625 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/ArgType.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/ArgTypeAndIndex.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/ArgTypeAndIndex.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..16d8d45c40f3417314e9722668bec7577ddf5f30 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/ArgTypeAndIndex.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/Attribute.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/Attribute.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f871993d113fda6d0873552cf8eaf741e09c740b Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/Attribute.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/AttributeType.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/AttributeType.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..61353931fbd2a8e11097841a4e60890a6e2ab331 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/AttributeType.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/Checkpoint.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/Checkpoint.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..916d1e471f89a1c313c59102cd62bb095c606696 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/Checkpoint.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/DeprecatedKernelCreateInfos.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/DeprecatedKernelCreateInfos.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..533e31e1c1ce21b7ca701d2d365db68eb3f9e6b2 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/DeprecatedKernelCreateInfos.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/DeprecatedNodeIndexAndKernelDefHash.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/DeprecatedNodeIndexAndKernelDefHash.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c2a79875ba599ed7573098238c37e94b34a275ff Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/DeprecatedNodeIndexAndKernelDefHash.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/DeprecatedSessionState.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/DeprecatedSessionState.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4f8cea44bef30958980c0125854994b6eb7cce40 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/DeprecatedSessionState.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/DeprecatedSubGraphSessionState.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/DeprecatedSubGraphSessionState.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6dc11d8c5e4d2cd74639dcd260510d7e99ea7b38 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/DeprecatedSubGraphSessionState.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/Dimension.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/Dimension.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..af8a3bace009291dd8a7d5876ffa8ddfc78f3645 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/Dimension.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/DimensionValue.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/DimensionValue.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..538e5569aebd80503be4a0165e9e8b8ba8bc56f0 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/DimensionValue.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/DimensionValueType.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/DimensionValueType.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..263f68e8c5277139e1d7d55a4a7af321817812d0 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/DimensionValueType.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/EdgeEnd.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/EdgeEnd.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4d5a106a2250cd56279f2d8cdb5e507fa0543443 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/EdgeEnd.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/FloatProperty.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/FloatProperty.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c37f2719b7781f8a938bd32ba65e6d96d92ae2a8 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/FloatProperty.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/Graph.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/Graph.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..07c5ace4bcda69ab2409e62c54a8a152bc819137 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/Graph.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/InferenceSession.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/InferenceSession.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..574490c8842f32b68469dbfbc9f8a5ecfee55245 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/InferenceSession.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/IntProperty.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/IntProperty.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2ca2797777af616b123c775971d76ff13504dce1 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/IntProperty.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/KernelTypeStrArgsEntry.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/KernelTypeStrArgsEntry.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..82bdfc4e06010c132e1ab74ccdc8753b718fcbf1 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/KernelTypeStrArgsEntry.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/KernelTypeStrResolver.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/KernelTypeStrResolver.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9a024be1c5b6420394db3c6ae9ee04c880d722a6 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/KernelTypeStrResolver.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/MapType.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/MapType.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8ce026c2d20b0c820fbebffd421ea3289118de09 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/MapType.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/Model.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/Model.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..845115e4aa2c80ceaa668d8fae6dfb4548e46a3d Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/Model.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/ModuleState.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/ModuleState.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ff79e28375d9f896d81ad2c35d5ef4cc9bdcf8d4 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/ModuleState.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/Node.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/Node.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..821ec6c1b783a1d3317273fa6d703c1abc52367f Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/Node.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/NodeEdge.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/NodeEdge.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..966a3f2b91d46f4bf9b03338313c25cbc8d88d91 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/NodeEdge.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/NodeType.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/NodeType.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0f004f35b93961af91c34efb885e796e64f6500d Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/NodeType.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/NodesToOptimizeIndices.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/NodesToOptimizeIndices.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9248d5d4cccbd2bcb66610caa0539d3bcb22f6ae Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/NodesToOptimizeIndices.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/OpIdKernelTypeStrArgsEntry.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/OpIdKernelTypeStrArgsEntry.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..20090cdcb2719c255725cb30cbb4b3218363a35a Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/OpIdKernelTypeStrArgsEntry.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/OperatorSetId.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/OperatorSetId.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f459b20c51975ae4d71747efd45bd90068c67940 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/OperatorSetId.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/OptimizerGroup.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/OptimizerGroup.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4ec9d72d1c903cb0feab060ce5a3a4c7f8682263 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/OptimizerGroup.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/ParameterOptimizerState.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/ParameterOptimizerState.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..47e30ecba2e5fda4050da1153d30cb9031b8c5f6 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/ParameterOptimizerState.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/PropertyBag.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/PropertyBag.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8671fd163ae7bc483b6d8d41434bc7bdc9c8a316 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/PropertyBag.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/RuntimeOptimizationRecord.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/RuntimeOptimizationRecord.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1589faf9cd3ed39e0610bfa071978d7c15bb6efa Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/RuntimeOptimizationRecord.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/RuntimeOptimizationRecordContainerEntry.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/RuntimeOptimizationRecordContainerEntry.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..393aedd9e4956064b4d49192632725eaf61a0fe3 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/RuntimeOptimizationRecordContainerEntry.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/RuntimeOptimizations.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/RuntimeOptimizations.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b6e188a40966e6b382eead73f50de9fd1d66ca94 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/RuntimeOptimizations.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/SequenceType.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/SequenceType.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..88e81381bb2b463840a3cebafdaa9cd1e61cde93 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/SequenceType.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/Shape.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/Shape.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a3612adf302ab1cf2d2b32d86a121c986e5299ea Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/Shape.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/SparseTensor.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/SparseTensor.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..58273295be73ae15d5a1e4adb35b8b7e3726e38e Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/SparseTensor.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/StringProperty.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/StringProperty.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0f8e5d14332d5b07b3912140ae884975186d4a67 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/StringProperty.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/StringStringEntry.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/StringStringEntry.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..afd983e7c6d2ef5591f4793c24384cdf76c2c176 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/StringStringEntry.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/Tensor.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/Tensor.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1011d7cd00ffe745568893f8503882313d82a313 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/Tensor.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/TensorDataType.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/TensorDataType.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5d33a7cdb1c0dfb5f2c16117280e0e00d4dca5c5 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/TensorDataType.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/TensorTypeAndShape.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/TensorTypeAndShape.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..369182502486138f78481bec975e0627630d85b6 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/TensorTypeAndShape.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/TypeInfo.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/TypeInfo.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ddaac998898bc34c9a24e7e5c609ae8056f506ef Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/TypeInfo.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/TypeInfoValue.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/TypeInfoValue.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cb66f45017dd12981bcbac6f9559feafb5c20e18 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/TypeInfoValue.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/ValueInfo.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/ValueInfo.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1d7ca8270c3211bfecf6aa26bde571ac29af79f0 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/ValueInfo.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..06bd282a45a968448d38119f556c31716c9b1e21 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_model_processor.py b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_model_processor.py new file mode 100644 index 0000000000000000000000000000000000000000..3343f44d919e239e2ad1281d616752aa832fd0e9 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/ort_model_processor.py @@ -0,0 +1,86 @@ +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. + +import ort_flatbuffers_py.fbs as fbs + +from .operator_type_usage_processors import OperatorTypeUsageManager + + +class OrtFormatModelProcessor: + "Class to process an ORT format model and determine required operators and types." + + def __init__(self, model_path: str, required_ops: dict, processors: OperatorTypeUsageManager): + """ + Initialize ORT format model processor + :param model_path: Path to model to load + :param required_ops: Dictionary required operator information will be added to. + :param processors: Operator type usage processors which will be called for each matching Node. + """ + self._required_ops = required_ops # dictionary of {domain: {opset:[operators]}} + self._file = open(model_path, "rb").read() # noqa: SIM115 + self._buffer = bytearray(self._file) + if not fbs.InferenceSession.InferenceSession.InferenceSessionBufferHasIdentifier(self._buffer, 0): + raise RuntimeError(f"File does not appear to be a valid ORT format model: '{model_path}'") + self._model = fbs.InferenceSession.InferenceSession.GetRootAsInferenceSession(self._buffer, 0).Model() + self._op_type_processors = processors + + @staticmethod + def _setup_type_info(graph: fbs.Graph, outer_scope_value_typeinfo={}): # noqa: B006 + """ + Setup the node args for this level of Graph. + We copy the current list which represents the outer scope values, and add the local node args to that + to create the valid list of values for the current Graph. + :param graph: Graph to create NodeArg list for + :param outer_scope_value_typeinfo: TypeInfo for outer scope values. Empty for the top-level graph in a model. + :return: Dictionary of NodeArg name to TypeInfo + """ + value_name_to_typeinfo = outer_scope_value_typeinfo.copy() + for j in range(graph.NodeArgsLength()): + n = graph.NodeArgs(j) + value_name_to_typeinfo[n.Name()] = n.Type() # TypeInfo for this NodeArg's name + + return value_name_to_typeinfo + + def _add_required_op(self, domain: str, opset: int, op_type: str): + if domain not in self._required_ops: + self._required_ops[domain] = {opset: {op_type}} + elif opset not in self._required_ops[domain]: + self._required_ops[domain][opset] = {op_type} + else: + self._required_ops[domain][opset].add(op_type) + + def _process_graph(self, graph: fbs.Graph, outer_scope_value_typeinfo: dict): + """ + Process one level of the Graph, descending into any subgraphs when they are found + :param outer_scope_value_typeinfo: Outer scope NodeArg dictionary from ancestor graphs + """ + # Merge the TypeInfo for all values in this level of the graph with the outer scope value TypeInfo. + value_name_to_typeinfo = OrtFormatModelProcessor._setup_type_info(graph, outer_scope_value_typeinfo) + + for i in range(graph.NodesLength()): + node = graph.Nodes(i) + + optype = node.OpType().decode() + domain = node.Domain().decode() or "ai.onnx" # empty domain defaults to ai.onnx + + self._add_required_op(domain, node.SinceVersion(), optype) + + if self._op_type_processors: + self._op_type_processors.process_node(node, value_name_to_typeinfo) + + # Read all the attributes + for j in range(node.AttributesLength()): + attr = node.Attributes(j) + attr_type = attr.Type() + if attr_type == fbs.AttributeType.AttributeType.GRAPH: + self._process_graph(attr.G(), value_name_to_typeinfo) + elif attr_type == fbs.AttributeType.AttributeType.GRAPHS: + # the ONNX spec doesn't currently define any operators that have multiple graphs in an attribute + # so entering this 'elif' isn't currently possible + for k in range(attr.GraphsLength()): + self._process_graph(attr.Graphs(k), value_name_to_typeinfo) + + def process(self): + graph = self._model.Graph() + outer_scope_value_typeinfo = {} # no outer scope values for the main graph + self._process_graph(graph, outer_scope_value_typeinfo) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/types.py b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/types.py new file mode 100644 index 0000000000000000000000000000000000000000..ff00cd22ea8bdba9119ec30b958530954a6b3650 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/types.py @@ -0,0 +1,85 @@ +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. + +import ort_flatbuffers_py.fbs as fbs + + +class FbsTypeInfo: + "Class to provide conversion between ORT flatbuffers schema values and C++ types" + + tensordatatype_to_string = { # noqa: RUF012 + fbs.TensorDataType.TensorDataType.FLOAT: "float", + fbs.TensorDataType.TensorDataType.UINT8: "uint8_t", + fbs.TensorDataType.TensorDataType.INT8: "int8_t", + fbs.TensorDataType.TensorDataType.UINT16: "uint16_t", + fbs.TensorDataType.TensorDataType.INT16: "int16_t", + fbs.TensorDataType.TensorDataType.INT32: "int32_t", + fbs.TensorDataType.TensorDataType.INT64: "int64_t", + fbs.TensorDataType.TensorDataType.STRING: "std::string", + fbs.TensorDataType.TensorDataType.BOOL: "bool", + fbs.TensorDataType.TensorDataType.FLOAT16: "MLFloat16", + fbs.TensorDataType.TensorDataType.DOUBLE: "double", + fbs.TensorDataType.TensorDataType.UINT32: "uint32_t", + fbs.TensorDataType.TensorDataType.UINT64: "uint64_t", + # fbs.TensorDataType.TensorDataType.COMPLEX64: 'complex64 is not supported', + # fbs.TensorDataType.TensorDataType.COMPLEX128: 'complex128 is not supported', + fbs.TensorDataType.TensorDataType.BFLOAT16: "BFloat16", + fbs.TensorDataType.TensorDataType.FLOAT8E4M3FN: "Float8E4M3FN", + fbs.TensorDataType.TensorDataType.FLOAT8E4M3FNUZ: "Float8E4M3FNUZ", + fbs.TensorDataType.TensorDataType.FLOAT8E5M2: "Float8E5M2", + fbs.TensorDataType.TensorDataType.FLOAT8E5M2FNUZ: "Float8E5M2FNUZ", + } + + @staticmethod + def typeinfo_to_str(type: fbs.TypeInfo): + value_type = type.ValueType() + value = type.Value() + type_str = "unknown" + + if value_type == fbs.TypeInfoValue.TypeInfoValue.tensor_type: + tensor_type_and_shape = fbs.TensorTypeAndShape.TensorTypeAndShape() + tensor_type_and_shape.Init(value.Bytes, value.Pos) + elem_type = tensor_type_and_shape.ElemType() + type_str = FbsTypeInfo.tensordatatype_to_string[elem_type] + + elif value_type == fbs.TypeInfoValue.TypeInfoValue.map_type: + map_type = fbs.MapType.MapType() + map_type.init(value.Bytes, value.Pos) + key_type = map_type.KeyType() # TensorDataType + key_type_str = FbsTypeInfo.tensordatatype_to_string[key_type] + value_type = map_type.ValueType() # TypeInfo + value_type_str = FbsTypeInfo.typeinfo_to_str(value_type) + type_str = f"std::map<{key_type_str},{value_type_str}>" + + elif value_type == fbs.TypeInfoValue.TypeInfoValue.sequence_type: + sequence_type = fbs.SequenceType.SequenceType() + sequence_type.Init(value.Bytes, value.Pos) + elem_type = sequence_type.ElemType() # TypeInfo + elem_type_str = FbsTypeInfo.typeinfo_to_str(elem_type) + # TODO: Decide if we need to wrap the type in a std::vector. Issue is that the element type is internal + # to the onnxruntime::Tensor class so we're really returning the type inside the Tensor not vector. + # For now, return the element type (which will be the Tensor element type, or a map) as + # an operator input or output will either be a sequence or a not, so we don't need to disambiguate + # between the two (i.e. we know if the returned value refers to the contents of a sequence, and can + # handle whether it's the element type of a Tensor in the sequence, or the map type in a sequence of maps + # due to this). + type_str = elem_type_str + else: + raise ValueError(f"Unknown or missing value type of {value_type}") + + return type_str + + +def get_typeinfo(name: str, value_name_to_typeinfo: dict) -> fbs.TypeInfo: + "Lookup a name in a dictionary mapping value name to TypeInfo." + if name not in value_name_to_typeinfo: + raise RuntimeError("Missing TypeInfo entry for " + name) + + return value_name_to_typeinfo[name] # TypeInfo object + + +def value_name_to_typestr(name: str, value_name_to_typeinfo: dict): + "Lookup TypeInfo for value name and convert to a string representing the C++ type." + type = get_typeinfo(name, value_name_to_typeinfo) + type_str = FbsTypeInfo.typeinfo_to_str(type) + return type_str diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/utils.py b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..8f9242860811c5f701c947822d5483bf2e009b08 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/tools/ort_format_model/utils.py @@ -0,0 +1,61 @@ +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. + +import pathlib +import typing + +from ..logger import get_logger +from .operator_type_usage_processors import OperatorTypeUsageManager +from .ort_model_processor import OrtFormatModelProcessor + +log = get_logger("ort_format_model.utils") + + +def _extract_ops_and_types_from_ort_models(model_files: typing.Iterable[pathlib.Path], enable_type_reduction: bool): + required_ops = {} + op_type_usage_manager = OperatorTypeUsageManager() if enable_type_reduction else None + + for model_file in model_files: + if not model_file.is_file(): + raise ValueError(f"Path is not a file: '{model_file}'") + model_processor = OrtFormatModelProcessor(str(model_file), required_ops, op_type_usage_manager) + model_processor.process() # this updates required_ops and op_type_processors + + return required_ops, op_type_usage_manager + + +def create_config_from_models( + model_files: typing.Iterable[pathlib.Path], output_file: pathlib.Path, enable_type_reduction: bool +): + """ + Create a configuration file with required operators and optionally required types. + :param model_files: Model files to use to generate the configuration file. + :param output_file: File to write configuration to. + :param enable_type_reduction: Include required type information for individual operators in the configuration. + """ + + required_ops, op_type_processors = _extract_ops_and_types_from_ort_models(model_files, enable_type_reduction) + + output_file.parent.mkdir(parents=True, exist_ok=True) + + with open(output_file, "w") as out: + out.write("# Generated from model/s:\n") + out.writelines(f"# - {model_file}\n" for model_file in sorted(model_files)) + + for domain in sorted(required_ops.keys()): + for opset in sorted(required_ops[domain].keys()): + ops = required_ops[domain][opset] + if ops: + out.write(f"{domain};{opset};") + if enable_type_reduction: + # type string is empty if op hasn't been seen + entries = [ + "{}{}".format(op, op_type_processors.get_config_entry(domain, op) or "") + for op in sorted(ops) + ] + else: + entries = sorted(ops) + + out.write("{}\n".format(",".join(entries))) + + log.info("Created config in %s", output_file) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/qdq_helpers/__init__.py b/python/user_packages/Python313/site-packages/onnxruntime/tools/qdq_helpers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/qdq_helpers/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/tools/qdq_helpers/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f185fe91c24b82173c924270821c8726a3c50865 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/tools/qdq_helpers/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/qdq_helpers/__pycache__/optimize_qdq_model.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/tools/qdq_helpers/__pycache__/optimize_qdq_model.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b26297b52d59615c78f6e5a58084406e155469f2 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/tools/qdq_helpers/__pycache__/optimize_qdq_model.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/qdq_helpers/optimize_qdq_model.py b/python/user_packages/Python313/site-packages/onnxruntime/tools/qdq_helpers/optimize_qdq_model.py new file mode 100644 index 0000000000000000000000000000000000000000..4f02d4e1dd0751cfe7a0aeaf6d11396f33064b12 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/tools/qdq_helpers/optimize_qdq_model.py @@ -0,0 +1,37 @@ +#!/usr/bin/env python3 +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. + +import argparse +import os +import pathlib + +import onnx + + +def optimize_qdq_model(): + parser = argparse.ArgumentParser( + os.path.basename(__file__), + description="Update a QDQ format ONNX model to ensure optimal performance when executed using ONNX Runtime.", + ) + + parser.add_argument("input_model", type=pathlib.Path, help="Provide path to ONNX model to update.") + parser.add_argument("output_model", type=pathlib.Path, help="Provide path to write updated ONNX model to.") + + args = parser.parse_args() + + model = onnx.load(str(args.input_model.resolve(strict=True))) + + # run QDQ model optimizations here + + # Originally, the fixing up of DQ nodes with multiple consumers was implemented as one such optimization. + # That was moved to an ORT graph transformer. + print("As of ORT 1.15, the fixing up of DQ nodes with multiple consumers is done by an ORT graph transformer.") + + # There are no optimizations being run currently but we expect that there may be in the future. + + onnx.save(model, str(args.output_model.resolve())) + + +if __name__ == "__main__": + optimize_qdq_model() diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/qnn/__pycache__/add_trans_cast.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/tools/qnn/__pycache__/add_trans_cast.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e7e321cefda6a1b4d02b08e351cb2e96a1396e8a Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/tools/qnn/__pycache__/add_trans_cast.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/qnn/__pycache__/gen_qnn_ctx_onnx_model.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/tools/qnn/__pycache__/gen_qnn_ctx_onnx_model.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9f449dd8035b73dae9035faea36737e58111d2dd Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/tools/qnn/__pycache__/gen_qnn_ctx_onnx_model.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/qnn/__pycache__/preprocess.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/tools/qnn/__pycache__/preprocess.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2b371f417007bfb89b58775c25bb3c39116fffd5 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/tools/qnn/__pycache__/preprocess.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/qnn/add_trans_cast.py b/python/user_packages/Python313/site-packages/onnxruntime/tools/qnn/add_trans_cast.py new file mode 100644 index 0000000000000000000000000000000000000000..5c47437b25c7a0eaa13346ae37cdb91a0635cfa4 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/tools/qnn/add_trans_cast.py @@ -0,0 +1,292 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +# -------------------------------------------------------------------------- + +import json +from argparse import ArgumentParser + +import onnx +from onnx import TensorProto, helper + + +def graph_topological_sort(graph): + deps_count = [0] * len(graph.node) # dependency count of each node + deps_to_nodes = {} # input to node indice + sorted_nodes = [] # initialize sorted_nodes + for node_idx, node in enumerate(graph.node): + # CANNOT use len(node.input) directly because input can be optional + deps_count[node_idx] = sum(1 for _ in node.input if _) + if deps_count[node_idx] == 0: # Constant doesn't depend on any inputs + sorted_nodes.append(graph.node[node_idx]) + continue + + for input_name in node.input: + if input_name not in deps_to_nodes: + deps_to_nodes[input_name] = [node_idx] + else: + deps_to_nodes[input_name].append(node_idx) + + # Note: this logic only applies to top level graph since a sub graph could use intializer from parent graph + initializer_names = [init.name for init in graph.initializer] + graph_input_names = [input.name for input in graph.input] + input_names = initializer_names + graph_input_names + input_names.sort() + prev_input_name = None + for input_name in input_names: + if prev_input_name == input_name: + continue + + prev_input_name = input_name + if input_name in deps_to_nodes: + for node_idx in deps_to_nodes[input_name]: + deps_count[node_idx] = deps_count[node_idx] - 1 + if deps_count[node_idx] == 0: + sorted_nodes.append(graph.node[node_idx]) + + start = 0 + end = len(sorted_nodes) + + while start < end: + for output in sorted_nodes[start].output: + if output in deps_to_nodes: + for node_idx in deps_to_nodes[output]: + deps_count[node_idx] = deps_count[node_idx] - 1 + if deps_count[node_idx] == 0: + sorted_nodes.append(graph.node[node_idx]) + end = end + 1 + start = start + 1 + + assert end == len(graph.node), "Graph is not a DAG" + graph.ClearField("node") + graph.node.extend(sorted_nodes) + + +class QnnTensorStruct: + def __init__(self): + self.name = "" + self.onnx_data_type = TensorProto.FLOAT + self.dim = [] + + +def qnn_data_type_to_onnx_data_type(qnn_data_type): + # QNN_DATATYPE_UFIXED_POINT_8 QNN_DATATYPE_UINT_8 + if qnn_data_type == 0x0408 or qnn_data_type == 0x0108: + return TensorProto.UINT8 + # QNN_DATATYPE_UFIXED_POINT_16 QNN_DATATYPE_UINT_16 + elif qnn_data_type == 0x0416 or qnn_data_type == 0x0116: + return TensorProto.UINT16 + # QNN_DATATYPE_UFIXED_POINT_32 QNN_DATATYPE_UINT_32 + elif qnn_data_type == 0x0432 or qnn_data_type == 0x0132: + return TensorProto.UINT32 + # QNN_DATATYPE_UINT_64 + elif qnn_data_type == 0x0164: + return TensorProto.UINT64 + # QNN_DATATYPE_FIXED_POINT_8 QNN_DATATYPE_INT_8 + elif qnn_data_type == 0x0308 or qnn_data_type == 0x0008: + return TensorProto.INT8 + # QNN_DATATYPE_FIXED_POINT_16 QNN_DATATYPE_INT_16 + elif qnn_data_type == 0x0316 or qnn_data_type == 0x0016: + return TensorProto.INT16 + # QNN_DATATYPE_FIXED_POINT_32 QNN_DATATYPE_INT_32 + elif qnn_data_type == 0x0332 or qnn_data_type == 0x0032: + return TensorProto.INT32 + # QNN_DATATYPE_INT_64 + elif qnn_data_type == 0x0064: + return TensorProto.INT64 + # QNN_DATATYPE_FLOAT_16 + elif qnn_data_type == 0x0216: + return TensorProto.FLOAT16 + # QNN_DATATYPE_FLOAT_32 + elif qnn_data_type == 0x0232: + return TensorProto.FLOAT + # QNN_DATATYPE_BOOL_8 + elif qnn_data_type == 0x0508: + return TensorProto.BOOL + else: + return TensorProto.UNDEFINED + + +def parse_qnn_json_file(qnn_json_file_path, qnn_input_output_tensor_dic): + with open(qnn_json_file_path) as qnn_json_file: + qnn_json = json.load(qnn_json_file) + assert "graph" in qnn_json, "QNN converted json file not valid. Can't find graph." + assert "tensors" in qnn_json["graph"], "QNN converted json file not valid. Can't find tensors." + for qnn_tensor_name, qnn_tensor_attribute in qnn_json["graph"]["tensors"].items(): + # type:0 - QNN input tensor, type:1 - QNN output tensor + assert ( + "type" in qnn_tensor_attribute + and "data_type" in qnn_tensor_attribute + and "dims" in qnn_tensor_attribute + ), "QNN converted json file not valid. Can't find some keys from tensors" + if qnn_tensor_attribute["type"] == 0 or qnn_tensor_attribute["type"] == 1: + qnn_tensor = QnnTensorStruct() + qnn_tensor.name = qnn_tensor_name + qnn_tensor.onnx_data_type = qnn_data_type_to_onnx_data_type(qnn_tensor_attribute["data_type"]) + qnn_tensor.dim = qnn_tensor_attribute["dims"] + qnn_input_output_tensor_dic[qnn_tensor_name] = qnn_tensor + + assert len(qnn_input_output_tensor_dic) > 1, ( + "Converted QNN model not valid. It should have at least 1 input & 1 output." + ) + + +def compare_onnx_shape_with_qnn_shape(onnx_dims, qnn_dims): + assert len(onnx_dims) == len(qnn_dims), "Onnx shape and Qnn shape has different rank." + return all(onnx_dims[i].dim_value == qnn_dims[i] for i in range(len(onnx_dims))) + + +def gen_to_channel_first_perm(rank): + assert rank > 2, "Shape rank should >2 for the Transpose node." + perm = [] + perm.append(0) + perm.append(rank - 1) + for i in range(1, rank - 1): + perm.append(i) # noqa: PERF402 + + return perm + + +def gen_to_channel_last_perm(rank): + assert rank > 2, "Shape rank should >2 for the Transpose node." + perm = [] + perm.append(0) + for i in range(2, rank): + perm.append(i) # noqa: PERF402 + perm.append(1) + + return perm + + +# Onnxruntime QNN EP can support context binary file generated by QNN tool chain. However QNN generated context binary file +# uses channel last data layout and 8 bits or 16 bits for input and output. +# This script gets the QNN model input & output information from QNN converted model_net.json file, compare them with Onnx model +# and inserts Cast, Transpose nodes to Onnx model if required +def main(): + parser = ArgumentParser( + "Insert Cast, Transpose nodes into Onnx model to make it aligned with QNN generated context binary." + ) + parser.add_argument("-m", "--onnx_model", help="Required. Path to Onnx model file.", required=True, type=str) + parser.add_argument( + "-q", "--qnn_json", help="Required. Path to Qnn converted model_net.json file.", required=True, type=str + ) + args = parser.parse_args() + + # Parse Qnn model_net.json file to get the graph input output information + qnn_input_output_tensor_dic = {} + parse_qnn_json_file(args.qnn_json, qnn_input_output_tensor_dic) + + model = onnx.load(args.onnx_model) + + nodes_to_add = [] + # Tranch the tensor name change to update the consumer nodes + graph_input_output_name_dic = {} + for graph_input in model.graph.input: + if graph_input.name in qnn_input_output_tensor_dic: + input_name_fater_node_insert = graph_input.name + qnn_input_tensor = qnn_input_output_tensor_dic[graph_input.name] + # Insert Cast node if Onnx input and Qnn input has different data type + if graph_input.type.tensor_type.elem_type != qnn_input_tensor.onnx_data_type: + # Insert Cast node + cast_input_name = input_name_fater_node_insert + cast_output_name = cast_input_name + "_qnn_cast" + input_cast_node = helper.make_node( + "Cast", + name=cast_output_name, + inputs=[cast_input_name], + outputs=[cast_output_name], + to=graph_input.type.tensor_type.elem_type, + ) + # Change input data type to Qnn input data type + graph_input.type.tensor_type.elem_type = qnn_input_tensor.onnx_data_type + nodes_to_add.extend([input_cast_node]) + input_name_fater_node_insert = cast_output_name + graph_input_output_name_dic[graph_input.name] = cast_output_name + + if not compare_onnx_shape_with_qnn_shape(graph_input.type.tensor_type.shape.dim, qnn_input_tensor.dim): + # Add Transpose node (channel last to channel first) + transpose_perm = gen_to_channel_first_perm(len(graph_input.type.tensor_type.shape.dim)) + transpose_input_name = input_name_fater_node_insert + transpose_output_name = transpose_input_name + "_qnn_trans" + input_transpose_node = helper.make_node( + "Transpose", + name=transpose_output_name, + inputs=[transpose_input_name], + outputs=[transpose_output_name], + perm=transpose_perm, + ) + nodes_to_add.extend([input_transpose_node]) + graph_input_output_name_dic[graph_input.name] = transpose_output_name + + # Change input shape to Qnn input shape + for i in range(len(graph_input.type.tensor_type.shape.dim)): + graph_input.type.tensor_type.shape.dim[i].dim_value = qnn_input_tensor.dim[i] + else: + raise AssertionError("Error: Onnx model input: " + graph_input.name + " not exist from QNN model input.") + + for graph_output in model.graph.output: + if graph_output.name in qnn_input_output_tensor_dic: + output_name_after_node_insert = graph_output.name + # Insert Cast node if Onnx input and Qnn input has idfferent data type + qnn_output_tensor = qnn_input_output_tensor_dic[graph_output.name] + if graph_output.type.tensor_type.elem_type != qnn_output_tensor.onnx_data_type: + # Insert Cast node + cast_output_name = output_name_after_node_insert + cast_input_name = cast_output_name + "_qnn_cast" + output_cast_node = helper.make_node( + "Cast", + name=cast_input_name, + inputs=[cast_input_name], + outputs=[cast_output_name], + to=qnn_output_tensor.onnx_data_type, + ) + # Change output data type to Onn output data type + graph_output.type.tensor_type.elem_type = qnn_output_tensor.onnx_data_type + nodes_to_add.extend([output_cast_node]) + output_name_after_node_insert = cast_input_name + graph_input_output_name_dic[graph_output.name] = cast_input_name + + if not compare_onnx_shape_with_qnn_shape(graph_output.type.tensor_type.shape.dim, qnn_output_tensor.dim): + # Add Transpose node (channel first to channel last) + transpose_perm = gen_to_channel_last_perm(len(graph_output.type.tensor_type.shape.dim)) + transpose_output_name = output_name_after_node_insert + transpose_input_name = transpose_output_name + "_qnn_trans" + output_transpose_node = helper.make_node( + "Transpose", + name=transpose_input_name, + inputs=[transpose_input_name], + outputs=[transpose_output_name], + perm=transpose_perm, + ) + nodes_to_add.extend([output_transpose_node]) + graph_input_output_name_dic[graph_output.name] = transpose_input_name + + # Change output shape to Qnn output shape + for i in range(len(graph_output.type.tensor_type.shape.dim)): + graph_output.type.tensor_type.shape.dim[i].dim_value = qnn_input_output_tensor_dic[ + graph_output.name + ].dim[i] + else: + raise AssertionError("Error: Onnx model output: " + graph_output.name + " not exist from QNN model output.") + + for node in model.graph.node: + for node_input_index, node_input in enumerate(node.input): + # update consumer node for graph inputs to connect to inserted node + if node_input in graph_input_output_name_dic: + node.input[node_input_index] = graph_input_output_name_dic[node_input] + + for node_output_index, node_output in enumerate(node.output): + # update producer node for graph outputs to connect to inserted node + if node_output in graph_input_output_name_dic: + node.output[node_output_index] = graph_input_output_name_dic[node_output] + + model.graph.node.extend(nodes_to_add) + graph_topological_sort(model.graph) + + # Add extra parameter all_tensors_to_one_file=False, size_threshold=5000 if the model exceeds protobuf 2GB limit e.g below + # onnx.save(model, args.onnx_model.replace(".onnx", "_add_trans.onnx"), all_tensors_to_one_file=False, size_threshold=5000) + onnx.save(model, args.onnx_model.replace(".onnx", "_add_trans.onnx")) + + +if __name__ == "__main__": + main() diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/qnn/gen_qnn_ctx_onnx_model.py b/python/user_packages/Python313/site-packages/onnxruntime/tools/qnn/gen_qnn_ctx_onnx_model.py new file mode 100644 index 0000000000000000000000000000000000000000..3d5aa6fa68fadaa23bbc021a58c1799f30119c47 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/tools/qnn/gen_qnn_ctx_onnx_model.py @@ -0,0 +1,364 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +# -------------------------------------------------------------------------- + +import json +from argparse import ArgumentParser + +import onnx +from onnx import TensorProto, helper + + +class QnnTensorStruct: + def __init__( + self, name="", onnx_data_type=TensorProto.FLOAT, is_quantized=False, scale=0.0, offset=0, dim=None, id=None + ): + self.name = name + self.onnx_data_type = onnx_data_type + self.is_quantized = is_quantized + self.scale = scale + self.offset = offset + self.dim = [] if dim is None else dim + self.id = id + + +def is_quantized_data_type(qnn_data_type, is_converter_json): + if is_converter_json: + # QNN_DATATYPE_UFIXED_POINT_8 QNN_DATATYPE_UFIXED_POINT_16 QNN_DATATYPE_FIXED_POINT_8 QNN_DATATYPE_FIXED_POINT_16 + return qnn_data_type == 0x0408 or qnn_data_type == 0x0416 or qnn_data_type == 0x0308 or qnn_data_type == 0x0316 + else: + return ( + qnn_data_type == "QNN_DATATYPE_UFIXED_POINT_8" + or qnn_data_type == "QNN_DATATYPE_UFIXED_POINT_16" + or qnn_data_type == "QNN_DATATYPE_FIXED_POINT_8" + or qnn_data_type == "QNN_DATATYPE_FIXED_POINT_16" + ) + + +def qnn_data_type_to_onnx_data_type(qnn_data_type, is_converter_json): + if is_converter_json: + # QNN_DATATYPE_UFIXED_POINT_8 QNN_DATATYPE_UINT_8 + if qnn_data_type == 0x0408 or qnn_data_type == 0x0108: + return TensorProto.UINT8 + # QNN_DATATYPE_UFIXED_POINT_16 QNN_DATATYPE_UINT_16 + elif qnn_data_type == 0x0416 or qnn_data_type == 0x0116: + return TensorProto.UINT16 + # QNN_DATATYPE_UFIXED_POINT_32 QNN_DATATYPE_UINT_32 + elif qnn_data_type == 0x0432 or qnn_data_type == 0x0132: + return TensorProto.UINT32 + # QNN_DATATYPE_UINT_64 + elif qnn_data_type == 0x0164: + return TensorProto.UINT64 + # QNN_DATATYPE_FIXED_POINT_8 QNN_DATATYPE_INT_8 + elif qnn_data_type == 0x0308 or qnn_data_type == 0x0008: + return TensorProto.INT8 + # QNN_DATATYPE_FIXED_POINT_16 QNN_DATATYPE_INT_16 + elif qnn_data_type == 0x0316 or qnn_data_type == 0x0016: + return TensorProto.INT16 + # QNN_DATATYPE_FIXED_POINT_32 QNN_DATATYPE_INT_32 + elif qnn_data_type == 0x0332 or qnn_data_type == 0x0032: + return TensorProto.INT32 + # QNN_DATATYPE_INT_64 + elif qnn_data_type == 0x0064: + return TensorProto.INT64 + # QNN_DATATYPE_FLOAT_16 + elif qnn_data_type == 0x0216: + return TensorProto.FLOAT16 + # QNN_DATATYPE_FLOAT_32 + elif qnn_data_type == 0x0232: + return TensorProto.FLOAT + # QNN_DATATYPE_BOOL_8 + elif qnn_data_type == 0x0508: + return TensorProto.BOOL + else: + return TensorProto.UNDEFINED + else: + # QNN_DATATYPE_UFIXED_POINT_8 QNN_DATATYPE_UINT_8 + if qnn_data_type == "QNN_DATATYPE_UFIXED_POINT_8" or qnn_data_type == "QNN_DATATYPE_UINT_8": + return TensorProto.UINT8 + # QNN_DATATYPE_UFIXED_POINT_16 QNN_DATATYPE_UINT_16 + elif qnn_data_type == "QNN_DATATYPE_UFIXED_POINT_16" or qnn_data_type == "QNN_DATATYPE_UINT_16": + return TensorProto.UINT16 + # QNN_DATATYPE_UFIXED_POINT_32 QNN_DATATYPE_UINT_32 + elif qnn_data_type == "QNN_DATATYPE_UFIXED_POINT_32" or qnn_data_type == "QNN_DATATYPE_UINT_32": + return TensorProto.UINT32 + # QNN_DATATYPE_UINT_64 + elif qnn_data_type == "QNN_DATATYPE_UINT_64": + return TensorProto.UINT64 + # QNN_DATATYPE_FIXED_POINT_8 QNN_DATATYPE_INT_8 + elif qnn_data_type == "QNN_DATATYPE_FIXED_POINT_8" or qnn_data_type == "QNN_DATATYPE_INT_8": + return TensorProto.INT8 + # QNN_DATATYPE_FIXED_POINT_16 QNN_DATATYPE_INT_16 + elif qnn_data_type == "QNN_DATATYPE_FIXED_POINT_16" or qnn_data_type == "QNN_DATATYPE_INT_16": + return TensorProto.INT16 + # QNN_DATATYPE_FIXED_POINT_32 QNN_DATATYPE_INT_32 + elif qnn_data_type == "QNN_DATATYPE_FIXED_POINT_32" or qnn_data_type == "QNN_DATATYPE_INT_32": + return TensorProto.INT32 + # QNN_DATATYPE_INT_64 + elif qnn_data_type == "QNN_DATATYPE_INT_64": + return TensorProto.INT64 + # QNN_DATATYPE_FLOAT_16 + elif qnn_data_type == "QNN_DATATYPE_FLOAT_16": + return TensorProto.FLOAT16 + # QNN_DATATYPE_FLOAT_32 + elif qnn_data_type == "QNN_DATATYPE_FLOAT_32": + return TensorProto.FLOAT + # QNN_DATATYPE_BOOL_8 + elif qnn_data_type == "QNN_DATATYPE_BOOL_8": + return TensorProto.BOOL + else: + return TensorProto.UNDEFINED + + +def parse_qnn_converter_json_file(qnn_convert_json, qnn_input_tensor_dic, qnn_output_tensor_dic): + is_qnn_converter_json = True + for qnn_tensor_name, qnn_tensor_attribute in qnn_convert_json["graph"]["tensors"].items(): + # type:0 - QNN input tensor, type:1 - QNN output tensor + assert ( + "type" in qnn_tensor_attribute + and "data_type" in qnn_tensor_attribute + and "dims" in qnn_tensor_attribute + and "id" in qnn_tensor_attribute + and "quant_params" in qnn_tensor_attribute + ), "QNN converted json file not valid. Can't find some keys from tensors" + + # If tensor is not IO, ignore it + if qnn_tensor_attribute["type"] not in [0, 1]: + continue + + # Get all graph inputs & output + qnn_tensor = QnnTensorStruct( + name=qnn_tensor_name, + onnx_data_type=qnn_data_type_to_onnx_data_type(qnn_tensor_attribute["data_type"], is_qnn_converter_json), + is_quantized=is_quantized_data_type(qnn_tensor_attribute["data_type"], is_qnn_converter_json), + dim=qnn_tensor_attribute["dims"], + id=qnn_tensor_attribute["id"], + ) + + if ( + qnn_tensor_attribute["quant_params"]["definition"] == 1 + and qnn_tensor_attribute["quant_params"]["encoding"] == 0 + ): + qnn_tensor.scale = qnn_tensor_attribute["quant_params"]["scale_offset"]["scale"] + qnn_tensor.offset = -qnn_tensor_attribute["quant_params"]["scale_offset"]["offset"] + + if qnn_tensor_attribute["type"] == 0: + qnn_input_tensor_dic[qnn_tensor_name] = qnn_tensor + else: + qnn_output_tensor_dic[qnn_tensor_name] = qnn_tensor + + assert len(qnn_input_tensor_dic) >= 1 and len(qnn_output_tensor_dic) >= 1, ( + "Converted QNN model not valid. It should have at least 1 input & 1 output." + ) + + +def generate_wrapper_onnx_file( + grap_name, + model_file_name, + qnn_input_tensor_dic, + qnn_output_tensor_dic, + disable_embed_mode, + qnn_ctx_file, + quantized_IO, + qnn_sdk_version="unknown", +): + graph_nodes = [] + ini_list = [] + value_infos = [] + + model_inputs = [] + for qnn_input in sorted(qnn_input_tensor_dic.values(), key=lambda inp: inp.id): + if qnn_input.is_quantized and not quantized_IO: + q_scale_input_name = qnn_input.name + "_scale" + q_offset_input_name = qnn_input.name + "_zp" + q_scale = helper.make_tensor(q_scale_input_name, TensorProto.FLOAT, [], [qnn_input.scale]) + ini_list.append(q_scale) + q_offset = helper.make_tensor(q_offset_input_name, qnn_input.onnx_data_type, [], [qnn_input.offset]) + ini_list.append(q_offset) + input_name = qnn_input.name + "_dq" + + q_node = helper.make_node( + "QuantizeLinear", + name=qnn_input.name, + inputs=[input_name, q_scale_input_name, q_offset_input_name], + outputs=[qnn_input.name], + ) + + graph_nodes.append(q_node) + model_inputs.append(helper.make_tensor_value_info(input_name, TensorProto.FLOAT, qnn_input.dim)) + value_infos.append(helper.make_tensor_value_info(qnn_input.name, qnn_input.onnx_data_type, qnn_input.dim)) + else: + model_inputs.append(helper.make_tensor_value_info(qnn_input.name, qnn_input.onnx_data_type, qnn_input.dim)) + + if disable_embed_mode: + ep_cache_context_content = qnn_ctx_file + ctx_embed_mode = 0 + else: + with open(qnn_ctx_file, "rb") as file: + ep_cache_context_content = file.read() + ctx_embed_mode = 1 + + qnn_ep_context_node = helper.make_node( + "EPContext", + name=grap_name, + inputs=qnn_input_tensor_dic.keys(), + outputs=qnn_output_tensor_dic.keys(), + ep_cache_context=ep_cache_context_content, + embed_mode=ctx_embed_mode, + ep_sdk_version=qnn_sdk_version, + source="Qnn", + domain="com.microsoft", + ) + graph_nodes.append(qnn_ep_context_node) + + model_outputs = [] + for qnn_output in sorted(qnn_output_tensor_dic.values(), key=lambda out: out.id): + if qnn_output.is_quantized and not quantized_IO: + dq_scale_input_name = qnn_output.name + "_scale" + dq_offset_input_name = qnn_output.name + "_zp" + dq_scale = helper.make_tensor(dq_scale_input_name, TensorProto.FLOAT, [], [qnn_output.scale]) + ini_list.append(dq_scale) + dq_offset = helper.make_tensor(dq_offset_input_name, qnn_output.onnx_data_type, [], [qnn_output.offset]) + ini_list.append(dq_offset) + output_name = qnn_output.name + "_dq" + + dq_node = helper.make_node( + "DequantizeLinear", + name=output_name, + inputs=[qnn_output.name, dq_scale_input_name, dq_offset_input_name], + outputs=[output_name], + ) + + graph_nodes.append(dq_node) + model_outputs.append(helper.make_tensor_value_info(output_name, TensorProto.FLOAT, qnn_output.dim)) + value_infos.append( + helper.make_tensor_value_info(qnn_output.name, qnn_output.onnx_data_type, qnn_output.dim) + ) + else: + model_outputs.append( + helper.make_tensor_value_info(qnn_output.name, qnn_output.onnx_data_type, qnn_output.dim) + ) + + graph_def = helper.make_graph(graph_nodes, "qnn-onnx-model", model_inputs, model_outputs, ini_list, "", value_infos) + + model_def = helper.make_model(graph_def, producer_name="MS") + + onnx.save(model_def, model_file_name) + + +# parse Qnn graph from the json file that extracted from context binary file +def parse_qnn_graph(qnn_graph, qnn_input_tensor_dic, qnn_output_tensor_dic): + is_qnn_converter_json = False + graph_name = qnn_graph["info"]["graphName"] + raw_inputs = qnn_graph["info"]["graphInputs"] + raw_outputs = qnn_graph["info"]["graphOutputs"] + + for raw_input in raw_inputs: + tensor_info = raw_input["info"] + qnn_tensor = QnnTensorStruct() + qnn_tensor.name = tensor_info["name"] + qnn_tensor.onnx_data_type = qnn_data_type_to_onnx_data_type(tensor_info["dataType"], is_qnn_converter_json) + qnn_tensor.is_quantized = is_quantized_data_type(tensor_info["dataType"], is_qnn_converter_json) + qnn_tensor.dim = tensor_info["dimensions"] + if ( + tensor_info["quantizeParams"]["definition"] == "QNN_DEFINITION_DEFINED" + and tensor_info["quantizeParams"]["quantizationEncoding"] == "QNN_QUANTIZATION_ENCODING_SCALE_OFFSET" + ): + qnn_tensor.scale = tensor_info["quantizeParams"]["scaleOffset"]["scale"] + qnn_tensor.offset = 0 - tensor_info["quantizeParams"]["scaleOffset"]["offset"] + qnn_input_tensor_dic[qnn_tensor.name] = qnn_tensor + + for raw_output in raw_outputs: + tensor_info = raw_output["info"] + qnn_tensor = QnnTensorStruct() + qnn_tensor.name = tensor_info["name"] + qnn_tensor.onnx_data_type = qnn_data_type_to_onnx_data_type(tensor_info["dataType"], is_qnn_converter_json) + qnn_tensor.is_quantized = is_quantized_data_type(tensor_info["dataType"], is_qnn_converter_json) + qnn_tensor.dim = tensor_info["dimensions"] + if ( + tensor_info["quantizeParams"]["definition"] == "QNN_DEFINITION_DEFINED" + and tensor_info["quantizeParams"]["quantizationEncoding"] == "QNN_QUANTIZATION_ENCODING_SCALE_OFFSET" + ): + qnn_tensor.scale = tensor_info["quantizeParams"]["scaleOffset"]["scale"] + qnn_tensor.offset = 0 - tensor_info["quantizeParams"]["scaleOffset"]["offset"] + qnn_output_tensor_dic[qnn_tensor.name] = qnn_tensor + + assert len(qnn_input_tensor_dic) >= 1 and len(qnn_output_tensor_dic) >= 1, ( + "Converted QNN model not valid. It should have at least 1 input & 1 output." + ) + + return graph_name + + +# Onnxruntime QNN EP can support context binary file generated by QNN tool chain. However QNN generated context binary file +# uses channel last data layout and 8 bits or 16 bits for input and output. +# This script gets the QNN model input & output information from QNN converted model_net.json file, compare them with Onnx model +# and inserts Cast, Transpose nodes to Onnx model if required +def main(): + parser = ArgumentParser("Generate Onnx model which includes the QNN context binary.") + parser.add_argument("-b", "--qnn_bin", help="Required. Path to Qnn context binary file.", required=True, type=str) + parser.add_argument( + "-q", "--qnn_json", help="Required. Path to Qnn converted model_net.json file.", required=True, type=str + ) + parser.add_argument( + "--disable_embed_mode", + action="store_true", + default=False, + help="Set embed_mode=1 which mean embed Qnn context binary into the onnx model. Otherwise, set context binary file path in the onnx model", + ) + parser.add_argument( + "--quantized_IO", + action="store_true", + default=False, + help="QNN converted context binary use quantized data as graph inputs and outputs. Will keep it if quantized_IO=True, otherwise, will insert Q and DQ nodes accordingly to make the graph inputs & outputs as float32 data type.", + ) + args = parser.parse_args() + + # Parse Qnn model_net.json file to get the graph input output information + + with open(args.qnn_json) as qnn_json_file: + qnn_json_obj = json.load(qnn_json_file) + if "graph" in qnn_json_obj and "tensors" in qnn_json_obj["graph"]: + print("This json file is from Qnn converter") + qnn_input_tensor_dic = {} + qnn_output_tensor_dic = {} + parse_qnn_converter_json_file(qnn_json_obj, qnn_input_tensor_dic, qnn_output_tensor_dic) + + generate_wrapper_onnx_file( + "QnnContext", + args.qnn_json.replace(".json", "_qnn_ctx.onnx"), + qnn_input_tensor_dic, + qnn_output_tensor_dic, + args.disable_embed_mode, + args.qnn_bin, + args.quantized_IO, + ) + elif "info" in qnn_json_obj and "graphs" in qnn_json_obj["info"]: + print("This json file is extracted from QNN context binary file") + qnn_version = qnn_json_obj["info"]["buildId"] + for qnn_graph in qnn_json_obj["info"]["graphs"]: + qnn_input_tensor_dic = {} + qnn_output_tensor_dic = {} + graph_name = parse_qnn_graph(qnn_graph, qnn_input_tensor_dic, qnn_output_tensor_dic) + + ctx_file_name = graph_name + "_qnn_ctx.onnx" + if not args.quantized_IO: + ctx_file_name = ctx_file_name.replace(".onnx", "_fp32_io.onnx") + + generate_wrapper_onnx_file( + graph_name, + ctx_file_name, + qnn_input_tensor_dic, + qnn_output_tensor_dic, + args.disable_embed_mode, + args.qnn_bin, + args.quantized_IO, + qnn_version, + ) + else: + print("json file unrecoginized.") + + +if __name__ == "__main__": + main() diff --git a/python/user_packages/Python313/site-packages/onnxruntime/tools/qnn/preprocess.py b/python/user_packages/Python313/site-packages/onnxruntime/tools/qnn/preprocess.py new file mode 100644 index 0000000000000000000000000000000000000000..3396bf196b4f2c687b1b605c3916334b3171334e --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/tools/qnn/preprocess.py @@ -0,0 +1,165 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- +"""Provide entry point to preprocess ONNX model especially for QNN.""" + +import argparse +import pathlib + +import onnx + +from onnxruntime.quantization.execution_providers import qnn + + +def _parse_arguments(): + """Parse cmdline arguments.""" + parser = argparse.ArgumentParser(description="Arguments for QNN model preprocess.") + + parser.add_argument("--input_model_path", "-i", required=True, help="Path to the input ONNX model.") + parser.add_argument("--output_model_path", "-o", required=True, help="Path to the output ONNX model.") + + # Save preprocessed model with external data. + parser.add_argument( + "--save_as_external_data", + action="store_true", + help="Whether the output model would be saved with external data.", + ) + parser.add_argument( + "--all_tensors_to_one_file", + action="store_true", + help="Whether to save all external data in one file or save each tensor to a file named with the tensor name.", + ) + parser.add_argument( + "--external_data_location", + help="Filename of the external file where all tensors are saved. The path is relative to the model path.", + ) + parser.add_argument( + "--external_data_size_threshold", + default=1024, + type=int, + help="Tensors with data size larger than this threshold are converted to external data.", + ) + parser.add_argument( + "--external_data_convert_attribute", + action="store_true", + help="Whether to save all tensors, including attribute tensors, to external data.", + ) + + # Preprocess options. + parser.add_argument( + "--fuse_layernorm", + action="store_true", + help="Whether to fuse matched sequences into LayerNormalization nodes if possible.", + ) + + # I/O layouts. + parser.add_argument( + "--inputs_to_make_channel_last", + nargs="+", + default=None, + help="List of graph input names to be transposed into channel-last.", + ) + + parser.add_argument( + "--outputs_to_make_channel_last", + nargs="+", + default=None, + help="List of graph output names to be transposed into channel-last.", + ) + + # Fix dynamic input shapes. + parser.add_argument( + "--dynamic_input_shapes", + nargs=2, + action="append", + type=str, + default=None, + help="Model input name and desired static shape in comma seprated format, for example: 'input' 1,3,256,256", + ) + + # Exclude initializer from input + parser.add_argument( + "--exclude_initializer_from_input", + action="store_true", + help="Whether to exclude initializer from input if model.ir_version >= 4", + ) + + return parser.parse_args() + + +def qnn_preprocess_model( + model_input: str | pathlib.Path | onnx.ModelProto, + model_output: str | pathlib.Path, + fuse_layernorm: bool = False, + save_as_external_data: bool = False, + all_tensors_to_one_file: bool = False, + external_data_location: str | None = None, + external_data_size_threshold: int = 1024, + external_data_convert_attribute: bool = False, + inputs_to_make_channel_last: list[str] | None = None, + outputs_to_make_channel_last: list[str] | None = None, + dynamic_input_shapes: list[tuple[str, str]] | None = None, + exclude_initializer_from_input: bool = False, +) -> bool: + """Preprocess ONNX model for QNN. + + Args: + model_input: A path or ONNX ModelProto specifiying the model to be preprocessed. + model_output: A path specifying where the preprocessed model to be saved. + fuse_layernorm: A bool specifying whether to fuse the matched sequence into a single LayerNormalization node. + Defaults to False. + save_as_external_data: A bool specifying whether to save model with external data. Defaults to False. + all_tensors_to_one_file: A bool specifying whether to save all external data in one file or save each tensor to + a file named with the tensor name. This argument is effective only when `save_as_external_data` is True. + Defaults to False. + external_data_location: A str specifying where to save the external data. The path is relative to the model + path. This argument is effective only when `save_as_external_data` is True. Defaults to the model name. + external_data_size_threshold: An int specifying the threshold of data size for tensors be saved as external + data. This argument is effective only when `save_as_external_data` is True. Defaults to 1024. + external_data_convert_attribute: A bool specifying whether to save all tensors including attributes as external + data. This argument is effective only when `save_as_external_data` is True. Defaults to False. + inputs_to_make_channel_last: A list of strs specifying graph input names to be transposed into channel-last. + Defaults to None. + outputs_to_make_channel_last: A list of strs specifying graph output names to be transposed into channel-last. + Defaults to None. + dynamic_input_shapes: A list of tuples specifying model input name to and its static shape in comma seprated + format, for example: [('input', '1,3,256,256')]. Defaults to None. + exclude_initializer_from_input: A bool specifying whether to exclude initializer from input. Defaults to False. + + Returns: + A bool indicating whether the model is modified. + """ + return qnn.qnn_preprocess_model( + model_input, + model_output, + fuse_layernorm=fuse_layernorm, + save_as_external_data=save_as_external_data, + all_tensors_to_one_file=all_tensors_to_one_file, + external_data_location=external_data_location, + external_data_size_threshold=external_data_size_threshold, + external_data_convert_attribute=external_data_convert_attribute, + inputs_to_make_channel_last=inputs_to_make_channel_last, + outputs_to_make_channel_last=outputs_to_make_channel_last, + dynamic_input_shapes=dynamic_input_shapes, + exclude_initializer_from_input=exclude_initializer_from_input, + ) + + +if __name__ == "__main__": + args = _parse_arguments() + qnn_preprocess_model( + args.input_model_path, + args.output_model_path, + fuse_layernorm=args.fuse_layernorm, + save_as_external_data=args.save_as_external_data, + all_tensors_to_one_file=args.all_tensors_to_one_file, + external_data_location=args.external_data_location, + external_data_size_threshold=args.external_data_size_threshold, + external_data_convert_attribute=args.external_data_convert_attribute, + inputs_to_make_channel_last=args.inputs_to_make_channel_last, + outputs_to_make_channel_last=args.outputs_to_make_channel_last, + dynamic_input_shapes=args.dynamic_input_shapes, + exclude_initializer_from_input=args.exclude_initializer_from_input, + ) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__init__.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8d4e73b5766956e304bb53e860612ed232322bc3 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__init__.py @@ -0,0 +1,8 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +# -------------------------------------------------------------------------- +import os +import sys + +sys.path.append(os.path.dirname(__file__)) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5ae43d763542365a54731e143de62be51273a128 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/affinity_helper.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/affinity_helper.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..66f99df409f2f3ef765d75d37b039016d22b7357 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/affinity_helper.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/benchmark.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/benchmark.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a6a9292dc205a7984c6b972e2f3eb66c78aca469 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/benchmark.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/benchmark_helper.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/benchmark_helper.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..31d448aea26ce8a861291377c9ace42dcfe7b3ad Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/benchmark_helper.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/bert_perf_test.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/bert_perf_test.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..46c710a1ec0a8e7f9e341bbd5c5f9d8ecb417ba8 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/bert_perf_test.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/bert_test_data.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/bert_test_data.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0e80c73d543a16bcaa21efc90bde601c3ae9c958 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/bert_test_data.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/compare_bert_results.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/compare_bert_results.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e461729d2995352dadf1dba868c2c90da6e1e173 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/compare_bert_results.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/constants.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/constants.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ec432f2c2e5ff2a0b3b72e1665826c1204302015 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/constants.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/convert_tf_models_to_pytorch.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/convert_tf_models_to_pytorch.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1a566fabdcc9bd3ffe19ce58614737ea1658fe90 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/convert_tf_models_to_pytorch.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/convert_to_packing_mode.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/convert_to_packing_mode.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c565c319db949f1a9728ff26f643b56f5bce1cc3 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/convert_to_packing_mode.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/dynamo_onnx_helper.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/dynamo_onnx_helper.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d30271f18ceb91f8e2064f15764b494aa99024c8 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/dynamo_onnx_helper.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/float16.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/float16.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fcb94dbec6ac6c49292f33528620ad2190c6c015 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/float16.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_attention.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_attention.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a472c483680dac2f6bef6d3e7b000205cf8ed13f Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_attention.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_attention_clip.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_attention_clip.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bb78bd5169964e9d468b7f1c0ce0886365f9cd08 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_attention_clip.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_attention_sam2.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_attention_sam2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ae773983bf37555ccb820c3116786aa39b95026d Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_attention_sam2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_attention_unet.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_attention_unet.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5e58bae072a365eea431c26b60882c2b7ad999cd Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_attention_unet.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_attention_vae.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_attention_vae.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..082b87d8ed0ea18cfe74caf6afac028488eb76fe Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_attention_vae.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_bart_attention.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_bart_attention.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..55dff4d7ca0277711e663034fe9c8dc4865c39f4 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_bart_attention.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_base.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_base.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0885bd1eb7bdd79040f26a91e13a7d7a53f88533 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_base.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_bias_add.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_bias_add.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0a7ba5dee1bd6517ffa30534af05ccf869c49349 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_bias_add.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_biasgelu.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_biasgelu.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..841a3bb316dd56f088120e044fee2dd0a4b31798 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_biasgelu.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_biassplitgelu.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_biassplitgelu.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..63a5f9cf0713c8c2cf028b45850a47c1b74a154c Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_biassplitgelu.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_conformer_attention.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_conformer_attention.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..520f1cabf60c984cc1612d37521bda25e0b6066a Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_conformer_attention.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_constant_fold.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_constant_fold.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bbb5bd3f597bd91aace9009f13d892dc50755a60 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_constant_fold.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_embedlayer.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_embedlayer.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4e04dcb10b0b16060b77c0f9ebb812a240e0d4ad Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_embedlayer.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_fastgelu.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_fastgelu.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..45cfd504f4e8f907f98aa5fb9dae7489dfe3d67d Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_fastgelu.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_gelu.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_gelu.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..033bb81bbb53d06940293b39fecaa3458254c76a Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_gelu.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_gelu_approximation.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_gelu_approximation.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fcf9189d8c59e9c2e66a1329bbce016b63ba6132 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_gelu_approximation.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_gemmfastgelu.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_gemmfastgelu.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..36ddf597ef1018424612633e4922608ba0490312 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_gemmfastgelu.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_gpt_attention.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_gpt_attention.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9ec72912071802fd45585a09df82f8b868bf83d6 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_gpt_attention.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_gpt_attention_megatron.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_gpt_attention_megatron.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a726013262ac624873a9f04e355506eb7bf8c34b Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_gpt_attention_megatron.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_gpt_attention_no_past.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_gpt_attention_no_past.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8219fc8eb0210e32fc44e017334556c84e550cf6 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_gpt_attention_no_past.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_group_norm.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_group_norm.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b41a9f5a6d5f2433f67472642756d7d2c08d4a27 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_group_norm.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_layernorm.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_layernorm.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e8667cd4e9bf295d90b18b157a8774e55147edfd Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_layernorm.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_mha_mmdit.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_mha_mmdit.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4d74a9eec9ee8eb05f795f24f2915e0de3b0a4cd Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_mha_mmdit.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_nhwc_conv.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_nhwc_conv.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5c58f9bdf067a94909be9d7247e0720b85e24807 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_nhwc_conv.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_options.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_options.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c732a38e8024f3be8d8697d24bd061f7a76687e4 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_options.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_qordered_attention.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_qordered_attention.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..81ac69ff0da409f50bb162e8b39ecd06f615ee60 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_qordered_attention.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_qordered_gelu.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_qordered_gelu.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c1c1391b45c7981f2e1dc00a5f24cb6b3af4ecb9 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_qordered_gelu.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_qordered_layernorm.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_qordered_layernorm.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4f7cbc866c7dfbf25594874d0d025c83d6fef2ae Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_qordered_layernorm.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_qordered_matmul.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_qordered_matmul.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0485dddf2a276d5367a1c5a651ac75f14a429294 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_qordered_matmul.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_quickgelu.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_quickgelu.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cf58c8d0f35cda800133c14018110dc770dd895a Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_quickgelu.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_reshape.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_reshape.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5fbbfa5bfc1c1daef28789c061176a031aa8ad1a Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_reshape.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_rotary_attention.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_rotary_attention.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..888fab7a04e54628e46899dc95022a83e1d85a02 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_rotary_attention.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_shape.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_shape.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4d108f48cab602ee0856b85898298a6010da83cd Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_shape.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_simplified_layernorm.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_simplified_layernorm.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d72cd8cdf8bffb8e4d3ef05f339cdc42838e40a7 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_simplified_layernorm.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_skip_group_norm.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_skip_group_norm.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9caf9c8335af23b13e9735d11c02bcb4ed4795e4 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_skip_group_norm.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_skiplayernorm.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_skiplayernorm.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..78299814995602be86aa93609a6db98aa29f0dd7 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_skiplayernorm.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_transpose.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_transpose.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bcc9aa3470128800d7b26d74aaf5ae6f62496720 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_transpose.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_utils.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_utils.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cad7036b01621a43d6039e18b7e808cf996088dd Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/fusion_utils.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/huggingface_models.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/huggingface_models.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..add150a45006d4cb94c920d0427a883d5076493d Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/huggingface_models.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/import_utils.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/import_utils.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0b2cfbfacd9885f93c83f14011fdd138d6309714 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/import_utils.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/io_binding_helper.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/io_binding_helper.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6e8cd10d57731d905d0b7db234a1a4e975dd8445 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/io_binding_helper.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/large_model_exporter.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/large_model_exporter.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8ec3133e879fa2ca601e7bb7bf7889eb4fe51a4d Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/large_model_exporter.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/machine_info.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/machine_info.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bb54644c14dbaa1c5021f474f27abbde2537c890 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/machine_info.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/metrics.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/metrics.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c7a06b0d1e8bfe5b0d73f0244d0039496d9e9694 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/metrics.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/onnx_exporter.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/onnx_exporter.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..749807cd2324a3f4e47b4de54cb723b60c2dcf95 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/onnx_exporter.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/onnx_model.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/onnx_model.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d7c60bfd0658edcb6de1ac3a4e614a1152667be0 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/onnx_model.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/onnx_model_bart.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/onnx_model_bart.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..847eb1253ab4fdc9fb2ecc65b829002bbc3c2701 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/onnx_model_bart.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/onnx_model_bert.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/onnx_model_bert.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9656859a54fdaa7986c01926e7cdc972051ae5f9 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/onnx_model_bert.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/onnx_model_bert_keras.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/onnx_model_bert_keras.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9e1420a49977a0b266f7df356104e7dee2945b20 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/onnx_model_bert_keras.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/onnx_model_bert_tf.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/onnx_model_bert_tf.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6aca952282b760ade4b8431065413f061867959d Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/onnx_model_bert_tf.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/onnx_model_clip.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/onnx_model_clip.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ab4da39dd45f3e5cc0d678d317567d27942f8bdc Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/onnx_model_clip.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/onnx_model_conformer.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/onnx_model_conformer.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..849db8cc0e690aa0b1476ec0e5a544f0f81650bb Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/onnx_model_conformer.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/onnx_model_gpt2.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/onnx_model_gpt2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0236c26b1b0cfef49cb533dfac4e49d90e66e04a Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/onnx_model_gpt2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/onnx_model_mmdit.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/onnx_model_mmdit.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5b5c44a9a44d06d0b28396f58e2512ae93fa60da Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/onnx_model_mmdit.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/onnx_model_phi.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/onnx_model_phi.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..38ae0efdbd61cf31c3f14f8aa2ae4d19b10037fe Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/onnx_model_phi.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/onnx_model_sam2.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/onnx_model_sam2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..158a04ec75875c4a5643d054fb5a89cc1884ae5b Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/onnx_model_sam2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/onnx_model_t5.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/onnx_model_t5.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c36f03955bca49815d82a76c0a6d56976908ee38 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/onnx_model_t5.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/onnx_model_tnlr.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/onnx_model_tnlr.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..201069c84e2513f24964a97fc5f1a7d5269da83b Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/onnx_model_tnlr.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/onnx_model_unet.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/onnx_model_unet.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..70a69bcd234e6c8253b386c8f4ef7ce63df6f8b6 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/onnx_model_unet.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/onnx_model_vae.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/onnx_model_vae.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b553ebb6b6b3bba844f6384e77f04cd12dfd6e0c Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/onnx_model_vae.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/onnx_utils.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/onnx_utils.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7b27c53e54e29a6ed2b661cea93e77795825dd81 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/onnx_utils.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/optimizer.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/optimizer.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..765f2832d87b073d2935416b0f4f4164efaaee99 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/optimizer.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/past_helper.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/past_helper.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fc917ebe4025aefa6aa86dd392007ac0ec231a50 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/past_helper.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/profile_result_processor.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/profile_result_processor.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f18c359a0c6e1c682726bc48952ee5a56d717411 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/profile_result_processor.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/profiler.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/profiler.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1f2fb4178ee134bb40c8ac2ebe2ca2107d14a97f Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/profiler.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/quantize_helper.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/quantize_helper.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..17d04989ff88c50cf1204b5bd1ab838762304c74 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/quantize_helper.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/shape_infer_helper.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/shape_infer_helper.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ed2999c2d13f64faf7fe000a2382e14fdeeaff93 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/shape_infer_helper.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/shape_optimizer.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/shape_optimizer.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..03febb47d19503bbd3483c9bf065776a947cf77a Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/shape_optimizer.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/torch_onnx_export_helper.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/torch_onnx_export_helper.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..43848261dac5238a34f697f64488a288187bc67a Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/__pycache__/torch_onnx_export_helper.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/fusion_utils.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/fusion_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..cc58b2066fc39c8ba3724f03c6a981ed95881c95 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/fusion_utils.py @@ -0,0 +1,321 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +# -------------------------------------------------------------------------- +from logging import getLogger + +import numpy +from numpy import array_equal, ndarray +from onnx import NodeProto, TensorProto, helper, numpy_helper +from onnx_model import OnnxModel + +logger = getLogger(__name__) + + +class FusionUtils: + def __init__(self, model: OnnxModel): + self.model: OnnxModel = model + + def cast_graph_input_to_int32(self, input_name: str) -> tuple[bool, str]: + graph_input = self.model.find_graph_input(input_name) + if graph_input is not None and graph_input.type.tensor_type.elem_type != TensorProto.INT32: + cast_output, cast_node = self.cast_input_to_int32(input_name) + logger.debug(f"Casted graph input {input_name} to int32") + return True, cast_output + + logger.debug(f"Did not cast graph input {input_name} to int32: found {graph_input is not None}") + return False, input_name + + def cast_input(self, input_name: str, target_type="int32"): + output_name = input_name + "_" + target_type + + if target_type == "int32": + to_type = int(TensorProto.INT32) + elif target_type == "float32": + to_type = int(TensorProto.FLOAT) + elif target_type == "float16": + to_type = int(TensorProto.FLOAT16) + else: + raise ValueError("Invalid target_type: {target_type}") + + cast_node = self.add_cast_node(input_name, to_type, output_name) + + return output_name, cast_node + + def add_cast_node( + self, + input_name: str, + to_type: int, + output_name: str | None = None, + output_name_to_node=None, + graph_name: str | None = None, + ): + if output_name is None: + output_name = input_name + f"_cast_to_{to_type}" + + # Avoid consequent Cast nodes. + inputs = [input_name] + if output_name_to_node is None: + output_name_to_node = self.model.output_name_to_node() + if input_name in output_name_to_node: + parent_node = output_name_to_node[input_name] + if parent_node and parent_node.op_type == "Cast": + inputs = [parent_node.input[0]] + + cast_node = helper.make_node("Cast", inputs=inputs, outputs=[output_name]) + + cast_node.attribute.extend([helper.make_attribute("to", to_type)]) + self.model.add_node(cast_node, graph_name=graph_name) + + return cast_node + + def cast_input_to_int32(self, input_name: str): + return self.cast_input(input_name, "int32") + + def remove_cast_int32(self, input_name: str): + input_name_to_nodes = self.model.input_name_to_nodes() + nodes = input_name_to_nodes[input_name] + for node in nodes: + if node.op_type == "Cast": + is_int32 = False + for att in node.attribute: + if att.name == "to" and att.i == int(TensorProto.INT32): + is_int32 = True + break + if is_int32: + output_name = node.output[0] + self.model.remove_node(node) + self.model.replace_input_of_all_nodes(output_name, input_name) + + @staticmethod + def update_node_input(node, i, new_input_name, input_name_to_nodes): + old_input_reference = 0 + if (node.input[i] in input_name_to_nodes) and node in input_name_to_nodes[node.input[i]]: + input_name_to_nodes[node.input[i]].remove(node) + old_input_reference = len(input_name_to_nodes[node.input[i]]) + + node.input[i] = new_input_name + + if new_input_name in input_name_to_nodes: + input_name_to_nodes[new_input_name].append(node) + else: + input_name_to_nodes[new_input_name] = [node] + + return old_input_reference + + @staticmethod + def skip_parent(model: OnnxModel, node, parent_node, input_name_to_nodes, node_input_index=0, parent_input_index=0): + """ + Before: + (input)-->parent-->node-->(output) + After: + (input)-->parent--> + | + +----->node-->(output) + + This function returns a flag whether the parent node can be removed. + """ + + old_input_name = node.input[node_input_index] + new_input_name = parent_node.input[parent_input_index] + old_input_reference = FusionUtils.update_node_input(node, node_input_index, new_input_name, input_name_to_nodes) + + # We can remove the first Transpose if its output is not used (linked to graph output or other nodes) anymore. + parent_can_be_removed = (old_input_reference == 0) and not model.find_graph_output(old_input_name) + + return parent_can_be_removed + + def get_squeeze_or_unsqueeze_axes(self, node: NodeProto) -> ndarray | None: + assert node.op_type in ["Squeeze", "Unsqueeze"] + + # For opset >= 13, axes is an input instead of an attribute. + if len(node.input) > 1: + return self.model.get_constant_value(node.input[1]) + + axes = None + for attr in node.attribute: + if attr.name == "axes": + axes = helper.get_attribute_value(attr) + return axes + + @staticmethod + def check_node_attribute(node, attribute_name: str, expected_value, default_value=None): + """Verify that a node has expected value for an attribute. + + Args: + node (NodeProto): a node to check + attribute_name (str): name of attribute + expected_value (Any): expected value of the attribute + default_value (Any, optional): default value if the attribute does not exist. Defaults to None. + + Returns: + bool: whether the check is passed or not + """ + value = default_value + for attr in node.attribute: + if attr.name == attribute_name: + value = helper.get_attribute_value(attr) + + if isinstance(expected_value, list): + return (isinstance(value, (ndarray, list))) and array_equal(expected_value, value, equal_nan=False) + else: + return value == expected_value + + @staticmethod + def transpose_2d_int8_tensor(tensor: TensorProto): + """Transpose a 2-D INT8 TensorProto + Args: + tensor (TensorProto): tensor to be transposed + Returns: + tensor (TensorProto): transposed tensor + """ + if not isinstance(tensor, TensorProto): + raise TypeError(f"Expected input type is an ONNX TensorProto but got {type(tensor)}") + + if len(tensor.dims) != 2 or tensor.data_type != TensorProto.INT8: + raise ValueError("Only INT8 2-D tensors can be transposed") + + if tensor.raw_data: + int32_data = numpy.reshape(numpy.frombuffer(tensor.raw_data, dtype="int8"), tensor.dims) + int32_transposed_data = numpy.transpose(int32_data, [1, 0]) + tensor.raw_data = int32_transposed_data.tobytes() + + else: + raise ValueError("only raw buffer supported") + + return tensor + + @staticmethod + def check_qdq_node_for_fusion(node: NodeProto, model: OnnxModel, allow_per_tensor_quantization_only=True): + """Verify if a provided QuantizeLinear (Q) / DequantizeLinear (DQ) node is a good candidate for fusion. + It is a good candidate for fusion if: + (1) The Q/DQ node is for per-tensor quantization if allow_per_tensor_quantization_only is `True` + (2) The Q/DQ node should have constant scale + (3) The Q/DQ node should have a zero point of 0 + Args: + node (NodeProto): a Q/DQ node to check + Returns: + bool: whether the check is passed or not + """ + if node.op_type not in {"QuantizeLinear", "DequantizeLinear"}: + logger.debug(f"Provided node is not a Q/DQ node. Op Type: {node.op_type}") + + scale = model.get_constant_value(node.input[1]) + + # Scale is not constant + if scale is None: + return False + + # Not per-tensor quantization + scale_has_single_element = scale.ndim == 0 or (scale.ndim == 1 and scale.shape[0] == 1) + if allow_per_tensor_quantization_only and not scale_has_single_element: + return False + + # If the Q/DQ node has no zero point input, it is assumed to be 0 (per ONNX spec) + if len(node.input) == 2: + return True + + # Zero point should be constant and should have a value of 0 + zero_point = model.get_constant_value(node.input[2]) + + # Zero point and scale should have same number of dims + if scale.ndim != zero_point.ndim: + return False + + # Zero point is not constant or zero point is not zero + if zero_point is None: + return False + + return numpy.all(zero_point == 0) + + def check_node_input_value(self, node, input_index: int, expected_value): + """Verify that a node has expected input value + + Args: + node (NodeProto): a node to check + input_index (int): index of its input to be verified + expected_value (Any): expected value of the input + + Returns: + bool: whether the check is passed or not + """ + assert len(node.input) > input_index + + value = self.model.get_constant_value(node.input[input_index]) + + if isinstance(expected_value, list): + return (isinstance(value, (ndarray, list))) and array_equal(expected_value, value, equal_nan=False) + else: + return value == expected_value + + def remove_identity_nodes(self): + """Remove Identity nodes, except those right before graph output.""" + nodes_to_remove = [] + graph_output_names = self.model.get_graphs_output_names() + for node in self.model.nodes(): + if node.op_type == "Identity": + if node.output[0] not in graph_output_names: + self.model.replace_input_of_all_nodes(node.output[0], node.input[0]) + nodes_to_remove.append(node) + + if nodes_to_remove: + self.model.remove_nodes(nodes_to_remove) + logger.info(f"Removed {len(nodes_to_remove)} Identity nodes") + + def remove_cascaded_cast_nodes(self): + self.model.remove_cascaded_cast_nodes() + + def remove_useless_cast_nodes(self): + self.model.remove_useless_cast_nodes() + + def remove_useless_reshape_nodes(self): + """Remove reshape node that is not needed based on symbolic shape inference: input and output has same shape""" + shape_infer = self.model.infer_runtime_shape(update=True) + if shape_infer is None: + return + + nodes_to_remove = [] + for node in self.model.nodes(): + if node.op_type == "Reshape": + input_shape = shape_infer.get_edge_shape(node.input[0]) + output_shape = shape_infer.get_edge_shape(node.output[0]) + if input_shape and output_shape and input_shape == output_shape: + logger.info( + f"Remove reshape node {node.name} since its input shape is same as output: {input_shape}" + ) + nodes_to_remove.append(node) + + if nodes_to_remove: + graph_input_names = set(self.model.get_graphs_input_names()) + graph_output_names = set(self.model.get_graphs_output_names()) + for node in nodes_to_remove: + if bool(set(node.output) & graph_output_names): + if ( + not bool(set(node.input) & graph_input_names) + and len(self.model.input_name_to_nodes()[node.input[0]]) == 1 # parent has only one child + ): + self.model.replace_output_of_all_nodes(node.input[0], node.output[0]) + else: + continue + else: + self.model.replace_input_of_all_nodes(node.output[0], node.input[0]) + self.model.remove_node(node) + + +class NumpyHelper: + @staticmethod + def to_array(tensor: TensorProto, fill_zeros: bool = False) -> ndarray: + # When weights are in external data format but not presented, we can still test the optimizer with two changes: + # (1) set fill_zeros = True (2) change load_external_data=False in optimizer.py + if fill_zeros: + return ndarray( + shape=tensor.dims, + dtype=helper.tensor_dtype_to_np_dtype(tensor.data_type), + ) + + if tensor.data_type == TensorProto.BFLOAT16: + import onnx_ir as ir # noqa: PLC0415 + + # Use onnx_ir to correctly handle bfloat16 tensors + return ir.from_proto(tensor).numpy() + return numpy_helper.to_array(tensor) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/huggingface_models.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/huggingface_models.py new file mode 100644 index 0000000000000000000000000000000000000000..f38390dfb74f0377e74bc6648e4cb060cc696241 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/huggingface_models.py @@ -0,0 +1,74 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +# Maps model class name to a tuple of model class +MODEL_CLASSES = [ + "AutoModel", + "AutoModelWithLMHead", + "AutoModelForSequenceClassification", + "AutoModelForQuestionAnswering", + "AutoModelForCausalLM", +] + +# Pretrained model name to a tuple of input names, opset_version, use_external_data_format, optimization model type +# Some models like GPT, T5, Bart etc has its own convert_to_onnx.py in models sub-directory, and they are excluded here. +MODELS = { + # BERT + "bert-base-cased": (["input_ids", "attention_mask", "token_type_ids"], 16, False, "bert"), + "bert-large-cased": (["input_ids", "attention_mask", "token_type_ids"], 16, False, "bert"), + # Transformer-XL (Models uses Einsum, which need opset version 16 or later.) + "transfo-xl-wt103": (["input_ids", "mems"], 16, False, "bert"), + # XLNet + "xlnet-base-cased": (["input_ids"], 16, False, "bert"), + "xlnet-large-cased": (["input_ids"], 16, False, "bert"), + # XLM + "xlm-mlm-en-2048": (["input_ids"], 16, True, "bert"), + "xlm-mlm-ende-1024": (["input_ids"], 16, False, "bert"), + "xlm-mlm-enfr-1024": (["input_ids"], 16, False, "bert"), + # RoBERTa + "roberta-base": (["input_ids", "attention_mask"], 16, False, "bert"), + "roberta-large": (["input_ids", "attention_mask"], 16, False, "bert"), + "roberta-large-mnli": (["input_ids", "attention_mask"], 16, False, "bert"), + "deepset/roberta-base-squad2": (["input_ids", "attention_mask"], 16, False, "bert"), + "distilroberta-base": (["input_ids", "attention_mask"], 16, False, "bert"), + # DistilBERT + "distilbert-base-uncased": (["input_ids", "attention_mask"], 16, False, "bert"), + "distilbert-base-uncased-distilled-squad": (["input_ids", "attention_mask"], 16, False, "bert"), + # CTRL + "ctrl": (["input_ids"], 16, True, "bert"), + # CamemBERT + "camembert-base": (["input_ids"], 16, False, "bert"), + # ALBERT + "albert-base-v1": (["input_ids"], 16, False, "bert"), + "albert-large-v1": (["input_ids"], 16, False, "bert"), + "albert-xlarge-v1": (["input_ids"], 16, True, "bert"), + # "albert-xxlarge-v1": (["input_ids"], 16, True, "bert"), + "albert-base-v2": (["input_ids"], 16, False, "bert"), + "albert-large-v2": (["input_ids"], 16, False, "bert"), + "albert-xlarge-v2": (["input_ids"], 16, True, "bert"), + # "albert-xxlarge-v2": (["input_ids"], 16, True, "bert"), + # XLM-RoBERTa + "xlm-roberta-base": (["input_ids"], 16, False, "bert"), + "xlm-roberta-large": (["input_ids"], 16, True, "bert"), + # FlauBERT + "flaubert/flaubert_small_cased": (["input_ids"], 16, False, "bert"), + "flaubert/flaubert_base_cased": (["input_ids"], 16, False, "bert"), + # "flaubert/flaubert_large_cased": (["input_ids"], 16, False, "bert"), + # Layoutlm + "microsoft/layoutlm-base-uncased": (["input_ids"], 16, False, "bert"), + "microsoft/layoutlm-large-uncased": (["input_ids"], 16, False, "bert"), + # Squeezebert + "squeezebert/squeezebert-uncased": (["input_ids"], 16, False, "bert"), + "squeezebert/squeezebert-mnli": (["input_ids"], 16, False, "bert"), + "squeezebert/squeezebert-mnli-headless": (["input_ids"], 16, False, "bert"), + "unc-nlp/lxmert-base-uncased": (["input_ids", "visual_feats", "visual_pos"], 16, False, "bert"), + # ViT + "google/vit-base-patch16-224": (["pixel_values"], 16, False, "vit"), + # Swin + "microsoft/swin-base-patch4-window7-224": (["pixel_values"], 16, False, "swin"), + "microsoft/swin-small-patch4-window7-224": (["pixel_values"], 16, False, "swin"), + "microsoft/swin-tiny-patch4-window7-224": (["pixel_values"], 16, False, "swin"), +} diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/import_utils.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/import_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..9015231850db6519b15e0d4887dc44f412640b00 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/import_utils.py @@ -0,0 +1,20 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +# -------------------------------------------------------------------------- +import importlib.metadata +import importlib.util + + +def is_installed(package): + try: + dist = importlib.metadata.distribution(package) + except importlib.metadata.PackageNotFoundError: + try: + spec = importlib.util.find_spec(package) + except ModuleNotFoundError: + return False + + return spec is not None + + return dist is not None diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/io_binding_helper.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/io_binding_helper.py new file mode 100644 index 0000000000000000000000000000000000000000..24c3917bf4341c899cffe0ccb149b65674d68475 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/io_binding_helper.py @@ -0,0 +1,538 @@ +import copy +import logging +from collections import OrderedDict +from collections.abc import Mapping +from typing import Any + +import numpy +import torch +from onnx import TensorProto + +from onnxruntime import InferenceSession, RunOptions + +# Type alias +ShapeDict = Mapping[str, tuple | list[int]] + +logger = logging.getLogger(__name__) + + +class TypeHelper: + @staticmethod + def get_input_type(ort_session: InferenceSession, name: str) -> str: + for _i, input in enumerate(ort_session.get_inputs()): + if input.name == name: + return input.type + raise ValueError(f"input name {name} not found") + + @staticmethod + def get_output_type(ort_session, name: str) -> str: + for _i, output in enumerate(ort_session.get_outputs()): + if output.name == name: + return output.type + + raise ValueError(f"output name {name} not found") + + @staticmethod + def ort_type_to_numpy_type(ort_type: str): + ort_type_to_numpy_type_map = { + "tensor(int64)": numpy.int64, + "tensor(int32)": numpy.int32, + "tensor(float)": numpy.float32, + "tensor(float16)": numpy.float16, + "tensor(bool)": bool, + "tensor(uint8)": numpy.uint8, + "tensor(int8)": numpy.int8, + "tensor(double)": numpy.float64, + "tensor(int16)": numpy.int16, + "tensor(uint16)": numpy.uint16, + "tensor(uint32)": numpy.uint32, + "tensor(uint64)": numpy.uint64, + "tensor(complex64)": numpy.complex64, + "tensor(complex128)": numpy.complex128, + } + if ort_type not in ort_type_to_numpy_type_map: + raise ValueError(f"{ort_type} not found in map") + + return ort_type_to_numpy_type_map[ort_type] + + @staticmethod + def ort_type_to_torch_type(ort_type: str): + ort_type_to_torch_type_map = { + "tensor(int64)": torch.int64, + "tensor(int32)": torch.int32, + "tensor(float)": torch.float32, + "tensor(float16)": torch.float16, + "tensor(bfloat16)": torch.bfloat16, + "tensor(bool)": torch.bool, + "tensor(uint8)": torch.uint8, + "tensor(int8)": torch.int8, + "tensor(double)": torch.float64, + "tensor(int16)": torch.int16, + "tensor(uint16)": torch.uint16, + "tensor(uint32)": torch.uint32, + "tensor(uint64)": torch.uint64, + "tensor(complex64)": torch.complex64, + "tensor(complex128)": torch.complex128, + "tensor(float8e4m3fn)": torch.float8_e4m3fn, + "tensor(float8e4m3fnuz)": torch.float8_e4m3fnuz, + "tensor(float8e5m2)": torch.float8_e5m2, + "tensor(float8e5m2fnuz)": torch.float8_e5m2fnuz, + "tensor(int4)": torch.int4, + "tensor(uint4)": torch.uint4, + } + if ort_type not in ort_type_to_torch_type_map: + raise ValueError(f"{ort_type} not found in map") + + return ort_type_to_torch_type_map[ort_type] + + @staticmethod + def get_io_onnx_type_map(ort_session: InferenceSession) -> dict[str, int]: + """Create a mapping from input/output name to onnx data type""" + name_to_onnx_type = {} + for input in ort_session.get_inputs(): + name_to_onnx_type[input.name] = TypeHelper.ort_type_to_onnx_type(input.type) + + for output in ort_session.get_outputs(): + name_to_onnx_type[output.name] = TypeHelper.ort_type_to_onnx_type(output.type) + return name_to_onnx_type + + @staticmethod + def ort_type_to_onnx_type(ort_type: str): + ort_type_to_onnx_type_map = { + "tensor(int64)": TensorProto.INT64, + "tensor(int32)": TensorProto.INT32, + "tensor(float)": TensorProto.FLOAT, + "tensor(float16)": TensorProto.FLOAT16, + "tensor(bfloat16)": TensorProto.BFLOAT16, + "tensor(bool)": TensorProto.BOOL, + "tensor(uint8)": TensorProto.UINT8, + "tensor(int8)": TensorProto.INT8, + "tensor(double)": TensorProto.DOUBLE, + "tensor(int16)": TensorProto.INT16, + "tensor(uint16)": TensorProto.UINT16, + "tensor(uint32)": TensorProto.UINT32, + "tensor(uint64)": TensorProto.UINT64, + "tensor(complex64)": TensorProto.COMPLEX64, + "tensor(complex128)": TensorProto.COMPLEX128, + "tensor(float8e4m3fn)": TensorProto.FLOAT8E4M3FN, + "tensor(float8e4m3fnuz)": TensorProto.FLOAT8E4M3FNUZ, + "tensor(float8e5m2)": TensorProto.FLOAT8E5M2, + "tensor(float8e5m2fnuz)": TensorProto.FLOAT8E5M2FNUZ, + "tensor(float4e2m1)": TensorProto.FLOAT4E2M1, + "tensor(int4)": TensorProto.INT4, + "tensor(uint4)": TensorProto.UINT4, + "tensor(string)": TensorProto.STRING, + } + if ort_type not in ort_type_to_onnx_type_map: + raise ValueError(f"{ort_type} not found in map") + + return ort_type_to_onnx_type_map[ort_type] + + @staticmethod + def numpy_type_to_torch_type(numpy_type: numpy.dtype): + numpy_type_to_torch_type_map = { + numpy.int64: torch.int64, + numpy.int32: torch.int32, + numpy.float32: torch.float32, + numpy.float16: torch.float16, + bool: torch.bool, + numpy.uint8: torch.uint8, + numpy.int8: torch.int8, + numpy.float64: torch.float64, + numpy.int16: torch.int16, + numpy.uint16: torch.uint16, + numpy.uint32: torch.uint32, + numpy.uint64: torch.uint64, + numpy.complex64: torch.complex64, + numpy.complex128: torch.complex128, + } + + if numpy_type not in numpy_type_to_torch_type_map: + raise ValueError(f"{numpy_type} not found in map") + + return numpy_type_to_torch_type_map[numpy_type] + + @staticmethod + def torch_type_to_numpy_type(torch_type: torch.dtype): + torch_type_to_numpy_type_map = { + torch.int64: numpy.int64, + torch.int32: numpy.int32, + torch.float32: numpy.float32, + torch.float16: numpy.float16, + torch.bool: bool, + torch.uint8: numpy.uint8, + torch.int8: numpy.int8, + torch.float64: numpy.float64, + torch.int16: numpy.int16, + torch.uint16: numpy.uint16, + torch.uint32: numpy.uint32, + torch.uint64: numpy.uint64, + torch.complex64: numpy.complex64, + torch.complex128: numpy.complex128, + } + + if torch_type not in torch_type_to_numpy_type_map: + raise ValueError(f"{torch_type} not found in map") + + return torch_type_to_numpy_type_map[torch_type] + + @staticmethod + def get_io_numpy_type_map(ort_session: InferenceSession) -> dict[str, numpy.dtype]: + """Create a mapping from input/output name to numpy data type""" + name_to_numpy_type = {} + for input in ort_session.get_inputs(): + name_to_numpy_type[input.name] = TypeHelper.ort_type_to_numpy_type(input.type) + + for output in ort_session.get_outputs(): + name_to_numpy_type[output.name] = TypeHelper.ort_type_to_numpy_type(output.type) + return name_to_numpy_type + + @staticmethod + def get_io_torch_type_map(ort_session: InferenceSession) -> dict[str, torch.dtype]: + """Create a mapping from input/output name to torch data type""" + name_to_torch_type = {} + for input in ort_session.get_inputs(): + name_to_torch_type[input.name] = TypeHelper.ort_type_to_torch_type(input.type) + + for output in ort_session.get_outputs(): + name_to_torch_type[output.name] = TypeHelper.ort_type_to_torch_type(output.type) + return name_to_torch_type + + +class IOBindingHelper: + @staticmethod + def get_output_buffers(ort_session: InferenceSession, output_shapes, device): + """Returns a dictionary of output name as key, and 1D tensor as value. The tensor has enough space for given shape.""" + output_buffers = {} + for name, shape in output_shapes.items(): + ort_type = TypeHelper.get_output_type(ort_session, name) + torch_type = TypeHelper.ort_type_to_torch_type(ort_type) + output_buffers[name] = torch.empty(numpy.prod(shape), dtype=torch_type, device=device) + return output_buffers + + @staticmethod + def prepare_io_binding( + ort_session, + input_ids: torch.Tensor, + position_ids: torch.Tensor, + attention_mask: torch.Tensor, + past: list[torch.Tensor], + output_buffers, + output_shapes, + ): + """IO binding for a session: bind inputs (input_ids, position_ids, attention_mask, past_*) and outputs.""" + + name_to_onnx_type = TypeHelper.get_io_onnx_type_map(ort_session) + + # Bind inputs and outputs to onnxruntime session + io_binding = ort_session.io_binding() + + # Bind inputs + assert input_ids.is_contiguous() + io_binding.bind_input( + "input_ids", + input_ids.device.type, + 0, + name_to_onnx_type["input_ids"], + list(input_ids.size()), + input_ids.data_ptr(), + ) + + if past is not None: + for i, past_i in enumerate(past): + assert past_i.is_contiguous() + + data_ptr = past_i.data_ptr() + if data_ptr == 0: + # When past_sequence_length is 0, its data_ptr will be zero. IO Binding asserts that data_ptr shall not be zero. + # Here we workaround and pass data pointer of input_ids. Actual data is not used for past so it does not matter. + data_ptr = input_ids.data_ptr() + + io_binding.bind_input( + f"past_{i}", + past_i.device.type, + 0, + name_to_onnx_type[f"past_{i}"], + list(past_i.size()), + data_ptr, + ) + + if attention_mask is not None: + assert attention_mask.is_contiguous() + io_binding.bind_input( + "attention_mask", + attention_mask.device.type, + 0, + name_to_onnx_type["attention_mask"], + list(attention_mask.size()), + attention_mask.data_ptr(), + ) + + if position_ids is not None: + assert position_ids.is_contiguous() + io_binding.bind_input( + "position_ids", + position_ids.device.type, + 0, + name_to_onnx_type["position_ids"], + list(position_ids.size()), + position_ids.data_ptr(), + ) + + # Bind outputs + for output in ort_session.get_outputs(): + output_name = output.name + output_buffer = output_buffers[output_name] + logger.debug(f"{output_name} device type={output_buffer.device.type} shape={list(output_buffer.size())}") + io_binding.bind_output( + output_name, + output_buffer.device.type, + 0, + name_to_onnx_type[output_name], + output_shapes[output_name], + output_buffer.data_ptr(), + ) + + return io_binding + + @staticmethod + def get_outputs_from_io_binding_buffer(ort_session, output_buffers, output_shapes, return_numpy=True): + """Copy results to cpu. Returns a list of numpy array.""" + ort_outputs = [] + for output in ort_session.get_outputs(): + output_name = output.name + buffer = output_buffers[output_name] + shape = output_shapes[output_name] + copy_tensor = buffer[0 : numpy.prod(shape)].reshape(shape).clone().detach() + if return_numpy: + ort_outputs.append(copy_tensor.cpu().numpy()) + else: + ort_outputs.append(copy_tensor) + return ort_outputs + + +class CudaSession: + """Inference Session with IO Binding for ONNX Runtime CUDA or TensorRT provider""" + + def __init__(self, ort_session: InferenceSession, device: torch.device, enable_cuda_graph=False): + self.ort_session = ort_session + self.input_names = [input.name for input in self.ort_session.get_inputs()] + self.output_names = [output.name for output in self.ort_session.get_outputs()] + self.io_name_to_onnx_type = TypeHelper.get_io_onnx_type_map(self.ort_session) + self.io_name_to_torch_type = TypeHelper.get_io_torch_type_map(self.ort_session) + self.io_binding = self.ort_session.io_binding() + self.enable_cuda_graph = enable_cuda_graph + + self.input_tensors = OrderedDict() + self.output_tensors = OrderedDict() + self.device = device + + # Pairs of input and output names that share the same buffer. + self.buffer_sharing: dict[str, str] = {} + + def set_buffer_sharing(self, input_name: str, output_name: str): + assert input_name in self.input_names + assert output_name in self.output_names + self.buffer_sharing[input_name] = output_name + self.buffer_sharing[output_name] = input_name + + def __del__(self): + del self.input_tensors + del self.output_tensors + del self.io_binding + + def bind_input_and_buffer_sharing(self, name: str, tensor: torch.Tensor): + device_id = tensor.device.index if tensor.device.index is not None else 0 + tensor_shape = [1] if len(tensor.shape) == 0 else list(tensor.shape) + + self.io_binding.bind_input( + name, + tensor.device.type, + device_id, + self.io_name_to_onnx_type[name], + tensor_shape, + tensor.data_ptr(), + ) + + if name in self.buffer_sharing: + self.io_binding.bind_output( + self.buffer_sharing[name], + tensor.device.type, + device_id, + self.io_name_to_onnx_type[name], + tensor_shape, + tensor.data_ptr(), + ) + self.output_tensors[self.buffer_sharing[name]] = tensor + + def allocate_buffers(self, shape_dict: ShapeDict): + """Allocate tensors for I/O Binding""" + if self.enable_cuda_graph: + for name, shape in shape_dict.items(): + if name in self.input_names: + # Reuse allocated buffer when the shape is same + if name in self.input_tensors: + if tuple(self.input_tensors[name].shape) == tuple(shape): + continue + raise RuntimeError("Expect static input shape for cuda graph") + + torch_dtype = self.io_name_to_torch_type[name] + tensor = torch.empty(tuple(shape), dtype=torch_dtype).to(device=self.device) + self.input_tensors[name] = tensor + self.bind_input_and_buffer_sharing(name, tensor) + + for name, shape in shape_dict.items(): + if name in self.output_names: + # Reuse allocated buffer when the shape is same + if name in self.output_tensors and tuple(self.output_tensors[name].shape) == tuple(shape): + continue + + if name in self.buffer_sharing: + continue + + torch_dtype = self.io_name_to_torch_type[name] + tensor = torch.empty(tuple(shape), dtype=torch_dtype).to(device=self.device) + self.output_tensors[name] = tensor + + self.io_binding.bind_output( + name, + tensor.device.type, + tensor.device.index if tensor.device.index is not None else 0, + self.io_name_to_onnx_type[name], + list(tensor.size()), + tensor.data_ptr(), + ) + + def infer(self, feed_dict: dict[str, torch.Tensor], run_options: RunOptions = None, synchronize: bool = True): + """Bind input tensors and run inference""" + for name, tensor in feed_dict.items(): + assert isinstance(tensor, torch.Tensor) and tensor.is_contiguous() + if name in self.input_names: + if self.enable_cuda_graph: + assert self.input_tensors[name].nelement() == tensor.nelement() + assert self.input_tensors[name].dtype == tensor.dtype + assert tensor.device.type == "cuda" + self.input_tensors[name].copy_(tensor) + else: + self.bind_input_and_buffer_sharing(name, tensor) + + if synchronize: + self.io_binding.synchronize_inputs() + self.ort_session.run_with_iobinding(self.io_binding, run_options) + self.io_binding.synchronize_outputs() + else: + self.ort_session.run_with_iobinding(self.io_binding, run_options) + + return self.output_tensors + + @staticmethod + def get_cuda_provider_options(device_id: int, enable_cuda_graph: bool, stream: int = 0) -> dict[str, Any]: + options = { + "device_id": device_id, + "arena_extend_strategy": "kSameAsRequested", + "enable_cuda_graph": enable_cuda_graph, + } + + # Stream is address of a CUDA stream. 0 means the default stream. + if stream != 0: + options["user_compute_stream"] = str(stream) + + return options + + +class GpuBinding(CudaSession): + def __init__( + self, + ort_session: InferenceSession, + device: torch.device, + shape_dict: ShapeDict, + enable_gpu_graph: bool = False, + gpu_graph_id: int = -1, + stream: int = 0, + buffer_sharing: dict[str, str] | None = None, + ): + super().__init__(ort_session, device, enable_gpu_graph) + if buffer_sharing: + for input_name, output_name in buffer_sharing.items(): + self.set_buffer_sharing(input_name, output_name) + + self.allocate_buffers(shape_dict) + self.gpu_graph_id = gpu_graph_id + # For cuda graph, we need to keep a copy of shape_dict to check if the shape is same in inference later. + self.shape_dict = copy.deepcopy(shape_dict) if enable_gpu_graph else None + self.stream = stream + # The gpu graph id of last run. It will be saved to image metadata. + self.last_run_gpu_graph_id = None + + def get_run_options(self, disable_cuda_graph_in_run: bool = False) -> RunOptions: + options = RunOptions() + + gpu_graph_id = -1 if disable_cuda_graph_in_run else self.gpu_graph_id + + options.add_run_config_entry("gpu_graph_id", str(gpu_graph_id)) + + self.last_run_gpu_graph_id = gpu_graph_id + + return options + + def infer(self, feed_dict: dict[str, torch.Tensor], disable_cuda_graph_in_run: bool = False): + run_options = self.get_run_options(disable_cuda_graph_in_run) + + if self.stream: + run_options.add_run_config_entry("disable_synchronize_execution_providers", "1") + + return super().infer(feed_dict, run_options) + + +class GpuBindingManager: + """A manager for I/O bindings that support multiple CUDA Graphs. + One cuda graph is reused for same input shape. Automatically add a new cuda graph for new input shape. + """ + + def __init__(self, ort_session: InferenceSession, device: torch.device, stream: int = 0, max_cuda_graphs: int = 1): + self.ort_session = ort_session + self.device = device + + # Binding supports cuda graphs. For a binding, it is able to disable cuda graph for a specific run. + self.graph_bindings = [] + + # Binding for not using cuda graph. + self.no_graph_binding = None + + self.stream = stream + + self.max_cuda_graphs = max_cuda_graphs + + def get_binding( + self, + shape_dict: ShapeDict, + use_cuda_graph: bool = False, + buffer_sharing: dict[str, str] | None = None, + ) -> GpuBinding: + for gpu_graph_binding in self.graph_bindings: + # Found a cuda graph that captured with the same shape + if gpu_graph_binding.shape_dict == shape_dict: + return gpu_graph_binding + + # Reached the maximum number of cuda graphs. Return a binding without cuda graph. + if len(self.graph_bindings) >= self.max_cuda_graphs or (not use_cuda_graph): + if self.no_graph_binding is None: + self.no_graph_binding = GpuBinding( + self.ort_session, self.device, shape_dict, stream=self.stream, buffer_sharing=buffer_sharing + ) + else: + self.no_graph_binding.allocate_buffers(shape_dict) + return self.no_graph_binding + + # This is a new input shape, create a new cuda graph + gpu_graph_binding = GpuBinding( + self.ort_session, + self.device, + shape_dict, + enable_gpu_graph=True, + gpu_graph_id=len(self.graph_bindings), + stream=self.stream, + buffer_sharing=buffer_sharing, + ) + self.graph_bindings.append(gpu_graph_binding) + return gpu_graph_binding diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/large_model_exporter.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/large_model_exporter.py new file mode 100644 index 0000000000000000000000000000000000000000..b9ae08cb439000c157b6937a9f72500178b2d6d9 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/large_model_exporter.py @@ -0,0 +1,396 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +# -------------------------------------------------------------------------- + +""" +Export LLM to onnx +""" + +import argparse +import inspect +import math +import os +import tempfile +from pathlib import Path + +import onnx +import torch +import transformers +from torch import nn + + +def disable_huggingface_init(): + """do not init model twice as it slow initialization""" + + torch.nn.init.kaiming_uniform_ = lambda x, *args, **kwargs: x + torch.nn.init.uniform_ = lambda x, *args, **kwargs: x + torch.nn.init.normal_ = lambda x, *args, **kwargs: x + torch.nn.init.constant_ = lambda x, *args, **kwargs: x + torch.nn.init.xavier_uniform_ = lambda x, *args, **kwargs: x + torch.nn.init.xavier_normal_ = lambda x, *args, **kwargs: x + torch.nn.init.kaiming_normal_ = lambda x, *args, **kwargs: x + torch.nn.init.orthogonal_ = lambda x, *args, **kwargs: x + + +def get_model_parameter_size(model: nn.Module): + """to calculate how much memory this model needs""" + param_size = 0 + param_sum = 0 + for param in model.parameters(): + param_size += param.nelement() * param.element_size() + param_sum += param.nelement() + buffer_size = 0 + buffer_sum = 0 + for buffer in model.buffers(): + buffer_size += buffer.nelement() * buffer.element_size() + buffer_sum += buffer.nelement() + all_size = (param_size + buffer_size) / 1024 / 1024 + return all_size + + +def initialize_model_and_sample_inputs(hf_model: str, cache_dir: str | None, tokenizer=None): + """ + get the pretrained torch model from hugginface, + and sample model-inputs + """ + + disable_huggingface_init() + + model = transformers.AutoModelForCausalLM.from_pretrained( # type: ignore + hf_model, torch_dtype=torch.float16, cache_dir=cache_dir, trust_remote_code=True + ) + if tokenizer is None: + tokenizer = hf_model + tokenizer = transformers.AutoTokenizer.from_pretrained(tokenizer) # type: ignore + + sample_inputs = tuple(tokenizer("Hello, my dog is cute", return_tensors="pt").values()) + return model, sample_inputs + + +def auto_pipeline_parallel(model: nn.Module, gpulist: list, sample_inputs: tuple): + """Make the model executable across multiple GPUs.""" + + def input_gpu_device_hook(mod, inputs, kwargs): + modifyed_inputs = [] + first_dev = None + for layer_input in inputs: + if type(layer_input) is not torch.Tensor: + modifyed_inputs.append(layer_input) + elif hasattr(mod, "weight"): + modifyed_inputs.append(layer_input.to(mod.weight.device)) + elif hasattr(mod, "parameters"): + device = next(mod.parameters(), layer_input).device + modifyed_inputs.append(layer_input.to(device)) + elif hasattr(next(mod.children(), None), "weight"): + modifyed_inputs.append(layer_input.to(next(mod.children()).weight.device)) + elif first_dev is not None and layer_input.device != first_dev: + modifyed_inputs.append(layer_input.to(first_dev)) + else: + modifyed_inputs.append(layer_input) + if first_dev is None: + first_dev = modifyed_inputs[0].device + for key, value in kwargs.items(): + if type(value) is torch.Tensor: + kwargs[key] = value.to(first_dev) + + return (tuple(modifyed_inputs), kwargs) + + def move_layer_to_device_rurc(mod, dev): + mod.to(dev) + for layer in mod.named_children(): + move_layer_to_device_rurc(layer[1], dev) + + model = model.half() + all_hooks = [] + all_hooks.append(model.register_forward_pre_hook(input_gpu_device_hook, with_kwargs=True)) + pre_fix = next(iter(model.named_children()))[0] + for top_name, top_module in model.named_children(): + for name, module in top_module.named_children(): + all_hooks.append(module.register_forward_pre_hook(input_gpu_device_hook, with_kwargs=True)) + if type(module) in [torch.nn.ModuleList]: + num_layers_on_each_gpu = math.floor(len(module) / len(gpulist)) + for idx, attn_layer in enumerate(module): + all_hooks.append(attn_layer.register_forward_pre_hook(input_gpu_device_hook, with_kwargs=True)) + + to_dev = gpulist[min(idx // num_layers_on_each_gpu, len(gpulist))] + attn_layer.to(to_dev) + move_layer_to_device_rurc(attn_layer, to_dev) + print(f"move {pre_fix}.{name}.{idx} to {to_dev}") + else: + module.to(gpulist[0]) + print(f"move {pre_fix}.{name} to {gpulist[0]}") + if len(list(top_module.named_children())) == 0: + top_module.to(gpulist[0]) + print(f"move {top_name} to {gpulist[0]}") + + with torch.no_grad(): + model(sample_inputs[0], attention_mask=sample_inputs[1]) + return model + + +def retrieve_onnx_inputs(model: nn.Module, sample_inputs: tuple, with_past: bool): + """ + auto retrieve onnx inputs from torch model as we can't enumlate all possibilities + for all models + """ + user_inputs = [] + + def hook_for_inputs(_, inputs, kwargs): + user_inputs.append((inputs, kwargs)) + return user_inputs[0] + + hook_handle = model.register_forward_pre_hook(hook_for_inputs, with_kwargs=True) + + forward_params = inspect.signature(model.forward).parameters + input_keys = list(forward_params.keys()) + default_values = [forward_params.get(key).default for key in input_keys] + out = model(sample_inputs[0], attention_mask=sample_inputs[1]) + hook_handle.remove() + user_inputs = user_inputs[0] + onnx_inputs = default_values + for idx, _val in enumerate(user_inputs[0]): + onnx_inputs[idx] = user_inputs[0][idx] + for key, value in user_inputs[1].items(): + idx = input_keys.index(key) + onnx_inputs[idx] = value + for idx, (key, value) in enumerate(zip(input_keys, onnx_inputs, strict=False)): + if type(value) is torch.Tensor: + value.to(model.device) + if "use_cache" in key: + onnx_inputs[idx] = with_past + out = model(sample_inputs[0], attention_mask=sample_inputs[1], use_cache=with_past) if with_past else out + + return input_keys, onnx_inputs, out.past_key_values + + +def move_to_appropriate_device(model: nn.Module, sample_inputs_tp: tuple) -> nn.Module: + """ + According to the model size, we will upload it to + CPU if has no GPU or enough GPU memory, + Single GPU if has only one GPU in local or model size is enough to fit one GPU + Multiple GPU if there is more than one gpu in local and model is too large + """ + total_mem_per_cpu = torch.cuda.get_device_properties(0).total_memory / 1024 / 1024 + + print(f"Model_Size = {get_model_parameter_size(model) / 1024} GB") + print(f"total_mem_per_cpu = {total_mem_per_cpu / 1024} GB") + if get_model_parameter_size(model) > total_mem_per_cpu * 0.45: + device_collection = [torch.device(i) for i in range(torch.cuda.device_count())] + if len(device_collection) > 1: + print( + f"{len(device_collection)} GPUs are used to export onnx, \ + Please set CUDA_VISIBLE_DEVICES to use specific GPU group" + ) + model = auto_pipeline_parallel(model, device_collection, sample_inputs_tp) + else: + print("!!!! convert model to float and export onnx using CPU") + model = model.cpu().float() + else: + print("Export model on a single GPU") + model = model.cuda().half() + return model + + +def adapt_inputs_to_device(sample_inputs: tuple, device: torch.device) -> tuple: + """move inputs to device""" + sample_inputs_ = [] + for sample_int in sample_inputs: + if isinstance(sample_int, torch.Tensor): + sample_inputs_.append(sample_int.to(device)) + else: + sample_inputs_.append(sample_int) + return tuple(sample_inputs_) + + +def fetch_onnx_inputs_outputs_name( + model: nn.Module, + onnx_inputs: list, + torch_input_names: tuple, + past_key_values: tuple, + with_past: bool, + input_with_past: bool, +): + """fetch onnx inputs and outputs name""" + num_of_past_key = 0 + kv_cache_axis = {0: "batch_size"} + # try get num_of_past_key and shape of past_key_value + if past_key_values is not None: + num_of_past_key = len(past_key_values) + seq_index = (torch.tensor(past_key_values[0][0].shape) == onnx_inputs[0].shape[-1]).nonzero().view(-1) + assert seq_index.numel() == 1 + kv_cache_axis = {0: "batch_size", seq_index.item(): "seq_len"} + + if not num_of_past_key: + num_of_past_key = model.config.num_hidden_layers + + # filter out constant inputs + onnx_inp_names = tuple( + [torch_input_names[i] for i in range(len(torch_input_names)) if isinstance(onnx_inputs[i], torch.Tensor)] + ) + assert "input_ids" in onnx_inp_names and "attention_mask" in onnx_inp_names, ( + "input_ids and attention_mask must be existed in inputs" + ) + onnx_out_names = ("logits",) + onnx_dynamic_axes = { + "input_ids": {0: "batch_size", 1: "seq_len"}, + "attention_mask": {0: "batch_size", 1: "seq_len"}, + } + # add dyanmic dimensions for the unkonw inputs + for idx, name in enumerate(onnx_inp_names): + if name not in onnx_dynamic_axes: + unknown_dims = {i: f"{idx}__unknown_dims__{i}" for i in range(onnx_inputs[idx].dim())} + onnx_dynamic_axes[name] = unknown_dims + if input_with_past: + for i in range(num_of_past_key): + onnx_inp_names += (f"past_key_values.{i}.key",) + onnx_inp_names += (f"past_key_values.{i}.value",) + + onnx_dynamic_axes[onnx_inp_names[-1]] = kv_cache_axis + onnx_dynamic_axes[onnx_inp_names[-2]] = kv_cache_axis + + if with_past or input_with_past: + for i in range(num_of_past_key): + onnx_out_names += (f"present.{i}.key",) + onnx_out_names += (f"present.{i}.value",) + + for idx, name in enumerate(torch_input_names): + if input_with_past: + if name == "past_key_values": + onnx_inputs[idx] = past_key_values + elif name == "attention_mask": + attn_mask = onnx_inputs[idx] + onnx_inputs[idx] = torch.cat( + (attn_mask, torch.ones((attn_mask.shape[0], 1), device=attn_mask.device, dtype=attn_mask.dtype)), + dim=1, + ) + elif name == "input_ids": + input_ids = onnx_inputs[idx] + onnx_inputs[idx] = input_ids[:, -1:] + + return onnx_inp_names, onnx_out_names, onnx_dynamic_axes + + +def do_export_internal(model: nn.Module, onnx_io_tuple: tuple, onnx_inputs: tuple, onnx_path: Path, opset: int): + """do export with torch.onnx.export""" + onnx_model_name = onnx_path.name + onnx_inp_names, onnx_out_names, onnx_dynamic_axes = onnx_io_tuple + # two step to export onnx + # 1. export onnx with lots of pieces of weights + # 2. save all weights to external data + with tempfile.TemporaryDirectory() as tmpdirname: + tmp_onnx = os.path.join(tmpdirname, "tmp.onnx") + + torch.onnx.export( + model=model, + args=tuple(onnx_inputs), + f=tmp_onnx, + verbose=False, + opset_version=opset, + input_names=onnx_inp_names, + output_names=onnx_out_names, + dynamic_axes=onnx_dynamic_axes, + dynamo=False, + ) + + onnx_path.unlink(missing_ok=True) + (onnx_path.parent / f"{onnx_model_name}_ext.data").unlink(missing_ok=True) + + onnx_model = onnx.load(str(tmp_onnx)) + onnx.save_model( + onnx_model, + str(onnx_path), + save_as_external_data=(len(os.listdir(tmpdirname)) > 1), + all_tensors_to_one_file=True, + location=f"{onnx_model_name}_ext.data", + size_threshold=1024, + convert_attribute=False, + ) + + +@torch.no_grad() +def export_onnx(hf_model: str, cache_dir: str | None, onnx_path_str: str, with_past: bool, opset: int): + """ + do export + model: torch model + onnx_path: where the onnx model saved to + sample_inputs_tp: inputs for torch model + """ + model, sample_inputs_tp = initialize_model_and_sample_inputs(hf_model, cache_dir) + + model = move_to_appropriate_device(model, sample_inputs_tp) + + sample_inputs = adapt_inputs_to_device(sample_inputs_tp, next(model.parameters()).device) + + # input_keys would be usesful if the model has some special inputs + input_keys, onnx_inputs, past_key_value = retrieve_onnx_inputs(model, sample_inputs, with_past) + + onnx_io_tuple = fetch_onnx_inputs_outputs_name(model, onnx_inputs, input_keys, past_key_value, with_past, False) + + onnx_model_name = "model.onnx" + onnx_path: Path = Path(onnx_path_str).absolute() + if onnx_path.suffix != ".onnx": + onnx_path = onnx_path / onnx_model_name + + do_export_internal(model, onnx_io_tuple, onnx_inputs, onnx_path, opset) + if not with_past: + return + + onnx_io_tuple = fetch_onnx_inputs_outputs_name(model, onnx_inputs, input_keys, past_key_value, with_past, True) + + onnx_model_name = "model_with_past.onnx" + onnx_path = onnx_path.parent / onnx_model_name + + do_export_internal(model, onnx_io_tuple, onnx_inputs, onnx_path, opset) + + +def parse_arguments(): + """arguments parsing.""" + parser = argparse.ArgumentParser() + + parser.add_argument( + "-m", + "--model", + required=True, + type=str, + default=["meta-llama/Llama-2-70b-hf"], + help="Pre-trained models in huggingface model hub", + ) + parser.add_argument( + "-s", + "--saved_path", + required=False, + type=str, + default="./onnx_models/", + help="where the onnx model will be saved", + ) + parser.add_argument( + "--cache_dir", + required=False, + type=str, + default=None, + help=("cache directly of huggingface, by setting this to avoid useless downloading if you have one"), + ) + parser.add_argument( + "--with_past", + action="store_true", + default=False, + help=("The tool will export onnx without past-key-value by default"), + ) + parser.add_argument( + "--opset", + required=False, + type=int, + default=17, + help=( + "the opset to save onnx model, \ + try to increase it if this opset doens't have new features you want" + ), + ) + return parser.parse_args() + + +if __name__ == "__main__": + args = parse_arguments() + + export_onnx(args.model, args.cache_dir, args.saved_path, args.with_past, args.opset) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/machine_info.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/machine_info.py new file mode 100644 index 0000000000000000000000000000000000000000..7fc77108769d65cc3f21ea94c36db953de621875 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/machine_info.py @@ -0,0 +1,230 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +# -------------------------------------------------------------------------- + +# It is used to dump machine information for Notebooks + +import argparse +import importlib.metadata +import json +import logging +import platform +from os import environ + +import cpuinfo +import psutil +from py3nvml.py3nvml import ( + NVMLError, + nvmlDeviceGetCount, + nvmlDeviceGetHandleByIndex, + nvmlDeviceGetMemoryInfo, + nvmlDeviceGetName, + nvmlInit, + nvmlShutdown, + nvmlSystemGetDriverVersion, +) + + +class MachineInfo: + """Class encapsulating Machine Info logic.""" + + def __init__(self, silent=False, logger=None): + self.silent = silent + + if logger is None: + logging.basicConfig( + format="%(asctime)s - %(name)s - %(levelname)s: %(message)s", + level=logging.INFO, + ) + self.logger = logging.getLogger(__name__) + else: + self.logger = logger + + self.machine_info = None + try: + self.machine_info = self.get_machine_info() + except Exception: + self.logger.exception("Exception in getting machine info.") + self.machine_info = None + + def get_machine_info(self): + """Get machine info in metric format""" + gpu_info = self.get_gpu_info_by_nvml() + cpu_info = cpuinfo.get_cpu_info() + + machine_info = { + "gpu": gpu_info, + "cpu": self.get_cpu_info(), + "memory": self.get_memory_info(), + "os": platform.platform(), + "python": self._try_get(cpu_info, ["python_version"]), + "packages": self.get_related_packages(), + "onnxruntime": self.get_onnxruntime_info(), + "pytorch": self.get_pytorch_info(), + "tensorflow": self.get_tensorflow_info(), + } + return machine_info + + def get_memory_info(self) -> dict: + """Get memory info""" + mem = psutil.virtual_memory() + return {"total": mem.total, "available": mem.available} + + def _try_get(self, cpu_info: dict, names: list) -> str: + for name in names: + if name in cpu_info: + value = cpu_info[name] + if isinstance(value, (list, tuple)): + return ",".join([str(i) for i in value]) + return value + return "" + + def get_cpu_info(self) -> dict: + """Get CPU info""" + cpu_info = cpuinfo.get_cpu_info() + + return { + "brand": self._try_get(cpu_info, ["brand", "brand_raw"]), + "cores": psutil.cpu_count(logical=False), + "logical_cores": psutil.cpu_count(logical=True), + "hz": self._try_get(cpu_info, ["hz_actual"]), + "l2_cache": self._try_get(cpu_info, ["l2_cache_size"]), + "flags": self._try_get(cpu_info, ["flags"]), + "processor": platform.uname().processor, + } + + def get_gpu_info_by_nvml(self) -> dict: + """Get GPU info using nvml""" + gpu_info_list = [] + driver_version = None + try: + nvmlInit() + driver_version = nvmlSystemGetDriverVersion() + deviceCount = nvmlDeviceGetCount() # noqa: N806 + for i in range(deviceCount): + handle = nvmlDeviceGetHandleByIndex(i) + info = nvmlDeviceGetMemoryInfo(handle) + gpu_info = {} + gpu_info["memory_total"] = info.total + gpu_info["memory_available"] = info.free + gpu_info["name"] = nvmlDeviceGetName(handle) + gpu_info_list.append(gpu_info) + nvmlShutdown() + except NVMLError as error: + if not self.silent: + self.logger.error("Error fetching GPU information using nvml: %s", error) + return None + + result = {"driver_version": driver_version, "devices": gpu_info_list} + + if "CUDA_VISIBLE_DEVICES" in environ: + result["cuda_visible"] = environ["CUDA_VISIBLE_DEVICES"] + return result + + def get_related_packages(self) -> list[str]: + related_packages = { + "onnxruntime-gpu", + "onnxruntime", + "onnx", + "transformers", + "protobuf", + "sympy", + "torch", + "tensorflow", + "flatbuffers", + "numpy", + "onnxconverter-common", + } + related_packages_list = {} + for dist in importlib.metadata.distributions(): + if dist.metadata["Name"].lower() in related_packages: + related_packages_list[dist.metadata["Name"].lower()] = dist.version + + return related_packages_list + + def get_onnxruntime_info(self) -> dict: + try: + import onnxruntime # noqa: PLC0415 + + return { + "version": onnxruntime.__version__, + "support_gpu": "CUDAExecutionProvider" in onnxruntime.get_available_providers(), + } + except ImportError as error: + if not self.silent: + self.logger.exception(error) + return None + except Exception as exception: + if not self.silent: + self.logger.exception(exception, False) + return None + + def get_pytorch_info(self) -> dict: + try: + import torch # noqa: PLC0415 + + return { + "version": torch.__version__, + "support_gpu": torch.cuda.is_available(), + "cuda": torch.version.cuda, + } + except ImportError as error: + if not self.silent: + self.logger.exception(error) + return None + except Exception as exception: + if not self.silent: + self.logger.exception(exception, False) + return None + + def get_tensorflow_info(self) -> dict: + try: + import tensorflow as tf # noqa: PLC0415 + + return { + "version": tf.version.VERSION, + "git_version": tf.version.GIT_VERSION, + "support_gpu": tf.test.is_built_with_cuda(), + } + except ImportError as error: + if not self.silent: + self.logger.exception(error) + return None + except ModuleNotFoundError as error: + if not self.silent: + self.logger.exception(error) + return None + + +def parse_arguments(): + parser = argparse.ArgumentParser() + + parser.add_argument( + "--silent", + required=False, + action="store_true", + help="Do not print error message", + ) + parser.set_defaults(silent=False) + + args = parser.parse_args() + return args + + +def get_machine_info(silent=True) -> str: + machine = MachineInfo(silent) + return json.dumps(machine.machine_info, indent=2) + + +def get_device_info(silent=True) -> str: + machine = MachineInfo(silent) + info = machine.machine_info + if info: + info = {key: value for key, value in info.items() if key in ["gpu", "cpu", "memory"]} + return json.dumps(info, indent=2) + + +if __name__ == "__main__": + args = parse_arguments() + print(get_machine_info(args.silent)) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/metrics.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..11f419059f73843455f9903addd9ddb2a77a2426 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/metrics.py @@ -0,0 +1,163 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +import datetime +import json + +import pandas as pd + + +class BaseObject: + def __init__(self): + self.customized = {} + + def to_dict(self): + default_values = self.__dict__.copy() + default_values.pop("customized", None) + default_values.update(self.customized) + + for k, v in default_values.items(): + if isinstance(v, BaseObject): + default_values[k] = v.to_dict() + + return {k: v for k, v in default_values.items() if v} + + +class ModelInfo(BaseObject): + def __init__( + self, + full_name: str | None = None, + is_huggingface: bool | None = False, + is_text_generation: bool | None = False, + short_name: str | None = None, + ): + super().__init__() + self.full_name = full_name + self.is_huggingface = is_huggingface + self.is_text_generation = is_text_generation + self.short_name = short_name + self.input_shape = [] + + +class BackendOptions(BaseObject): + def __init__( + self, + enable_profiling: bool | None = False, + execution_provider: str | None = None, + use_io_binding: bool | None = False, + ): + super().__init__() + self.enable_profiling = enable_profiling + self.execution_provider = execution_provider + self.use_io_binding = use_io_binding + + +class Config(BaseObject): + def __init__( + self, + backend: str | None = "onnxruntime", + batch_size: int | None = 1, + seq_length: int | None = 0, + precision: str | None = "fp32", + warmup_runs: int | None = 1, + measured_runs: int | None = 10, + ): + super().__init__() + self.backend = backend + self.batch_size = batch_size + self.seq_length = seq_length + self.precision = precision + self.warmup_runs = warmup_runs + self.measured_runs = measured_runs + self.model_info = ModelInfo() + self.backend_options = BackendOptions() + + +class Metadata(BaseObject): + def __init__( + self, + device: str | None = None, + package_name: str | None = None, + package_version: str | None = None, + platform: str | None = None, + python_version: str | None = None, + ): + super().__init__() + self.device = device + self.package_name = package_name + self.package_version = package_version + self.platform = platform + self.python_version = python_version + + +class Metrics(BaseObject): + def __init__( + self, + latency_ms_mean: float | None = 0.0, + throughput_qps: float | None = 0.0, + max_memory_usage_GB: float | None = 0.0, + ): + super().__init__() + self.latency_ms_mean = latency_ms_mean + self.throughput_qps = throughput_qps + self.max_memory_usage_GB = max_memory_usage_GB + + +class BenchmarkRecord: + def __init__( + self, + model_name: str, + precision: str, + backend: str, + device: str, + package_name: str, + package_version: str, + batch_size: int | None = 1, + warmup_runs: int | None = 1, + measured_runs: int | None = 10, + trigger_date: str | None = None, + ): + self.config = Config() + self.metrics = Metrics() + self.metadata = Metadata() + self.trigger_date = trigger_date or datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") + + self.config.model_info.full_name = model_name + self.config.precision = precision + self.config.backend = backend + self.config.batch_size = batch_size + self.config.warmup_runs = warmup_runs + self.config.measured_runs = measured_runs + self.metadata.device = device + self.metadata.package_name = package_name + self.metadata.package_version = package_version + + def to_dict(self) -> dict: + return { + "config": self.config.to_dict(), + "metadata": self.metadata.to_dict(), + "metrics": self.metrics.to_dict(), + "trigger_date": self.trigger_date, + } + + def to_json(self) -> str: + return json.dumps(self.to_dict(), default=str) + + @classmethod + def save_as_csv(cls, file_name: str, records: list) -> None: + if records is None or len(records) == 0: + return + rds = [record.to_dict() for record in records] + df = pd.json_normalize(rds) + df.to_csv(file_name, index=False) + + @classmethod + def save_as_json(cls, file_name: str, records: list) -> None: + if records is None or len(records) == 0: + return + rds = [record.to_dict() for record in records] + with open(file_name, "w") as f: + json.dump(rds, f, indent=4, default=str) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/bart/__init__.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/bart/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5ef71ce9e355e17ea1c2ca9fb648951d917734b5 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/bart/__init__.py @@ -0,0 +1,12 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +# -------------------------------------------------------------------------- +import os.path +import sys + +sys.path.append(os.path.dirname(__file__)) + +transformers_dir = os.path.normpath(os.path.join(os.path.dirname(__file__), "..", "..")) +if transformers_dir not in sys.path: + sys.path.append(transformers_dir) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/bart/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/bart/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..084253aed00fdb32968f7d1ec8111734e8a420e1 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/bart/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/bart/__pycache__/export.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/bart/__pycache__/export.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..174ff939a79d01726f6474f72746d1fbe38d01dd Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/bart/__pycache__/export.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/bart/export.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/bart/export.py new file mode 100644 index 0000000000000000000000000000000000000000..ee05793cab0ed2984a3a3c742e80c3961dd0de14 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/bart/export.py @@ -0,0 +1,98 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +import argparse +import logging +import os +import sys + +from utils import ( + chain_enc_dec_with_beamsearch, + export_summarization_edinit, + export_summarization_enc_dec_past, + onnx_inference, +) + +# GLOBAL ENVS +logging.basicConfig( + format="%(asctime)s | %(levelname)s | %(name)s | [%(filename)s:%(lineno)d] %(message)s", + datefmt="%Y-%m-%d %H:%M:%S", + level=os.environ.get("LOGLEVEL", "INFO").upper(), + stream=sys.stdout, +) +logger = logging.getLogger("generate") + + +def print_args(args): + for arg in vars(args): + logger.info(f"{arg}: {getattr(args, arg)}") + + +def user_command(): + parent_parser = argparse.ArgumentParser(add_help=False) + parent_parser.add_argument("--max_length", type=int, default=20, help="default to 20") + parent_parser.add_argument("--min_length", type=int, default=0, help="default to 0") + parent_parser.add_argument("-o", "--output", type=str, default="onnx_models", help="default name is onnx_models.") + parent_parser.add_argument("-i", "--input_text", type=str, default=None, help="input text") + parent_parser.add_argument("-s", "--spm_path", type=str, default=None, help="tokenizer model from sentencepice") + parent_parser.add_argument("-v", "--vocab_path", type=str, help="vocab dictionary") + parent_parser.add_argument("-b", "--num_beams", type=int, default=5, help="default to 5") + parent_parser.add_argument("--repetition_penalty", type=float, default=1.0, help="default to 1.0") + parent_parser.add_argument("--no_repeat_ngram_size", type=int, default=3, help="default to 3") + parent_parser.add_argument("--early_stopping", type=bool, default=False, help="default to False") + parent_parser.add_argument("--opset_version", type=int, default=14, help="minimum is 14") + + parent_parser.add_argument("--no_encoder", action="store_true") + parent_parser.add_argument("--no_decoder", action="store_true") + parent_parser.add_argument("--no_chain", action="store_true") + parent_parser.add_argument("--no_inference", action="store_true") + + required_args = parent_parser.add_argument_group("required input arguments") + required_args.add_argument( + "-m", + "--model_dir", + type=str, + required=True, + help="The directory contains input huggingface model. \ + An official model like facebook/bart-base is also acceptable.", + ) + + print_args(parent_parser.parse_args()) + return parent_parser.parse_args() + + +if __name__ == "__main__": + args = user_command() + if args.opset_version < 14: + raise ValueError(f"The minimum supported opset version is 14! The given one was {args.opset_version}.") + + isExist = os.path.exists(args.output) # noqa: N816 + if not isExist: + os.makedirs(args.output) + + # beam search op only supports CPU for now + args.device = "cpu" + logger.info("ENV: CPU ...") + + if not args.input_text: + args.input_text = ( + "PG&E stated it scheduled the blackouts in response to forecasts for high winds " + "amid dry conditions. The aim is to reduce the risk of wildfires. Nearly 800 thousand customers were " + "scheduled to be affected by the shutoffs which were expected to last through at least midday tomorrow." + ) + + if not args.no_encoder: + logger.info("========== EXPORTING ENCODER ==========") + export_summarization_edinit.export_encoder(args) + if not args.no_decoder: + logger.info("========== EXPORTING DECODER ==========") + export_summarization_enc_dec_past.export_decoder(args) + if not args.no_chain: + logger.info("========== CONVERTING MODELS ==========") + chain_enc_dec_with_beamsearch.convert_model(args) + if not args.no_inference: + logger.info("========== INFERENCING WITH ONNX MODEL ==========") + onnx_inference.run_inference(args) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/bert/__init__.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/bert/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5ef71ce9e355e17ea1c2ca9fb648951d917734b5 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/bert/__init__.py @@ -0,0 +1,12 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +# -------------------------------------------------------------------------- +import os.path +import sys + +sys.path.append(os.path.dirname(__file__)) + +transformers_dir = os.path.normpath(os.path.join(os.path.dirname(__file__), "..", "..")) +if transformers_dir not in sys.path: + sys.path.append(transformers_dir) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/bert/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/bert/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1568da95ece800044f3e86aec45f1b8f052cc68c Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/bert/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/bert/__pycache__/eval_squad.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/bert/__pycache__/eval_squad.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2516046ddd5ca372b57652cd07d203e63289886f Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/bert/__pycache__/eval_squad.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/bert/eval_squad.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/bert/eval_squad.py new file mode 100644 index 0000000000000000000000000000000000000000..1a3e1a311867788fbd3066107e02c90a77a46785 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/bert/eval_squad.py @@ -0,0 +1,329 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +# -------------------------------------------------------------------------- +# +# This script evaluates accuracy of ONNX models for question-answering task on SQuAD data set. +# Example to evaluate raw and optimized model for CUDA in Linux: +# pip3 install datasets evaluate optimum transformers onnxruntime-gpu +# +# python3 eval_squad.py -m bert-large-uncased-whole-word-masking-finetuned-squad -s 384 -b 1 --use_io_binding +# +# python3 -m onnxruntime.transformers.optimizer \ +# --input ./bert-large-uncased-whole-word-masking-finetuned-squad/model.onnx \ +# --output ./bert-large-uncased-whole-word-masking-finetuned-squad/optimized_model.onnx +# +# python3 eval_squad.py -m bert-large-uncased-whole-word-masking-finetuned-squad -s 384 -b 1 --use_io_binding \ +# --onnx ./bert-large-uncased-whole-word-masking-finetuned-squad/optimized_model.onnx +# +# Snippet of example output in A100: +# {'exact': 86.65089877010406, 'f1': 92.99433524952254, 'total': 10570, 'HasAns_exact': 86.65089877010406 +# 'total_time_in_seconds': 81.69239814393222, 'samples_per_second': 129.387804008115, +# 'latency_in_seconds': 0.007728703703304846, 'provider': 'CUDAExecutionProvider', +# 'pretrained_model_name': 'bert-large-uncased-whole-word-masking-finetuned-squad', +# 'batch_size': 1, 'sequence_length': 384, 'use_io_binding': True} +import argparse +import csv +import os +import time + +try: + from importlib.metadata import PackageNotFoundError, version +except ImportError: + from importlib_metadata import PackageNotFoundError, version + +from pathlib import Path +from typing import Any + +from datasets import load_dataset +from evaluate import evaluator +from optimum.onnxruntime import ORTModelForQuestionAnswering +from optimum.version import __version__ as optimum_version +from packaging import version as version_check +from transformers import AutoTokenizer, pipeline + +if version_check.parse(optimum_version) < version_check.parse("1.13.1"): + raise ImportError(f"Please install optimum>=1.13.1. Current version: {optimum_version}.") + +PRETRAINED_SQUAD_MODELS = [ + "bert-large-uncased-whole-word-masking-finetuned-squad", + "deepset/roberta-base-squad2", + "distilbert-base-cased-distilled-squad", +] + + +def get_package_version(package_name: str): + try: + return version(package_name) + except PackageNotFoundError: + return None + + +def load_onnx_model( + model_id: str, onnx_path: str | None = None, provider="CUDAExecutionProvider", use_io_binding: bool = False +): + """Load onnx model given pretrained model name and optional ONNX model path. If onnx_path is None, + the default onnx model from optimum will be used. + + Args: + model_id (str): pretrained model name or checkpoint path + onnx_path (Optional[str], optional): path of onnx model to evaluate. Defaults to None. + + Returns: + model: ORTModel for the onnx model + onnx_path: the path of onnx model + """ + + if onnx_path is None: + # Export onnx to a sub-directory named by the model id + model = ORTModelForQuestionAnswering.from_pretrained( + model_id, export=True, provider=provider, use_io_binding=use_io_binding + ) + save_onnx_dir = os.path.join(".", model_id) + model.save_pretrained(save_onnx_dir) + onnx_path = os.path.join(save_onnx_dir, "model.onnx") + print("Model is exported to onnx file:", onnx_path) + else: + model = ORTModelForQuestionAnswering.from_pretrained( + os.path.dirname(onnx_path), + file_name=Path(onnx_path).name, + provider=provider, + use_io_binding=use_io_binding, + # provider_options={"enable_skip_layer_norm_strict_mode": True}, + ) + + return model, onnx_path + + +def output_details(results: list[dict[str, Any]], csv_filename: str): + """Output a CSV file with detail of each test results. + + Args: + results (List[Dict[str, Any]]): list of JSON results. + csv_filename (str): path of output CSV file + """ + with open(csv_filename, mode="a", newline="", encoding="ascii") as csv_file: + column_names = [ + "pretrained_model_name", + "onnx_path", + "provider", + "disable_fused_attention", + "batch_size", + "sequence_length", + "use_io_binding", + "exact", + "f1", + "total", + "HasAns_exact", + "HasAns_f1", + "HasAns_total", + "best_exact", + "best_exact_thresh", + "best_f1", + "best_f1_thresh", + "total_time_in_seconds", + "samples_per_second", + "latency_in_seconds", + ] + + csv_writer = csv.DictWriter(csv_file, fieldnames=column_names) + csv_writer.writeheader() + for result in results: + csv_writer.writerow(result) + + csv_file.flush() + + print(f"Detail results are saved to csv file: {csv_filename}") + + +def output_summary(results: list[dict[str, Any]], csv_filename: str, metric_name: str): + """Output a CSV file with summary of a metric on combinations of batch_size and sequence_length. + + Args: + results (List[Dict[str, Any]]): list of JSON results. + csv_filename (str): path of output CSV file + metric_name (str): the metric to summarize + """ + with open(csv_filename, mode="a", newline="", encoding="ascii") as csv_file: + header_names = [ + "pretrained_model_name", + "onnx_path", + "provider", + "disable_fused_attention", + "use_io_binding", + ] + + model_list = list({result["onnx_path"] for result in results}) + model_list.sort() + + batch_sizes = list({result["batch_size"] for result in results}) + batch_sizes.sort() + + sequence_lengths = list({result["sequence_length"] for result in results}) + sequence_lengths.sort() + + key_names = [] + for sequence_length in sequence_lengths: + for batch_size in batch_sizes: + key_names.append(f"b{batch_size}_s{sequence_length}") + + csv_writer = csv.DictWriter(csv_file, fieldnames=header_names + key_names) + csv_writer.writeheader() + + for model in model_list: + row = {} + + # Metric value for given pair of batch_size and sequence_length. + # Assume that (onnx_path, batch_size and sequence_length) are unique so keep first occurrence only. + values = {} + values.update(dict.fromkeys(key_names, "")) + + for result in results: + if result["onnx_path"] == model and result[metric_name]: + headers = {k: v for k, v in result.items() if k in header_names} + if not row: + row.update(headers) + + batch_size = result["batch_size"] + sequence_length = result["sequence_length"] + key = f"b{batch_size}_s{sequence_length}" + + if key in key_names: + values[key] = result[metric_name] + + if row: + for key in key_names: + row[key] = values.get(key, "") + csv_writer.writerow(row) + + csv_file.flush() + + print(f"Summary results for {metric_name} are saved to csv file: {csv_filename}") + + +def main(): + args = parse_arguments() + print(args) + + for name in ["onnxruntime-gpu", "onnxruntime", "onnx", "torch", "transformers", "optimum", "datasets", "evaluate"]: + package_version = get_package_version(name) + if package_version: + print(f"{name} version", package_version) + + pretrained_model_name = args.model_name + if args.onnx and not os.path.exists(args.onnx): + raise RuntimeError(f"Onnx model path does not exist: {args.onnx}") + + disable_fused_attention = os.environ.get("ORT_DISABLE_FUSED_ATTENTION", "0") == "1" + + all_results = [] + tokenizer = AutoTokenizer.from_pretrained(pretrained_model_name) + for sequence_length in args.sequence_lengths: + tokenizer.model_max_length = sequence_length + tokenizer.doc_stride = min(sequence_length // 2, 128) + if args.onnx is None: + print("Exporting onnx model. It might take a few minutes...") + start_time = time.time() + ort_model, onnx_path = load_onnx_model(pretrained_model_name, args.onnx, args.provider, args.use_io_binding) + latency = time.time() - start_time + print(f"Onnx model exported or loaded in {latency:.1f} seconds") + + print(ort_model.config) + if sequence_length > ort_model.config.max_position_embeddings: + raise RuntimeError("sequence length should not be larger than {ort_model.config.max_position_embeddings}") + + qa_pipeline = pipeline( + "question-answering", model=ort_model, tokenizer=tokenizer, question_first=True, batch_size=args.batch_size + ) + + task_evaluator = evaluator("question-answering") + print("Loading dataset...") + start_time = time.time() + squad_dataset = load_dataset("squad", split=f"validation[:{args.total}]" if args.total > 0 else "validation") + latency = time.time() - start_time + print(f"Dataset loaded in {latency:.1f} seconds") + + print("Evaluating squad_v2 with ORT. It might take a few minutes...") + start_time = time.time() + result = task_evaluator.compute( + model_or_pipeline=qa_pipeline, + data=squad_dataset, + metric="squad_v2", + squad_v2_format=True, + ) + latency = time.time() - start_time + print(f"Evaluation done in {latency:.1f} seconds") + + result["provider"] = args.provider + result["disable_fused_attention"] = disable_fused_attention + result["pretrained_model_name"] = pretrained_model_name + result["onnx_path"] = onnx_path + result["batch_size"] = args.batch_size + result["sequence_length"] = sequence_length + result["use_io_binding"] = args.use_io_binding + print(result) + + all_results.append(result) + + output_details(all_results, "detail.csv") + + for metric_name in ["f1", "exact", "samples_per_second"]: + output_summary(all_results, f"{metric_name}.csv", metric_name) + + +def parse_arguments(argv=None): + parser = argparse.ArgumentParser() + + parser.add_argument( + "-m", + "--model_name", + required=False, + type=str, + default=PRETRAINED_SQUAD_MODELS[0], + help=f"Checkpoint directory or pre-trained model names in the list: {PRETRAINED_SQUAD_MODELS}", + ) + + parser.add_argument( + "-s", + "--sequence_lengths", + nargs="+", + type=int, + default=[384], + help="Sequence lengths for onnx model inputs. It could have multiple values.", + ) + + parser.add_argument( + "-b", + "--batch_size", + type=int, + default=1, + help="batch size for inference.", + ) + + parser.add_argument("-t", "--total", type=int, default=0, help="Total samples to test. 0 means all samples.") + + parser.add_argument( + "--onnx", + required=False, + type=str, + default=None, + help="Optional onnx model path. If not specified, optimum will be used to export onnx model for testing.", + ) + + parser.add_argument( + "--provider", + required=False, + default="CUDAExecutionProvider", + help="Select which Execution Provider to use for runs. Default is CUDAExecutionProvider.", + ) + + parser.add_argument("--use_io_binding", required=False, action="store_true", help="Use IO Binding for GPU.") + parser.set_defaults(use_io_binding=False) + + args = parser.parse_args(argv) + + return args + + +if __name__ == "__main__": + main() diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/gpt2/__init__.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/gpt2/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5ef71ce9e355e17ea1c2ca9fb648951d917734b5 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/gpt2/__init__.py @@ -0,0 +1,12 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +# -------------------------------------------------------------------------- +import os.path +import sys + +sys.path.append(os.path.dirname(__file__)) + +transformers_dir = os.path.normpath(os.path.join(os.path.dirname(__file__), "..", "..")) +if transformers_dir not in sys.path: + sys.path.append(transformers_dir) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/gpt2/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/gpt2/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4a0d8dab3ef00a166a0c75d28ed82a1915612a6d Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/gpt2/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/gpt2/__pycache__/benchmark_gpt2.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/gpt2/__pycache__/benchmark_gpt2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..030fea854476b99efc0fc0a484ee504923c171f7 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/gpt2/__pycache__/benchmark_gpt2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/gpt2/__pycache__/convert_to_onnx.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/gpt2/__pycache__/convert_to_onnx.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dbed9af09ceeac9280bc1ddd8576ba761944ca9b Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/gpt2/__pycache__/convert_to_onnx.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/gpt2/__pycache__/gpt2_helper.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/gpt2/__pycache__/gpt2_helper.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7896845ae4e08e6c2b637ffef9f5867511030fbc Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/gpt2/__pycache__/gpt2_helper.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/gpt2/__pycache__/gpt2_parity.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/gpt2/__pycache__/gpt2_parity.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..41eb3b5ff999c59c84d949f8ef0a24998eebf17b Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/gpt2/__pycache__/gpt2_parity.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/gpt2/__pycache__/gpt2_tester.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/gpt2/__pycache__/gpt2_tester.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c2c79c4b6f6e52709f36eeeb967eca5b7ea3a669 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/gpt2/__pycache__/gpt2_tester.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/gpt2/__pycache__/parity_check_helper.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/gpt2/__pycache__/parity_check_helper.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e7cdbe11fe26d757c55230bfadfc74c6d67761e3 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/gpt2/__pycache__/parity_check_helper.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/gpt2/benchmark_gpt2.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/gpt2/benchmark_gpt2.py new file mode 100644 index 0000000000000000000000000000000000000000..1140d8ce1a9efd5a7e52c569d6630ef1fb4b88d3 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/gpt2/benchmark_gpt2.py @@ -0,0 +1,413 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- +# This script benchmarks gpt2 model with past state. +# For gpt2 model without past state, use benchmark.py to measure performance. + +import argparse +import csv +import logging +import os +from datetime import datetime + +import psutil +import torch +from benchmark_helper import ( + Precision, + create_onnxruntime_session, + get_ort_environment_variables, + prepare_environment, + setup_logger, +) +from gpt2_helper import DEFAULT_TOLERANCE, MODEL_CLASSES, PRETRAINED_GPT2_MODELS, Gpt2Helper +from packaging import version +from quantize_helper import QuantizeHelper +from transformers import AutoConfig +from transformers import __version__ as transformers_version + +logger = logging.getLogger("") + + +def parse_arguments(argv=None): + parser = argparse.ArgumentParser() + + parser.add_argument( + "-m", + "--model_name_or_path", + required=True, + type=str, + help="Model path, or pretrained model name selected in the list: " + ", ".join(PRETRAINED_GPT2_MODELS), + ) + + parser.add_argument( + "--model_class", + required=False, + type=str, + default="GPT2LMHeadModel", + choices=list(MODEL_CLASSES.keys()), + help="Model type selected in the list: " + ", ".join(MODEL_CLASSES.keys()), + ) + + parser.add_argument( + "--cache_dir", + required=False, + type=str, + default=os.path.join(".", "cache_models"), + help="Directory to cache pre-trained models", + ) + + parser.add_argument( + "--onnx_dir", + required=False, + type=str, + default=os.path.join(".", "onnx_models"), + help="Directory to store onnx models", + ) + + parser.add_argument( + "--test_times", + required=False, + default=100, + type=int, + help="Number of repeat times to get average inference latency.", + ) + + parser.add_argument( + "-v", + "--validate_onnx", + required=False, + action="store_true", + help="Validate ONNX model", + ) + + parser.add_argument( + "-o", + "--optimize_onnx", + required=False, + action="store_true", + help="Use optimizer.py to optimize onnx model", + ) + parser.set_defaults(optimize_onnx=False) + + parser.add_argument( + "--stage", + type=int, + default=0, + required=False, + choices=[0, 1, 2], + help="Stage in generation: 1 (initial decoder), 2 (decoder), 0 (both). " + "1 - decode the first token when past_sequence_length is zero; " + "2 - decode the remaining tokens when past_sequence_length is not zero; " + "0 - one onnx model for both stages 1 and 2. " + "Note that we will optimize 1 and 2 differently for best performance.", + ) + + parser.add_argument("--use_gpu", required=False, action="store_true", help="use GPU for inference") + parser.set_defaults(use_gpu=False) + + parser.add_argument( + "-p", + "--precision", + type=Precision, + default=Precision.FLOAT32, + choices=list(Precision), + help="Precision of model to run. fp32 for full precision, fp16 for half precision, and int8 for quantization", + ) + + parser.add_argument("--torchscript", required=False, action="store_true", help="use Torchscript") + parser.set_defaults(torchscript=False) + + parser.add_argument("-b", "--batch_sizes", nargs="+", type=int, default=[1], help="batch size") + + parser.add_argument( + "--sequence_lengths", + nargs="+", + type=int, + default=[1], + help="sequence lengths (excluding past)", + ) + + parser.add_argument( + "-s", + "--past_sequence_lengths", + nargs="+", + type=int, + default=[8, 16, 32, 64, 128, 256], + help="past sequence lengths", + ) + + parser.add_argument( + "-r", + "--result_csv", + required=False, + default=None, + help="CSV file for saving summary results.", + ) + + parser.add_argument("--thread_num", required=False, type=int, default=-1, help="Threads to use") + + parser.add_argument("--include_copy_output_latency", required=False, action="store_true") + parser.set_defaults(include_copy_output_latency=False) + + parser.add_argument("--verbose", required=False, action="store_true") + parser.set_defaults(verbose=False) + + parser.add_argument("--output_torch_latency", required=False, action="store_true") + parser.set_defaults(output_torch_latency=False) + + parser.add_argument("--disable_io_binding", required=False, action="store_true") + parser.set_defaults(disable_io_binding=False) + + args = parser.parse_args(argv) + + return args + + +def main(args): + if version.parse(transformers_version) < version.parse( + "3.1.0" + ): # past_key_values name does not exist in 3.0.2 or older + raise RuntimeError("This tool requires transformers 3.1.0 or later.") + + logger.info(f"Arguments:{args}") + if args.precision == Precision.FLOAT16: + assert args.optimize_onnx and args.use_gpu, "fp16 requires --optimize_onnx --use_gpu" + + if args.precision == Precision.INT8: + assert not args.use_gpu, "quantization only supports CPU" + + if args.stage == 1: + assert args.past_sequence_lengths == [0], "past_sequence_lengths shall be 0 for stage==1 (init decoder)" + + torch.set_num_threads(psutil.cpu_count(logical=True) if args.thread_num <= 0 else args.thread_num) + print(torch.__config__.parallel_info()) + + cache_dir = args.cache_dir + output_dir = args.onnx_dir + prepare_environment(cache_dir, output_dir, args.use_gpu) + + model_class = MODEL_CLASSES[args.model_class][0] + gpt2helper = Gpt2Helper + config = AutoConfig.from_pretrained(args.model_name_or_path, torchscript=args.torchscript, cache_dir=cache_dir) + model = model_class.from_pretrained(args.model_name_or_path, config=config, cache_dir=cache_dir) + + # This script does not support float16 for PyTorch. + # if args.float16: + # model.half() + + device = torch.device("cuda:0" if args.use_gpu else "cpu") + model.to(device) + use_external_data_format = config.n_layer > 24 # TODO: find a way to check model size > 2GB + onnx_model_paths = gpt2helper.get_onnx_paths( + output_dir, + args.model_name_or_path, + args.model_class, + has_past=True, + new_folder=use_external_data_format, + ) + + onnx_model_path = onnx_model_paths["raw"] + use_padding = MODEL_CLASSES[args.model_class][2] + gpt2helper.export_onnx( + model, + device, + onnx_model_path, + args.verbose, + use_external_data_format, + has_position_ids=use_padding, + has_attention_mask=use_padding, + ) + + if args.optimize_onnx or args.precision != Precision.FLOAT32: + onnx_model_path = onnx_model_paths[str(args.precision) if args.precision != Precision.INT8 else "fp32"] + gpt2helper.optimize_onnx( + onnx_model_paths["raw"], + onnx_model_path, + args.precision == Precision.FLOAT16, + model.config.num_attention_heads, + model.config.hidden_size, + use_external_data_format, + auto_mixed_precision=True, + stage=args.stage, + ) + + if args.precision == Precision.INT8: + logger.info("quantizing model...") + QuantizeHelper.quantize_onnx_model(onnx_model_path, onnx_model_paths["int8"], use_external_data_format) + model = QuantizeHelper.quantize_torch_model(model) + logger.info("finished quantizing model") + onnx_model_path = onnx_model_paths["int8"] + + if args.torchscript: + model = gpt2helper.torchscript( + model, + config, + device, + has_position_ids=use_padding, + has_attention_mask=use_padding, + ) + + session = create_onnxruntime_session( + onnx_model_path, + args.use_gpu, + enable_all_optimization=False, + num_threads=args.thread_num, + verbose=args.verbose, + ) + if session is None: + return + + # Allocate output buffers for IO Binding + max_output_shapes = gpt2helper.get_output_shapes( + max(args.batch_sizes), + max(args.past_sequence_lengths), + max(args.sequence_lengths), + config, + args.model_class, + ) + output_buffers = gpt2helper.get_output_buffers(max_output_shapes, device, args.precision == Precision.FLOAT16) + + csv_filename = args.result_csv or "benchmark_result_{}.csv".format(datetime.now().strftime("%Y%m%d-%H%M%S")) + with open(csv_filename, mode="a", newline="") as csv_file: + column_names = [ + "model_name", + "model_class", + "stage", + "environment_variables", + "gpu", + "precision", + "optimizer", + "torchscript", + "batch_size", + "sequence_length", + "past_sequence_length", + "disable_io_binding", + "torch_latency", + "onnxruntime_latency", + ] + csv_writer = csv.DictWriter(csv_file, fieldnames=column_names) + csv_writer.writeheader() + + for batch_size in args.batch_sizes: + for sequence_length in args.sequence_lengths: + for past_sequence_length in args.past_sequence_lengths: + assert batch_size > 0 and sequence_length > 0 and past_sequence_length >= 0 + logger.debug( + "Running test for batch_size=%d sequence_length=%d past_sequence_length=%d ...", + batch_size, + sequence_length, + past_sequence_length, + ) + + dummy_inputs = gpt2helper.get_dummy_inputs( + batch_size, + past_sequence_length, + sequence_length, + config.num_attention_heads, + config.hidden_size, + config.n_layer, + config.vocab_size, + device, + float16=(args.precision == Precision.FLOAT16), + has_position_ids=use_padding, + has_attention_mask=use_padding, + ) + output_shapes = gpt2helper.get_output_shapes( + batch_size, + past_sequence_length, + sequence_length, + config, + args.model_class, + ) + + try: + if args.validate_onnx or args.output_torch_latency: + outputs, torch_latency = gpt2helper.pytorch_inference(model, dummy_inputs, args.test_times) + + # Dump Torch output shape + for i, value in enumerate(outputs): + if isinstance(value, tuple): + logger.debug( + f"torch output {i} is tuple of size {len(value)}, shape {value[0].shape}" + ) + else: + logger.debug(f"torch output {i} shape {value.shape}") + else: + outputs = None + torch_latency = None + + if args.disable_io_binding: + ort_outputs, ort_latency = gpt2helper.onnxruntime_inference( + session, dummy_inputs, args.test_times + ) + else: + ort_outputs, ort_latency = gpt2helper.onnxruntime_inference_with_binded_io( + session, + dummy_inputs, + output_buffers, + output_shapes, + args.test_times, + return_numpy=False, + include_copy_output_latency=args.include_copy_output_latency, + ) + + if args.validate_onnx: + copy_outputs = ort_outputs + if not args.disable_io_binding: + # Results of IO binding might be in GPU. Copy outputs to CPU for comparison. + copy_outputs = [] + for output in ort_outputs: + copy_outputs.append(output.cpu().numpy()) + + if gpt2helper.compare_outputs( + outputs, + copy_outputs, + model_class=args.model_class, + rtol=DEFAULT_TOLERANCE[args.precision], + atol=DEFAULT_TOLERANCE[args.precision], + ): + logger.info( + f"Pytorch and ONNX Runtime outputs are all close (tolerance={DEFAULT_TOLERANCE[args.precision]})." + ) + + logger.info( + "batch_size=%d, sequence_length=%d, past_sequence_length=%d, onnxruntime_latency=%.2f %s %s", + batch_size, + sequence_length, + past_sequence_length, + ort_latency, + "(disable_io_binding)" if args.disable_io_binding else "", + ", torch_latency={torch_latency}" if torch_latency else "", + ) + + row = { + "model_name": args.model_name_or_path, + "model_class": args.model_class, + "stage": args.stage, + "environment_variables": get_ort_environment_variables(), + "gpu": args.use_gpu, + "precision": args.precision, + "optimizer": args.optimize_onnx, + "torchscript": args.torchscript, + "batch_size": batch_size, + "sequence_length": sequence_length, + "past_sequence_length": past_sequence_length, + "disable_io_binding": args.disable_io_binding, + "torch_latency": f"{torch_latency:.2f}" if torch_latency else "None", + "onnxruntime_latency": f"{ort_latency:.2f}", + } + csv_writer.writerow(row) + except Exception: + logger.error("Exception", exc_info=True) # noqa: G201 + return None + + logger.info(f"Results are saved to file {csv_filename}") + return csv_filename + + +if __name__ == "__main__": + args = parse_arguments() + setup_logger(args.verbose) + main(args) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/gpt2/convert_to_onnx.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/gpt2/convert_to_onnx.py new file mode 100644 index 0000000000000000000000000000000000000000..7318c8c6d078bd9ad8626dbf089b0897248daf32 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/gpt2/convert_to_onnx.py @@ -0,0 +1,566 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- +""" +This converts GPT2 model to onnx. Examples: +(1) Convert pretrained model 'gpt2' to ONNX + python convert_to_onnx.py -m gpt2 --output gpt2.onnx +(2) Convert pretrained model 'distilgpt2' to ONNX, and use optimizer to get float16 model. + python convert_to_onnx.py -m distilgpt2 --output distilgpt2_fp16.onnx -o -p fp16 +(3) Convert a model check point to ONNX, and run optimization and int8 quantization + python convert_to_onnx.py -m ./my_model_checkpoint/ --output my_model_int8.onnx -o -p int8 + +""" + +import argparse +import csv +import json +import logging +import os +import shutil +import sys +import warnings +from pathlib import Path + +import numpy +import torch +from benchmark_helper import ( + Precision, + create_onnxruntime_session, + get_ort_environment_variables, + prepare_environment, + setup_logger, +) +from gpt2_helper import DEFAULT_TOLERANCE, MODEL_CLASSES, PRETRAINED_GPT2_MODELS, Gpt2Helper +from gpt2_tester import Gpt2Tester +from packaging import version +from quantize_helper import QuantizeHelper +from transformers import AutoConfig +from transformers import __version__ as transformers_version + +from onnxruntime import __version__ as ort_version + +logger = logging.getLogger("") + + +def parse_arguments(argv=None): + parser = argparse.ArgumentParser() + + parser.add_argument( + "-m", + "--model_name_or_path", + required=True, + type=str, + help="Model path, or pretrained model name in the list: " + ", ".join(PRETRAINED_GPT2_MODELS), + ) + + parser.add_argument( + "--model_class", + required=False, + type=str, + default="GPT2LMHeadModel", + choices=list(MODEL_CLASSES.keys()), + help="Model type selected in the list: " + ", ".join(MODEL_CLASSES.keys()), + ) + + parser.add_argument( + "--cache_dir", + required=False, + type=str, + default=os.path.join(".", "cache_models"), + help="Directory to cache pre-trained models", + ) + + parser.add_argument( + "--output", + required=False, + type=str, + default=os.path.join(".", "onnx_models"), + help="Output directory, or model path ends with .onnx", + ) + + parser.add_argument( + "-o", + "--optimize_onnx", + required=False, + action="store_true", + help="Use optimizer.py to optimize onnx model", + ) + parser.set_defaults(optimize_onnx=False) + + parser.add_argument("--use_gpu", required=False, action="store_true", help="use GPU for inference") + parser.set_defaults(use_gpu=False) + + parser.add_argument( + "--provider", + required=False, + default=None, + choices=["dml", "migraphx", "cuda", "tensorrt"], + help="use dml, cuda, tensorrt or migraphx for respective backend", + ) + + parser.add_argument( + "--tolerance", + required=False, + type=float, + default=0, + help="the absolute and relative tolerance for parity verification", + ) + + parser.add_argument( + "--input_test_file", + "-i", + required=False, + type=str, + default="", + help="Path to the file with inputs to test with", + ) + + parser.add_argument( + "-p", + "--precision", + required=False, + type=Precision, + default=Precision.FLOAT32, + choices=list(Precision), + help="Precision of model to run. fp32 for full precision, fp16 for half or mixed precision, and int8 for quantization", + ) + + parser.add_argument( + "-t", + "--test_cases", + required=False, + type=int, + default=1000, + help="Number of test cases per run for parity", + ) + parser.add_argument( + "-r", + "--test_runs", + required=False, + type=int, + default=10, + help="Number of runs for parity. It is used for significance test.", + ) + + parser.add_argument("--verbose", required=False, action="store_true") + parser.set_defaults(verbose=False) + + parser.add_argument("-e", "--use_external_data_format", required=False, action="store_true") + parser.set_defaults(use_external_data_format=False) + + parser.add_argument("--overwrite", required=False, action="store_true") + parser.set_defaults(overwrite=False) + + parser.add_argument( + "--use_int64_inputs", + required=False, + action="store_true", + help="Use int32 instead of int64 for input_ids, position_ids and attention_mask.", + ) + parser.set_defaults(use_int64_inputs=False) + + parser.add_argument( + "-s", + "--stage", + type=int, + default=0, + required=False, + choices=[0, 1, 2], + help="Stage in generation: 1 (initial decoder), 2 (decoder), 0 (both). " + "1 - decode the first token when past_sequence_length is zero; " + "2 - decode the remaining tokens when past_sequence_length is not zero; " + "0 - one onnx model for both stages 1 and 2. " + "Note that we will optimize 1 and 2 differently for best performance.", + ) + + fp16_option_group = parser.add_argument_group( + 'float to float16 conversion parameters that works when "--precision fp16" is specified' + ) + + fp16_option_group.add_argument( + "-a", + "--auto_mixed_precision", + required=False, + action="store_true", + help="Convert to mixed precision automatically. Other float16 conversion parameters will be ignored.", + ) + fp16_option_group.set_defaults(auto_mixed_precision=False) + + fp16_option_group.add_argument( + "--keep_io_types", + required=False, + action="store_true", + help="Use float32 for past inputs, present and logits outputs.", + ) + fp16_option_group.set_defaults(keep_io_types=False) + + fp16_option_group.add_argument( + "--io_block_list", + nargs="+", + default=[], + help="List of inputs or outputs in float32 instead of float16", + ) + + fp16_option_group.add_argument( + "--op_block_list", + nargs="+", + default=[], + help="List of operators (like Add LayerNormalization SkipLayerNormalization EmbedLayerNormalization FastGelu) " + "to compute in float32 instead of float16.", + ) + + fp16_option_group.add_argument( + "--node_block_list", + nargs="+", + default=[], + help="List of node names to compute in float32 instead of float16.", + ) + + fp16_option_group.add_argument( + "--force_fp16_initializers", + required=False, + action="store_true", + help="Convert all float initializers to float16.", + ) + fp16_option_group.set_defaults(force_fp16_initializers=False) + + args = parser.parse_args(argv) + + return args + + +def get_onnx_model_size(onnx_path: str, use_external_data_format: bool): + if not use_external_data_format: + return os.path.getsize(onnx_path) + else: + return sum([f.stat().st_size for f in Path(onnx_path).parent.rglob("*")]) + + +def get_latency_name(batch_size, sequence_length, past_sequence_length): + return f"average_latency(batch_size={batch_size},sequence_length={sequence_length},past_sequence_length={past_sequence_length})" + + +def main(argv=None, experiment_name: str = "", run_id: str = "0", csv_filename: str = "gpt2_parity_results.csv"): + warnings.warn( + "This example is deprecated. Use the Olive recipe instead: " + "https://github.com/microsoft/olive-recipes/tree/main", + DeprecationWarning, + stacklevel=2, + ) + + result = {} + if version.parse(transformers_version) < version.parse( + "3.1.0" + ): # past_key_values name does not exist in 3.0.2 or older + raise RuntimeError("This tool requires transformers 3.1.0 or later.") + + args = parse_arguments(argv) + setup_logger(args.verbose) + + if not experiment_name: + experiment_name = " ".join(argv if argv else sys.argv[1:]) + + if args.tolerance == 0: + args.tolerance = DEFAULT_TOLERANCE[args.precision] + + logger.info(f"Arguments:{args}") + + cache_dir = args.cache_dir + output_dir = args.output if not args.output.endswith(".onnx") else os.path.dirname(args.output) + prepare_environment(cache_dir, output_dir, args.use_gpu) + + if args.precision != Precision.FLOAT32: + assert args.optimize_onnx, "fp16/int8 requires --optimize_onnx" + + if args.precision == Precision.FLOAT16: + assert args.use_gpu, "fp16 requires --use_gpu" + + if args.precision == Precision.INT8: + assert not args.use_gpu, "quantization only supports CPU" + + model_class = MODEL_CLASSES[args.model_class][0] + use_padding = MODEL_CLASSES[args.model_class][2] + + gpt2helper = Gpt2Helper + config = AutoConfig.from_pretrained(args.model_name_or_path, cache_dir=cache_dir) + model = model_class.from_pretrained(args.model_name_or_path, config=config, cache_dir=cache_dir) + + device = torch.device("cuda:0" if args.use_gpu else "cpu") + model.eval().to(device) + + if (not args.use_external_data_format) and (config.n_layer > 24): + logger.info("Try --use_external_data_format when model size > 2GB") + + onnx_model_paths = gpt2helper.get_onnx_paths( + output_dir, + args.model_name_or_path, + args.model_class, + new_folder=(args.precision == Precision.INT8), + remove_existing=["fp32", "fp16", "int8"], + ) # Do not remove raw model to save time in parity test + + raw_onnx_model = onnx_model_paths["raw"] + + int_data_type = torch.int64 if args.use_int64_inputs else torch.int32 + + if os.path.exists(raw_onnx_model) and not args.overwrite: + logger.warning(f"Skip exporting ONNX model since it existed: {raw_onnx_model}") + else: + logger.info(f"Exporting ONNX model to {raw_onnx_model}") + gpt2helper.export_onnx( + model, + device, + raw_onnx_model, + args.verbose, + args.use_external_data_format, + has_position_ids=use_padding, + has_attention_mask=use_padding, + input_ids_dtype=int_data_type, + position_ids_dtype=int_data_type, + attention_mask_dtype=int_data_type, + ) + + fp16_params = {"keep_io_types": args.keep_io_types} + if args.io_block_list: + fp16_params["keep_io_types"] = args.io_block_list + if args.node_block_list: + fp16_params["node_block_list"] = args.node_block_list + if args.op_block_list: + fp16_params["op_block_list"] = args.op_block_list + if args.force_fp16_initializers: + fp16_params["force_fp16_initializers"] = args.force_fp16_initializers + + is_io_float16 = args.precision == Precision.FLOAT16 and not args.keep_io_types + + optimized_ops = "" + all_ops = "" + if args.optimize_onnx or args.precision != Precision.FLOAT32: + output_path = onnx_model_paths[str(args.precision) if args.precision != Precision.INT8 else "fp32"] + + logger.info(f"Optimizing model to {output_path}") + m = gpt2helper.optimize_onnx( + raw_onnx_model, + output_path, + args.precision == Precision.FLOAT16, + model.config.num_attention_heads, + model.config.hidden_size, + args.use_external_data_format, + auto_mixed_precision=args.auto_mixed_precision, + stage=args.stage, + **fp16_params, + ) + + nodes = m.nodes() + op_list = {node.op_type for node in nodes} + all_ops = ",".join(op_list) + + # print optimized operators + optimized_op_counter = m.get_fused_operator_statistics() + if optimized_op_counter: + optimized_ops = ",".join([key for key in optimized_op_counter if optimized_op_counter[key] > 0]) + else: + output_path = raw_onnx_model + + if args.precision == Precision.INT8: + logger.info("quantizing model...") + QuantizeHelper.quantize_onnx_model(output_path, onnx_model_paths["int8"], args.use_external_data_format) + model = QuantizeHelper.quantize_torch_model(model) + logger.info("finished quantizing model") + output_path = onnx_model_paths["int8"] + + if args.output.endswith(".onnx") and output_path != args.output and not args.use_external_data_format: + shutil.move(output_path, args.output) + output_path = args.output + + logger.info(f"Output path: {output_path}") + model_size_in_MB = int(get_onnx_model_size(output_path, args.use_external_data_format) / 1024 / 1024) # noqa: N806 + + provider = args.provider + session = create_onnxruntime_session( + output_path, args.use_gpu, provider, enable_all_optimization=True, verbose=args.verbose + ) + if args.model_class == "GPT2LMHeadModel" and session is not None: + parity_result = gpt2helper.test_parity( + session, + model, + device, + is_io_float16, + rtol=args.tolerance, + atol=args.tolerance, + model_class=args.model_class, + has_position_ids=use_padding, + has_attention_mask=use_padding, + input_ids_dtype=int_data_type, + position_ids_dtype=int_data_type, + attention_mask_dtype=int_data_type, + test_cases_per_run=args.test_cases, + total_runs=args.test_runs, + stage=args.stage, + verbose=args.verbose, + ) + + # An example configuration for testing performance + batch_size = 8 + sequence_length = 32 if args.stage == 1 else 1 + past_sequence_length = 0 if args.stage == 1 else 32 + + latency = gpt2helper.test_performance( + session, + model, + device, + is_io_float16, + total_runs=100, + use_io_binding=True, + model_class=args.model_class, + has_position_ids=use_padding, + has_attention_mask=use_padding, + input_ids_dtype=int_data_type, + position_ids_dtype=int_data_type, + attention_mask_dtype=int_data_type, + batch_size=batch_size, + sequence_length=sequence_length, + past_sequence_length=past_sequence_length, + ) + + if args.precision == Precision.FLOAT16: + logger.info(f"fp16 conversion parameters:{fp16_params}") + + # Write results to file + latency_name = get_latency_name(batch_size, sequence_length, past_sequence_length) + csv_file_existed = os.path.exists(csv_filename) + with open(csv_filename, mode="a", newline="") as csv_file: + column_names = [ + "experiment", + "run_id", + "model_name", + "model_class", + "stage", + "gpu", + "precision", + "optimizer", + "test_cases", + "runs", + "keep_io_types", + "io_block_list", + "op_block_list", + "node_block_list", + "force_fp16_initializers", + "auto_mixed_precision", + "optimized_operators", + "operators", + "environment_variables", + "onnxruntime", + latency_name, + "top1_match_rate", + "onnx_size_in_MB", + "diff_50_percentile", + "diff_90_percentile", + "diff_95_percentile", + "diff_99_percentile", + "diff_pass_rate", + "nan_rate", + "top1_match_rate_per_run", + ] + csv_writer = csv.DictWriter(csv_file, fieldnames=column_names) + if not csv_file_existed: + csv_writer.writeheader() + row = { + "experiment": experiment_name, + "run_id": run_id, + "model_name": args.model_name_or_path, + "model_class": args.model_class, + "stage": args.stage, + "gpu": args.use_gpu, + "precision": args.precision, + "optimizer": args.optimize_onnx, + "test_cases": args.test_cases, + "runs": args.test_runs, + "keep_io_types": args.keep_io_types, + "io_block_list": args.io_block_list, + "op_block_list": args.op_block_list, + "node_block_list": args.node_block_list, + "force_fp16_initializers": args.force_fp16_initializers, + "auto_mixed_precision": args.auto_mixed_precision, + "optimized_operators": optimized_ops, + "operators": all_ops, + "environment_variables": get_ort_environment_variables(), + "onnxruntime": ort_version, + latency_name: f"{latency:.2f}", + "diff_50_percentile": parity_result["max_diff_percentile_50"], + "diff_90_percentile": parity_result["max_diff_percentile_90"], + "diff_95_percentile": parity_result["max_diff_percentile_95"], + "diff_99_percentile": parity_result["max_diff_percentile_99"], + "diff_pass_rate": parity_result["diff_pass_rate"], + "nan_rate": parity_result["nan_rate"], + "top1_match_rate": parity_result["top1_match_rate"], + "top1_match_rate_per_run": parity_result["top1_match_rate_per_run"], + "onnx_size_in_MB": f"{model_size_in_MB}", + } + logger.info(f"result: {row}") + result.update(row) + csv_writer.writerow(row) + + if args.input_test_file: + test_inputs = [] + # Each line of test file is a JSON string like: + # {"input_ids": [[14698, 257, 1310, 13688, 319, 326]]} + with open(args.input_test_file) as read_f: + for _, line in enumerate(read_f): + line = line.rstrip() # noqa: PLW2901 + data = json.loads(line) + input_ids = torch.from_numpy(numpy.asarray(data["input_ids"], dtype=numpy.int64)).to(device) + + if use_padding: + if "attention_mask" in data: + numpy_float = numpy.float16 if is_io_float16 else numpy.float32 + attention_mask = torch.from_numpy(numpy.asarray(data["attention_mask"], dtype=numpy_float)).to( + device + ) + else: + padding = -1 + attention_mask = (input_ids != padding).type(torch.float16 if is_io_float16 else torch.float32) + input_ids.masked_fill_(input_ids == padding, 0) + + if "position_ids" in data: + position_ids = torch.from_numpy(numpy.asarray(data["position_ids"], dtype=numpy.int64)).to( + device + ) + else: + position_ids = attention_mask.long().cumsum(-1) - 1 + position_ids.masked_fill_(position_ids < 0, 0) + + inputs = { + "input_ids": input_ids.to(int_data_type), + "position_ids": position_ids.to(int_data_type), + "attention_mask": attention_mask.to(int_data_type), + } + else: + inputs = {"input_ids": input_ids.to(int_data_type)} + + test_inputs.append(inputs) + + Gpt2Tester.test_generation( + session, + model, + device, + test_inputs, + precision=args.precision, + model_class=args.model_class, + top_k=20, + top_k_no_order=True, + max_steps=24, + max_inputs=0, + verbose=args.verbose, + save_test_data=3, + save_test_data_dir=Path(output_path).parent, + ) + + logger.info(f"Done. Output model: {output_path}") + return result + + +if __name__ == "__main__": + main() diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/gpt2/gpt2_helper.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/gpt2/gpt2_helper.py new file mode 100644 index 0000000000000000000000000000000000000000..536f1c2171f18254faebe3af02388907477c4415 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/gpt2/gpt2_helper.py @@ -0,0 +1,1031 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- +# This script helps onnx conversion and validation for GPT2 model with past state. +import logging +import os +import pickle +import random +import shutil +import tempfile +import time +from pathlib import Path + +import numpy +import onnx +import torch +from benchmark_helper import Precision +from float16 import float_to_float16_max_diff +from fusion_options import FusionOptions +from io_binding_helper import IOBindingHelper +from onnx_model import OnnxModel +from optimizer import optimize_model +from torch_onnx_export_helper import torch_onnx_export +from transformers import GPT2Config, GPT2LMHeadModel, GPT2Model, TFGPT2Model + +logger = logging.getLogger(__name__) + +PRETRAINED_GPT2_MODELS = ["distilgpt2", "gpt2", "gpt2-medium", "gpt2-large", "gpt2-xl"] + +DEFAULT_TOLERANCE = { + Precision.FLOAT32: 0.0005, + Precision.FLOAT16: 0.2, + Precision.INT8: 3.0, +} + + +class GPT2ModelNoPastState(GPT2Model): + """Here we wrap a class to disable past state output.""" + + def __init__(self, config): + super().__init__(config) + + def forward(self, input_ids): + return super().forward(input_ids, use_cache=False, return_dict=False) + + +class TFGPT2ModelNoPastState(TFGPT2Model): + """Here we wrap a class to disable past state output.""" + + def __init__(self, config): + config.use_cache = False + super().__init__(config) + + def forward(self, input_ids): + return super().call(input_ids, use_cache=False) + + +class MyGPT2Model(GPT2Model): + """Here we wrap a class for Onnx model conversion for GPT2Model with past state.""" + + def __init__(self, config): + super().__init__(config) + + @staticmethod + def post_process(result, num_layer): + if isinstance(result[1][0], (tuple, list)): + assert len(result[1]) == num_layer and len(result[1][0]) == 2 + # assert len(result[1][0][0].shape) == 4 and result[1][0][0].shape == result[1][0][1].shape + present = [] + for i in range(num_layer): + # Since transformers v4.*, past key and values are separated outputs. + # Here we concate them into one tensor to be compatible with Attention operator. + present.append( + torch.cat( + (result[1][i][0].unsqueeze(0), result[1][i][1].unsqueeze(0)), + dim=0, + ) + ) + return (result[0], tuple(present)) + + return result + + def forward(self, input_ids, position_ids, attention_mask, *past): + result = super().forward( + input_ids, + position_ids=position_ids, + attention_mask=attention_mask, + past_key_values=past, + return_dict=False, + ) + return MyGPT2Model.post_process(result, self.config.n_layer) + + +class MyGPT2LMHeadModel(GPT2LMHeadModel): + """Here we wrap a class for Onnx model conversion for GPT2LMHeadModel with past state.""" + + def __init__(self, config): + super().__init__(config) + + def forward(self, input_ids, position_ids, attention_mask, *past): + result = super().forward( + input_ids, + position_ids=position_ids, + attention_mask=attention_mask, + past_key_values=past, + return_dict=False, + ) + + return MyGPT2Model.post_process(result, self.config.n_layer) + + +class MyGPT2LMHeadModel_NoPadding(GPT2LMHeadModel): # noqa: N801 + """Here we wrap a class for Onnx model conversion for GPT2LMHeadModel with past state and no padding. + When you always use batch_size=1 in inference, there is no padding in inputs. In such case, position_ids + and attention_mask need no be in inputs. + """ + + def __init__(self, config): + super().__init__(config) + + def forward(self, input_ids, *past): + result = super().forward(input_ids, past_key_values=past, return_dict=False) + + return MyGPT2Model.post_process(result, self.config.n_layer) + + +# Maps model class name to a tuple of model class, name of first output and use padding or not +MODEL_CLASSES = { + "GPT2LMHeadModel": (MyGPT2LMHeadModel, "logits", True), + "GPT2LMHeadModel_NoPadding": (MyGPT2LMHeadModel_NoPadding, "logits", False), + "GPT2Model": (MyGPT2Model, "last_state", True), +} + + +class Gpt2Inputs: + def __init__(self, input_ids, position_ids, attention_mask, past): + self.input_ids: torch.LongTensor = input_ids + self.position_ids: torch.LongTensor = position_ids + self.attention_mask: torch.LongTensor | torch.FloatTensor | torch.HalfTensor = attention_mask + self.past: list[torch.FloatTensor] | list[torch.HalfTensor] = past + + def to_list(self) -> list: + input_list = [v for v in [self.input_ids, self.position_ids, self.attention_mask] if v is not None] + if self.past: + input_list.extend(self.past) + + return input_list + + def to_tuple(self) -> tuple: + return tuple(v for v in [self.input_ids, self.position_ids, self.attention_mask, self.past] if v is not None) + + def to_fp32(self): + # For attention mask, only convert fp16 to fp32, and keep the original type if it is integer. + attention_mask = None + if self.attention_mask is not None: + attention_mask = ( + self.attention_mask.to(dtype=torch.float32) + if (self.attention_mask.dtype == torch.float16) + else self.attention_mask + ) + + past = [p.to(dtype=torch.float32) for p in self.past] + return Gpt2Inputs(self.input_ids, self.position_ids, attention_mask, past) + + +class Gpt2Helper: + """A helper class for Gpt2 model conversion, inference and verification.""" + + @staticmethod + def get_dummy_inputs( + batch_size: int, + past_sequence_length: int, + sequence_length: int, + num_attention_heads: int, + hidden_size: int, + num_layer: int, + vocab_size: int, + device: torch.device, + float16: bool = False, + has_position_ids: bool = True, + has_attention_mask: bool = True, + input_ids_dtype: torch.dtype = torch.int32, + position_ids_dtype: torch.dtype = torch.int32, + attention_mask_dtype: torch.dtype = torch.int32, + left_side_padding: bool = True, + ) -> Gpt2Inputs: + """Create random inputs for GPT2 model. + Returns torch tensors of input_ids, position_ids, attention_mask and a list of past state tensors. + """ + float_type = torch.float16 if float16 else torch.float32 + past_shape = [ + 2, + batch_size, + num_attention_heads, + past_sequence_length, + int(hidden_size / num_attention_heads), + ] + + past = [(torch.rand(past_shape, dtype=float_type, device=device) * 2.0 - 1.0) for _ in range(num_layer)] + input_ids = torch.randint( + low=0, + high=vocab_size - 1, + size=(batch_size, sequence_length), + dtype=input_ids_dtype, + device=device, + ) + + attention_mask = None + if has_attention_mask: + total_sequence_length = past_sequence_length + sequence_length + attention_mask = torch.ones( + [batch_size, total_sequence_length], + dtype=attention_mask_dtype, + device=device, + ) + + if total_sequence_length >= 2: + for i in range(batch_size): + padding_length = random.randint(0, total_sequence_length - 1) + if left_side_padding: + attention_mask[i, :padding_length] = 0 + else: # right side padding + attention_mask[i, total_sequence_length - padding_length :] = 0 + + # Deduce position_ids from attention mask + position_ids = None + if has_position_ids: + position_ids = attention_mask.long().cumsum(-1) - 1 + position_ids.masked_fill_(position_ids < 0, 0) + position_ids = position_ids[:, past_sequence_length:].to(position_ids_dtype) + + return Gpt2Inputs(input_ids, position_ids, attention_mask, past) + + @staticmethod + def get_output_shapes( + batch_size: int, + past_sequence_length: int, + sequence_length: int, + config: GPT2Config, + model_class: str = "GPT2LMHeadModel", + ) -> dict[str, list[int]]: + """Returns a dictionary with output name as key, and shape as value.""" + num_attention_heads = config.num_attention_heads + hidden_size = config.hidden_size + num_layer = config.num_hidden_layers + vocab_size = config.vocab_size + + output_name = MODEL_CLASSES[model_class][1] + + last_state_shape = [ + batch_size, + sequence_length, + vocab_size if output_name == "logits" else hidden_size, + ] + present_state_shape = [ + 2, + batch_size, + num_attention_heads, + past_sequence_length + sequence_length, + int(hidden_size / num_attention_heads), + ] + + output_shapes = {output_name: last_state_shape} + for i in range(num_layer): + output_shapes["present_" + str(i)] = present_state_shape + + return output_shapes + + @staticmethod + def auto_increase_buffer_size(output_buffers, output_shapes): + for key in output_shapes: + assert key in output_buffers + buffer = output_buffers[key] + if numpy.prod(output_shapes[key]) > buffer.nelement(): + output_buffers[key] = torch.empty( + numpy.prod(output_shapes[key]), + dtype=buffer.dtype, + device=buffer.device, + ) + + @staticmethod + def get_output_buffers(output_shapes, device, is_float16=False): + """Returns a dictionary of output name as key, and 1D tensor as value. The tensor has enough space for given shape.""" + data_type = torch.float16 if is_float16 else torch.float32 + + output_buffers = {} + for name, shape in output_shapes.items(): + output_buffers[name] = torch.empty(numpy.prod(shape), dtype=data_type, device=device) + return output_buffers + + @staticmethod + def diff_outputs(torch_outputs, ort_outputs, relative=False): + """Returns the maximum difference between PyTorch and OnnxRuntime outputs.""" + expected_outputs = torch_outputs[0].cpu().numpy() + diff = numpy.abs(expected_outputs - ort_outputs[0]) + if relative: + return numpy.amax(diff / (numpy.abs(expected_outputs) + 1e-6)) + else: + return numpy.amax(diff) + + @staticmethod + def compare_outputs(torch_outputs, ort_outputs, rtol=1e-03, atol=1e-03, **kwargs): + """Returns True if torch and ORT outputs are close for given thresholds, and False otherwise. + Note: need kwargs since Gpt2BeamSearchHelper.compare_outputs has an extra parameter model_class + """ + is_close = numpy.allclose(ort_outputs[0], torch_outputs[0].cpu().numpy(), rtol=rtol, atol=atol) + logger.debug(f"PyTorch and OnnxRuntime output 0 (last_state) are close: {is_close}") + + is_all_close = is_close + num_layers = len(ort_outputs) - 1 + + for layer in range(num_layers): + is_close = numpy.allclose( + ort_outputs[1 + layer], + torch_outputs[1][layer].cpu().numpy(), + rtol=rtol, + atol=atol, + ) + logger.debug(f"PyTorch and OnnxRuntime layer {layer} state (present_{layer}) are close:{is_close}") + is_all_close = is_all_close and is_close + + if not is_all_close: + max_abs_diff = Gpt2Helper.diff_outputs(torch_outputs, ort_outputs) + logger.info(f"PyTorch and OnnxRuntime results are not all close: max_abs_diff={max_abs_diff:.5f}") + + return is_all_close + + @staticmethod + def compare_outputs_v2(torch_outputs, ort_outputs, atol=1e-06): + """Compare outputs from PyTorch and OnnxRuntime + + Args: + torch_outputs (Tuple[Torch.Tensor]): PyTorch model output + ort_outputs (List[numpy.ndarray]): OnnxRuntime output + atol (float, optional): Absolute tollerance. Defaults to 1e-06. + + Returns: + is_all_close(bool): whether all elements are close. + max_abs_diff(float): maximum absolute difference. + messages(str): a list of debug message for each output + """ + is_all_close = True + is_top1_matched = False + max_diffs = [] + messages = [] + for i in range(len(ort_outputs)): + ort_output = ort_outputs[i] + torch_output = (torch_outputs[0] if i == 0 else torch_outputs[1][i - 1]).cpu().numpy() + is_close = numpy.allclose(ort_output, torch_output, atol=atol, rtol=0) + max_diffs.append(numpy.amax(numpy.abs(torch_output - ort_output))) + is_all_close = is_all_close and is_close + + if numpy.isnan(torch_output).any(): + logger.debug(f"PyTorch output {i} has nan") + if numpy.isinf(torch_output).any(): + logger.debug(f"PyTorch output {i} has inf") + if numpy.isnan(ort_output).any(): + logger.debug(f"ORT output {i} has nan") + if numpy.isinf(ort_output).any(): + logger.debug(f"ORT output {i} has inf") + + diff = numpy.fabs(ort_output - torch_output) + idx = numpy.unravel_index(diff.argmax(), diff.shape) + messages.append( + f"diff={diff[idx]:.9f} index={idx} ort={ort_output[idx]:.9f} torch={float(torch_output[idx]):.9f}" + ) + + if i == 0: # logits + ort_max_index = numpy.unravel_index(numpy.argmax(ort_output, axis=None), ort_output.shape) + torch_max_index = numpy.unravel_index(numpy.argmax(torch_output, axis=None), torch_output.shape) + is_top1_matched = numpy.array_equal(ort_max_index, torch_max_index) + + max_diff_output_index = max_diffs.index(max(max_diffs)) + return ( + is_all_close, + max(max_diffs), + max_diff_output_index, + messages, + is_top1_matched, + ) + + @staticmethod + def export_onnx( + model, + device, + onnx_model_path: str, + verbose: bool = False, + use_external_data_format: bool = False, + has_position_ids: bool = True, + has_attention_mask: bool = True, + input_ids_dtype: torch.dtype = torch.int32, + position_ids_dtype: torch.dtype = torch.int32, + attention_mask_dtype: torch.dtype = torch.int32, + ): + """Export GPT-2 model with past state to ONNX model.""" + config: GPT2Config = model.config + num_layer = config.n_layer + dummy_inputs = Gpt2Helper.get_dummy_inputs( + batch_size=1, + past_sequence_length=1, + sequence_length=1, + num_attention_heads=config.num_attention_heads, + hidden_size=config.hidden_size, + num_layer=num_layer, + vocab_size=config.vocab_size, + device=device, + float16=False, + has_position_ids=has_position_ids, + has_attention_mask=has_attention_mask, + input_ids_dtype=input_ids_dtype, + position_ids_dtype=position_ids_dtype, + attention_mask_dtype=attention_mask_dtype, + ) + input_list = dummy_inputs.to_list() + + with torch.no_grad(): + outputs = model(*input_list) + + past_names = [f"past_{i}" for i in range(num_layer)] + present_names = [f"present_{i}" for i in range(num_layer)] + + # GPT2Model outputs last_state; GPT2LMHeadModel outputs logits (prediction_scores) + assert outputs[0].shape[2] == config.vocab_size or outputs[0].shape[2] == config.hidden_size + output_names = ["logits" if outputs[0].shape[2] == config.vocab_size else "last_state", *present_names] + + # Shape of input tensors: + # input_ids: (batch_size, seq_len) + # past_{i}: (2, batch_size, num_heads, past_seq_len, hidden_size/num_heads) + # attention_mask: (batch_size, past_seq_len + seq_len) + # Shape of output tensors: + # last_state: (batch_size, seq_len, hidden_size) + # or logits: (batch_size, seq_len, vocab_size) + # present_{i}: (2, batch_size, num_heads, past_seq_len + seq_len, hidden_size/num_heads) + dynamic_axes = { + "input_ids": {0: "batch_size", 1: "seq_len"}, + output_names[0]: {0: "batch_size", 1: "seq_len"}, + } + for name in past_names: + dynamic_axes[name] = {1: "batch_size", 3: "past_seq_len"} + for name in present_names: + dynamic_axes[name] = {1: "batch_size", 3: "total_seq_len"} + + input_names = ["input_ids"] + if has_position_ids: + dynamic_axes["position_ids"] = {0: "batch_size", 1: "seq_len"} + input_names.append("position_ids") + if has_attention_mask: + dynamic_axes["attention_mask"] = {0: "batch_size", 1: "total_seq_len"} + input_names.append("attention_mask") + input_names.extend(past_names) + + assert len(outputs) == 2 and len(outputs[1]) == num_layer + + logger.info( + f"Shapes: input_ids={dummy_inputs.input_ids.shape} past={dummy_inputs.past[0].shape} output={outputs[0].shape} present={outputs[1][0].shape}" + ) + + Path(onnx_model_path).parent.mkdir(parents=True, exist_ok=True) + + if use_external_data_format: + # We let PyTorch export onnx to a temp directory first, then convert external data to one file. + with tempfile.TemporaryDirectory() as tmp_dir_name: + temp_onnx_model_path = os.path.join(tmp_dir_name, "gpt2.onnx") + Path(temp_onnx_model_path).parent.mkdir(parents=True, exist_ok=True) + + torch_onnx_export( + model, + args=tuple(input_list), + f=temp_onnx_model_path, + export_params=True, + input_names=input_names, + output_names=output_names, + dynamic_axes=dynamic_axes, + opset_version=14, + do_constant_folding=True, + use_external_data_format=True, + verbose=verbose, + ) + + model = onnx.load_model(temp_onnx_model_path, load_external_data=True) + OnnxModel.save( + model, + onnx_model_path, + save_as_external_data=True, + all_tensors_to_one_file=True, + ) + else: + torch_onnx_export( + model, + args=tuple(input_list), + f=onnx_model_path, + export_params=True, + input_names=input_names, + output_names=output_names, + dynamic_axes=dynamic_axes, + opset_version=11, + do_constant_folding=True, + use_external_data_format=False, + verbose=verbose, + ) + + @staticmethod + def optimize_onnx( + onnx_model_path, + optimized_model_path, + is_float16, + num_attention_heads, + hidden_size, + use_external_data_format=False, + auto_mixed_precision=False, + stage=0, + **kwargs, + ): + """Optimize ONNX model with an option to convert it to use mixed precision.""" + optimization_options = FusionOptions("gpt2") + + m = optimize_model( + onnx_model_path, + model_type="gpt2", + num_heads=num_attention_heads, + hidden_size=hidden_size, + opt_level=0, + optimization_options=optimization_options, + use_gpu=False, + ) + + if is_float16: + if auto_mixed_precision: + Gpt2Helper.auto_mixed_precision(m) + else: + if "keep_io_types" not in kwargs: + kwargs["keep_io_types"] = False + m.convert_float_to_float16(use_symbolic_shape_infer=True, **kwargs) + + m.save_model_to_file(optimized_model_path, use_external_data_format) + return m + + @staticmethod + def auto_mixed_precision( + onnx_model: OnnxModel, + op_block_list: list[str] = [ # noqa: B006 + "Add", + "LayerNormalization", + "SkipLayerNormalization", + "FastGelu", + "EmbedLayerNormalization", + ], + ): + """Convert GPT-2 model to mixed precision. + It detects whether original model has fp16 weights, and set parameters for float16 conversion automatically. + Args: + onnx_model (OnnxModel): optimized ONNX model + op_block_list (List[str], optional): operators to compute in fp32. Defaults to ["Add", "LayerNormalization", + "SkipLayerNormalization", "FastGelu", "EmbedLayerNormalization"] + Returns: + parameters(dict): a dictionary of parameters used in float16 conversion + """ + op_full_set = {node.op_type for node in onnx_model.nodes()} + fp32_op_set = set(op_block_list) + fp16_op_set = op_full_set.difference(fp32_op_set) + logger.info(f"fp32 op: {fp32_op_set} fp16 op: {fp16_op_set}") + + # logits is the first output + logits_output_name = onnx_model.graph().output[0].name + + # We use the weight in last MatMul node to detect whether the model is stored with float16 weights from training. + is_weight_fp16_precision = False + output_name_to_node = onnx_model.output_name_to_node() + assert logits_output_name in output_name_to_node + node = output_name_to_node[logits_output_name] + last_matmul_node = None + if node.op_type == "MatMul": + last_matmul_node = node + logger.info(f"Found last MatMul node for logits: {node.name}") + initializer = None + for input in node.input: + initializer = onnx_model.get_initializer(input) + if initializer is not None: + break + + # when the max difference of value after converting float to float16 is lower than a threshold (1e-6), + # we can deduce that the weights are stored in float16 precision. + max_diff = float_to_float16_max_diff(initializer) + logger.debug(f"max diff of converting weights in last MatMul node {node.name}: {max_diff}") + is_weight_fp16_precision = max_diff < 1e-6 + else: + logger.warning(f"Failed to find MatMul node for logits. Found {node.op_type} of node {node.name}") + + keep_io_types = [] + node_block_list = [] + if (not is_weight_fp16_precision) and (last_matmul_node is not None): + # When original weight is float32 precision, keep logits and last MatMul in float32 could get better precision. + keep_io_types = [logits_output_name] + node_block_list = [last_matmul_node.name] + + parameters = { + "keep_io_types": keep_io_types, + "op_block_list": op_block_list, + "node_block_list": node_block_list, + "force_fp16_initializers": is_weight_fp16_precision, + } + + logger.info(f"auto_mixed_precision parameters: {parameters}") + onnx_model.convert_float_to_float16(use_symbolic_shape_infer=True, **parameters) + + return parameters + + @staticmethod + def pytorch_inference(model, inputs: Gpt2Inputs, total_runs: int = 0): + """Run inference of PyTorch model, and returns average latency in ms when total_runs > 0 besides outputs.""" + logger.debug("start pytorch_inference") + + # Convert it to fp32 as the PyTroch model cannot deal with half input. + input_list = inputs.to_fp32().to_list() + + with torch.no_grad(): + outputs = model(*input_list) + + if total_runs == 0: + return outputs + + latency = [] + with torch.no_grad(): + for _ in range(total_runs): + start = time.time() + outputs = model(*input_list) + latency.append(time.time() - start) + + average_latency = sum(latency) * 1000 / len(latency) + logger.debug("PyTorch inference time = {} ms".format(format(average_latency, ".2f"))) # noqa: G001 + + return outputs, average_latency + + @staticmethod + def onnxruntime_inference(ort_session, inputs: Gpt2Inputs, total_runs: int = 0): + """Run inference of ONNX model, and returns average latency in ms when total_runs > 0 besides outputs.""" + logger.debug("start onnxruntime_inference") + + ort_inputs = {"input_ids": numpy.ascontiguousarray(inputs.input_ids.cpu().numpy())} + + if inputs.past is not None: + for i, past_i in enumerate(inputs.past): + ort_inputs[f"past_{i}"] = numpy.ascontiguousarray(past_i.cpu().numpy()) + + if inputs.attention_mask is not None: + ort_inputs["attention_mask"] = numpy.ascontiguousarray(inputs.attention_mask.cpu().numpy()) + + if inputs.position_ids is not None: + ort_inputs["position_ids"] = numpy.ascontiguousarray(inputs.position_ids.cpu().numpy()) + + ort_outputs = ort_session.run(None, ort_inputs) + if total_runs == 0: + return ort_outputs + + latency = [] + for _ in range(total_runs): + start = time.time() + ort_outputs = ort_session.run(None, ort_inputs) + latency.append(time.time() - start) + + average_latency = sum(latency) * 1000 / len(latency) + logger.debug("OnnxRuntime Inference time = {} ms".format(format(average_latency, ".2f"))) # noqa: G001 + + return ort_outputs, average_latency + + @staticmethod + def prepare_io_binding( + ort_session, + input_ids, + position_ids, + attention_mask, + past, + output_buffers, + output_shapes, + ): + """Returnas IO binding object for a session.""" + return IOBindingHelper.prepare_io_binding( + ort_session, + input_ids, + position_ids, + attention_mask, + past, + output_buffers, + output_shapes, + ) + + @staticmethod + def get_outputs_from_io_binding_buffer(ort_session, output_buffers, output_shapes, return_numpy=True): + """Copy results to cpu. Returns a list of numpy array.""" + return IOBindingHelper.get_outputs_from_io_binding_buffer( + ort_session, output_buffers, output_shapes, return_numpy + ) + + @staticmethod + def onnxruntime_inference_with_binded_io( + ort_session, + inputs: Gpt2Inputs, + output_buffers: dict[str, torch.Tensor], + output_shapes: dict[str, list[int]], + total_runs: int = 0, + return_numpy: bool = True, + include_copy_output_latency: bool = False, + ): + """Inference with IO binding. Returns outputs, and optional latency when total_runs > 0.""" + logger.debug("start onnxruntime_inference_with_binded_io") + + # Bind inputs and outputs to onnxruntime session + io_binding = Gpt2Helper.prepare_io_binding( + ort_session, + inputs.input_ids, + inputs.position_ids, + inputs.attention_mask, + inputs.past, + output_buffers, + output_shapes, + ) + + # Run onnxruntime with io binding + ort_session.run_with_iobinding(io_binding) + + # Copy results to cpu for verification + ort_outputs = Gpt2Helper.get_outputs_from_io_binding_buffer( + ort_session, output_buffers, output_shapes, return_numpy + ) + + if total_runs == 0: + return ort_outputs + + latency = [] + for _ in range(total_runs): + start = time.time() + # Run onnxruntime with io binding + ort_session.run_with_iobinding(io_binding) + if include_copy_output_latency: + _ = Gpt2Helper.get_outputs_from_io_binding_buffer( + ort_session, output_buffers, output_shapes, return_numpy + ) + latency.append(time.time() - start) + + average_latency = sum(latency) * 1000 / len(latency) + logger.debug("OnnxRuntime with IO binding inference time = %.2f ms", average_latency) + + return ort_outputs, average_latency + + @staticmethod + def save_outputs(i, ort_outputs, torch_outputs): + with open(f"ort_outputs_{i}.pickle", "wb") as f: + pickle.dump(ort_outputs, f) + logger.info(f"ORT output are saved to ort_outputs_{i}.pickle") + + with open(f"torch_outputs_{i}.pickle", "wb") as f: + pickle.dump(torch_outputs, f) + logger.info(f"Torch output are saved to torch_outputs_{i}.pickle") + + @staticmethod + def save_inputs(i, dummy_inputs, ort_outputs, torch_outputs): + with open(f"dummy_inputs_{i}.pickle", "wb") as f: + pickle.dump(dummy_inputs, f) + logger.info(f"inputs are saved to dummy_inputs_{i}.pickle") + + @staticmethod + def test_parity( + ort_session, + model, + device, + is_float16=False, + rtol=5e-4, + atol=5e-4, + test_cases_per_run=10000, + total_runs=1, + use_io_binding=True, + model_class="GPT2LMHeadModel", + has_position_ids=True, + has_attention_mask=True, + input_ids_dtype=torch.int32, + position_ids_dtype=torch.int32, + attention_mask_dtype=torch.int32, + stage=0, + verbose=False, + enable_pickle_output=False, + ): + """Generate random inputs and compare the results of PyTorch and Onnx Runtime.""" + + config: GPT2Config = model.config + + logger.info( + f"Running parity test (atol={atol}, test_cases={test_cases_per_run}, runs={total_runs}, use_io_binding={use_io_binding}, model_class={model_class}, is_float16={is_float16}) ..." + ) + + max_batch_size = 8 + max_past_seq_len = 4 # Do not use large number here for higher chance of hitting empty past (past_seq_len=0) + max_seq_len = 2 + + output_buffers = None + if use_io_binding: + max_output_shapes = Gpt2Helper.get_output_shapes( + max_batch_size, max_past_seq_len, max_seq_len, config, model_class + ) + output_buffers = Gpt2Helper.get_output_buffers(max_output_shapes, device, is_float16) + + passed_test_cases = 0 + top1_matched_cases = 0 + + max_abs_diff_list = [] + top1_matched_cases_per_run = [0] * total_runs + total_test_cases = test_cases_per_run * total_runs + for i in range(total_test_cases): + run_id = int(i / test_cases_per_run) + sequence_length = random.randint(1, max_seq_len) + past_sequence_length = 0 if (stage == 1) else random.randint(0, max_past_seq_len) + batch_size = random.randint(1, max_batch_size) + + logger.debug( + f"Running parity test for batch_size={batch_size} past_sequence_length={past_sequence_length}..." + ) + dummy_inputs = Gpt2Helper.get_dummy_inputs( + batch_size, + past_sequence_length, + sequence_length, + config.num_attention_heads, + config.hidden_size, + config.n_layer, + config.vocab_size, + device, + is_float16, + has_position_ids, + has_attention_mask, + input_ids_dtype=input_ids_dtype, + position_ids_dtype=position_ids_dtype, + attention_mask_dtype=attention_mask_dtype, + left_side_padding=True, + ) + outputs = Gpt2Helper.pytorch_inference(model, dummy_inputs) + if use_io_binding: + ort_outputs = Gpt2Helper.onnxruntime_inference(ort_session, dummy_inputs) + else: + output_shapes = Gpt2Helper.get_output_shapes( + batch_size, + past_sequence_length, + sequence_length, + config, + model_class, + ) + ort_outputs = Gpt2Helper.onnxruntime_inference_with_binded_io( + ort_session, dummy_inputs, output_buffers, output_shapes + ) + + ( + is_all_close, + max_abs_diff, + max_diff_output_index, + messages, + is_top1_matched, + ) = Gpt2Helper.compare_outputs_v2(outputs, ort_outputs, atol=atol) + if not numpy.isnan(max_abs_diff): + max_abs_diff_list.append(max_abs_diff) + if is_all_close: + passed_test_cases += 1 + + if is_top1_matched: + top1_matched_cases += 1 + top1_matched_cases_per_run[run_id] += 1 + + if verbose and not is_all_close: + logger.info( + f"test_case={i} batch_size={batch_size} past_sequence_length={past_sequence_length} sequence_length={sequence_length} MaxDiff={max_abs_diff}" + ) + for i, message in enumerate(messages): # noqa: PLW2901 + logger.info(f"\t{i}: Name={ort_session.get_outputs()[i].name}, {message}") + + # Collect data for debugging + if enable_pickle_output and (numpy.isnan(max_abs_diff) or max_abs_diff > 100 * atol): + Gpt2Helper.save_inputs(i, dummy_inputs) + Gpt2Helper.save_outputs(i, ort_outputs, outputs) + + if max_abs_diff_list: + result = { + f"max_diff_percentile_{p}": f"{numpy.percentile(max_abs_diff_list, p):.5f}" for p in [50, 90, 95, 99] + } + else: + result = {f"max_diff_percentile_{p}": "nan" for p in [50, 90, 95, 99]} + + result["top1_match_rate"] = top1_matched_cases * 1.0 / total_test_cases + result["top1_match_rate_per_run"] = [x * 1.0 / test_cases_per_run for x in top1_matched_cases_per_run] + result["diff_pass_rate"] = passed_test_cases * 1.0 / total_test_cases + result["nan_rate"] = (total_test_cases - len(max_abs_diff_list)) * 1.0 / total_test_cases + + logger.info( + f"Parity Test Cases={total_test_cases}; Passed={passed_test_cases}; Nan={total_test_cases - len(max_abs_diff_list)}; Top1_Matched={top1_matched_cases}" + ) + + if passed_test_cases > 0.95 * total_test_cases: + logger.info(f"Parity is good: passed rate={int(passed_test_cases * 100 / total_test_cases):.0f}%") + + return result + + @staticmethod + def test_performance( + ort_session, + model, + device, + is_float16=False, + total_runs=100, + use_io_binding=True, + model_class="GPT2LMHeadModel", + has_position_ids=True, + has_attention_mask=True, + input_ids_dtype=torch.int32, + position_ids_dtype=torch.int32, + attention_mask_dtype=torch.int32, + batch_size=8, + sequence_length=1, + past_sequence_length=32, + ): + """Generate random inputs and measure average latency of Onnx Runtime.""" + + config: GPT2Config = model.config + + output_buffers = None + if use_io_binding: + output_shapes = Gpt2Helper.get_output_shapes( + batch_size, past_sequence_length, sequence_length, config, model_class + ) + output_buffers = Gpt2Helper.get_output_buffers(output_shapes, device, is_float16) + + dummy_inputs = Gpt2Helper.get_dummy_inputs( + batch_size, + past_sequence_length, + sequence_length, + config.num_attention_heads, + config.hidden_size, + config.n_layer, + config.vocab_size, + device, + is_float16, + has_position_ids, + has_attention_mask, + input_ids_dtype=input_ids_dtype, + position_ids_dtype=position_ids_dtype, + attention_mask_dtype=attention_mask_dtype, + ) + + if use_io_binding: + _, latency = Gpt2Helper.onnxruntime_inference(ort_session, dummy_inputs, total_runs) + else: + _, latency = Gpt2Helper.onnxruntime_inference_with_binded_io( + ort_session, dummy_inputs, output_buffers, output_shapes, total_runs + ) + + return latency + + @staticmethod + def torchscript(model, config, device, has_position_ids=True, has_attention_mask=True): + """JIT trace for TorchScript.""" + input_list = Gpt2Helper.get_dummy_inputs( + batch_size=1, + past_sequence_length=1, + sequence_length=1, + num_attention_heads=config.num_attention_heads, + hidden_size=config.hidden_size, + num_layer=config.n_layer, + vocab_size=config.vocab_size, + device=device, + float16=False, + has_position_ids=has_position_ids, + has_attention_mask=has_attention_mask, + ).to_list() + return torch.jit.trace(model, input_list) + + @staticmethod + def get_onnx_paths( + output_dir, + model_name_or_path, + model_class: str = "GPT2LMHeadModel", + has_past=True, + new_folder=False, + remove_existing=["raw", "fp32", "fp16", "int8"], # noqa: B006 + ): + """Build a path name for given model based on given attributes.""" + model_name = model_name_or_path + if os.path.isdir(model_name_or_path): + model_name = Path(model_name_or_path).parts[-1] + else: + model_name.split("/")[-1] + + if model_class != "GPT2LMHeadModel": + model_name += "_" + model_class + + if has_past: + model_name += "_past" + + if new_folder: + suffix = {"raw": "", "fp32": "_fp32", "fp16": "_fp16", "int8": "_int8"} + # Remove the directories if existed. + for model_type in ["raw", "fp32", "fp16", "int8"]: + new_dir = os.path.join(output_dir, model_name + suffix[model_type]) + if os.path.exists(new_dir): + if model_type in remove_existing: + try: + shutil.rmtree(new_dir) + logger.info(f"Removed the existed directory: {new_dir}") + except OSError as e: + logger.info(f"Failed to remove the directory {new_dir}: {e.strerror}") + else: + logger.info(f"Directory for {model_type} existed: {new_dir}") + + # store each model to its own directory (for external data format). + return { + "raw": os.path.join(os.path.join(output_dir, model_name), model_name + ".onnx"), + "fp32": os.path.join( + os.path.join(output_dir, model_name + "_fp32"), + model_name + "_fp32.onnx", + ), + "fp16": os.path.join( + os.path.join(output_dir, model_name + "_fp16"), + model_name + "_fp16.onnx", + ), + "int8": os.path.join( + os.path.join(output_dir, model_name + "_int8"), + model_name + "_int8.onnx", + ), + } + + return { + "raw": os.path.join(output_dir, model_name + ".onnx"), + "fp32": os.path.join(output_dir, model_name + "_fp32.onnx"), + "fp16": os.path.join(output_dir, model_name + "_fp16.onnx"), + "int8": os.path.join(output_dir, model_name + "_int8.onnx"), + } diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/gpt2/gpt2_parity.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/gpt2/gpt2_parity.py new file mode 100644 index 0000000000000000000000000000000000000000..3153fc502220f3c1aae21f22a46563a8dfcce053 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/gpt2/gpt2_parity.py @@ -0,0 +1,513 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +# This script uses different configurations in mixed precision conversion for GPT-2 model, and +# measures the inference latency, top 1 match rate (compared to PyTorch FP32 model) and ONNX model size. +# It outputs a csv file with Mann-Whitney U test and T-Test on each pair of experiments, where +# pvalue < 0.05 means two experiments have significant difference on top 1 match rate. +# User could use this script to select the best mixed precision model according to these metrics. + +import argparse +import csv +import datetime +import json +import logging +import os + +import onnx +import scipy.stats +from benchmark_helper import get_ort_environment_variables, setup_logger +from convert_to_onnx import main +from gpt2_helper import PRETRAINED_GPT2_MODELS, Gpt2Helper +from onnx_model import OnnxModel + +logger = logging.getLogger("") + + +def parse_arguments(argv=None): + parser = argparse.ArgumentParser() + + parser.add_argument( + "-m", + "--model_name_or_path", + required=True, + type=str, + help="Model path, or pretrained model name in the list: " + ", ".join(PRETRAINED_GPT2_MODELS), + ) + + parser.add_argument( + "--csv", + required=False, + type=str, + default="gpt2_parity_results.csv", + help="path of csv file to save the result", + ) + + parser.add_argument( + "--test_cases", + required=False, + type=int, + default=500, + help="number of test cases per run", + ) + + parser.add_argument("--runs", required=False, type=int, default=40, help="number of repeated runs") + + parser.add_argument("--use_gpu", required=False, action="store_true", help="use GPU for inference") + parser.set_defaults(use_gpu=False) + + parser.add_argument( + "--all", + required=False, + action="store_true", + help="run all combinations of mixed precision", + ) + parser.set_defaults(all=False) + + parser.add_argument("-e", "--use_external_data_format", required=False, action="store_true") + parser.set_defaults(use_external_data_format=False) + + parser.add_argument("--verbose", required=False, action="store_true") + parser.set_defaults(verbose=False) + + parser.add_argument( + "--skip_test", + required=False, + action="store_true", + help="do not run test, and only rank experiments based on existing csv file", + ) + parser.set_defaults(skip_test=False) + + parser.add_argument( + "--overwrite", + required=False, + action="store_true", + help="Overwrite existing csv file", + ) + parser.set_defaults(overwrite=False) + + args = parser.parse_args(argv) + + return args + + +class ParityTask: + def __init__(self, test_cases, total_runs, csv_path): + self.total_runs = total_runs + self.test_cases = test_cases + self.csv_path = csv_path + self.results = [] + self.run_id = 0 + + def run(self, argv, experiment_name): + start_time = datetime.datetime.now().strftime("%Y%m%d%H%M%S") + run_id = f"{start_time}_{self.run_id}" + self.run_id += 1 + + try: + result = main( + [*argv, "-t", f"{self.test_cases}", "-r", f"{self.total_runs}"], + experiment_name=experiment_name, + run_id=run_id, + csv_filename=self.csv_path, + ) + if result: + self.results.append(result) + except Exception: + logger.exception(f"Failed to run experiment {experiment_name}") + result = None + + return result + + +def load_results_from_csv(csv_path): + rows = [] + import csv # noqa: PLC0415 + + with open(csv_path, newline="") as csvfile: + reader = csv.DictReader(csvfile) + for row in reader: + rows.append(row) # noqa: PERF402 + return rows + + +def get_latency(row): + for name in row: + if name.startswith("average_latency(batch_size="): + return float(row[name]) + + raise RuntimeError("Failed to get average_latency from output") + + +def score(row): + """Scoring function based on 3 metrics. The larger score is better.""" + latency_in_ms = get_latency(row) + top1_match_rate = float(row["top1_match_rate"]) + onnx_size_in_MB = float(row["onnx_size_in_MB"]) # noqa: N806 + # A simple scoring function: cost of 0.1ms latency ~ 0.1% match rate ~ 100MB size + return top1_match_rate * 1000 - latency_in_ms * 10 - onnx_size_in_MB / 100 + + +def print_wins(wins, rows, test_name): + print() + print("*" * 10) + + row_map = {} + for row in rows: + row_map[row["run_id"]] = row + + sorted_wins = dict( + sorted( + wins.items(), + key=lambda item: (item[1], score(row_map[item[0]])), + reverse=True, + ) + ) + logger.debug(f"{test_name} Wins:{sorted_wins}") + logger.info(f"Based on {test_name} wins and a scoring function, the ranking:") + + rank = 0 + previous_value = -1 + for count, (key, value) in enumerate(sorted_wins.items()): + if value != previous_value: + rank = count + previous_value = value + + for row in rows: + if row["run_id"] == key: + logger.info( + "{:02d}: WINs={:02d}, run_id={}, latency={:5.2f}, top1_match={:.4f}, size={}_MB, experiment={}, {}".format( # noqa: G001 + rank, + value, + key, + get_latency(row), + float(row["top1_match_rate"]), + row["onnx_size_in_MB"], + row["experiment"], + get_ort_environment_variables(), + ) + ) + break + + +def run_significance_test(rows, output_csv_path): + """Run U test and T test.""" + utest_wins = {} + ttest_wins = {} + for row in rows: + run_id = row["run_id"] + utest_wins[run_id] = 0 + ttest_wins[run_id] = 0 + + with open(output_csv_path, "w", newline="") as csvfile: + column_names = [ + "model_name", + "run_id_1", + "experiment_1", + "top1_match_rate_1", + "run_id_2", + "experiment_2", + "top1_match_rate_2", + "U_statistic", + "U_pvalue", + "T_statistic", + "T_pvalue", + ] + + writer = csv.DictWriter(csvfile, fieldnames=column_names) + writer.writeheader() + + required_match_columns = ["model_name", "test_cases", "runs"] + num_results = len(rows) + for i in range(num_results - 1): + result1 = rows[i] + + if isinstance(result1["top1_match_rate_per_run"], str): + a = json.loads(result1["top1_match_rate_per_run"]) + else: + a = result1["top1_match_rate_per_run"] + + for j in range(i + 1, num_results, 1): + result2 = rows[j] + + all_matched = True + for column in required_match_columns: + if result1[column] != result2[column]: + all_matched = False + break + if not all_matched: + continue + + if isinstance(result2["top1_match_rate_per_run"], str): + b = json.loads(result2["top1_match_rate_per_run"]) + else: + b = result2["top1_match_rate_per_run"] + + try: + utest_statistic, utest_pvalue = scipy.stats.mannwhitneyu( + a, b, use_continuity=True, alternative="two-sided" + ) # TODO: shall we use one-sided: less or greater according to "top1_match_rate" + except ValueError: # ValueError: All numbers are identical in mannwhitneyu + utest_statistic = None + utest_pvalue = None + ttest_statistic, ttest_pvalue = scipy.stats.ttest_ind(a, b, axis=None, equal_var=True) + + if utest_pvalue is not None and utest_pvalue < 0.05: + if float(result1["top1_match_rate"]) > float(result2["top1_match_rate"]): + utest_wins[result1["run_id"]] += 1 + else: + utest_wins[result2["run_id"]] += 1 + + if ttest_pvalue < 0.05: + if float(result1["top1_match_rate"]) > float(result2["top1_match_rate"]): + ttest_wins[result1["run_id"]] += 1 + else: + ttest_wins[result2["run_id"]] += 1 + + row = { + "model_name": result1["model_name"], + "run_id_1": result1["run_id"], + "experiment_1": result1["experiment"], + "top1_match_rate_1": float(result1["top1_match_rate"]), + "run_id_2": result2["run_id"], + "experiment_2": result2["experiment"], + "top1_match_rate_2": float(result2["top1_match_rate"]), + "U_statistic": utest_statistic, + "U_pvalue": utest_pvalue, + "T_statistic": ttest_statistic, + "T_pvalue": ttest_pvalue, + } + + writer.writerow(row) + logger.info(f"U-Test and T-Test results are output to {output_csv_path}") + print_wins(utest_wins, rows, "U-Test") + print_wins(ttest_wins, rows, "T-Test") + + +def get_last_matmul_node_name(raw_onnx_model: str): + model = onnx.load(raw_onnx_model) + onnx_model = OnnxModel(model) + output_name_to_node = onnx_model.output_name_to_node() + + assert model.graph.output[0].name in output_name_to_node + node = output_name_to_node[model.graph.output[0].name] + if node.op_type == "MatMul": + logger.info(f"Found last MatMul node for logits: {node.name}") + return node.name + + logger.warning(f"Failed to find MatMul node for logits. Found {node.op_type} of node {node.name}") + return None + + +def get_mixed_precision_parameters(args, last_matmul_node_name, op_block_list): + model = args.model_name_or_path + parameters = f"-m {model} -o --use_gpu -p fp16".split() + if args.use_external_data_format: + parameters.append("--use_external_data_format") + parameters += [ + "--io_block_list", + "logits", + "--node_block_list", + last_matmul_node_name, + ] + + if op_block_list: + parameters.extend(["--op_block_list", *op_block_list]) + + return parameters + + +def run_candidate( + task: ParityTask, + args, + last_matmul_node_name, + op_block_list=["FastGelu", "LayerNormalization"], # noqa: B006 +): + parameters = get_mixed_precision_parameters(args, last_matmul_node_name, op_block_list) + op_block_list_str = ",".join(sorted(op_block_list)) + + if op_block_list: + name = f"Mixed precision baseline + {op_block_list_str} in FP32" + else: + name = f"Mixed precision baseline (logits output and last MatMul node {last_matmul_node_name} in FP32)" + + env_vars = get_ort_environment_variables() + if env_vars: + name = name + f" ({env_vars})" + + task.run(parameters, name) + + +def get_baselines(args): + model = args.model_name_or_path + fp32_baseline = f"-m {model} -o -p fp32".split() + if args.use_gpu: + fp32_baseline.append("--use_gpu") + if args.use_external_data_format: + fp32_baseline.append("--use_external_data_format") + + fp16_baseline = f"-m {model} -o --use_gpu -p fp16".split() + if args.use_external_data_format: + fp16_baseline.append("--use_external_data_format") + + return fp32_baseline, fp16_baseline + + +def run_tuning_step0(task, fp16_baseline, all_ops, optimized_ops): + """Step 0 is to check which operator in FP16 causes most loss""" + fp32_logits = ["--io_block_list", "logits"] + task.run(fp16_baseline + fp32_logits, "FP16 except logits") + + fp32_io = ["--keep_io_types"] + task.run(fp16_baseline + fp32_io, "Graph I/O FP32, Other FP16") + + # Only weights in FP16 + task.run( + fp16_baseline + fp32_io + ["--op_block_list"] + list(all_ops) + ["--force_fp16_initializers"], + "FP32 except weights in FP16", + ) + + optimized_ops_results = [] + op_list = optimized_ops + for op in op_list: + op_block_list = ["--op_block_list"] + [o for o in op_list if o != op] + result = task.run(fp16_baseline + fp32_io + op_block_list, f"FP32 except {op} in FP16") + if result: + optimized_ops_results.append(result) + + # Check which optimized operator causes the most loss in precision + min_result = min(optimized_ops_results, key=lambda y: y["top1_match_rate"]) + print("step 0: optimized operator causes the most loss in precision", min_result) + + +def run_tuning_step1(task, mixed_precision_baseline, optimized_ops): + """Step 1 is to figure out which optimized operator in FP32 could benefit most""" + for op in optimized_ops: + op_block_list = ["--op_block_list", op] + task.run( + mixed_precision_baseline + op_block_list, + f"Mixed precision baseline + {op} in FP32", + ) + + +def run_tuning_step2(task, mixed_precision_baseline, optimized_ops): + """Assumed that you have run step 0 and 1 to figure out that Logits FP32 and some operators shall be in FP32, + This step will try add one more operator. + """ + candidate_fp32_ops = ["FastGelu", "LayerNormalization", "SkipLayerNormalization"] + fp32_ops = [x for x in candidate_fp32_ops if x in optimized_ops] + for op in optimized_ops: + if op not in fp32_ops: + op_block_list = [*fp32_ops, op] + task.run( + [*mixed_precision_baseline, "--op_block_list", *op_block_list], + "Mixed precision baseline + {},{} in FP32".format(",".join(fp32_ops), op), + ) + + +def run_parity(task: ParityTask, args): + onnx_model_paths = Gpt2Helper.get_onnx_paths( + "onnx_models", + args.model_name_or_path, + new_folder=args.use_external_data_format, + remove_existing=[], + ) + + fp32_baseline, fp16_baseline = get_baselines(args) + + result = task.run(fp32_baseline, "FP32 baseline") + + optimized_ops = [] + if result and ("optimized_operators" in result) and result["optimized_operators"]: + optimized_ops = result["optimized_operators"].split(",") + else: + raise RuntimeError("Failed to get optimized operators") + + all_ops = [] + if result and ("operators" in result) and result["operators"]: + all_ops = result["operators"].split(",") + else: + raise RuntimeError("Failed to get operators") + + # The following tests for fp16 requires GPU + if not args.use_gpu: + logger.info("skip mixed precision since --use_gpu is not specified") + return + + task.run(fp16_baseline, "FP16 baseline") + + last_matmul_node_name = get_last_matmul_node_name(onnx_model_paths["raw"]) + + # Mixed precision baseline + run_candidate(task, args, last_matmul_node_name, op_block_list=[]) + + def get_fp32_ops(x): + return [op for op in x if op in all_ops] + + if args.all: + run_tuning_step0(task, fp16_baseline, all_ops, optimized_ops) + mixed_precision_baseline = get_mixed_precision_parameters(args, last_matmul_node_name, op_block_list=[]) + run_tuning_step1(task, mixed_precision_baseline, optimized_ops) + run_tuning_step2(task, mixed_precision_baseline, optimized_ops) + else: + run_candidate( + task, + args, + last_matmul_node_name, + op_block_list=get_fp32_ops(["SkipLayerNormalization", "LayerNormalization", "Add"]), + ) + run_candidate(task, args, last_matmul_node_name, op_block_list=["FastGelu"]) + + # Run a few good candidates + run_candidate( + task, + args, + last_matmul_node_name, + op_block_list=get_fp32_ops(["FastGelu", "SkipLayerNormalization", "LayerNormalization", "Add"]), + ) + run_candidate( + task, + args, + last_matmul_node_name, + op_block_list=get_fp32_ops( + ["FastGelu", "EmbedLayerNormalization", "SkipLayerNormalization", "LayerNormalization", "Add"] + ), + ) + + +if __name__ == "__main__": + args = parse_arguments() + setup_logger(args.verbose) + + if args.test_cases < 100 or args.runs < 20 or args.test_cases * args.runs < 10000: + logger.warning( + "Not enough test cases or runs to get stable results or test significance. " + "Recommend test_cases >= 100, runs >= 20, test_cases * runs >= 10000." + ) + + if os.path.exists(args.csv) and not args.skip_test: + if not args.overwrite: + raise RuntimeError( + f"Output file {args.csv} existed. Please remove the file, or use either --skip_test or --overwrite." + ) + else: + logger.info("Remove existing file %s since --overwrite is specified", args.csv) + os.remove(args.csv) + + task = ParityTask(args.test_cases, args.runs, args.csv) + + if not args.skip_test: + run_parity(task, args) + + try: + rows = load_results_from_csv(task.csv_path) + except Exception: + logger.exception(f"Failed to load csv {task.csv_path}") + rows = task.results + + logger.info("Start running significance tests...") + summary_csv = task.csv_path.replace(".csv", ".stats.csv") + run_significance_test(rows, summary_csv) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/gpt2/gpt2_tester.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/gpt2/gpt2_tester.py new file mode 100644 index 0000000000000000000000000000000000000000..1b832e3241dd63b335f252cc25f77d59b5ca1960 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/gpt2/gpt2_tester.py @@ -0,0 +1,501 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- +# This script helps evaluation of GPT-2 model. +import logging +import math +import os +import statistics +import timeit + +import numpy +import torch +from benchmark_helper import Precision +from gpt2_helper import Gpt2Helper, Gpt2Inputs + +logger = logging.getLogger(__name__) + + +class Gpt2Metric: + def __init__(self, treatment_name, baseline_name="Torch", top_k=20): + assert top_k > 1 and top_k <= 100 + self.baseline = baseline_name + self.treatment = treatment_name + self.name: str = f"{treatment_name} vs {baseline_name}" + self.top_k = top_k + self.top_1_error: int = 0 + self.top_k_error: int = 0 + self.total_samples: int = 0 + self.max_logits_diff: float = 0 # for non-empty past state + self.max_logits_diff_no_past: float = 0 # for empty past state + self.batch_top1_error: torch.FloatTensor = None # top 1 error for current batch + self.batch_topk_error: torch.FloatTensor = None # top k error for current batch + self.seq_len_latency = {} + + def print(self): + if self.baseline != self.treatment: + print("---") + print(f"Metrics for {self.treatment} (baseline={self.baseline}):") + if self.total_samples > 0: + top_1_error_rate = 100.0 * self.top_1_error / self.total_samples + top_k_error_rate = 100.0 * self.top_k_error / self.total_samples + print( + f"Total={self.total_samples} Top1Error={self.top_1_error} ({top_1_error_rate:.2f}%) Top{self.top_k}Error={self.top_k_error} ({top_k_error_rate:.2f}%)" + ) + print("Max logits diffs:") + print(f"\twith past = {self.max_logits_diff:.6f}") + print(f"\tempty past = {self.max_logits_diff_no_past:.6f}") + else: + print(f"Metrics for {self.treatment} (baseline):") + + if self.seq_len_latency: + print("Past sequence length range and average latency:") + total = 0 + count = 0 + for key in sorted(self.seq_len_latency.keys()): + average = statistics.mean(self.seq_len_latency[key]) * 1000.0 + if key == 0: + print(f"\t{key}: \t{average:.2f} ms") + else: + print(f"\t[{2**key}, {2 ** (key + 1) - 1}]:\t{average:.2f} ms") + total += average * len(self.seq_len_latency[key]) + count += len(self.seq_len_latency[key]) + print(f"Average Latency: {total / count:.2f} ms") + + def diff_logits(self, baseline_logits, treatment_logits, is_empty_past: bool): + diff = (baseline_logits - treatment_logits).abs().max() + if is_empty_past: + self.max_logits_diff_no_past = max(self.max_logits_diff_no_past, diff) + else: + self.max_logits_diff = max(self.max_logits_diff, diff) + + return diff + + def start_batch(self, batch_size: int): + self.total_samples += batch_size + self.batch_top1_error = torch.zeros((batch_size, 1), dtype=torch.bool) + self.batch_topk_error = torch.zeros((batch_size, 1), dtype=torch.bool) + + def eval_batch(self, baseline, treatment, past_seq_len, verbose=True): + self._eval_topk(baseline.top_1_tokens, treatment.top_1_tokens, 1, verbose) + self._eval_topk(baseline.top_k_tokens, treatment.top_k_tokens, self.top_k, verbose) + + max_diff = self.diff_logits(baseline.logits, treatment.logits, past_seq_len == 0) + if verbose: + print(f"Max logits diffs of {self.name}: {max_diff}") + + def _eval_topk(self, baseline_topk, treatment_topk, top_k, verbose=True): + if not torch.all(torch.eq(baseline_topk, treatment_topk)): + if top_k == 1: + if verbose: + print(f"Generated tokens not matched for {self.name}") + self.batch_top1_error |= torch.eq(baseline_topk, treatment_topk).logical_not() + else: + if verbose: + print( + f"Top {top_k} tokens not matched for {self.name}. This will lead to wrong beam search results" + ) + self.batch_topk_error |= ( + torch.eq(baseline_topk, treatment_topk).logical_not().sum(1).unsqueeze(dim=1) > 0 + ) + + def end_batch(self): + self.top_1_error += self.batch_top1_error.sum() + self.top_k_error += self.batch_topk_error.sum() + + def add_latency(self, past_seq_len, latency): + key = int(math.log2(past_seq_len)) + 1 if past_seq_len > 0 else 0 + if key not in self.seq_len_latency: + self.seq_len_latency[key] = [] + self.seq_len_latency[key].append(latency) + + +class Gpt2Tester: + def __init__( + self, + input_ids, + position_ids, + attention_mask, + num_attention_heads, + hidden_size, + num_layer, + device, + is_fp16=False, + top_k=20, + top_k_required_order=False, + ): + self.batch_size = input_ids.shape[0] + self.input_length = input_ids.shape[1] + self.n_layer = num_layer + + self.input_ids = input_ids + self.position_ids = position_ids + self.attention_mask = attention_mask + + self.has_position_ids = position_ids is not None + self.has_attention_mask = attention_mask is not None + + # Empty past state for first inference + self.past = [] + past_shape = [ + 2, + self.batch_size, + num_attention_heads, + 0, + hidden_size // num_attention_heads, + ] + for _i in range(num_layer): + empty_past = torch.empty(past_shape).type(torch.float16 if is_fp16 else torch.float32) + self.past.append(empty_past.to(device)) + + self.logits = None + self.top_1_tokens = None + self.top_k_tokens = None + self.top_k = top_k + self.top_k_required_order = top_k_required_order + + def get_inputs(self) -> Gpt2Inputs: + return Gpt2Inputs(self.input_ids, self.position_ids, self.attention_mask, self.past) + + def save_test_data(self, session, output, save_test_data_dir, test_case_id): + from onnx import numpy_helper # noqa: PLC0415 + + path = os.path.join(save_test_data_dir, "test_data_set_" + str(test_case_id)) + if os.path.exists(path): + print(f"Directory {path} existed. Skip saving test data") + return + + os.makedirs(path, exist_ok=True) + + def add_tensor(input_tensors, torch_tensor, name): + input_tensors.append(numpy_helper.from_array(torch_tensor.clone().cpu().numpy(), name)) + + input_tensors = [] + add_tensor(input_tensors, self.input_ids, "input_ids") + + if self.has_position_ids: + add_tensor(input_tensors, self.position_ids, "position_ids") + + if self.has_attention_mask: + add_tensor(input_tensors, self.attention_mask, "attention_mask") + + for i in range(self.n_layer): + add_tensor(input_tensors, self.past[i], "past_" + str(i)) + + for i, tensor in enumerate(input_tensors): + with open(os.path.join(path, f"input_{i}.pb"), "wb") as f: + f.write(tensor.SerializeToString()) + + output_names = [output.name for output in session.get_outputs()] + for i, _name in enumerate(output_names): + tensor = numpy_helper.from_array( + output[i] if isinstance(output[i], numpy.ndarray) else output[i].clone().cpu().numpy() + ) + with open(os.path.join(path, f"output_{i}.pb"), "wb") as f: + f.write(tensor.SerializeToString()) + + print(f"Test data saved to directory {path}") + + def update(self, output, step, device): + """ + Update the inputs for next inference. + """ + self.logits = ( + torch.from_numpy(output[0]) if isinstance(output[0], numpy.ndarray) else output[0].clone().detach().cpu() + ) + + self.top_1_tokens = Gpt2Tester.predict_next_token(self.logits) + self.top_k_tokens = Gpt2Tester.predict_next_token(self.logits, self.top_k, self.top_k_required_order) + + self.input_ids = self.top_1_tokens.clone().detach().reshape([self.batch_size, 1]).to(device) + + if self.has_position_ids: + self.position_ids = ( + torch.tensor([self.input_length + step - 1]).unsqueeze(0).repeat(self.batch_size, 1).to(device) + ) + + if self.has_attention_mask: + self.attention_mask = torch.cat( + [ + self.attention_mask, + torch.ones([self.batch_size, 1]).type_as(self.attention_mask), + ], + 1, + ).to(device) + + self.past = [] + + if isinstance(output[1], tuple): # past in torch output is tuple + self.past = list(output[1]) + else: + for i in range(self.n_layer): + past_i = ( + torch.from_numpy(output[i + 1]) + if isinstance(output[i + 1], numpy.ndarray) + else output[i + 1].clone().detach() + ) + self.past.append(past_i.to(device)) + + def diff(self, baseline): + """ + Compare inputs and logits output. + """ + + print("start diff...") + if self.logits is not None: + max_io_diff = (self.logits - baseline.logits).abs().max() + if max_io_diff > 1e-4: + print(f"Max logits difference is too large: {max_io_diff}") + + if not torch.all(self.input_ids == baseline.input_ids): + print("Input_ids is different", self.input_ids, baseline.input_ids) + + if self.has_position_ids: + if not torch.all(self.position_ids == baseline.position_ids): + print( + "position_ids is different", + self.position_ids, + baseline.position_ids, + ) + + if self.has_attention_mask: + if not torch.all(self.attention_mask == baseline.attention_mask): + print( + "attention_mask is different", + self.attention_mask, + baseline.attention_mask, + ) + + assert len(self.past) == len(baseline.past) + + for i, past_i in enumerate(self.past): + assert past_i.shape == baseline.past[i].shape + if past_i.nelement() > 0: + max_past_diff = (past_i - baseline.past[i]).abs().max() + if max_past_diff > 1e-4: + print(f"max_past_diff[{i}]={max_past_diff}") + + @staticmethod + def predict_next_token(logits, top_k=1, required_order=False): + """ + Get top k topkens based on logits. + """ + + # logits has shape (batch_size, seq_len, vocab_size) + # last token logits has shape (batch_size, vocab_size) + lastTokenLogits = logits[:, -1] # noqa: N806 + if top_k == 1: + generatedTokens = torch.argmax(lastTokenLogits, 1, True) # noqa: N806 + return generatedTokens + else: + topk = torch.argsort(lastTokenLogits, -1, descending=True)[:, :top_k] + if not required_order: + sorted_topk, _ = topk.sort() + return sorted_topk + return topk + + @staticmethod + def diff_present(onnx_output, onnx_io_output, n_layer): + """ + Compare the present outputs of two outputs from ONNX Runtime. + """ + present_diff_max = [] + for i in range(n_layer): + onnx_present_i = ( + torch.from_numpy(onnx_output[i + 1]) + if isinstance(onnx_output[i + 1], numpy.ndarray) + else onnx_output[i + 1] + ) + onnx_io_present_i = ( + torch.from_numpy(onnx_io_output[i + 1]) + if isinstance(onnx_io_output[i + 1], numpy.ndarray) + else onnx_io_output[i + 1] + ) + max_diff = (onnx_present_i - onnx_io_present_i).abs().max() + present_diff_max.append(max_diff) + print(f"present_diff_max={present_diff_max}") + + @staticmethod + def is_quantized_onnx_model(onnx_model_path): + """ + Returns True if the ONNX model is quantized. + """ + from onnx import load # noqa: PLC0415 + + model = load(onnx_model_path) + from onnxruntime.quantization.quantize import __producer__ as quantize_producer # noqa: PLC0415 + + return model.producer_name == quantize_producer + + @staticmethod + def test_generation( + session, + model, + device, + test_inputs, + precision=Precision.FLOAT32, + model_class="Gpt2LMHeadModel", + top_k=20, + top_k_no_order=True, + max_steps=24, + max_inputs=0, + verbose=False, + save_test_data=0, + save_test_data_dir=".", + ): + """ + Test Generation using greedy beam search (without sampling) to compare PyTorch and ONNX model. + It will print top 1 and top k errors on the given test inputs. + """ + print( + f"start test generation: (top_k={top_k} top_k_no_order={top_k_no_order} max_steps={max_steps} test_inputs={len(test_inputs)} max_inputs={max_inputs})" + ) + n_layer = model.config.n_layer + n_head = model.config.n_head + n_embd = model.config.n_embd + eos_token_id = model.config.eos_token_id + test_data_saved = 0 + + is_float16 = precision == Precision.FLOAT16 + if is_float16: + assert "float16" in session.get_outputs()[0].type + + # We will still use fp32 torch model as baseline when onnx model if fp16 + model.eval().to(device) + + # Allocate initial buffers for IO Binding of ONNX Runtimne. The buffer size will automatically increase later. + init_output_shapes = Gpt2Helper.get_output_shapes( + batch_size=4, + past_sequence_length=128, + sequence_length=32, + config=model.config, + model_class=model_class, + ) + output_buffers = Gpt2Helper.get_output_buffers(init_output_shapes, device, is_float16=is_float16) + + baseline_name = "Torch" + treatment_name = "Quantized Onnx" if precision == Precision.INT8 else "Onnx" + torch_metric = Gpt2Metric(baseline_name, baseline_name, top_k) + onnx_metric = Gpt2Metric(treatment_name, baseline_name, top_k) + onnx_io_metric = Gpt2Metric(treatment_name + " with IO Binding", baseline_name, top_k) + + for i, inputs in enumerate(test_inputs): + if max_inputs > 0 and i == max_inputs: + break + if i % 10 == 0: + print(f"{i}") + input_ids = inputs["input_ids"] + position_ids = inputs.get("position_ids", None) + attention_mask = inputs.get("attention_mask", None) + + onnx_runner = Gpt2Tester( + input_ids, + position_ids, + attention_mask, + n_head, + n_embd, + n_layer, + device, + is_float16, + top_k, + not top_k_no_order, + ) + onnx_io_runner = Gpt2Tester( + input_ids, + position_ids, + attention_mask, + n_head, + n_embd, + n_layer, + device, + is_float16, + top_k, + not top_k_no_order, + ) + torch_runner = Gpt2Tester( + input_ids, + position_ids, + attention_mask, + n_head, + n_embd, + n_layer, + device, + False, + top_k, + not top_k_no_order, + ) # Torch model baseline is fp32 + + batch_size = torch_runner.batch_size + onnx_metric.start_batch(batch_size) + onnx_io_metric.start_batch(batch_size) + + with torch.no_grad(): + done = torch.zeros(batch_size, dtype=torch.bool) + for step in range(max_steps): + seq_len = list(onnx_runner.input_ids.size())[1] + past_seq_len = list(onnx_runner.past[0].size())[3] + + start_time = timeit.default_timer() + pytorch_output = Gpt2Helper.pytorch_inference(model, torch_runner.get_inputs()) + torch_metric.add_latency(past_seq_len, timeit.default_timer() - start_time) + torch_runner.update(pytorch_output, step, device) + + onnx_output, avg_latency_ms = Gpt2Helper.onnxruntime_inference( + session, onnx_runner.get_inputs(), total_runs=1 + ) + onnx_metric.add_latency(past_seq_len, avg_latency_ms / 1000.0) + onnx_runner.update(onnx_output, step, device) + + output_shapes = Gpt2Helper.get_output_shapes( + batch_size, + past_seq_len, + seq_len, + model.config, + model_class=model_class, + ) + Gpt2Helper.auto_increase_buffer_size(output_buffers, output_shapes) + + ( + onnx_io_output, + avg_latency_ms, + ) = Gpt2Helper.onnxruntime_inference_with_binded_io( + session, + onnx_io_runner.get_inputs(), + output_buffers, + output_shapes, + total_runs=1, + return_numpy=False, + include_copy_output_latency=True, + ) + onnx_io_metric.add_latency(past_seq_len, avg_latency_ms / 1000.0) + + if test_data_saved < save_test_data: + onnx_io_runner.save_test_data(session, onnx_io_output, save_test_data_dir, test_data_saved) + test_data_saved += 1 + + onnx_io_runner.update(onnx_io_output, step, device) + + if verbose: + onnx_runner.diff(onnx_io_runner) + Gpt2Tester.diff_present(onnx_output, onnx_io_output, n_layer) + + print("Top 1 tokens:") + print("\tTorch", torch_runner.top_1_tokens) + print("\tONNX", onnx_runner.top_1_tokens) + print("\tONNX with IO binding", onnx_io_runner.top_1_tokens) + + onnx_metric.eval_batch(torch_runner, onnx_runner, past_seq_len, verbose=verbose) + onnx_io_metric.eval_batch(torch_runner, onnx_io_runner, past_seq_len, verbose=verbose) + + done = done | (torch_runner.top_1_tokens == eos_token_id).any() + if torch.all(done): + break + + onnx_metric.end_batch() + onnx_io_metric.end_batch() + + torch_metric.print() + onnx_metric.print() + onnx_io_metric.print() diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/gpt2/parity_check_helper.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/gpt2/parity_check_helper.py new file mode 100644 index 0000000000000000000000000000000000000000..2d514ed2f8b3769579dc1c267a7a76f382447a68 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/gpt2/parity_check_helper.py @@ -0,0 +1,146 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- +# This script helps debugging parity issue for two same onnx models with fp16 and fp32 format +# Please build ORT with --cmake_extra_defines onnxruntime_DEBUG_NODE_INPUTS_OUTPUTS=ON + +import math +import multiprocessing +import os +from pathlib import Path + +import numpy +import torch +from benchmark_helper import create_onnxruntime_session +from gpt2_helper import Gpt2Helper +from onnx import TensorProto, numpy_helper + +NON_ZERO_VALUE = str(1) +ZERO_VALUE = str(0) + + +def environ_setting_nodes(node_name_filter=None, node_type_filter=None): + # Set I/O data as default + os.environ["ORT_DEBUG_NODE_IO_DUMP_SHAPE_DATA"] = ZERO_VALUE + os.environ["ORT_DEBUG_NODE_IO_DUMP_INPUT_DATA"] = NON_ZERO_VALUE + os.environ["ORT_DEBUG_NODE_IO_DUMP_OUTPUT_DATA"] = NON_ZERO_VALUE + if node_name_filter is not None: + os.environ["ORT_DEBUG_NODE_IO_NAME_FILTER"] = node_name_filter + elif node_type_filter is not None: + os.environ["ORT_DEBUG_NODE_IO_OP_TYPE_FILTER"] = node_type_filter + else: + os.environ["ORT_DEBUG_NODE_IO_DUMPING_DATA_TO_FILES_FOR_ALL_NODES_IS_OK"] = NON_ZERO_VALUE + + +def environ_setting_paths(output_path): + # Set dumping values to files as default + os.environ["ORT_DEBUG_NODE_IO_DUMP_DATA_DESTINATION"] = "files" + os.environ["ORT_DEBUG_NODE_IO_OUTPUT_DIR"] = output_path + + +def environ_reset(): + for flag in [ + "ORT_DEBUG_NODE_IO_DUMP_SHAPE_DATA", + "ORT_DEBUG_NODE_IO_DUMP_INPUT_DATA", + "ORT_DEBUG_NODE_IO_DUMP_OUTPUT_DATA", + "ORT_DEBUG_NODE_IO_NAME_FILTER", + "ORT_DEBUG_NODE_IO_OP_TYPE_FILTER", + "ORT_DEBUG_NODE_IO_DUMP_DATA_TO_FILES", + "ORT_DEBUG_NODE_IO_OUTPUT_DIR", + "ORT_DEBUG_NODE_IO_DUMPING_DATA_TO_FILES_FOR_ALL_NODES_IS_OK", + ]: + if flag in os.environ: + del os.environ[flag] + + +def inference(model_path, dummy_inputs, outputs_path, use_gpu): + environ_reset() + environ_setting_nodes() + environ_setting_paths(outputs_path) + session = create_onnxruntime_session(model_path, use_gpu, enable_all_optimization=False) + Gpt2Helper.onnxruntime_inference(session, dummy_inputs) + + +def generate_outputs_files(model_path, dummy_inputs, outputs_path, use_gpu): + dir_path = Path(outputs_path) + if dir_path.exists() and dir_path.is_dir(): + import shutil # noqa: PLC0415 + + shutil.rmtree(outputs_path) + dir_path.mkdir(parents=True, exist_ok=True) + + process = multiprocessing.Process(target=inference, args=(model_path, dummy_inputs, outputs_path, use_gpu)) + process.start() + process.join() + + +def post_processing(outputs_path, outputs_path_other): + # Compare outputs with e.g. fp16 and fp32 + record = {} + if_close = {} + + import glob # noqa: PLC0415 + + for filename in glob.glob(os.path.join(outputs_path, "*.tensorproto")): + filename_other = os.path.join(outputs_path_other, Path(filename).name) + if not os.path.exists(filename_other): + continue + with open(filename, "rb") as f: + tensor = TensorProto() + tensor.ParseFromString(f.read()) + array = numpy_helper.to_array(tensor) + with open(filename_other, "rb") as f: # noqa: PLW2901 + tensor_other = TensorProto() + tensor_other.ParseFromString(f.read()) + array_other = numpy_helper.to_array(tensor_other) + if array_other.size == 0: + continue + diff = numpy.average(numpy.abs(array_other - array) / (numpy.abs(array_other) + 1e-6)) + if math.isnan(diff): + continue + record[Path(filename).name.split(".")[0]] = diff + if_close[Path(filename).name.split(".")[0]] = numpy.allclose(array, array_other, rtol=1e-04, atol=1e-04) + + results = ["Node\tDiff\tClose"] + for k, v in sorted(record.items(), key=lambda x: x[1], reverse=True): + results.append(f"{k}\t{v}\t{if_close[k]}") + for line in results: + print(line) + + +if __name__ == "__main__": + # Below example shows how to use this helper to investigate parity issue of gpt-2 fp32 and fp16 onnx model + # Please build ORT with --cmake_extra_defines onnxruntime_DEBUG_NODE_INPUTS_OUTPUTS=ON !! + multiprocessing.set_start_method("spawn") + + # Generate Inputs + sequence_length = 8 + past_sequence_length = 8 + batch_size = 5 + dummy_inputs_fp16 = Gpt2Helper.get_dummy_inputs( + batch_size, + past_sequence_length, + sequence_length, + 12, + 768, + 12, + 50257, + device=torch.device("cpu"), + float16=True, + ) + dummy_inputs_fp32 = dummy_inputs_fp16.to_fp32() + + # Get GPT-2 model from huggingface using convert_to_onnx.py + os.system("python convert_to_onnx.py -m gpt2 --output gpt2_fp32.onnx -o -p fp32 --use_gpu") + os.system("python convert_to_onnx.py -m gpt2 --output gpt2_fp16.onnx -o -p fp16 --use_gpu") + + # Specify the directory to dump the node's I/O + outputs_path_fp32_gpu = "./fp32_gpu" + outputs_path_fp16_gpu = "./fp16_gpu" + generate_outputs_files("./gpt2_fp32.onnx", dummy_inputs_fp32, outputs_path_fp32_gpu, use_gpu=True) + generate_outputs_files("./gpt2_fp16.onnx", dummy_inputs_fp16, outputs_path_fp16_gpu, use_gpu=True) + + # Compare each node's I/O value and sort based on average rtol + post_processing(outputs_path_fp16_gpu, outputs_path_fp32_gpu) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/llama/__init__.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/llama/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8f9a57c902589567201d260a9248c59309a74576 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/llama/__init__.py @@ -0,0 +1,12 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +# -------------------------------------------------------------------------- +import os +import sys + +sys.path.append(os.path.dirname(__file__)) + +transformers_dir = os.path.normpath(os.path.join(os.path.dirname(__file__), "..", "..")) +if transformers_dir not in sys.path: + sys.path.append(transformers_dir) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/llama/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/llama/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fde4d70bbbef9f6dec6d9aa49f9e9ecb52d9804c Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/llama/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/llama/__pycache__/benchmark.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/llama/__pycache__/benchmark.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2bf2c0f8c6578a92d18258518a7c9028f76bdedb Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/llama/__pycache__/benchmark.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/llama/__pycache__/benchmark_all.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/llama/__pycache__/benchmark_all.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..597789c5fc55d69d9c06006842660595a8c40cb5 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/llama/__pycache__/benchmark_all.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/llama/__pycache__/benchmark_e2e.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/llama/__pycache__/benchmark_e2e.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dbce9ef360d57b161fe586f1e6bd135ff314bb9e Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/llama/__pycache__/benchmark_e2e.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/llama/__pycache__/convert_to_onnx.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/llama/__pycache__/convert_to_onnx.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..789c785a68e025d2f91b87e803ab1ed833a47ad1 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/llama/__pycache__/convert_to_onnx.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/llama/__pycache__/dist_settings.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/llama/__pycache__/dist_settings.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..96e16e4b74e624d4fad2659fac54ecdccf023e4e Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/llama/__pycache__/dist_settings.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/llama/__pycache__/llama_inputs.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/llama/__pycache__/llama_inputs.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c0ce32ea4307e98611c706f173fe6ac7847e6d1f Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/llama/__pycache__/llama_inputs.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/llama/__pycache__/llama_parity.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/llama/__pycache__/llama_parity.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..04113296160f94b3e4141be9cb5ffc565bd1c962 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/llama/__pycache__/llama_parity.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/llama/__pycache__/llama_torch.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/llama/__pycache__/llama_torch.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..41eea1a88db8d44d1af1d30aa8a98a0a90c4620d Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/llama/__pycache__/llama_torch.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/llama/__pycache__/quant_kv_dataloader.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/llama/__pycache__/quant_kv_dataloader.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..314ed34b203b93cdde353d3376e3046dd719f0c7 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/llama/__pycache__/quant_kv_dataloader.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/llama/benchmark.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/llama/benchmark.py new file mode 100644 index 0000000000000000000000000000000000000000..656d67f46342b86c91d52680fb05d484ea8d5c1f --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/llama/benchmark.py @@ -0,0 +1,700 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- +import argparse +import datetime +import gc +import itertools +import logging +import os +import sys +import time + +import numpy as np +import onnx +import psutil +import torch +from benchmark_helper import measure_memory, setup_logger +from dist_settings import get_rank, get_size +from llama_inputs import ( + add_io_bindings_as_ortvalues, + get_merged_sample_with_past_kv_inputs, + get_msft_sample_inputs, + get_sample_inputs, + get_sample_with_past_kv_inputs, + verify_ort_inputs, +) +from optimum.onnxruntime import ORTModelForCausalLM +from torch.profiler import ProfilerActivity, profile, record_function +from tqdm import trange +from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer + +import onnxruntime as ort + +logger = logging.getLogger(__name__) + + +# For determining whether the ONNX model can do both prompt generation and token generation or only one of the two +def get_ort_model_inputs_len(args, model): + if args.benchmark_type in {"hf-pt-eager", "hf-pt-compile"}: + return 0 + if args.benchmark_type == "hf-ort": + try: + # New Optimum export (https://github.com/huggingface/optimum/blob/888332364c2e0091da1fc974737c7e277af168bf/optimum/onnxruntime/modeling_ort.py#L268) + return len(model.inputs_names) + except Exception: + # Old Optimum export (https://github.com/huggingface/optimum/blob/c5ad7f971cb0a494eac03dc0909f146725f999c5/optimum/onnxruntime/base.py#L54) + return len(model.decoder.input_names) + return len(model.get_inputs()) + + +def get_inputs(args: argparse.Namespace, ort_model_inputs_len: int): + init_inputs, iter_inputs = None, None + + # For past_present_share_buffer: + # Set max_seq_len to 2048 for Microsoft LLaMA-2 model since that is the max value currently supported + # Set max_seq_len to config value for other models + max_seq_len = 2048 if args.benchmark_type == "ort-msft" else args.config.max_position_embeddings + + if args.benchmark_type in {"hf-pt-eager", "hf-pt-compile"}: + init_inputs = get_sample_inputs( + args.config, + args.target_device, + args.batch_size, + args.sequence_length, + return_dict=True, + ) + iter_inputs = get_sample_with_past_kv_inputs( + args.config, + args.target_device, + args.batch_size, + args.sequence_length, + use_fp16=args.use_fp16, + return_dict=True, + ) + + elif args.benchmark_type in {"hf-ort"}: + if ort_model_inputs_len == 3: # [input_ids, attention_mask, position_ids] + # Using split models in Optimum (e.g. created by Optimum export) + init_inputs = get_sample_inputs( + args.config, + args.target_device, + args.batch_size, + args.sequence_length, + return_dict=True, + ) + iter_inputs = get_sample_with_past_kv_inputs( + args.config, + args.target_device, + args.batch_size, + args.sequence_length, + use_fp16=args.use_fp16, + return_dict=True, + ) + else: + # Using merged model in Optimum (e.g. created by convert_to_onnx export) + init_inputs = get_merged_sample_with_past_kv_inputs( + args.config, + args.target_device, + args.batch_size, + seq_len=args.sequence_length, + past_seq_len=0, + max_seq_len=max_seq_len, + use_fp16=args.use_fp16, + use_buffer_share=args.use_buffer_share, + engine="pt", + return_dict=True, + ) + iter_inputs = get_merged_sample_with_past_kv_inputs( + args.config, + args.target_device, + args.batch_size, + seq_len=1, + past_seq_len=args.sequence_length, + max_seq_len=max_seq_len, + use_fp16=args.use_fp16, + use_buffer_share=args.use_buffer_share, + engine="pt", + return_dict=True, + ) + + elif args.benchmark_type == "ort-convert-to-onnx": + # Microsoft export from convert_to_onnx + init_inputs = get_merged_sample_with_past_kv_inputs( + args.config, + args.target_device, + args.batch_size, + seq_len=args.sequence_length, + past_seq_len=0, + max_seq_len=max_seq_len, + use_fp16=args.use_fp16, + use_buffer_share=args.use_buffer_share, + engine="ort", + return_dict=True, + world_size=args.world_size, + ) + iter_inputs = get_merged_sample_with_past_kv_inputs( + args.config, + args.target_device, + args.batch_size, + seq_len=1, + past_seq_len=args.sequence_length, + max_seq_len=max_seq_len, + use_fp16=args.use_fp16, + use_buffer_share=args.use_buffer_share, + engine="ort", + return_dict=True, + world_size=args.world_size, + ) + + elif args.benchmark_type == "ort-msft": + # Microsoft export from https://github.com/microsoft/Llama-2-Onnx + split_kv = ort_model_inputs_len > 5 # original inputs: [x, attn_mask, k_cache, v_cache, pos] + + init_inputs = get_msft_sample_inputs( + args.config, + args.batch_size, + past_seq_len=0, + seq_len=args.sequence_length, + max_seq_len=max_seq_len, + use_fp16=args.use_fp16, + use_buffer_share=args.use_buffer_share, + split_kv=split_kv, + ) + iter_inputs = get_msft_sample_inputs( + args.config, + args.batch_size, + past_seq_len=args.sequence_length, + seq_len=1, + max_seq_len=max_seq_len, + use_fp16=args.use_fp16, + use_buffer_share=args.use_buffer_share, + split_kv=split_kv, + ) + + else: + raise Exception("Unable to auto-detect inputs for provided model") + + return init_inputs, iter_inputs + + +def get_model(args: argparse.Namespace): + model, sess_options = None, None + start_time, end_time = None, None + + # There are multiple sources that the model could come from: + # 1) Benchmark LLaMA-2 from unofficial source on Hugging Face + # 2) Benchmark LLaMA-2 from official source on Hugging Face, which requires an authentication token + # 3) Benchmark LLaMA-2 from local download of model + # 4) Benchmark LLaMA-2 from Microsoft (already optimized, available at https://github.com/microsoft/Llama-2-Onnx) + # 5) Benchmark LLaMA-2 from convert_to_onnx + + if args.benchmark_type in {"hf-pt-eager", "hf-pt-compile"}: + source = args.hf_pt_dir_path if args.hf_pt_dir_path else args.model_name + start_time = time.time() + model = AutoModelForCausalLM.from_pretrained( + source, + torch_dtype=torch.float16 if args.use_fp16 else torch.float32, + use_auth_token=args.auth, + trust_remote_code=args.auth, + use_cache=True, + cache_dir=args.cache_dir, + ).to(args.target_device) + end_time = time.time() + + if args.benchmark_type == "hf-pt-compile": + model = torch.compile(model) + + elif args.benchmark_type in {"hf-ort", "ort-msft", "ort-convert-to-onnx"}: + sess_options = ort.SessionOptions() + sess_options.enable_profiling = args.profile + if args.verbose: + sess_options.log_verbosity_level = 1 + sess_options.log_severity_level = 1 + + else: + raise Exception(f"Cannot recognize {args.benchmark_type}") + + if args.benchmark_type == "hf-ort": + # Optimum export or convert_to_onnx.py export + provider = args.execution_provider[0] if type(args.execution_provider) is tuple else args.execution_provider + provider_options = args.execution_provider[1] if type(args.execution_provider) is tuple else None + + decoder_file_name = None + decoder_with_past_file_name = None + for filename in os.listdir(args.hf_ort_dir_path): + if ".onnx" not in filename or ".onnx_data" in filename or ".onnx.data" in filename: + continue + if "decoder_model" in filename or filename == "model.onnx": + decoder_file_name = filename + if "decoder_with_past_model" in filename: + decoder_with_past_file_name = filename + if "decoder_merged_model" in filename: + decoder_file_name = filename + decoder_with_past_file_name = filename + + start_time = time.time() + model = ORTModelForCausalLM.from_pretrained( + args.hf_ort_dir_path, + decoder_file_name=decoder_file_name, + decoder_with_past_file_name=decoder_with_past_file_name, + use_auth_token=args.auth, + trust_remote_code=args.auth, + use_io_binding=True, # Large perf gain even for cpu due to avoiding output copy. + use_merged=(True if decoder_file_name == "model.onnx" else None), + provider=provider, + provider_options=provider_options, + session_options=sess_options, + ) + end_time = time.time() + + if args.benchmark_type in {"ort-msft", "ort-convert-to-onnx"}: + # Ex: Microsoft export from https://github.com/microsoft/Llama-2-Onnx + logger.info(f"Loading model from {args.ort_model_path.format(args.rank)}") + start_time = time.time() + model = ort.InferenceSession( + args.ort_model_path.format(args.rank), + sess_options, + providers=[args.execution_provider], + ) + end_time = time.time() + + logger.info(f"Loaded model in {end_time - start_time} s") + return model + + +def time_fn(args, fn, inputs): + # Warm up + warmup_range = ( + range(args.warmup_runs) + if args.benchmark_type in {"ort-msft", "ort-convert-to-onnx"} + else trange(args.warmup_runs, file=sys.stdout, desc="Warm up") + ) + + if args.verbose: + outputs = fn(inputs) + logger.info(outputs) + + input_sync = lambda *kwargs: ( # noqa: E731 + args.io_binding.synchronize_inputs() + if args.device != "cpu" and args.benchmark_type in {"ort-msft", "ort-convert-to-onnx"} # ORT synchronize + else lambda *kwargs: ( + torch.cuda.synchronize() + if args.device != "cpu" and torch.cuda.is_available() # PyTorch synchronize + else lambda *kwargs: None + ) + ) # no-op function + + output_sync = lambda *kwargs: ( # noqa: E731 + args.io_binding.synchronize_outputs() + if args.device != "cpu" and args.benchmark_type in {"ort-msft", "ort-convert-to-onnx"} # ORT synchronize + else lambda *kwargs: ( + torch.cuda.synchronize() + if args.device != "cpu" and torch.cuda.is_available() # PyTorch synchronize + else lambda *kwargs: None + ) + ) # no-op function + + for _ in warmup_range: + input_sync() + fn(inputs) + output_sync() + + # Benchmark + total_time = 0 + bench_range = ( + range(args.num_runs) + if args.benchmark_type in {"ort-msft", "ort-convert-to-onnx"} + else trange(args.num_runs, file=sys.stdout, desc="Benchmark") + ) + for _ in bench_range: + input_sync() + start_time = time.time() + + fn(inputs) + + output_sync() + end_time = time.time() + + total_time += end_time - start_time + + # Newline print after trange in order to print metrics on new lines without progress bar on same line + if args.benchmark_type not in {"ort-msft", "ort-convert-to-onnx"}: + logger.info("") + + latency = total_time / args.num_runs + throughput = args.batch_size / latency + + if args.rank == 0: + logger.info(f"Batch Size: {args.batch_size}") + logger.info(f"Sequence Length: {args.sequence_length}") + logger.info(f"Latency: {latency} s") + logger.info(f"Throughput: {throughput} tps") + return + + +def profile_fn(args, fn, inputs, inputs_type): + # Filename prefix format: + # "b_s_--___" + prefix = f"b{args.batch_size}_s{args.sequence_length}_{args.benchmark_type.lower()}-{args.precision}-{args.device}_{fn.__name__.replace('_', '-')}_{inputs_type}_{datetime.datetime.now():%Y-%m-%d_%H:%M:%S}" + filename = None + + if args.benchmark_type in {"hf-pt-eager", "hf-pt-compile"}: + # Profile PyTorch kernels + with profile( # noqa: SIM117 + activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA], record_shapes=True, profile_memory=True + ) as prof: + with record_function("model_inference"): + fn(inputs) + prof_data = prof.key_averages(group_by_stack_n=5).table(sort_by=args.pt_filter_by, row_limit=args.pt_num_rows) + + filename = os.path.join(args.log_folder, f"{prefix}.log") + with open(filename, "w") as f: + f.write(prof_data) + + else: + # Profile ORT kernels + fn(inputs) + + # Set new log name for ORT profile log generated + filename = f"{prefix}.json" + + return filename + + +def measure_fn(args, fn, inputs): + # Measure CPU usage + pid = os.getpid() + process = psutil.Process(pid) + process.cpu_percent(interval=0.1) + + fn(inputs) + if args.rank == 0: + logger.info(f"CPU usage: {process.cpu_percent(interval=None) / psutil.cpu_count(logical=False)}%") + + # Measure memory usage + gc.collect() + torch.cuda.empty_cache() + measure_memory(is_gpu=(args.device != "cpu"), func=lambda: fn(inputs)) + + # Flush output so memory usage is printed + sys.stdout.flush() + + +def run_hf_inference(args, init_inputs, iter_inputs, model): + # Inference steps to measure + def get_logits(inputs): + # Inference pass without decoding + outputs = model(**inputs) + return outputs + + # Examples of other inference steps that can be measured: + # To use, uncomment the function and assign it to `generate_fn` + + # def get_pred_ids(inputs): + # # Inference pass with predicted token ids generation + # predicted_ids = model.generate(**inputs) + # return predicted_ids + + # def gen_and_dec(inputs): + # # Inference pass with generation and decoding + # predicted_ids = get_pred_ids(inputs) + # transcription = [] + # for bs in range(args.batch_size): + # for rs in range(args.num_return_sequences): + # transcription.append( + # args.tokenizer.batch_decode( + # predicted_ids[bs * args.num_return_sequences + rs], skip_special_tokens=True + # )[0] + # ) + # return transcription + + generate_fn = get_logits + + if args.benchmark_type == "hf-pt-compile": + # Run forward pass once with each set of inputs to process through Dynamo + generate_fn(init_inputs) + generate_fn(iter_inputs) + + if args.profile: + new_logname = profile_fn(args, generate_fn, init_inputs, "prompt") + if args.benchmark_type == "hf-ort": + # Turn profiling off to stop appending to log + old_logname = model.decoder.session.end_profiling() + logger.warning(f"Renaming {old_logname} to {new_logname}") + os.rename(old_logname, os.path.join(args.log_folder, new_logname)) + + new_logname = profile_fn(args, generate_fn, iter_inputs, "token") + if args.benchmark_type == "hf-ort": + # Turn profiling off to stop appending to log + old_logname = model.decoder_with_past.session.end_profiling() + logger.warning(f"Renaming {old_logname} to {new_logname}") + os.rename(old_logname, os.path.join(args.log_folder, new_logname)) + + return + + # PyTorch evaluations + logger.info("\nEvaluating `model(inputs)` step to get past_key_values") + time_fn(args, generate_fn, init_inputs) + measure_fn(args, generate_fn, init_inputs) + + logger.info("\nEvaluating `model(inputs)` step with past_key_values") + time_fn(args, generate_fn, iter_inputs) + measure_fn(args, generate_fn, iter_inputs) + + +def run_ort_inference(args, init_inputs, iter_inputs, model): + def prepare_ort_inputs(inputs, kv_cache_ortvalues): + # Verify model inputs + inputs = verify_ort_inputs(model, inputs) + + # Add IO bindings for non-CPU execution providers + if args.device != "cpu": + io_binding, kv_cache_ortvalues = add_io_bindings_as_ortvalues( + model, inputs, args.device, int(args.rank), args.use_buffer_share, kv_cache_ortvalues + ) + setattr(args, "io_binding", io_binding) # noqa: B010 + return io_binding, kv_cache_ortvalues + + return inputs, kv_cache_ortvalues + + def with_io_binding(io_binding): + # Inference pass with IO binding + model.run_with_iobinding(io_binding) + + def without_io_binding(inputs): + # Inference pass without IO binding + outputs = model.run(None, inputs) + return outputs + + generate_fn = with_io_binding if args.device != "cpu" else without_io_binding + kv_cache_ortvalues = {} + + if args.profile: + ort_init_inputs, kv_cache_ortvalues = prepare_ort_inputs(init_inputs, kv_cache_ortvalues) + new_logname = profile_fn(args, generate_fn, ort_init_inputs, "prompt") + + # Turn profiling off to stop appending to log file + old_logname = model.end_profiling() + logger.warning(f"Renaming {old_logname} to {new_logname}") + os.rename(old_logname, os.path.join(args.log_folder, new_logname)) + + # Re-initialize model for new log file instead of appending to old log file + model = get_model(args) + ort_iter_inputs, kv_cache_ortvalues = prepare_ort_inputs(iter_inputs, kv_cache_ortvalues) + new_logname = profile_fn(args, generate_fn, ort_iter_inputs, "token") + + # Turn profiling off to stop appending to log + old_logname = model.end_profiling() + logger.warning(f"Renaming {old_logname} to {new_logname}") + os.rename(old_logname, os.path.join(args.log_folder, new_logname)) + return + + # ORT evaluations + logger.info("\nEvaluating `model(inputs)` step to get past_key_values") + ort_init_inputs, kv_cache_ortvalues = prepare_ort_inputs(init_inputs, kv_cache_ortvalues) + time_fn(args, generate_fn, ort_init_inputs) + measure_fn(args, generate_fn, ort_init_inputs) + + logger.info("\nEvaluating `model(inputs)` step with past_key_values") + ort_iter_inputs, kv_cache_ortvalues = prepare_ort_inputs(iter_inputs, kv_cache_ortvalues) + time_fn(args, generate_fn, ort_iter_inputs) + measure_fn(args, generate_fn, ort_iter_inputs) + + +def run_inference(args, init_inputs, iter_inputs, model): + if args.benchmark_type in {"hf-pt-eager", "hf-pt-compile", "hf-ort"}: + run_hf_inference(args, init_inputs, iter_inputs, model) + elif args.benchmark_type in {"ort-msft", "ort-convert-to-onnx"}: + run_ort_inference(args, init_inputs, iter_inputs, model) + else: + raise Exception(f"Cannot recognize {args.benchmark_type}") + + +def get_args(rank=0): + parser = argparse.ArgumentParser() + parser.add_argument( + "-bt", + "--benchmark-type", + type=str, + required=True, + choices=[ + "hf-pt-eager", + "hf-pt-compile", + "hf-ort", + "ort-msft", + "ort-convert-to-onnx", + ], + ) + parser.add_argument( + "-m", + "--model-name", + type=str, + required=True, + help="Hugging Face name of model (e.g. 'meta-llama/Llama-2-7b-hf')", + ) + parser.add_argument( + "-a", "--auth", default=False, action="store_true", help="Use Hugging Face authentication token to access model" + ) + + # Args for choosing the model + parser.add_argument( + "-p", + "--precision", + required=True, + type=str, + default="fp32", + choices=["int4", "int8", "fp16", "fp32"], + help="Precision for model. For ONNX models, the model's precision should be set before running this script.", + ) + parser.add_argument( + "--hf-pt-dir-path", + type=str, + default="", + help="Path to directory containing all PyTorch files (e.g. tokenizer, PyTorch model)", + ) + parser.add_argument( + "--hf-ort-dir-path", + type=str, + default="", + help="Path to directory containing all ONNX files (e.g. tokenizer, decoder_merged, decoder, decoder_with_past)", + ) + parser.add_argument( + "--ort-model-path", + type=str, + default="", + help="Path to ONNX model", + ) + + # Args for running and evaluating the model + parser.add_argument( + "-b", + "--batch-sizes", + default="1 2", + ) + parser.add_argument( + "-s", + "--sequence-lengths", + default="32 64 128 256 512", + ) + parser.add_argument( + "-d", + "--device", + type=str, + default="cuda" if torch.cuda.is_available() else "cpu", + choices=["cpu", "cuda"], + ) + parser.add_argument("-id", "--device-id", type=int, default=0) + parser.add_argument("-w", "--warmup-runs", type=int, default=5) + parser.add_argument("-n", "--num-runs", type=int, default=10) + parser.add_argument("--seed", type=int, default=2) + + # Args for decoding logic + parser.add_argument("--max-length", type=int, default=32) + parser.add_argument("--num-return-sequences", type=int, default=1) + + # Args for accessing detailed info + parser.add_argument("--profile", default=False, action="store_true") + parser.add_argument( + "--pt-filter-by", type=str, default="self_cpu_time_total", help="What to filter PyTorch profiler by" + ) + parser.add_argument("--pt-num-rows", type=int, default=1000, help="Number of rows for PyTorch profiler to display") + parser.add_argument("--verbose", default=False, action="store_true") + parser.add_argument("--log-folder", type=str, default=os.path.join("."), help="Folder to cache log files") + parser.add_argument( + "--cache-dir", + type=str, + required=True, + default="./model_cache", + help="Cache dir where Hugging Face files are stored", + ) + + args = parser.parse_args() + + # Set seed properties + np.random.seed(args.seed) + torch.manual_seed(args.seed) + + # Set runtime properties + if "ort" in args.benchmark_type: + setattr(args, "execution_provider", f"{args.device.upper()}ExecutionProvider") # noqa: B010 + if args.execution_provider == "CUDAExecutionProvider": + args.execution_provider = (args.execution_provider, {"device_id": rank}) + + # Check that paths have been specified for any benchmarking with ORT + if args.benchmark_type == "hf-ort": + assert args.hf_ort_dir_path, "Please specify a path to `--hf-ort-dir-path`" + if args.benchmark_type in {"ort-msft", "ort-convert-to-onnx"}: + assert args.ort_model_path, "Please specify a path to `--ort-model-path`" + + args.batch_sizes = args.batch_sizes.split(" ") + args.sequence_lengths = args.sequence_lengths.split(" ") + + # Use FP32 precision for FP32, INT8, INT4 CPU models, use FP16 precision for FP16 and INT4 GPU models + args.precision = ( + "fp32" if args.precision in {"int8", "fp32"} or (args.precision == "int4" and args.device == "cpu") else "fp16" + ) + + # Check that only one (batch_size, sequence_length) combination is set for profiling + if args.profile: + assert len(args.batch_sizes) == 1 and len(args.sequence_lengths) == 1, ( + "Please provide only one (batch_size, sequence_length) combination for profiling" + ) + + return args + + +def main(): + rank = get_rank() + world_size = get_size() + + args = get_args(rank) + setup_logger(args.verbose) + logger.info(args.__dict__) + torch.backends.cudnn.benchmark = True + + args.rank = rank + args.world_size = world_size + tokenizer = AutoTokenizer.from_pretrained( + args.model_name, cache_dir=args.cache_dir, use_auth_token=args.auth, trust_remote_code=args.auth + ) + config = AutoConfig.from_pretrained( + args.model_name, cache_dir=args.cache_dir, use_auth_token=args.auth, trust_remote_code=args.auth + ) + target_device = f"cuda:{args.rank}" if args.device != "cpu" else args.device + use_fp16 = args.precision == "fp16" + + setattr(args, "tokenizer", tokenizer) # noqa: B010 + setattr(args, "config", config) # noqa: B010 + setattr(args, "target_device", target_device) # noqa: B010 + setattr(args, "use_fp16", use_fp16) # noqa: B010 + + # Get model and model info + model = get_model(args) + ort_model_inputs_len = get_ort_model_inputs_len(args, model) + + # Check if past_present_share_buffer can be enabled (only for FP16 models with GQA) + if args.benchmark_type in {"ort-convert-to-onnx", "ort-msft"}: + onnx_model = onnx.load_model(args.ort_model_path.format(args.rank), load_external_data=False) + gqa_nodes = list(filter(lambda node: node.op_type == "GroupQueryAttention", onnx_model.graph.node)) + + use_buffer_share = use_fp16 and len(gqa_nodes) > 0 and args.device != "cpu" + setattr(args, "use_buffer_share", use_buffer_share) # noqa: B010 + else: + setattr(args, "use_buffer_share", False) # noqa: B010 + + # Measure prompt cost (init_inputs) and generated token cost (iter_inputs) + for batch_size, sequence_length in itertools.product(args.batch_sizes, args.sequence_lengths): + if args.rank == 0: + logger.info(f"\nBatch size = {batch_size} and sequence length = {sequence_length}...") + setattr(args, "batch_size", int(batch_size)) # noqa: B010 + setattr(args, "sequence_length", int(sequence_length)) # noqa: B010 + + init_inputs, iter_inputs = get_inputs(args, ort_model_inputs_len) + run_inference(args, init_inputs, iter_inputs, model) + + +if __name__ == "__main__": + main() diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/llama/benchmark_all.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/llama/benchmark_all.py new file mode 100644 index 0000000000000000000000000000000000000000..287391e5ffd2186c90b5d1d8cd614556eb6022e0 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/llama/benchmark_all.py @@ -0,0 +1,488 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- +import argparse +import datetime +import json +import logging +import os +import subprocess + +import torch +from benchmark_helper import setup_logger +from metrics import BenchmarkRecord + +logger = logging.getLogger(__name__) + + +def get_args(): + parser = argparse.ArgumentParser() + + parser.add_argument( + "-b", + "--batch-sizes", + type=str, + default="1 2", + ) + + parser.add_argument( + "-s", + "--sequence-lengths", + type=str, + default="8 16 32 64 128 256 512", + ) + + parser.add_argument( + "-w", + "--warmup-runs", + type=int, + default=5, + ) + + parser.add_argument( + "-n", + "--num-runs", + type=int, + default=1000, + ) + + parser.add_argument( + "--hf-pt-eager", + default=False, + action="store_true", + help="Benchmark in PyTorch without `torch.compile`", + ) + + parser.add_argument( + "--hf-pt-compile", + default=False, + action="store_true", + help="Benchmark in PyTorch with `torch.compile`", + ) + + parser.add_argument( + "--hf-ort-dir-path", + type=str, + default="", + help="Path to folder containing ONNX models for Optimum + ORT benchmarking", + ) + + parser.add_argument( + "--ort-msft-model-path", + type=str, + default="", + help="Path to ONNX model from https://github.com/microsoft/Llama-2-Onnx", + ) + + parser.add_argument( + "--ort-convert-to-onnx-model-path", + type=str, + default="", + help="Path to ONNX model from convert_to_onnx", + ) + + parser.add_argument( + "--cache-dir", + type=str, + default="./model_cache", + help="Cache dir where Hugging Face files are stored", + ) + + parser.add_argument( + "--model-name", + type=str, + required=True, + help="Model name in Hugging Face", + ) + + parser.add_argument( + "--precision", + type=str, + required=True, + choices=["int4", "int8", "fp16", "fp32"], + help="Precision to run model", + ) + + parser.add_argument( + "--device", + type=str, + required=True, + choices=["cpu", "cuda"], + help="Device to benchmark models", + ) + + parser.add_argument( + "--device-id", + type=int, + default=0, + help="GPU device ID", + ) + + parser.add_argument( + "--verbose", + default=False, + action="store_true", + help="Print detailed logs", + ) + + parser.add_argument( + "--timeout", + type=int, + default=10, + help="Number of mins to attempt the benchmark before moving on", + ) + + parser.add_argument( + "--log-folder", + type=str, + default=None, + help="Path to folder to save logs and results", + ) + + args = parser.parse_args() + + setattr(args, "model_size", args.model_name.split("/")[-1].replace(".", "-")) # noqa: B010 + log_folder_name = f"./{args.model_size}_{args.precision}" + if not args.log_folder: + args.log_folder = log_folder_name + os.makedirs(args.log_folder, exist_ok=True) + + # Convert timeout value to secs + args.timeout *= 60 + + return args + + +def process_log_file(device_id, log_file, base_results): + entries = [] + batch_size, sequence_length, step = None, None, None + latency_s, latency_ms, throughput, memory = None, None, None, None + + batch_pattern = "Batch Size: " + sequence_pattern = "Sequence Length: " + prompt_step_pattern = "to get past_key_values" + per_token_step_pattern = "with past_key_values" + latency_pattern = "Latency: " + throughput_pattern = "Throughput: " + memory_pattern = "peak=" + + with open(log_file) as f: + for input_line in f: + line = input_line.replace("\n", "") + + if batch_pattern in line: + batch_size = int(line[len(batch_pattern) :]) + elif sequence_pattern in line: + sequence_length = int(line[len(sequence_pattern) :]) + elif prompt_step_pattern in line: + step = "prompt" + elif per_token_step_pattern in line: + step = "per-token" + elif latency_pattern in line: + latency_s = float(line[len(latency_pattern) : line.rfind(" ")]) + latency_ms = latency_s * 1000 + elif throughput_pattern in line: + throughput = float(line[len(throughput_pattern) : line.rfind(" ")]) + elif memory_pattern in line: + if "CPU" in line: + # Example format for log entry: + # CPU memory usage: before=1000.0 MB, peak=2000.0 MB + memory = float(line[line.rfind("=") + 1 : line.rfind(" MB")]) / 1000 + else: + # Example format for log entry: + # GPU memory usage: before=[{'device_id': 0, 'name': 'NVIDIA A100-SXM4-80GB', 'max_used_MB': 69637.25}, {'device_id': 1, 'name': 'NVIDIA A100-SXM4-80GB', 'max_used_MB': 890.625}] peak=[{'device_id': 0, 'name': 'NVIDIA A100-SXM4-80GB', 'max_used_MB': 73861.25}, {'device_id': 1, 'name': 'NVIDIA A100-SXM4-80GB', 'max_used_MB': 890.625}] + peak = line[line.find(memory_pattern) + len(memory_pattern) :].replace("'", '"') + usage = json.loads(peak)[device_id]["max_used_MB"] + memory = float(usage) / 1000 + + # Append log entry to list of entries + entry = base_results + [ # noqa: RUF005 + batch_size, + sequence_length, + step, + latency_s, + latency_ms, + throughput, + memory, + ] + entries.append(entry) + + return entries + + +def save_results(results, filename): + import pandas as pd # noqa: PLC0415 + + df = pd.DataFrame( + results, + columns=[ + "Warmup Runs", + "Measured Runs", + "Model Name", + "Engine", + "Precision", + "Device", + "Batch Size", + "Sequence Length", + "Step", + "Latency (s)", + "Latency (ms)", + "Throughput (tps)", + "Memory (GB)", + ], + ) + + # Set column types + df["Warmup Runs"] = df["Warmup Runs"].astype("int") + df["Measured Runs"] = df["Measured Runs"].astype("int") + df["Batch Size"] = df["Batch Size"].astype("int") + df["Sequence Length"] = df["Sequence Length"].astype("int") + df["Latency (s)"] = df["Latency (s)"].astype("float") + df["Latency (ms)"] = df["Latency (ms)"].astype("float") + df["Throughput (tps)"] = df["Throughput (tps)"].astype("float") + df["Memory (GB)"] = df["Memory (GB)"].astype("float") + + # get package name and version + import pkg_resources # noqa: PLC0415 + + installed_packages = pkg_resources.working_set + installed_packages_list = sorted( + [f"{i.key}=={i.version}" for i in installed_packages if i.key in ["onnxruntime", "onnxruntime-gpu"]] + ) + + ort_pkg_name = "" + ort_pkg_version = "" + if installed_packages_list: + ort_pkg_name = installed_packages_list[0].split("==")[0] + ort_pkg_version = installed_packages_list[0].split("==")[1] + + # Save results to csv with standard format + records = [] + for _, row in df.iterrows(): + if row["Engine"] in ["optimum-ort", "onnxruntime"]: + record = BenchmarkRecord( + row["Model Name"], row["Precision"], "onnxruntime", row["Device"], ort_pkg_name, ort_pkg_version + ) + elif row["Engine"] in ["pytorch-eager", "pytorch-compile"]: + record = BenchmarkRecord( + row["Model Name"], row["Precision"], "pytorch", row["Device"], torch.__name__, torch.__version__ + ) + else: + record = BenchmarkRecord(row["Model Name"], row["Precision"], row["Engine"], row["Device"], "", "") + record.config.warmup_runs = row["Warmup Runs"] + record.config.measured_runs = row["Measured Runs"] + record.config.batch_size = row["Batch Size"] + record.config.seq_length = row["Sequence Length"] + record.config.customized["measure_step"] = row["Step"] + record.config.customized["engine"] = row["Engine"] + record.metrics.customized["latency_s_mean"] = row["Latency (s)"] + record.metrics.latency_ms_mean = row["Latency (ms)"] + record.metrics.customized["throughput_tps"] = row["Throughput (tps)"] + record.metrics.max_memory_usage_GB = row["Memory (GB)"] + + records.append(record) + + BenchmarkRecord.save_as_csv(filename, records) + BenchmarkRecord.save_as_json(filename.replace(".csv", ".json"), records) + logger.info(f"Results saved in {filename}!") + + +def benchmark(args, benchmark_cmd, engine): + log_filename = f"{engine}_{datetime.datetime.now():%Y-%m-%d_%H:%M:%S}.log" + log_path = os.path.join(args.log_folder, log_filename) + with open(log_path, "w") as log_file: + process = subprocess.Popen(benchmark_cmd, stdout=log_file, stderr=log_file) + try: + process.wait(args.timeout) + except subprocess.TimeoutExpired: + process.kill() + + # Create entries for csv + logger.info("Gathering data from log files...") + base_results = [args.warmup_runs, args.num_runs, args.model_name, engine, args.precision, args.device] + results = process_log_file(args.device_id, log_path, base_results) + + return results + + +def main(): + args = get_args() + setup_logger(args.verbose) + logger.info(args.__dict__) + torch.backends.cudnn.benchmark = True + + all_results = [] + os.environ["CUDA_VISIBLE_DEVICES"] = str(args.device_id) + + # Benchmark PyTorch without torch.compile + if args.hf_pt_eager: + benchmark_cmd = [ + "python", + "-m", + "models.llama.benchmark", + "--benchmark-type", + "hf-pt-eager", + "--model-name", + args.model_name, + "--precision", + args.precision, + "--batch-sizes", + args.batch_sizes, + "--sequence-lengths", + args.sequence_lengths, + "--device", + args.device, + "--warmup-runs", + str(args.warmup_runs), + "--num-runs", + str(args.num_runs), + "--log-folder", + args.log_folder, + "--cache-dir", + args.cache_dir, + "--auth", + ] + logger.info("Benchmark PyTorch without torch.compile") + results = benchmark(args, benchmark_cmd, "pytorch-eager") + all_results.extend(results) + + # Benchmark PyTorch with torch.compile + if args.hf_pt_compile: + benchmark_cmd = [ + "python", + "-m", + "models.llama.benchmark", + "--benchmark-type", + "hf-pt-compile", + "--model-name", + args.model_name, + "--precision", + args.precision, + "--batch-sizes", + args.batch_sizes, + "--sequence-lengths", + args.sequence_lengths, + "--device", + args.device, + "--warmup-runs", + str(args.warmup_runs), + "--num-runs", + str(args.num_runs), + "--log-folder", + args.log_folder, + "--cache-dir", + args.cache_dir, + "--auth", + ] + logger.info("Benchmark PyTorch with torch.compile") + results = benchmark(args, benchmark_cmd, "pytorch-compile") + all_results.extend(results) + + # Benchmark Optimum + ONNX Runtime + if args.hf_ort_dir_path: + benchmark_cmd = [ + "python", + "-m", + "models.llama.benchmark", + "--benchmark-type", + "hf-ort", + "--hf-ort-dir-path", + args.hf_ort_dir_path, + "--model-name", + args.model_name, + "--precision", + args.precision, + "--batch-sizes", + args.batch_sizes, + "--sequence-lengths", + args.sequence_lengths, + "--device", + args.device, + "--warmup-runs", + str(args.warmup_runs), + "--num-runs", + str(args.num_runs), + "--log-folder", + args.log_folder, + "--cache-dir", + args.cache_dir, + "--auth", + ] + logger.info("Benchmark Optimum + ONNX Runtime") + results = benchmark(args, benchmark_cmd, "optimum-ort") + all_results.extend(results) + + # Benchmark Microsoft model in ONNX Runtime + if args.ort_msft_model_path: + benchmark_cmd = [ + "python", + "-m", + "models.llama.benchmark", + "--benchmark-type", + "ort-msft", + "--ort-model-path", + args.ort_msft_model_path, + "--model-name", + args.model_name, + "--precision", + args.precision, + "--batch-sizes", + args.batch_sizes, + "--sequence-lengths", + args.sequence_lengths, + "--device", + args.device, + "--warmup-runs", + str(args.warmup_runs), + "--num-runs", + str(args.num_runs), + "--log-folder", + args.log_folder, + "--cache-dir", + args.cache_dir, + ] + logger.info("Benchmark Microsoft model in ONNX Runtime") + results = benchmark(args, benchmark_cmd, "ort-msft") + all_results.extend(results) + + # Benchmark convert_to_onnx model in ONNX Runtime + if args.ort_convert_to_onnx_model_path: + benchmark_cmd = [ + "python", + "-m", + "models.llama.benchmark", + "--benchmark-type", + "ort-convert-to-onnx", + "--ort-model-path", + args.ort_convert_to_onnx_model_path, + "--model-name", + args.model_name, + "--precision", + args.precision, + "--batch-sizes", + args.batch_sizes, + "--sequence-lengths", + args.sequence_lengths, + "--device", + args.device, + "--warmup-runs", + str(args.warmup_runs), + "--num-runs", + str(args.num_runs), + "--log-folder", + args.log_folder, + "--cache-dir", + args.cache_dir, + ] + logger.info("Benchmark convert_to_onnx model in ONNX Runtime") + results = benchmark(args, benchmark_cmd, "onnxruntime") + all_results.extend(results) + + csv_file = f"{args.model_size}_{args.precision}_{datetime.datetime.now():%Y-%m-%d_%H:%M:%S}.csv" + save_results(all_results, os.path.join(args.log_folder, csv_file)) + + +if __name__ == "__main__": + main() diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/llama/benchmark_e2e.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/llama/benchmark_e2e.py new file mode 100644 index 0000000000000000000000000000000000000000..b6a9dd4e2df20ba3c8b9bb3b589b33f707ff27fd --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/llama/benchmark_e2e.py @@ -0,0 +1,608 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +# This is an end-to-end benchmarking script for the Hugging Face LLaMA-2 model. +# +# Prerequisites: +# 1) Install `huggingface-cli`: +# +# $ pip install huggingface_hub +# +# 2) Authenticate with Hugging Face's CLI: +# +# $ huggingface-cli login +# +# 3) Accept Meta's license in Hugging Face to access the models at https://huggingface.co/meta-llama/ +# +# 4) Install the latest ONNX Runtime version +# +# $ pip install onnxruntime-gpu +# +# 5) Install flash attention v2 +# +# $ pip install flash-attn --no-build-isolation +# +# 6) Install bitsandbytes +# +# $ pip install bitsandbytes + +from __future__ import annotations + +import argparse +import datetime +import gc +import itertools +import json +import logging +import os +import textwrap +import time + +import numpy as np +import pandas as pd +import torch +from benchmark_helper import setup_logger +from llama_inputs import add_io_bindings_as_tensors, get_initial_inputs_and_outputs +from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig + +import onnxruntime as ort + +logger = logging.getLogger(__name__) + + +def get_model(args: argparse.Namespace): + if args.benchmark_type in {"pt-eager", "pt-compile"}: + model = None + if args.onnx_precision == "int4" and args.device == "cuda": + bnb_config = BitsAndBytesConfig( + load_in_4bit=True, + bnb_4bit_use_double_quant=True, + bnb_4bit_quant_type="nf4", + bnb_4bit_compute_dtype=torch.float16, + ) + + model = AutoModelForCausalLM.from_pretrained( + args.hf_dir_path if args.hf_dir_path != "" else args.model_name, + cache_dir=args.cache_dir, + torch_dtype=args.torch_dtype, + use_auth_token=args.auth, + trust_remote_code=args.trust, + use_cache=True, + attn_implementation="flash_attention_2", + quantization_config=bnb_config, + max_memory={args.device_id: "80GB"}, + ) + else: + try: + model = AutoModelForCausalLM.from_pretrained( + args.hf_dir_path if args.hf_dir_path != "" else args.model_name, + cache_dir=args.cache_dir, + torch_dtype=args.torch_dtype, + use_auth_token=args.auth, + trust_remote_code=args.trust, + use_cache=True, + attn_implementation=("flash_attention_2" if args.device == "cuda" else "sdpa"), + ).to(args.target_device) + except Exception as e: + # When flash_attention or sdpa doesn't support a model, it throws an exception. + # Rather than stopping a process, run as eager mode. + print("Try to load a model using eager mode: ", e) + model = AutoModelForCausalLM.from_pretrained( + args.hf_dir_path if args.hf_dir_path != "" else args.model_name, + cache_dir=args.cache_dir, + torch_dtype=args.torch_dtype, + use_auth_token=args.auth, + trust_remote_code=args.trust, + use_cache=True, + attn_implementation="eager", + ).to(args.target_device) + + model.eval() + + if args.benchmark_type == "pt-compile": + model = torch.compile(model) + + else: + sess_options = ort.SessionOptions() + ep = ( + ("CUDAExecutionProvider", {"device_id": args.device_id}) + if args.device == "cuda" + else "CPUExecutionProvider" + ) + model = ort.InferenceSession(args.onnx_model_path, sess_options=sess_options, providers=[ep]) + + return model + + +def run_inference(args, model, runs, inputs, outputs): + if args.benchmark_type == "pt-compile": + with torch.no_grad(): + outputs = model(**inputs) + + # Synchronize inputs + io_binding = None + if args.benchmark_type in {"pt-eager", "pt-compile"}: + if args.device != "cpu": + torch.cuda.synchronize(args.target_device) + else: + io_binding = add_io_bindings_as_tensors(model, inputs, outputs, args.use_fp16, args.use_buffer_share) + io_binding.synchronize_inputs() + + # Run inference + start = time.perf_counter() + for _ in range(runs): + if args.benchmark_type in {"pt-eager", "pt-compile"}: + with torch.no_grad(): + outputs = model(**inputs) + if args.device != "cpu": + torch.cuda.synchronize(args.target_device) + else: + model.run_with_iobinding(io_binding) + io_binding.synchronize_outputs() + + end = time.perf_counter() + avg = (end - start) / runs + return avg, outputs + + +def prepare_model_for_inference(args, model, config, tokenizer, prompt_length, prompt): + clear_cache() + inputs, outputs = get_initial_inputs_and_outputs( + config, tokenizer, prompt_length, prompt, args.target_device, args.use_fp16, args.use_buffer_share, args.engine + ) + _, outputs = run_inference(args, model, args.warmup_runs, inputs, outputs) + return inputs, outputs + + +def clear_cache(): + gc.collect() + torch.cuda.empty_cache() + + +def save_results(results, filename, gen_length): + df = pd.DataFrame( + results, + columns=[ + "Batch Size", + "Prompt Length", + "Prompt Processing Latency (ms)", + "Prompt Processing Throughput (tps)", + "Sampling Latency (ms)", + "Sampling Throughput (tps)", + "First Token Generated Latency (ms)", + "First Token Generated Throughput (tps)", + f"Average Latency of First {gen_length // 2} Tokens Generated (ms)", + f"Average Throughput of First {gen_length // 2} Tokens Generated (tps)", + f"Average Latency of First {gen_length} Tokens Generated (ms)", + f"Average Throughput of First {gen_length} Tokens Generated (tps)", + "Wall-Clock Latency (s)", + "Wall-Clock Throughput (tps)", + ], + ) + + df.to_csv(filename, index=False) + logger.info(f"Results saved in {filename}!") + + +def get_args(): + parser = argparse.ArgumentParser() + + parser.add_argument( + "-bt", + "--benchmark-type", + type=str, + required=True, + choices=["pt-eager", "pt-compile", "ort"], + ) + + parser.add_argument( + "-m", + "--model-name", + type=str, + required=False, + help="Hugging Face name of model (e.g. 'meta-llama/Llama-2-7b-hf')", + ) + + parser.add_argument( + "-a", + "--auth", + default=False, + action="store_true", + help="Use Hugging Face authentication token to access model", + ) + + parser.add_argument( + "-t", + "--trust", + default=False, + action="store_true", + help="Whether or not to allow for custom models defined on the Hugging Face Hub in their own modeling files", + ) + + parser.add_argument( + "-c", + "--cache-dir", + type=str, + default=os.path.join(".", "model_cache"), + help="Path to directory containing all Hugging Face files (e.g. config, tokenizer, PyTorch model). Use when loading model as `AutoModel.from_pretrained(model_name, cache_dir=cache_dir)`.", + ) + + parser.add_argument( + "--hf-dir-path", + type=str, + default="", + help="Path to directory containing all Hugging Face files (e.g. config, tokenizer, PyTorch model). Use when loading model as `AutoModel.from_pretrained(folder_path)`.", + ) + + parser.add_argument( + "-o", + "--onnx-model-path", + required=False, + help="Path to ONNX model", + ) + + parser.add_argument( + "-f", + "--prompts-file", + required=True, + default=os.path.join(".", "models", "llama", "prompts.json"), + help="JSON file containing entries in the format 'prompt length: prompt' where prompt length = tokenized length of prompt", + ) + + parser.add_argument( + "--use_buffer_share", + default=False, + action="store_true", + help="Use when GroupQueryAttention (GQA) is in ONNX model", + ) + + ( + parser.add_argument( + "--anomaly-filtering", + default=False, + action="store_true", + help="Use this flag to filter anomaly accelerator times for tokens generated. \ + This may give more accurate latency and throughput metrics for tokens generated. \ + Wall-clock metrics are still reported with anomaly times though.", + ), + ) + + parser.add_argument( + "-b", + "--batch-sizes", + default="1 2", + ) + + parser.add_argument( + "-s", + "--prompt-lengths", + default="16 64 256 1024", + ) + + parser.add_argument( + "-p", + "--precision", + required=True, + type=str, + default="fp32", + choices=["int4", "int8", "fp16", "fp32"], + help="Precision for model. For ONNX models, the model's precision should be set before running this script.", + ) + + parser.add_argument( + "-g", + "--generation-length", + type=int, + default=256, + help="Number of new tokens to generate", + ) + + parser.add_argument( + "-d", + "--device", + type=str, + default="cuda" if torch.cuda.is_available() else "cpu", + choices=["cpu", "cuda"], + ) + + parser.add_argument("-id", "--device-id", type=int, default=0) + parser.add_argument("-w", "--warmup-runs", type=int, default=5) + parser.add_argument("-n", "--num-runs", type=int, default=100) + parser.add_argument("--seed", type=int, default=2) + + args = parser.parse_args() + + # Set seed properties + np.random.seed(args.seed) + torch.manual_seed(args.seed) + + # Set runtime properties + if "ort" in args.benchmark_type: + setattr(args, "execution_provider", f"{args.device.upper()}ExecutionProvider") # noqa: B010 + if args.execution_provider == "CUDAExecutionProvider": + args.execution_provider = (args.execution_provider, {"device_id": args.device_id}) + + # Check that paths have been specified for any benchmarking with ORT + if args.benchmark_type == "ort": + assert args.onnx_model_path, "Please specify a path to `--onnx-model-path`" + + args.batch_sizes = args.batch_sizes.split(" ") + args.prompt_lengths = args.prompt_lengths.split(" ") + + # Use FP32 precision for FP32, INT8, INT4 CPU models, use FP16 precision for FP16 and INT4 GPU models + setattr(args, "onnx_precision", args.precision) # noqa: B010 + args.precision = ( + "fp32" if args.precision in {"int8", "fp32"} or (args.precision == "int4" and args.device == "cpu") else "fp16" + ) + + target_device = f"cuda:{args.device_id}" if args.device != "cpu" else args.device + torch_dtype = torch.float16 if args.precision == "fp16" else torch.float32 + engine = "ort" if args.benchmark_type == "ort" else "pt" + setattr(args, "target_device", target_device) # noqa: B010 + setattr(args, "torch_dtype", torch_dtype) # noqa: B010 + setattr(args, "engine", engine) # noqa: B010 + setattr(args, "use_fp16", args.precision == "fp16") # noqa: B010 + + args.use_buffer_share = args.use_buffer_share and engine == "ort" + + return args + + +def main(): + args = get_args() + setup_logger(False) + logger.info(args.__dict__) + + # Get prompts and prompt sizes + size_to_prompt = None + with open(args.prompts_file) as f: + size_to_prompt = json.load(f, object_hook=lambda d: {int(k): v for k, v in d.items()}) + + # Get config, tokenizer, and model + config = AutoConfig.from_pretrained( + args.hf_dir_path if args.hf_dir_path != "" else args.model_name, + cache_dir=args.cache_dir, + use_auth_token=args.auth, + trust_remote_code=args.trust, + ) + tokenizer = AutoTokenizer.from_pretrained( + args.hf_dir_path if args.hf_dir_path != "" else args.model_name, + cache_dir=args.cache_dir, + use_auth_token=args.auth, + trust_remote_code=args.trust, + ) + model = get_model(args) + + all_csv_metrics = [] + for batch_size, prompt_length in itertools.product(args.batch_sizes, args.prompt_lengths): + batch_size, prompt_length = int(batch_size), int(prompt_length) # noqa: PLW2901 + logger.info(f"Running batch size = {batch_size}, prompt length = {prompt_length}") + clear_cache() + max_length = prompt_length + args.generation_length + + if prompt_length not in size_to_prompt: + raise NotImplementedError( + textwrap.dedent( + f""" + A prompt of size {prompt_length} was not found in '{args.prompts_file}'. There are a couple of solutions to fix this. + 1) You can change one of the keys in '{args.prompts_file}' to be {prompt_length}. + If {prompt_length} < actual prompt's length, the benchmark E2E tool will repeat the first word in the prompt until {prompt_length} = actual prompt's length. + If {prompt_length} > actual prompt's length, the benchmark E2E tool will automatically trim the actual prompt's length so that {prompt_length} = actual prompt's length. + 2) You can add a new key-value entry in '{args.prompts_file}' of the form '{prompt_length}': 'your prompt goes here'. + """ + ) + ) + prompt = [size_to_prompt[prompt_length]] * batch_size + csv_metrics = [batch_size, prompt_length] + + try: + # Measure prompt processing + logger.info("Measuring prompt processing...") + inputs, outputs = prepare_model_for_inference(args, model, config, tokenizer, prompt_length, prompt) + accelerator_prompt_latency_s, outputs = run_inference(args, model, args.num_runs, inputs, outputs) + + # Calculate prompt metrics + accelerator_prompt_latency_ms = accelerator_prompt_latency_s * 1000 + accelerator_prompt_thrpt = batch_size * (prompt_length / accelerator_prompt_latency_s) + logger.info(f"Average Latency of Prompt Processing: {accelerator_prompt_latency_ms} ms") + logger.info( + f"Average Throughput of Prompt Processing: {batch_size * (prompt_length / accelerator_prompt_latency_s)} tps" + ) + csv_metrics.extend([accelerator_prompt_latency_ms, accelerator_prompt_thrpt]) + + # Measure token generation + logger.info("Measuring token generation...") + clear_cache() + inputs, outputs = prepare_model_for_inference(args, model, config, tokenizer, prompt_length, prompt) + + all_token_ids = inputs["input_ids"].clone() + current_length = all_token_ids.shape[-1] + num_heads = config.num_key_value_heads + head_size = ( + config.head_dim if hasattr(config, "head_dim") else config.hidden_size // config.num_attention_heads + ) + + has_eos = torch.zeros(batch_size, device=args.target_device, dtype=torch.bool) + + # 0th entry will have prompt accelerator time, 1st entry onwards will have token generation accelerator time + accelerator_times = [] + sampling_times = [] # cost to sample after each model run + + wall_clock_start_time = time.perf_counter() + while current_length <= max_length: + # Run inference + accelerator_time_latency_s, outputs = run_inference(args, model, 1, inputs, outputs) + accelerator_times.append(accelerator_time_latency_s) + + # Sample with argmax (greedy search) + sampling_start_time = time.perf_counter() + if outputs["logits"].shape[1] > 1: + prompt_end_indices = inputs["attention_mask"].sum(1) - 1 + idxs = ( + prompt_end_indices.unsqueeze(dim=1) + .repeat(1, config.vocab_size) + .view(batch_size, 1, config.vocab_size) + ) + next_token_logits = torch.gather(outputs["logits"], 1, idxs).squeeze() + else: + next_token_logits = outputs["logits"][:, -1, :] + next_tokens = torch.argmax(next_token_logits, dim=-1) + + # Check if we previously reached EOS token id or if generated token id is EOS token id + has_eos = has_eos | next_tokens == tokenizer.eos_token_id + + # Determine which new tokens to add to list of all token ids + # Add EOS token ids for batch entries that ended early (ragged batching scenario where some batch entries ended early and some haven't) + tokens_to_add = next_tokens.masked_fill(has_eos, tokenizer.eos_token_id).reshape([batch_size, 1]) + sampling_end_time = time.perf_counter() + sampling_times.append(sampling_end_time - sampling_start_time) + + all_token_ids = torch.cat([all_token_ids, tokens_to_add], dim=-1) + current_length += 1 + + # Update inputs for next inference run + inputs["input_ids"] = tokens_to_add + inputs["attention_mask"] = torch.cat( + [inputs["attention_mask"], (~has_eos).to(torch.int64).reshape(batch_size, 1)], 1 + ) + if "position_ids" in inputs: + inputs["position_ids"] = torch.max(inputs["position_ids"], dim=1)[0].reshape(batch_size, 1) + 1 + + # Set logits to zeros for next inference run and re-use memory buffer + if outputs["logits"].shape[1] != 1: + outputs["logits"] = outputs["logits"][:, :1, :].contiguous() + outputs["logits"].zero_() + + # Update KV caches for next inference run + if args.engine == "pt": + # Update KV caches for PyTorch + inputs["past_key_values"] = outputs["past_key_values"] + elif not args.use_buffer_share: + # Update KV caches for ONNX Runtime if buffer sharing is not used + for i in range(config.num_hidden_layers): + inputs[f"past_key_values.{i}.key"] = outputs[f"present.{i}.key"] + inputs[f"past_key_values.{i}.value"] = outputs[f"present.{i}.value"] + + new_sequence_length = inputs["attention_mask"].shape[1] + for i in range(config.num_hidden_layers): + present_key = torch.zeros( + batch_size, + num_heads, + new_sequence_length, + head_size, + device=args.target_device, + dtype=args.torch_dtype, + ) + present_value = torch.zeros( + batch_size, + num_heads, + new_sequence_length, + head_size, + device=args.target_device, + dtype=args.torch_dtype, + ) + outputs.update( + { + f"present.{i}.key": present_key.contiguous(), + f"present.{i}.value": present_value.contiguous(), + } + ) + + wall_clock_end_time = time.perf_counter() + + # Filter out any anomaly accelerator times (e.g. for `torch.compile`) + accelerator_times.pop(0) # Remove prompt processing time + if args.anomaly_filtering: + anomaly_threshold_factor = 10 + min_time_s = min(accelerator_times) + orig_size = len(accelerator_times) + accelerator_times = list( + filter(lambda acc_time: acc_time < anomaly_threshold_factor * min_time_s, accelerator_times) + ) + new_size = len(accelerator_times) + logger.info( + f"Filtered out {orig_size - new_size} anomaly accelerator times that are {anomaly_threshold_factor}x greater than {min_time_s * 1000} ms..." + ) + + ####################################################### + # Calculate sampling and first token generated metrics + ####################################################### + + # Calculate sampling metrics + avg_sampling_latency_s = sum(sampling_times) / len(sampling_times) + avg_sampling_latency_ms = avg_sampling_latency_s * 1000 + avg_sampling_thrpt = batch_size * (1 / avg_sampling_latency_s) + logger.info(f"Average Latency of Sampling: {avg_sampling_latency_ms} ms") + logger.info(f"Average Throughput of Sampling: {avg_sampling_thrpt} tps") + + # Calculate first token generated metrics + first_token_latency_s = accelerator_times[0] + first_token_latency_ms = first_token_latency_s * 1000 + first_token_thrpt = batch_size * (1 / first_token_latency_s) + logger.info(f"Latency of First Token Generated: {first_token_latency_ms} ms") + logger.info(f"Throughput of First Token Generated: {first_token_thrpt} tps") + + #################################################### + # Calculate first `halfway` token generated metrics + #################################################### + + halfway = args.generation_length // 2 + halfway_token_latency_s = sum(accelerator_times[:halfway]) / len(accelerator_times[:halfway]) + halfway_token_latency_ms = halfway_token_latency_s * 1000 + halfway_token_thrpt = batch_size * (1 / halfway_token_latency_s) + logger.info(f"Average Latency of First {halfway} Tokens Generated: {halfway_token_latency_ms} ms") + logger.info(f"Average Throughput of First {halfway} Tokens Generated: {halfway_token_thrpt} tps") + + ######################################### + # Calculate all tokens generated metrics + ######################################### + + all_token_latency_s = sum(accelerator_times) / len(accelerator_times) + all_token_latency_ms = all_token_latency_s * 1000 + all_token_thrpt = batch_size * (1 / all_token_latency_s) + logger.info( + f"Average Latency of First {args.generation_length} Tokens Generated: {all_token_latency_ms} ms" + ) + logger.info(f"Average Throughput of First {args.generation_length} Tokens Generated: {all_token_thrpt} tps") + + ############################### + # Calculate wall clock metrics + ############################### + + wall_clock_latency_s = wall_clock_end_time - wall_clock_start_time + wall_clock_thrpt = batch_size * ((prompt_length + args.generation_length) / wall_clock_latency_s) + logger.info(f"Wall-Clock Latency: {wall_clock_latency_s} s") + logger.info( + f"Wall-Clock Throughput: {batch_size * ((prompt_length + args.generation_length) / wall_clock_latency_s)} tps" + ) + + # Add metrics to CSV + logger.info("Adding results to CSV") + csv_metrics.extend( + [ + avg_sampling_latency_ms, + avg_sampling_thrpt, + first_token_latency_ms, + first_token_thrpt, + halfway_token_latency_ms, + halfway_token_thrpt, + all_token_latency_ms, + all_token_thrpt, + wall_clock_latency_s, + wall_clock_thrpt, + ] + ) + all_csv_metrics.append(csv_metrics) + + except Exception as e: + logger.info(f"Could not benchmark at batch size = {batch_size}, prompt length = {prompt_length} - {e}") + + filename = f"benchmark_{args.engine}_e2e_{datetime.datetime.now():%Y-%m-%d_%H:%M:%S}.csv" + save_results(all_csv_metrics, filename, args.generation_length) + + +if __name__ == "__main__": + main() diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/llama/convert_to_onnx.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/llama/convert_to_onnx.py new file mode 100644 index 0000000000000000000000000000000000000000..44ce403bb562cd87d2fa1baa7a5d3a18d08a33d3 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/llama/convert_to_onnx.py @@ -0,0 +1,1066 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- +from __future__ import annotations + +import argparse +import logging +import os +import shutil +import subprocess +import sys +import tempfile +import warnings +from itertools import chain + +import onnx +import torch +from benchmark_helper import Precision, prepare_environment, setup_logger +from convert_generation import replace_mha_with_gqa +from dist_settings import barrier, get_rank, get_size, init_dist +from llama_inputs import get_merged_sample_with_past_kv_inputs, get_sample_inputs, get_sample_with_past_kv_inputs +from llama_parity import main as parity_check +from llama_torch import setup_torch_model + +# to patch transformers before exporting for transformers >= 4.45 +from models.torch_export_patches import bypass_export_some_errors +from models.torch_export_patches.patch_inputs import convert_dynamic_axes_into_dynamic_shapes +from onnx_model import OnnxModel +from optimizer import optimize_model +from packaging import version +from transformers import AutoConfig, AutoModelForCausalLM + +from onnxruntime import __version__ as ort_version +from onnxruntime import quantization as ort_quantization + +if version.parse(ort_version) < version.parse("1.22.0"): + from onnxruntime.quantization.matmul_4bits_quantizer import MatMul4BitsQuantizer as MatMulNBitsQuantizer +else: + from onnxruntime.quantization.matmul_nbits_quantizer import MatMulNBitsQuantizer + +torch_export_onnx_opset_version = 14 +logger = logging.getLogger("") +init_dist() + + +def get_model_dynamic_axes(input_names: list[str], output_names: list[str]): + dynamic_axes = {} + for name in input_names + output_names: + if name in input_names: + # shape is (batch_size, sequence_length) + dynamic_axes[name] = {0: "batch_size", 1: "sequence_length"} + elif name == "logits": + # shape is (batch_size, sequence_length, vocab_size) + dynamic_axes[name] = {0: "batch_size", 1: "sequence_length"} + elif "present" in name: + # shape is (batch_size, num_heads, sequence_length, head_size) + dynamic_axes[name] = {0: "batch_size", 2: "sequence_length"} + else: + raise Exception("Unknown input or output name found") + return dynamic_axes + + +def get_model_with_past_kv_dynamic_axes(input_names: list[str], output_names: list[str]): + dynamic_axes = {} + for name in input_names + output_names: + if name in {"input_ids", "position_ids"}: + # shape is (batch_size, 1) + dynamic_axes[name] = {0: "batch_size"} + elif name == "attention_mask": + # shape is (batch_size, past_sequence_length + 1) + dynamic_axes[name] = {0: "batch_size", 1: "past_sequence_length + 1"} + elif "past" in name: + # shape is (batch_size, num_heads, past_sequence_length, head_size) + dynamic_axes[name] = {0: "batch_size", 2: "past_sequence_length"} + elif name == "logits": + # shape is (batch_size, 1, vocab_size) + dynamic_axes[name] = {0: "batch_size"} + elif "present" in name: + # shape is (batch_size, num_heads, past_sequence_length + 1, head_size) + dynamic_axes[name] = {0: "batch_size", 2: "past_sequence_length + 1"} + else: + raise Exception("Unknown input or output name found") + return dynamic_axes + + +def get_merged_model_dynamic_axes(input_names: list[str], output_names: list[str]): + dynamic_axes = {} + for name in input_names + output_names: + if name in {"input_ids", "position_ids"}: + # shape is (batch_size, sequence_length) + dynamic_axes[name] = {0: "batch_size", 1: "sequence_length"} + elif name == "attention_mask": + # shape is (batch_size, past_sequence_length + sequence_length) = (batch_size, total_sequence_length) + # for prompt generation, past_sequence_length = 0 + # for token generation, sequence_length = 1 + dynamic_axes[name] = {0: "batch_size", 1: "total_sequence_length"} + elif "past" in name: + # shape is (batch_size, num_heads, past_sequence_length, head_size) + dynamic_axes[name] = {0: "batch_size", 2: "past_sequence_length"} + elif name == "logits": + # shape is (batch_size, sequence_length, vocab_size) + dynamic_axes[name] = {0: "batch_size", 1: "sequence_length"} + elif "present" in name: + # shape is (batch_size, num_heads, past_sequence_length + sequence_length, head_size) = (batch_size, num_heads, total_sequence_length, head_size) + # for prompt generation, past_sequence_length = 0 + # for token generation, sequence_length = 1 + dynamic_axes[name] = {0: "batch_size", 2: "total_sequence_length"} + else: + raise Exception("Unknown input or output name found") + return dynamic_axes + + +def save_onnx_model(onnx_model: onnx.ModelProto, output_path: str, data_path: str): + onnx.save( + onnx_model, + output_path, + save_as_external_data=True, + all_tensors_to_one_file=True, + location=data_path, + size_threshold=1024, + convert_attribute=False, + ) + + +def run_dynamo_export( + args: argparse.Namespace, l_config: AutoConfig, llama: AutoModelForCausalLM, rank: int = 0, world_size: int = 1 +): + from torch._dynamo import config # noqa: PLC0415 + + config.capture_scalar_outputs = True + + # Dummy values for export + batch_size, sequence_length, past_sequence_length = 2, 8, 3 + device = llama.device if args.model_name == "Llama-2-70b-hf" else torch.device("cpu") + + temp_name = args.model_name.lower().replace("-", "").replace("_", "") + max_sequence_length = 16384 if "codellama" in temp_name else 4096 if "llama2" in temp_name else 2048 + + # Export decoder_with_past_model.onnx + input_ids, attn_mask, pos_ids, past_kv = get_merged_sample_with_past_kv_inputs( + l_config, + device, + batch_size, + sequence_length, + past_sequence_length, + max_seq_len=max_sequence_length, + use_fp16=False, + world_size=world_size, + ) + temp_dir = tempfile.TemporaryDirectory() + temp_path = os.path.join(temp_dir.name, "temp.onnx") + + input_names = ["input_ids", "attention_mask", "position_ids"] + output_names = [ + "logits", + *list( + chain.from_iterable((f"present.{i}.key", f"present.{i}.value") for i in range(l_config.num_hidden_layers)) + ), + ] + dynamic_axes = get_model_dynamic_axes(input_names, output_names) + + model_args = (input_ids, attn_mask, pos_ids, past_kv) + model_args, model_kwargs, dynamic_shapes = convert_dynamic_axes_into_dynamic_shapes( + llama, args=model_args, dynamic_axes=dynamic_axes, prefix_mapping={"present": "past_key_values"} + ) + + with bypass_export_some_errors(patch_transformers=True): + torch.onnx.export( + llama, + (), + temp_path, + kwargs=model_kwargs, + dynamic_shapes=dynamic_shapes, + dynamo=True, + verbose=args.verbose, + optimize=True, + ) + + # Check decoder_with_past_model.onnx and save all external data to one file + onnx.checker.check_model(temp_path) + onnx.shape_inference.infer_shapes_path(temp_path) + + output_path = os.path.join(args.output, f"rank_{rank}_{args.model_name}_decoder_with_past_model_fp32.onnx") + onnx_model = onnx.load_model(temp_path, load_external_data=True) + save_onnx_model(onnx_model, output_path, f"rank_{rank}_{args.model_name}_decoder_with_past_model_fp32.onnx.data") + del onnx_model + temp_dir.cleanup() + + logger.info(f"The {args.model_name} ONNX model has been successfully created with the Dynamo exporter!") + + +def _prepare_dir(dir_path): + if not os.path.exists(dir_path): + os.makedirs(dir_path) + + +def run_torchscript_separate_export( + args: argparse.Namespace, l_config: AutoConfig, llama: AutoModelForCausalLM, rank: int = 0, world_size: int = 1 +): + # Dummy values for export + batch_size, sequence_length = 2, 8 + + # set device used to export model + # for llama-2-70b we will use current gpus to speed up export process + # for other models, we will use CPU to make sure we have enough memory to do export + device = llama.device if args.model_name == "Llama-2-70b-hf" else torch.device("cpu") + + # Export decoder_model.onnx + decoder_inputs = get_sample_inputs(l_config, device, batch_size, sequence_length) + + input_names = ["input_ids", "attention_mask", "position_ids"] + output_names = [ + "logits", + *list( + chain.from_iterable((f"present.{i}.key", f"present.{i}.value") for i in range(l_config.num_hidden_layers)) + ), + ] + dynamic_axes = get_model_dynamic_axes(input_names, output_names) + + # Avoid using system temp dir to avoid overflood on hard disk as 70b model is very large. + # Use temp folder per rank to avoid race condition here. + temp_dir = f"./temp_{rank}" + _prepare_dir(temp_dir) + temp_path = os.path.join(temp_dir, "temp.onnx") + torch.onnx.export( + llama, + args=decoder_inputs, + f=temp_path, + export_params=True, + input_names=input_names, + output_names=output_names, + dynamic_axes=dynamic_axes, + opset_version=torch_export_onnx_opset_version, + do_constant_folding=True, + verbose=args.verbose, + dynamo=False, + ) + + # Check decoder_model.onnx and save all external data to one file + onnx.checker.check_model(temp_path) + onnx.shape_inference.infer_shapes_path(temp_path) + + output_path = os.path.join(args.output, f"rank_{rank}_{args.model_name}_decoder_model_fp32.onnx") + onnx_model = onnx.load_model(temp_path, load_external_data=True) + save_onnx_model( + onnx_model, + output_path, + f"rank_{rank}_{args.model_name}_decoder_model_fp32.onnx.data", + ) + del onnx_model + shutil.rmtree(temp_dir) + + # Export decoder_with_past_model.onnx + decoder_with_past_inputs = get_sample_with_past_kv_inputs( + l_config, + device, + batch_size, + sequence_length, + use_fp16=False, + world_size=world_size, + ) + input_names = [ + "input_ids", + "attention_mask", + "position_ids", + *list( + chain.from_iterable( + (f"past_key_values.{i}.key", f"past_key_values.{i}.value") for i in range(l_config.num_hidden_layers) + ) + ), + ] + output_names = [ + "logits", + *list( + chain.from_iterable((f"present.{i}.key", f"present.{i}.value") for i in range(l_config.num_hidden_layers)) + ), + ] + dynamic_axes = get_model_with_past_kv_dynamic_axes(input_names, output_names) + + # Avoid using system temp dir to avoid overflood on hard disk as 70b model is very large. + # Use temp folder per rank to avoid race condition here. + temp_dir = f"./temp_past_{rank}" + _prepare_dir(temp_dir) + temp_path = os.path.join(temp_dir, "temp.onnx") + torch.onnx.export( + llama, + args=decoder_with_past_inputs, + f=temp_path, + export_params=True, + input_names=input_names, + output_names=output_names, + dynamic_axes=dynamic_axes, + opset_version=torch_export_onnx_opset_version, + do_constant_folding=True, + verbose=args.verbose, + dynamo=False, + ) + + # Check decoder_with_past_model.onnx and save all external data to one file + onnx.checker.check_model(temp_path) + onnx.shape_inference.infer_shapes_path(temp_path) + + output_path = os.path.join(args.output, f"rank_{rank}_{args.model_name}_decoder_with_past_model_fp32.onnx") + onnx_model = onnx.load_model(temp_path, load_external_data=True) + save_onnx_model( + onnx_model, + output_path, + f"rank_{rank}_{args.model_name}_decoder_with_past_model_fp32.onnx.data", + ) + del onnx_model + shutil.rmtree(temp_dir) + + logger.info( + f"The {args.model_name} separate ONNX model has been successfully created with the TorchScript exporter!" + ) + + +def run_torchscript_merged_export( + args: argparse.Namespace, l_config: AutoConfig, llama: AutoModelForCausalLM, rank: int = 0, world_size: int = 1 +): + # Dummy values for export + batch_size, sequence_length, past_sequence_length = 2, 8, 0 + + # set device used to export model + # for llama-2-70b we will use current gpus to speed up export process + # for other models, we will use CPU to make sure we have enough memory to do export + device = llama.device if args.model_name == "Llama-2-70b-hf" else torch.device("cpu") + + temp_name = args.model_name.lower().replace("-", "").replace("_", "") + max_sequence_length = 16384 if "codellama" in temp_name else 4096 if "llama2" in temp_name else 2048 + + # Export decoder_merged_model.onnx + decoder_merged_inputs = get_merged_sample_with_past_kv_inputs( + l_config, + device, + batch_size, + sequence_length, + past_sequence_length, + max_seq_len=max_sequence_length, + use_fp16=False, + world_size=world_size, + ) + input_names = [ + "input_ids", + "attention_mask", + "position_ids", + *list( + chain.from_iterable( + (f"past_key_values.{i}.key", f"past_key_values.{i}.value") for i in range(l_config.num_hidden_layers) + ) + ), + ] + output_names = [ + "logits", + *list( + chain.from_iterable((f"present.{i}.key", f"present.{i}.value") for i in range(l_config.num_hidden_layers)) + ), + ] + dynamic_axes = get_merged_model_dynamic_axes(input_names, output_names) + + # Avoid using system temp dir to avoid overflood on hard disk as 70b model is very large. + # Use temp folder per rank to avoid race condition here. + temp_dir = f"./temp_{rank}" + _prepare_dir(temp_dir) + temp_path = os.path.join(temp_dir, "temp.onnx") + + torch.onnx.export( + llama, + args=decoder_merged_inputs, + f=temp_path, + export_params=True, + input_names=input_names, + output_names=output_names, + dynamic_axes=dynamic_axes, + opset_version=torch_export_onnx_opset_version, + do_constant_folding=True, + verbose=args.verbose, + dynamo=False, + ) + + # Check decoder_merged_model.onnx and save all external data to one file + onnx.checker.check_model(temp_path) + onnx.shape_inference.infer_shapes_path(temp_path) + + output_path = os.path.join(args.output, f"rank_{rank}_{args.model_name}_decoder_merged_model_fp32.onnx") + onnx_model = onnx.load_model(temp_path, load_external_data=True) + save_onnx_model( + onnx_model, + output_path, + f"rank_{rank}_{args.model_name}_decoder_merged_model_fp32.onnx.data", + ) + del onnx_model + shutil.rmtree(temp_dir) + + logger.info(f"The {args.model_name} merged ONNX model has been successfully created with the TorchScript exporter!") + + +# Optimize the model as FP32 +def optimize_export( + args: argparse.Namespace, + config: AutoConfig, + input_path: str, + output_path: str, + remove_model: bool = True, + world_size: int = 1, + window_size: int = -1, +): + from fusion_options import FusionOptions # noqa: PLC0415 + + optimization_options = FusionOptions("gpt2") + + model_opt = optimize_model( + input_path, + model_type="gpt2", + num_heads=config.num_attention_heads, + hidden_size=config.hidden_size, + opt_level=0, + optimization_options=optimization_options, + only_onnxruntime=False, + ) + if args.use_gqa: + model_opt = use_group_query_attention(config, model_opt, world_size, window_size) + model_opt.save_model_to_file(output_path, use_external_data_format=True) + + # Run symbolic shape inference on optimized model to avoid shape errors during runtime + # Ex: Before attention fusion, RotaryEmbedding assumes a 4D input and produces a 4D output. + # After attention fusion, RotaryEmbedding expects a 3D input and produces a 3D output. + wheel_cmd = [sys.executable, "-m", "onnxruntime.tools.symbolic_shape_infer"] + source_cmd = [sys.executable, "../symbolic_shape_infer.py"] + symbolic_shape_infer_args = [ + "--input", + output_path, + "--output", + output_path, + "--auto_merge", + "--save_as_external_data", + "--all_tensors_to_one_file", + "--external_data_location", + os.path.basename(output_path) + ".data", + ] + + file_path = os.path.dirname(__file__) + if os.path.exists(os.path.join(file_path, "../../../tools/symbolic_shape_infer.py")): + main_cmd = wheel_cmd + else: + main_cmd = source_cmd + subprocess.run(main_cmd + symbolic_shape_infer_args) # noqa: PLW1510 + + logger.info(f"The ONNX model at {input_path} has been successfully optimized and saved at {output_path}!") + if remove_model: + remove_existing_model(input_path) + + +def convert_to_float16(args: argparse.Namespace, old_paths: list[str], rank: int = 0): + decoder_model_fp16_path = os.path.join(args.output, f"rank_{rank}_{args.model_name}_decoder_model_fp16.onnx") + decoder_with_past_model_fp16_path = os.path.join( + args.output, f"rank_{rank}_{args.model_name}_decoder_with_past_model_fp16.onnx" + ) + decoder_merged_model_fp16_path = os.path.join( + args.output, f"rank_{rank}_{args.model_name}_decoder_merged_model_fp16.onnx" + ) + new_paths = [decoder_model_fp16_path, decoder_with_past_model_fp16_path, decoder_merged_model_fp16_path] + + logger.info("Converting to float16...") + for fp32_path, fp16_path in zip(old_paths, new_paths, strict=False): + if os.path.exists(fp32_path): + model = OnnxModel(onnx.load_model(fp32_path, load_external_data=True)) + model.convert_float_to_float16(keep_io_types=False) + model.save_model_to_file(fp16_path, use_external_data_format=True) + del model + logger.info(f"The ONNX model at {fp32_path} has been converted to float16 and saved at {fp16_path}!") + remove_existing_model(fp32_path) + + logger.info(f"The {args.model_name} ONNX model has been successfully converted to float16!") + return new_paths + + +def use_group_query_attention(config: AutoConfig, model_opt: OnnxModel, world_size: int = 1, window_size: int = -1): + # Replace MultiHeadAttention with GroupQueryAttention + model_opt = replace_mha_with_gqa(model_opt, "attention_mask", config.num_key_value_heads, world_size, window_size) + model_opt.prune_graph() + model_opt.update_graph(allow_remove_graph_inputs=True) + return model_opt + + +def smooth_quant( + args: argparse.Namespace, + decoder_model_fp32_path: str, + decoder_with_past_model_fp32_path: str, + decoder_model_int8_path: str, + decoder_with_past_model_int8_path: str, +): + from neural_compressor import PostTrainingQuantConfig, set_workspace # noqa: PLC0415 + from neural_compressor import quantization as intel_quantization # noqa: PLC0415 + from onnx.external_data_helper import load_external_data_for_model # noqa: PLC0415 + from quant_kv_dataloader import QuantKVDataLoader # noqa: PLC0415 + + set_workspace(args.nc_workspace) + quantization_config = PostTrainingQuantConfig( + calibration_sampling_size=[args.calibration_sampling_size], + recipes={ + "optypes_to_exclude_output_quant": ["MatMul"], + "smooth_quant": True, + "smooth_quant_args": {"alpha": args.smooth_quant_alpha}, + }, + op_type_dict={ + "^((?!(MatMul|Gather|Conv)).)*$": { + "weight": {"dtype": ["fp32"]}, + "activation": {"dtype": ["fp32"]}, + } + }, + ) + + # Convert decoder_model.onnx to INT8 + decoder_model_int8 = intel_quantization.fit( + decoder_model_fp32_path, + quantization_config, + calib_dataloader=QuantKVDataLoader(args), + ) + load_external_data_for_model( + decoder_model_int8._model, + os.path.split(decoder_model_int8._model_path)[0], + ) + save_onnx_model( + decoder_model_int8._model, + decoder_model_int8_path, + f"{args.model_name}_decoder_model_int8.onnx.data", + ) + del decoder_model_int8 + logger.info( + f"The ONNX model at {decoder_model_fp32_path} has been quantized to int8 and saved at {decoder_model_int8_path}!" + ) + remove_existing_model(decoder_model_fp32_path) + + # Convert decoder_with_past_model.onnx to INT8 + decoder_with_past_model_int8 = intel_quantization.fit( + decoder_with_past_model_fp32_path, + quantization_config, + calib_dataloader=QuantKVDataLoader(args, onnx_model_path=decoder_model_fp32_path), + ) + load_external_data_for_model( + decoder_with_past_model_int8._model, + os.path.split(decoder_with_past_model_int8._model_path)[0], + ) + save_onnx_model( + decoder_with_past_model_int8._model, + decoder_with_past_model_int8_path, + f"{args.model_name}_decoder_with_past_model_int8.onnx.data", + ) + del decoder_with_past_model_int8 + logger.info( + f"The ONNX model at {decoder_with_past_model_fp32_path} has been quantized to int8 and saved at {decoder_with_past_model_int8_path}!" + ) + remove_existing_model(decoder_with_past_model_fp32_path) + + logger.info(f"The {args.model_name} ONNX model has been successfully quantized to int8!") + + logger.warning(f"Removing {args.nc_workspace}") + shutil.rmtree(args.nc_workspace) + + +def remove_existing_model(model_path: str): + # Remove ONNX model and its external data + data_path = os.path.join(model_path + ".data") + os.remove(model_path) + os.remove(data_path) + logger.warning(f"Removed {model_path} and {data_path}") + + +def remove_existing_files(output_path: str): + for filename in os.listdir(output_path): + filepath = os.path.join(output_path, filename) + if ".onnx" in filename or ".onnx.data" in filename: + os.remove(filepath) + logger.warning(f"Removed {filepath}") + + +def optimize_optimum(config: AutoConfig, args: argparse.Namespace): + tmp_file = os.path.join(args.output, args.model_name + ".tmp.onnx") + output_file = os.path.join(args.output, args.model_name + ".onnx") + window_size = -1 if not hasattr(config, "sliding_window") else config.sliding_window + optimize_export(args, config, args.input, tmp_file, remove_model=False, window_size=window_size) + logger.info(f"Model successfully optimized to {tmp_file}") + opt_model = OnnxModel(onnx.load_model(tmp_file, load_external_data=True)) + if args.precision == Precision.FLOAT16: + opt_model.convert_float_to_float16(keep_io_types=False) + logger.info("Model successfully fused and quantized to FP16!") + opt_model.save_model_to_file(output_file, use_external_data_format=True) + logger.info(f"Output model successfully saved to {output_file}") + logger.info(f"Removing {tmp_file}") + remove_existing_model(tmp_file) + + +def get_args(): + parser = argparse.ArgumentParser() + + parser.add_argument( + "-m", + "--model_name", + required=True, + help="Model name in Hugging Face", + ) + + parser.add_argument( + "-i", + "--input", + required=False, + default=os.path.join("."), + help="Directory path to PyTorch model and associated files if saved on disk, or ONNX model file location if optimize_optimum is passed.", + ) + + parser.add_argument( + "-o", + "--output", + required=False, + default=os.path.join(".", "llama_onnx_models"), + help="Directory path to save exported model files in", + ) + + parser.add_argument( + "-p", + "--precision", + required=False, + type=Precision, + default=Precision.FLOAT32, + choices=[Precision.FLOAT32, Precision.FLOAT16, Precision.INT8, Precision.INT4], + help="Precision to export model in", + ) + + parser.add_argument( + "-e", + "--execution_provider", + required=False, + default="cpu", + choices=["cpu", "cuda"], + help="Execution provider to verify parity with", + ) + + parser.add_argument( + "-r", + "--reexport", + required=False, + action="store_true", + help="Re-export models and overwrite existing models in output folder", + ) + parser.set_defaults(reexport=False) + + parser.add_argument( + "--use_gqa", + required=False, + action="store_true", + help="Use GroupQueryAttention instead of MultiHeadAttention", + ) + parser.set_defaults(use_gqa=False) + + parser.add_argument( + "--no_merged", + required=False, + action="store_true", + help="Export models into 2 ONNX files instead of 1. Deprecated in favor of exporting into 1 ONNX file.", + ) + parser.set_defaults(no_merged=False) + + parser.add_argument( + "-q", + "--quantization_method", + default="", + choices=["blockwise", "smooth_quant", "quantize_dynamic"], + help="Run a specific quantization algorithm (blockwise for int4, smooth_quant for int8, quantize_dynamic for int8). Blockwise is recommended. Need to install extra packages in `requirements-quant.txt` for SmoothQuant.", + ) + + blockwise_group = parser.add_argument_group("blockwise (4-bit quantization)") + + parser.add_argument("--bits", default=4, type=int, help="the target bits to represent weight") + + blockwise_group.add_argument( + "--block_size", + required=False, + default=32, + type=int, + help="Block size to quantize with. See https://github.com/microsoft/onnxruntime/blob/main/onnxruntime/python/tools/quantization/matmul_nbits_quantizer.py for details.", + ) + + blockwise_group.add_argument( + "--int4_accuracy_level", + required=False, + type=int, + help="Accuracy level of the 4-bit quantized MatMul computation. " + "Refer to the MatMulNBits contrib op's 'accuracy_level' attribute for details " + "(https://github.com/microsoft/onnxruntime/blob/main/docs/ContribOperators.md#commicrosoftmatmulnbits).", + ) + + smooth_quant_group = parser.add_argument_group("smooth_quant (8-bit quantization)") + + smooth_quant_group.add_argument( + "--smooth_quant_alpha", + required=False, + default=0.8, + type=float, + help="Strength to control migration difficulty from activation to weights. Default is 0.8 to match value \ + used in original paper for LLaMA. Paper recommends using values in [0.4, 0.6] range. \ + Link to paper: https://arxiv.org/pdf/2211.10438.pdf", + ) + + smooth_quant_group.add_argument( + "--smooth_quant_dataset", + required=False, + default="NeelNanda/pile-10k", + help="Path to dataset for calibration during quantization", + ) + + smooth_quant_group.add_argument( + "--pad_max", + required=False, + default=196, + type=int, + help="Max padding size", + ) + + smooth_quant_group.add_argument( + "--calibration_sampling_size", + required=False, + type=int, + default=8, + help="Calibration sampling size for quantization config", + ) + + smooth_quant_group.add_argument( + "--nc_workspace", + required=False, + type=str, + default=os.path.join(".", "nc_workspace"), + help="Workspace to save intermediate files generated by Intel's Neural Compressor package.", + ) + + quantize_dynamic_group = parser.add_argument_group("quantize_dynamic (8-bit quantization)") + + quantize_dynamic_group.add_argument( + "--quantize_embedding_layer", + required=False, + action="store_true", + help="Quantize MatMul, GEMM, and Gather.", + ) + quantize_dynamic_group.set_defaults(quantize_embedding_layer=False) + + quantize_dynamic_group.add_argument( + "--quantize_per_channel", + required=False, + action="store_true", + help="Quantize weights per each channel.", + ) + quantize_dynamic_group.set_defaults(quantize_per_channel=False) + + quantize_dynamic_group.add_argument( + "--quantize_reduce_range", + required=False, + action="store_true", + help="Quantize weights with 7 bits.", + ) + quantize_dynamic_group.set_defaults(quantize_reduce_range=False) + + parser.add_argument( + "-v", + "--verbose", + action="store_true", + help="Print verbose logs", + ) + parser.set_defaults(verbose=False) + + parser.add_argument( + "-d", + "--use_dynamo_export", + action="store_true", + help="Use the new Dynamo exporter instead of the old TorchScript exporter", + ) + parser.set_defaults(use_dynamo_export=False) + + parser.add_argument( + "--cache_dir", + required=False, + type=str, + default="./model_cache", + help="model cache dir to override default HF cache dir to avoid overflood the /home dir", + ) + + parser.add_argument( + "--optimize_optimum", + action="store_true", + help="Avoid exporting model, only apply quantizations and optimizations to existing model exported from optimum.", + ) + + parser.add_argument( + "--small_gpu", + action="store_true", + help="Load the llama in GPU every time for parity_check if it's running in a machine which GPU memory < 36GB.", + ) + + parser.set_defaults(optimize_optimum=False) + + args = parser.parse_args() + return args + + +def main(): + warnings.warn( + "This example is deprecated. Use the Olive recipe instead: " + "https://github.com/microsoft/olive-recipes/tree/main", + DeprecationWarning, + stacklevel=2, + ) + if version.parse(torch.__version__) < version.parse("2.2.0"): + logger.error(f"Detected PyTorch version {torch.__version__}. Please upgrade and use v2.2.0 or newer.") + return + + args = get_args() + setup_logger(args.verbose) + prepare_environment(args.input, args.output, args.execution_provider != "cpu") + if args.reexport: + remove_existing_files(args.output) + logger.info(f"Arguments: {args}") + + world_size = get_size() + rank = get_rank() + args.world_size = world_size + + # Load model and config + use_auth_token = args.input == os.path.join(".") + setattr(args, "use_auth_token", use_auth_token) # noqa: B010 + + original_model_name = args.model_name + setattr(args, "original_model_name", original_model_name) # noqa: B010 + args.model_name = args.model_name.split("/")[-1] + + setattr(args, "device_name", "cpu" if args.execution_provider == "cpu" else f"cuda:{rank}") # noqa: B010 + setattr(args, "device", torch.device(args.device_name)) # noqa: B010 + + location = args.original_model_name if use_auth_token else args.input + + if args.optimize_optimum: + config = AutoConfig.from_pretrained(args.original_model_name, cache_dir=args.cache_dir) + optimize_optimum(config, args) + return + + # Use CUDA for LLaMA-2-70B to speed up export and CPU for other models + l_config, llama = setup_torch_model( + args, location, use_auth_token, device=args.device if args.model_name == "Llama-2-70b-hf" else None + ) + + assert l_config.num_attention_heads % world_size == 0 and l_config.num_key_value_heads % world_size == 0 + + barrier() + for i in range(world_size): + if i == rank: + # Set model paths for FP32 model + decoder_model_fp32_path = os.path.join( + args.output, f"rank_{rank}_{args.model_name}_decoder_model_fp32.onnx" + ) + decoder_with_past_model_fp32_path = os.path.join( + args.output, f"rank_{rank}_{args.model_name}_decoder_with_past_model_fp32.onnx" + ) + decoder_merged_model_fp32_path = os.path.join( + args.output, f"rank_{rank}_{args.model_name}_decoder_merged_model_fp32.onnx" + ) + old_paths = [decoder_model_fp32_path, decoder_with_past_model_fp32_path, decoder_merged_model_fp32_path] + + missing_separate_exports = ( + args.no_merged + and not os.path.exists(decoder_model_fp32_path) + and not os.path.exists(decoder_with_past_model_fp32_path) + ) + missing_merged_export = not args.no_merged and not os.path.exists(decoder_merged_model_fp32_path) + + # Export to ONNX + if missing_separate_exports or missing_merged_export: + if args.use_dynamo_export: + logger.warning("Please ensure you have installed PyTorch, ONNX, and ONNX Script as follows.") + logger.warning("Step 1 - PyTorch nightly: https://pytorch.org/get-started/locally/") + logger.warning("Step 2 - ONNX weekly: https://pypi.org/project/onnx-weekly/") + logger.warning( + "Step 3 - ONNX Script from source: https://github.com/microsoft/onnxscript#installing-onnx-script" + ) + logger.warning( + "Note: After you install ONNX weekly, omit `onnx` when running the first line for installing ONNX Script. This is because you already installed `onnx-weekly` in the previous step." + ) + run_dynamo_export(args, l_config, llama) + elif args.no_merged: + run_torchscript_separate_export(args, l_config, llama, rank, world_size) + else: + run_torchscript_merged_export(args, l_config, llama, rank, world_size) + del llama # Delete LLaMA model from memory since it will be loaded again during parity check + + # Set model paths to store FP32 optimized model + decoder_model_fp32_opt_path = os.path.join( + args.output, f"rank_{rank}_{args.model_name}_decoder_model_fp32_opt.onnx" + ) + decoder_with_past_model_fp32_opt_path = os.path.join( + args.output, f"rank_{rank}_{args.model_name}_decoder_with_past_model_fp32_opt.onnx" + ) + decoder_merged_model_fp32_opt_path = os.path.join( + args.output, f"rank_{rank}_{args.model_name}_decoder_merged_model_fp32_opt.onnx" + ) + new_paths = [ + decoder_model_fp32_opt_path, + decoder_with_past_model_fp32_opt_path, + decoder_merged_model_fp32_opt_path, + ] + + # Run the optimizer script. + logger.info("Optimizing models...") + for orig_path, opt_path in zip(old_paths, new_paths, strict=False): + if os.path.exists(orig_path): + optimize_export(args, l_config, input_path=orig_path, output_path=opt_path, world_size=world_size) + + # Re-assign default FP32 model paths as their optimized versions + decoder_model_fp32_path = decoder_model_fp32_opt_path + decoder_with_past_model_fp32_path = decoder_with_past_model_fp32_opt_path + decoder_merged_model_fp32_path = decoder_merged_model_fp32_opt_path + old_paths = [decoder_model_fp32_path, decoder_with_past_model_fp32_path, decoder_merged_model_fp32_path] + + logger.info( + f"The {args.model_name} ONNX model has been successfully optimized with the ORT transformer optimizer script!" + ) + + # Change precision of exported models from FP32 + if args.precision == Precision.FLOAT16: + new_paths = convert_to_float16(args, old_paths, rank) + + elif args.precision == Precision.INT8: + decoder_model_int8_path = os.path.join( + args.output, f"rank_{rank}_{args.model_name}_decoder_model_int8.onnx" + ) + decoder_with_past_model_int8_path = os.path.join( + args.output, f"rank_{rank}_{args.model_name}_decoder_with_past_model_int8.onnx" + ) + decoder_merged_model_int8_path = os.path.join( + args.output, f"rank_{rank}_{args.model_name}_decoder_merged_model_int8.onnx" + ) + new_paths = [decoder_model_int8_path, decoder_with_past_model_int8_path, decoder_merged_model_int8_path] + + if args.quantization_method == "smooth_quant": + if not args.no_merged: + logger.error("SmoothQuant must be used on separately exported models") + else: + logger.info( + f"Quantizing {decoder_model_fp32_path} and {decoder_with_past_model_fp32_path} to int8" + ) + smooth_quant(args, old_paths[0], old_paths[1], new_paths[0], new_paths[1]) + + elif args.quantization_method == "quantize_dynamic": + logger.warning( + "The `quantize_dynamic` method is deprecated in favor of `smooth_quant` instead. Precision loss may be high with `quantize_dynamic`." + ) + + logger.info("Quantizing to int8...") + for fp32_path, int8_path in zip(old_paths, new_paths, strict=False): + if os.path.exists(fp32_path): + ort_quantization.quantize_dynamic( + fp32_path, + int8_path, + op_types_to_quantize=( + ["MatMul", "Gemm", "Gather"] + if args.quantize_embedding_layer + else ["MatMul", "Gemm"] + ), + per_channel=args.quantize_per_channel, + reduce_range=args.quantize_reduce_range, + use_external_data_format=True, + extra_options={"MatMulConstBOnly": True}, + ) + logger.info( + f"The ONNX model at {fp32_path} has been quantized to int8 and saved at {int8_path}!" + ) + remove_existing_model(decoder_model_fp32_path) + + logger.info(f"The {args.model_name} ONNX model has been successfully quantized to int8!") + + else: + raise Exception(f"Could not recognize {args.quantization_method} as a quantization method") + + elif args.precision == Precision.INT4: + if args.execution_provider != "cpu": + old_paths = convert_to_float16(args, old_paths, rank) + + decoder_model_int4_path = os.path.join( + args.output, f"rank_{rank}_{args.model_name}_decoder_model_int4.onnx" + ) + decoder_with_past_model_int4_path = os.path.join( + args.output, f"rank_{rank}_{args.model_name}_decoder_with_past_model_int4.onnx" + ) + decoder_merged_model_int4_path = os.path.join( + args.output, f"rank_{rank}_{args.model_name}_decoder_merged_model_int4.onnx" + ) + new_paths = [decoder_model_int4_path, decoder_with_past_model_int4_path, decoder_merged_model_int4_path] + + for fp_path, int4_path in zip(old_paths, new_paths, strict=False): + if os.path.exists(fp_path): + model = onnx.load_model(fp_path, load_external_data=True) + quant = MatMulNBitsQuantizer( + model=model, + bits=args.bits, + block_size=args.block_size, + is_symmetric=True, + accuracy_level=args.int4_accuracy_level, + nodes_to_exclude=[], + ) + quant.process() + quant.model.save_model_to_file(int4_path, use_external_data_format=True) + del model + del quant + logger.info(f"The ONNX model at {fp_path} has been quantized to int4 and saved at {int4_path}!") + remove_existing_model(fp_path) + barrier() + + logger.info("Verifying parity on all ONNX models created") + + # Use FP32 precision for FP32, INT8, INT4 CPU models, use FP16 precision for FP16 and INT4 GPU models + args.precision = ( + "fp32" + if args.precision in {Precision.INT8, Precision.FLOAT32} + or (args.precision == Precision.INT4 and args.execution_provider == "cpu") + else "fp16" + ) + + # Verify parity on all saved ONNX models + for filename in os.listdir(args.output): + if ( + ".data" in filename + or ".onnx" not in filename + or args.precision not in filename + or f"rank_{rank}" not in filename + ): + continue + + parity_cmd = [ + "-m", + original_model_name, + "-o", + os.path.join(args.output, filename), + "-ep", + args.execution_provider, + "--precision", + args.precision, + "--cache_dir", + args.cache_dir, + "--torch_model_directory", + args.input, + ] + if args.small_gpu: + parity_cmd.append("--small_gpu") + if "with_past" in filename: + parity_cmd.append("--use_past_kv") + if "merged" in filename: + parity_cmd.append("--merged") + + try: + logger.info(f"check parity with cmd: {parity_cmd}") + parity_check(parity_cmd) + except Exception as e: + logger.exception(f"An error occurred while verifying parity: {e}") + sys.exit(-1) + + +if __name__ == "__main__": + main() diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/llama/dist_settings.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/llama/dist_settings.py new file mode 100644 index 0000000000000000000000000000000000000000..db8f8eae7f841e8cbeac0416b44b4dc60ebcccb0 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/llama/dist_settings.py @@ -0,0 +1,57 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- +import os + +import torch.distributed as dist + + +def init_dist(): + if "LOCAL_RANK" in os.environ: + int(os.environ["LOCAL_RANK"]) + rank = int(os.environ["RANK"]) + world_size = int(os.environ["WORLD_SIZE"]) + + dist.init_process_group("nccl", init_method="tcp://127.0.0.1:7645", world_size=world_size, rank=rank) + elif "OMPI_COMM_WORLD_LOCAL_RANK" in os.environ: + int(os.environ.get("OMPI_COMM_WORLD_LOCAL_RANK", "0")) + rank = int(os.environ.get("OMPI_COMM_WORLD_RANK", "0")) + world_size = int(os.environ.get("OMPI_COMM_WORLD_SIZE", "1")) + + dist.init_process_group("nccl", init_method="tcp://127.0.0.1:7647", world_size=world_size, rank=rank) + else: + # don't need to do init for single process + pass + + +def _get_comm(): + try: + from mpi4py import MPI # noqa: PLC0415 + + comm = MPI.COMM_WORLD + return comm + except ImportError: + return None + + +def get_rank(): + comm = _get_comm() + return comm.Get_rank() if comm is not None else 0 + + +def get_size(): + comm = _get_comm() + return comm.Get_size() if comm is not None else 1 + + +def barrier(): + comm = _get_comm() + if comm is not None: + comm.Barrier() + + +def print_out(*args): + if get_rank() == 0: + print(*args) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/llama/llama_inputs.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/llama/llama_inputs.py new file mode 100644 index 0000000000000000000000000000000000000000..71b312eb9360daf78370d9f7bd5f260445ab9ec2 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/llama/llama_inputs.py @@ -0,0 +1,504 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- +from __future__ import annotations + +import numpy as np +import torch +from transformers import AutoConfig, AutoTokenizer +from transformers.cache_utils import DynamicCache + +from onnxruntime import InferenceSession, OrtValue + + +# Get position_ids from attention_mask +def get_position_ids(attention_mask: torch.Tensor, use_past_kv: bool): + position_ids = attention_mask.long().cumsum(-1) - 1 + position_ids.masked_fill_(attention_mask == 0, 1) + if use_past_kv: + # Shape: (batch_size, 1) + position_ids = position_ids[:, -1].unsqueeze(-1) + + # Shape: (batch_size, sequence_length) + return position_ids + + +# Inputs for first pass to get initial past_key_values +# input_ids: (batch_size, sequence_length) +# attention_mask: (batch_size, sequence_length) +# position_ids: (batch_size, sequence_length) +def get_sample_inputs( + config: AutoConfig, + device: torch.device, + batch_size: int, + seq_len: int, + engine: str = "pt", + return_dict: bool = False, +): + input_ids = torch.randint(low=0, high=config.vocab_size, size=(batch_size, seq_len), dtype=torch.int64) + attention_mask = torch.ones(batch_size, seq_len, dtype=torch.int64) + position_ids = get_position_ids(attention_mask, use_past_kv=False) + + # Convert inputs to NumPy (for ORT) or send to device (for PyTorch) + input_ids = input_ids.numpy() if engine == "ort" else input_ids.to(device) + attention_mask = attention_mask.numpy() if engine == "ort" else attention_mask.to(device) + position_ids = position_ids.numpy() if engine == "ort" else position_ids.to(device) + + if not return_dict: + # For export + return (input_ids, attention_mask, position_ids) + + inputs = { + "input_ids": input_ids, + "attention_mask": attention_mask, + "position_ids": position_ids, + } + return inputs + + +# Inputs for subsequent passes with past_key_values +# input_ids: (batch_size, 1) +# attention_mask: (batch_size, past_sequence_length + 1) +# position_ids: (batch_size, 1) +# past_key: (batch_size, num_heads, past_sequence_length, head_size) +# past_value: (batch_size, num_heads, past_sequence_length, head_size) +def get_sample_with_past_kv_inputs( + config: AutoConfig, + device: torch.device, + batch_size: int, + past_seq_len: int, + use_fp16: bool = False, + engine: str = "pt", + return_dict: bool = False, + world_size: int = 1, +): + input_ids = torch.randint(low=0, high=config.vocab_size, size=(batch_size, 1), dtype=torch.int64) + attention_mask = torch.ones(batch_size, past_seq_len + 1, dtype=torch.int64) + # position_ids is of shape (batch_size, 1) + position_ids = get_position_ids(attention_mask, use_past_kv=True) + past_kv = get_past_kv_inputs(config, batch_size, past_seq_len, use_fp16, world_size=world_size) + + # Convert inputs to NumPy (for ORT) or send to device (for PyTorch) + input_ids = input_ids.numpy() if engine == "ort" else input_ids.to(device) + attention_mask = attention_mask.numpy() if engine == "ort" else attention_mask.to(device) + position_ids = position_ids.numpy() if engine == "ort" else position_ids.to(device) + past_kv = ( + flatten_past_kv_inputs(past_kv) if engine == "ort" else [(kv[0].to(device), kv[1].to(device)) for kv in past_kv] + ) + + if not return_dict: + # For export + assert isinstance(past_kv, list) + return (input_ids, attention_mask, position_ids, past_kv) + + inputs = { + "input_ids": input_ids, + "attention_mask": attention_mask, + "position_ids": position_ids, + } + if engine == "ort": + assert isinstance(past_kv, dict) + inputs.update(past_kv) + else: + assert isinstance(past_kv, list) + inputs["past_key_values"] = past_kv + + return inputs + + +# Inputs for all passes with past_key_values +# input_ids: (batch_size, sequence_length) +# attention_mask: (batch_size, past_sequence_length + sequence_length) +# position_ids: (batch_size, sequence_length) +# past_key: (batch_size, num_heads, kv_sequence_length, head_size) +# For models with GQA, kv_sequence_length = max_sequence_length +# For models without GQA, kv_sequence_length = past_sequence_length +# past_value: (batch_size, num_heads, kv_sequence_length, head_size) +# For models with GQA, kv_sequence_length = max_sequence_length +# For models without GQA, kv_sequence_length = past_sequence_length +def get_merged_sample_with_past_kv_inputs( + config: AutoConfig, + device: torch.device, + batch_size: int, + seq_len: int, + past_seq_len: int, + max_seq_len: int, + use_fp16: bool = False, + use_buffer_share: bool = False, + engine: str = "pt", + return_dict: bool = False, + world_size: int = 1, +): + input_ids = torch.randint(low=0, high=config.vocab_size, size=(batch_size, seq_len), dtype=torch.int64) + attention_mask = torch.ones(batch_size, past_seq_len + seq_len, dtype=torch.int64) + # position_ids is of shape (batch_size, seq_len) for prompt generation, (batch_size, 1) for token generation + position_ids = get_position_ids(attention_mask, use_past_kv=(past_seq_len != 0)) + past_kv = get_past_kv_inputs(config, batch_size, past_seq_len, use_fp16, world_size=world_size) + + # Convert inputs to NumPy (for ORT) or send to device (for PyTorch) + input_ids = input_ids.numpy() if engine == "ort" else input_ids.to(device) + attention_mask = attention_mask.numpy() if engine == "ort" else attention_mask.to(device) + position_ids = position_ids.numpy() if engine == "ort" else position_ids.to(device) + past_kv = ( + flatten_past_kv_inputs(past_kv) if engine == "ort" else [(kv[0].to(device), kv[1].to(device)) for kv in past_kv] + ) + + if not return_dict: + # For export + assert isinstance(past_kv, list) + return (input_ids, attention_mask, position_ids, past_kv) + + inputs = { + "input_ids": input_ids, + "attention_mask": attention_mask, + "position_ids": position_ids, + } + if engine == "ort": + assert isinstance(past_kv, dict) + inputs.update(past_kv) + + if use_buffer_share: + inputs = enable_past_present_share_buffer(inputs, past_seq_len, max_seq_len) + + else: + assert isinstance(past_kv, list) + inputs["past_key_values"] = past_kv + + return inputs + + +# Inputs for Microsoft export from https://github.com/microsoft/Llama-2-Onnx +def get_msft_sample_inputs( + config: AutoConfig, + batch_size: int, + past_seq_len: int, + seq_len: int, + max_seq_len: int, + use_fp16: bool, + use_buffer_share: bool, + split_kv: bool, +): + np_dtype = np.float16 if use_fp16 else np.float32 + head_size = config.hidden_size // config.num_attention_heads + + if not split_kv: + ort_inputs = { + "x": np.random.rand(batch_size, seq_len, config.hidden_size).astype(np_dtype), + "attn_mask": (-10000.0 * np.triu(np.ones((batch_size, max_seq_len, max_seq_len)), k=1)).astype(np_dtype), + "k_cache": np.random.rand( + batch_size, config.num_hidden_layers, past_seq_len, config.num_attention_heads, head_size + ).astype(np_dtype), + "v_cache": np.random.rand( + batch_size, config.num_hidden_layers, past_seq_len, config.num_attention_heads, head_size + ).astype(np_dtype), + "pos": np.array(past_seq_len, dtype=np.int64), + } + else: + ort_inputs = { + "x": np.random.rand(batch_size, seq_len, config.hidden_size).astype(np_dtype), + "attn_mask": (np.triu(np.ones((batch_size, max_seq_len, max_seq_len), dtype=np.int32), k=1) - 1).astype( + np.int32 + ), + "pos": np.array(past_seq_len, dtype=np.int64), + } + for i in range(config.num_hidden_layers): + ort_inputs.update( + { + f"k_{i}_cache": np.random.rand( + batch_size, config.num_attention_heads, past_seq_len, head_size + ).astype(np_dtype), + f"v_{i}_cache": np.random.rand( + batch_size, config.num_attention_heads, past_seq_len, head_size + ).astype(np_dtype), + } + ) + + if use_buffer_share: + ort_inputs = enable_past_present_share_buffer(ort_inputs, past_seq_len, max_seq_len) + + return ort_inputs + + +# Create past_key_values +# Each is of shape (batch_size, num_heads, past_sequence_length, head_size) +def get_past_kv_inputs(config: AutoConfig, batch_size: int, past_seq_len: int, use_fp16: bool, world_size: int = 1): + num_heads = config.num_key_value_heads // world_size + head_size = config.head_dim if hasattr(config, "head_dim") else config.hidden_size // config.num_attention_heads + torch_dtype = torch.float16 if use_fp16 else torch.float32 + past_kv = [ + ( + torch.rand(batch_size, num_heads, past_seq_len, head_size, dtype=torch_dtype), + torch.rand(batch_size, num_heads, past_seq_len, head_size, dtype=torch_dtype), + ) + for _ in range(config.num_hidden_layers) + ] + return past_kv + + +# Convert list of past_key_values to dict of past_key and past_value +def flatten_past_kv_inputs(past_key_values: list[tuple[torch.Tensor, torch.Tensor]]): + past_kv = {} + for i, (past_k, past_v) in enumerate(past_key_values): + if isinstance(past_key_values, DynamicCache): + past_kv[f"past_key_values_key_cache_{i}"] = past_k.detach().cpu().numpy() + past_kv[f"past_key_values_value_cache_{i}"] = past_v.detach().cpu().numpy() + else: + past_kv[f"past_key_values.{i}.key"] = past_k.detach().cpu().numpy() + past_kv[f"past_key_values.{i}.value"] = past_v.detach().cpu().numpy() + return past_kv + + +# Format PyTorch inputs to ONNX Runtime inputs +def convert_inputs_for_ort( + pt_inputs: dict, + use_buffer_share: bool = False, + past_seq_len: int = 0, + max_seq_len: int = 2048, +): + ort_inputs = {} + for k, v in pt_inputs.items(): + if isinstance(v, np.ndarray): + ort_inputs[k] = v + elif k == "past_key_values": + ort_inputs.update(flatten_past_kv_inputs(v)) + else: + ort_inputs[k] = v.detach().cpu().numpy() + + # Reshape KV caches if using past-present-share-buffer + if use_buffer_share: + ort_inputs = enable_past_present_share_buffer(ort_inputs, past_seq_len, max_seq_len) + + return ort_inputs + + +# Re-allocate KV caches from (batch_size, num_heads, past_sequence_length, head_size) to +# (batch_size, num_heads, max_sequence_length, head_size) for past-present buffer sharing +def enable_past_present_share_buffer(ort_inputs: dict, past_seq_len: int, max_seq_len: int): + for k, v in ort_inputs.items(): + # Allocate new buffers with max_sequence_length for GQA + if "cache" in k or "past_key_values" in k: + # Copy v (BxSxPxH) into new_v (BxSxMxH) + batch_size, num_heads, _, head_size = v.shape + new_v = np.zeros((batch_size, num_heads, max_seq_len, head_size), dtype=v.dtype) + new_v[:batch_size, :num_heads, :past_seq_len, :head_size] = v + ort_inputs[k] = new_v + return ort_inputs + + +# Verify ONNX Runtime inputs with model +def verify_ort_inputs(model: InferenceSession, ort_inputs: dict): + # Check that all model inputs will be provided + model_inputs = {model_input.name for model_input in model.get_inputs()} + user_inputs = set(ort_inputs.keys()) + missing_inputs = model_inputs - user_inputs + if len(missing_inputs): + print(f"The following model inputs are missing: {missing_inputs}") + raise Exception("There are missing inputs to the model. Please add them and try again.") + + # Remove unnecessary inputs from model inputs + unnecessary_inputs = user_inputs - model_inputs + if len(unnecessary_inputs): + for unnecessary_input in unnecessary_inputs: + del ort_inputs[unnecessary_input] + + return ort_inputs + + +# Add IO bindings for execution providers using OrtValue +# Use when you need to run inference once or twice to save memory +def add_io_bindings_as_ortvalues( + model: InferenceSession, + ort_inputs: dict, + device: str, + device_id: int, + use_buffer_share: bool, + kv_cache_ortvalues: dict, +): + io_binding = model.io_binding() + + model_inputs = {i.name for i in model.get_inputs()} + for k, v in ort_inputs.items(): + # Use this check to handle scenarios such as INT4 CUDA and FP16 CUDA models with + # GQA + RotaryEmbedding fusion where `position_ids` is removed as an ONNX model input + # but `position_ids` is used as a PyTorch model input + if k not in model_inputs: + continue + + # Bind OrtValue inputs to device + if use_buffer_share and ("cache" in k or "past_key_values" in k): + if k not in kv_cache_ortvalues: + v_device = OrtValue.ortvalue_from_numpy(v, device_type=device, device_id=device_id) + io_binding.bind_ortvalue_input(k, v_device) + kv_cache_ortvalues[k] = v_device + else: + kv_cache_ortvalues[k].update_inplace(v) + io_binding.bind_ortvalue_input(k, kv_cache_ortvalues[k]) + else: + v_device = OrtValue.ortvalue_from_numpy(v, device_type=device, device_id=device_id) + io_binding.bind_ortvalue_input(k, v_device) + + for output in model.get_outputs(): + name = output.name + if use_buffer_share and ("out" in name or "present" in name): + # Bind present KV cache outputs to past KV cache inputs in order to buffer share + input_name = name.replace("out", "cache").replace("present", "past_key_values") + io_binding.bind_ortvalue_output(name, kv_cache_ortvalues[input_name]) + else: + io_binding.bind_output(name, device_type=device, device_id=device_id) + + return io_binding, kv_cache_ortvalues + + +# Add IO bindings for execution providers using PyTorch tensors +# Use when you need to run inference many times +def add_io_bindings_as_tensors( + model: InferenceSession, inputs: dict, outputs: dict, use_fp16: bool, use_buffer_share: bool +): + # Verify model inputs + inputs = verify_ort_inputs(model, inputs) + + device = None + pt_to_np = { + "torch.int32": np.int32, + "torch.int64": np.int64, + "torch.float16": np.float16, + "torch.float32": np.float32, + } + + # Bind inputs/outputs to IO binding + io_binding = model.io_binding() + for k, v in inputs.items(): + io_binding.bind_input( + name=k, + device_type=v.device.type, + device_id=0 if v.device.type == "cpu" else v.device.index, + element_type=pt_to_np[repr(v.dtype)], + shape=tuple(v.shape), + buffer_ptr=v.data_ptr(), + ) + device = v.device + + for output in model.get_outputs(): + name = output.name + # Bind KV cache outputs to KV cache inputs + v = ( + inputs[name.replace("present", "past_key_values")] + if use_buffer_share and "present" in name + else outputs[name] + ) + io_binding.bind_output( + name=name, + device_type=device.type, + device_id=0 if device.type == "cpu" else device.index, + element_type=(np.float16 if use_fp16 else np.float32), + shape=tuple(v.shape), + buffer_ptr=v.data_ptr(), + ) + + return io_binding + + +# Get actual inputs when using real data (instead of sample data) and initialize outputs +def get_initial_inputs_and_outputs( + config: AutoConfig, + tokenizer: AutoTokenizer, + requested_length: int, + prompt: list[str], + device: torch.device, + use_fp16: bool, + use_buffer_share: bool, + engine: str, +): + tokenizer.pad_token = tokenizer.eos_token + encodings_dict = tokenizer.batch_encode_plus(prompt, padding=True) + torch_dtype = torch.float16 if use_fp16 else torch.float32 + + # input_ids: pad token id is 0 + # attention_mask: pad token id is 0 + # position_ids: pad token id is 1 + input_ids = torch.tensor(encodings_dict["input_ids"], device=device, dtype=torch.int64) + attention_mask = torch.tensor(encodings_dict["attention_mask"], device=device, dtype=torch.int64) + position_ids = get_position_ids(attention_mask, use_past_kv=False) + + # Check if tokenized prompt length matches the requested prompt length + tokenized_length = input_ids.shape[-1] + if tokenized_length > requested_length: + # Shorten the inputs from (batch_size, tokenized_length) to (batch_size, requested_length) + input_ids = input_ids[:, :requested_length] + attention_mask = attention_mask[:, :requested_length] + position_ids = get_position_ids(attention_mask, use_past_kv=False) + elif tokenized_length < requested_length: + # Lengthen the inputs from (batch_size, tokenized_length) to (batch_size, requested_length) + input_ids_first_col = input_ids[:, 0].unsqueeze(0).T + attention_mask_first_col = attention_mask[:, 0].unsqueeze(0).T + for _ in range(requested_length - tokenized_length): + input_ids = torch.hstack((input_ids_first_col, input_ids)) + attention_mask = torch.hstack((attention_mask_first_col, attention_mask)) + position_ids = get_position_ids(attention_mask, use_past_kv=False) + + tokenized_length = input_ids.shape[-1] + assert tokenized_length == requested_length + + # Create inputs + inputs = { + "input_ids": input_ids.contiguous() if engine == "ort" else input_ids, + "attention_mask": attention_mask.contiguous() if engine == "ort" else attention_mask, + "position_ids": position_ids.contiguous() if engine == "ort" else position_ids, + } + if engine != "ort": + inputs["past_key_values"] = [] + + # Get shape of KV cache inputs + batch_size, sequence_length = input_ids.shape + max_sequence_length = config.max_position_embeddings + num_heads = config.num_key_value_heads + head_size = config.head_dim if hasattr(config, "head_dim") else config.hidden_size // config.num_attention_heads + + # Create KV cache inputs + for i in range(config.num_hidden_layers): + past_key = torch.zeros( + batch_size, + num_heads, + max_sequence_length if use_buffer_share else 0, + head_size, + device=device, + dtype=torch_dtype, + ) + past_value = torch.zeros( + batch_size, + num_heads, + max_sequence_length if use_buffer_share else 0, + head_size, + device=device, + dtype=torch_dtype, + ) + if engine == "ort": + inputs.update( + { + f"past_key_values.{i}.key": past_key.contiguous(), + f"past_key_values.{i}.value": past_value.contiguous(), + } + ) + else: + inputs["past_key_values"].append((past_key, past_value)) + + outputs = None + if engine == "ort": + # Create outputs + logits = torch.zeros(batch_size, sequence_length, config.vocab_size, device=device, dtype=torch_dtype) + outputs = {"logits": logits.contiguous()} + if not use_buffer_share: + for i in range(config.num_hidden_layers): + present_key = torch.zeros( + batch_size, num_heads, sequence_length, head_size, device=device, dtype=torch_dtype + ) + present_value = torch.zeros( + batch_size, num_heads, sequence_length, head_size, device=device, dtype=torch_dtype + ) + outputs.update( + {f"present.{i}.key": present_key.contiguous(), f"present.{i}.value": present_value.contiguous()} + ) + + return inputs, outputs diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/llama/llama_parity.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/llama/llama_parity.py new file mode 100644 index 0000000000000000000000000000000000000000..f4037e2c5e1495fee5489fe49613884bd03e9e37 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/llama/llama_parity.py @@ -0,0 +1,343 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- +from __future__ import annotations + +import argparse +import logging +import os +import time + +import numpy as np +import packaging.version as pv +import torch +from benchmark_helper import setup_logger +from dist_settings import get_rank, get_size +from llama_inputs import ( + add_io_bindings_as_ortvalues, + convert_inputs_for_ort, + get_merged_sample_with_past_kv_inputs, + get_sample_inputs, + get_sample_with_past_kv_inputs, + verify_ort_inputs, +) +from llama_torch import setup_torch_model +from models.torch_export_patches.cache_helper import make_dynamic_cache +from transformers import AutoConfig +from transformers import __version__ as transformers_version +from transformers.cache_utils import DynamicCache + +import onnxruntime as ort + +logger = logging.getLogger("") + + +def get_sequence_lengths(args: argparse.Namespace, config: AutoConfig): + past_sequence_length, curr_sequence_length = (8, 1) if args.use_past_kv else (0, 8) + max_sequence_length = config.max_position_embeddings + return past_sequence_length, curr_sequence_length, max_sequence_length + + +def get_inputs(args: argparse.Namespace, config: AutoConfig): + # Dummy values for parity + world_size = get_size() + batch_size = 2 + past_sequence_length, sequence_length, max_sequence_length = get_sequence_lengths(args, config) + + if args.merged: + inputs = get_merged_sample_with_past_kv_inputs( + config, + args.device, + batch_size, + seq_len=sequence_length, + past_seq_len=past_sequence_length, + max_seq_len=max_sequence_length, + use_fp16=args.use_fp16, + use_buffer_share=args.use_buffer_share, + return_dict=True, + world_size=world_size, + ) + elif args.use_past_kv: + inputs = get_sample_with_past_kv_inputs( + config, + args.device, + batch_size, + sequence_length, + use_fp16=args.use_fp16, + return_dict=True, + world_size=world_size, + ) + else: + inputs = get_sample_inputs(config, args.device, batch_size, sequence_length, return_dict=True) + + return inputs + + +def torch_deepcopy(value): + if isinstance(value, (int, float, str)): + return value + if isinstance(value, tuple): + return tuple(torch_deepcopy(v) for v in value) + if isinstance(value, list): + return [torch_deepcopy(v) for v in value] + if isinstance(value, set): + return {torch_deepcopy(v) for v in value} + if isinstance(value, dict): + return {k: torch_deepcopy(v) for k, v in value.items()} + if isinstance(value, np.ndarray): + return value.copy() + if hasattr(value, "clone"): + return value.clone() + if isinstance(value, DynamicCache): + return make_dynamic_cache(torch_deepcopy(list(zip(value.key_cache, value.value_cache, strict=False)))) + # We should have a code using serialization, deserialization assuming a model + # cannot be exported without them. + raise NotImplementedError(f"torch_deepcopy not implemented for type {type(value)}") + + +def verify_parity( + args: argparse.Namespace, + location: str, + use_auth_token: bool, + kv_cache_ortvalues: dict, + pytorch_model: None | torch.nn.Module = None, + config: None | AutoConfig = None, +): + # If it's running in a machine where GPU memory < 36GB, it should unload the model in GPU in time and free the GPU memory for ORT. + py_model = pytorch_model + if py_model is None: + config, py_model = setup_torch_model( + args, + location, + use_auth_token, + torch_dtype=(torch.float16 if args.use_fp16 else torch.float32), + device=args.device, + ) + + inputs = get_inputs(args, config) + + if "past_key_values" in inputs and pv.Version(transformers_version) >= pv.Version("4.45"): + # Using DynamicCache + inputs["past_key_values"] = make_dynamic_cache(inputs["past_key_values"]) + + # Run inference with PyTorch + inputs_after_deepcopy = torch_deepcopy(inputs) + if args.execution_provider != "cpu": + torch.cuda.synchronize() + start_time = time.time() + # If there is a cache in the inputs, we need to make a copy as the model modifies them inplace. + # DynamicCache inherits from torch.nn.Module in some version of transformers. + # We need to make the copy manually. + pt_outputs = py_model(**inputs_after_deepcopy).logits.detach().cpu().numpy() + if args.execution_provider != "cpu": + torch.cuda.synchronize() + end_time = time.time() + logger.info(f"PyTorch took {end_time - start_time} s") + + if args.small_gpu and py_model is not None: + del py_model + torch.cuda.empty_cache() + + # Run inference with ORT + past_sequence_length, _, max_sequence_length = get_sequence_lengths(args, config) + inputs = convert_inputs_for_ort( + inputs, + use_buffer_share=args.use_buffer_share, + past_seq_len=past_sequence_length, + max_seq_len=max_sequence_length, + ) + + ep = f"{args.execution_provider.upper()}ExecutionProvider" + if ep == "CUDAExecutionProvider": + ep = (ep, {"device_id": args.rank}) + ort_model = ort.InferenceSession( + args.onnx_model_path, + sess_options=ort.SessionOptions(), + providers=[ep], + ) + inputs = verify_ort_inputs(ort_model, inputs) + + # Add IO bindings for non-CPU execution providers + if args.execution_provider != "cpu": + io_binding, kv_cache_ortvalues = add_io_bindings_as_ortvalues( + ort_model, + ort_inputs=inputs, + device=args.execution_provider, + device_id=int(args.rank), + use_buffer_share=args.use_buffer_share, + kv_cache_ortvalues=kv_cache_ortvalues, + ) + + io_binding.synchronize_inputs() + start_time = time.time() + ort_model.run_with_iobinding(io_binding) + io_binding.synchronize_outputs() + end_time = time.time() + + ort_outputs = io_binding.copy_outputs_to_cpu()[0] # Get logits + del ort_model + + else: + start_time = time.time() + ort_outputs = ort_model.run(None, inputs) + end_time = time.time() + + ort_outputs = ort_outputs[0] # Get logits + + logger.info(f"ONNX Runtime took {end_time - start_time} s") + + # Compare PyTorch and ONNX Runtime accuracy + tol = 2e1 if "int4" in args.onnx_model_path or "int8" in args.onnx_model_path else 5e-1 + parity = np.allclose(pt_outputs, ort_outputs, rtol=tol, atol=tol) + logger.warning(f"Are PyTorch and ONNX Runtime results close? {parity}") + if not parity: + logger.warning(f"Max diff: {np.max(pt_outputs - ort_outputs)}") + return kv_cache_ortvalues + + +def get_args(argv: list[str]): + parser = argparse.ArgumentParser() + + parser.add_argument( + "-m", + "--model_name", + required=False, + help="Model name in Hugging Face", + ) + + parser.add_argument( + "-t", + "--torch_model_directory", + required=False, + default=os.path.join("."), + help="Path to folder containing PyTorch model and associated files if saved on disk", + ) + + parser.add_argument( + "-o", + "--onnx_model_path", + required=True, + default=os.path.join("."), + help="Path to ONNX model (with external data files saved in the same folder as the model)", + ) + + parser.add_argument( + "-ep", + "--execution_provider", + required=False, + default="cpu", + choices=["cpu", "cuda"], + help="Execution provider to verify parity with", + ) + + parser.add_argument( + "-v", + "--verbose", + action="store_true", + help="Print verbose logs", + ) + parser.set_defaults(verbose=False) + + parser.add_argument( + "-p", + "--use_past_kv", + action="store_true", + help="Use past key and past value as inputs to the model. Necessary for decoder_with_past_model.onnx models.", + ) + parser.set_defaults(use_past_kv=False) + + parser.add_argument( + "-g", + "--use_buffer_share", + action="store_true", + help="Use if model has GroupQueryAttention and you want to enable past-present buffer sharing", + ) + parser.set_defaults(use_buffer_share=False) + + parser.add_argument( + "--merged", + action="store_true", + help="Use merged model (i.e. decoder_merged_model.onnx).", + ) + parser.set_defaults(merged=False) + + parser.add_argument( + "-fp", + "--precision", + required=True, + choices=["int4", "int8", "fp16", "fp32"], + help="Precision of model", + ) + + parser.add_argument( + "--cache_dir", + required=False, + type=str, + default="./model_cache", + help="model cache dir to override default HF cache dir to avoid overflood the /home dir", + ) + + # The argument is used for CI mainly, because the CI machine has 24G GPU memory at most. + parser.add_argument( + "--small_gpu", + action="store_true", + help="Load the llama in GPU every time for parity_check if it's running in a machine which GPU memory < 36GB. ", + ) + + args = parser.parse_args() if argv == [] else parser.parse_args(argv) + + # Use FP32 precision for FP32, INT8, INT4 CPU models, use FP16 precision for FP16 and INT4 GPU models + args.precision = ( + "fp32" + if args.precision in {"int8", "fp32"} or (args.precision == "int4" and args.execution_provider == "cpu") + else "fp16" + ) + return args + + +def main(argv: list[str] = []): # noqa: B006 + args = get_args(argv) + setup_logger(args.verbose) + logger.info(f"Arguments: {args}") + rank = get_rank() + + # Load model and config + setattr(args, "use_fp16", args.precision == "fp16") # noqa: B010 + args.rank = rank + setattr(args, "device_name", "cpu" if args.execution_provider == "cpu" else f"cuda:{rank}") # noqa: B010 + setattr(args, "device", torch.device(args.device_name)) # noqa: B010 + use_auth_token = args.torch_model_directory == os.path.join(".") + location = args.model_name if use_auth_token else args.torch_model_directory + + kv_cache_ortvalues = {} + if not args.merged: + verify_parity(args, location, use_auth_token, kv_cache_ortvalues) + else: + config = llama = None + if not args.small_gpu: + config, llama = setup_torch_model( + args, + location, + use_auth_token, + torch_dtype=(torch.float16 if args.use_fp16 else torch.float32), + device=args.device, + ) + + # Verify prompt processing in merged model (decoder_model.onnx) + args.use_past_kv = False + kv_cache_ortvalues = verify_parity( + args, location, use_auth_token, kv_cache_ortvalues, pytorch_model=llama, config=config + ) + + # Verify token generation in merged model (decoder_with_past_model.onnx) + args.use_past_kv = True + verify_parity(args, location, use_auth_token, kv_cache_ortvalues, pytorch_model=llama, config=config) + + +if __name__ == "__main__": + seed = 2 + np.random.seed(seed) + torch.manual_seed(seed) + main() diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/llama/llama_torch.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/llama/llama_torch.py new file mode 100644 index 0000000000000000000000000000000000000000..41d6b8afedc078f30016b95aa5f53e5c6e2311e7 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/llama/llama_torch.py @@ -0,0 +1,47 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- +import logging +import os + +import torch +from dist_settings import barrier, get_rank, get_size +from transformers import AutoConfig, AutoModelForCausalLM + +logger = logging.getLogger("") + + +def setup_torch_model(args, location, auth, torch_dtype=torch.float32, device=None): + world_size = get_size() + logger.info(f"world_size: {world_size}") + rank = get_rank() + barrier() + + if not os.path.exists(args.cache_dir): + os.makedirs(args.cache_dir, exist_ok=True) + + for i in range(world_size): + if i == rank % (world_size): + l_config = AutoConfig.from_pretrained( + location, use_auth_token=auth, cache_dir=args.cache_dir, trust_remote_code=auth + ) + l_config.use_cache = True + l_config._attn_implementation = "eager" # "eager" uses LlamaAttention for attention layer + llama = AutoModelForCausalLM.from_pretrained( + location, + use_auth_token=auth, + trust_remote_code=auth, + config=l_config, + torch_dtype=torch_dtype, + cache_dir=args.cache_dir, + ) + if world_size > 1: + llama.parallel_model() + if device: + llama.to(device) + llama.eval() + llama.requires_grad_(False) + barrier() + return l_config, llama diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/llama/quant_kv_dataloader.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/llama/quant_kv_dataloader.py new file mode 100644 index 0000000000000000000000000000000000000000..c9e609fc3a0058d872ed35fd3df2cd4c439bd991 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/llama/quant_kv_dataloader.py @@ -0,0 +1,108 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- +import argparse + +import numpy as np +import torch +from benchmark_helper import create_onnxruntime_session +from datasets import load_dataset +from llama_inputs import get_position_ids +from torch.nn.functional import pad +from torch.utils.data import DataLoader +from transformers import LlamaTokenizer + + +class QuantKVDataLoader: + def __init__(self, args: argparse.Namespace, onnx_model_path: str = ""): + self.batch_size = 1 + self.pad_max = args.pad_max + + tokenizer = LlamaTokenizer.from_pretrained(args.original_model_name, use_auth_token=args.use_auth_token) + dataset = load_dataset(args.smooth_quant_dataset, split="train") + dataset = dataset.map(lambda examples: tokenizer(examples["text"]), batched=True) + dataset.set_format(type="torch", columns=["input_ids", "attention_mask"]) + + self.dataloader = DataLoader( + dataset, + batch_size=self.batch_size, + shuffle=False, + collate_fn=self.collate_batch, + ) + self.decoder_model = ( + create_onnxruntime_session( + onnx_model_path, + args.execution_provider != "cpu", # use_gpu + provider=args.execution_provider, + verbose=args.verbose, + ) + if onnx_model_path + else None + ) + + def collate_batch(self, batch): + input_ids_batched = [] + attention_mask_batched = [] + position_ids_batched = [] + labels = [] + + for text in batch: + # Set inputs for model + input_ids = text["input_ids"] + attention_mask = torch.ones(len(input_ids)) + position_ids = get_position_ids(attention_mask, use_past_kv=False) + label = len(input_ids) - 1 + + # Pad input data because all model inputs must have same shape + pad_len = self.pad_max - input_ids.shape[0] + input_ids = pad(input_ids, (0, pad_len), value=1) + attention_mask = pad(attention_mask, (0, pad_len), value=0) + position_ids = pad(position_ids, (0, pad_len), value=0) + + input_ids_batched.append(input_ids) + attention_mask_batched.append(attention_mask) + position_ids_batched.append(position_ids) + labels.append(label) + + input_ids_batched = torch.vstack(input_ids_batched) + attention_mask_batched = torch.vstack(attention_mask_batched) + position_ids_batched = torch.vstack(position_ids_batched) + labels = torch.tensor(labels) + + return (input_ids_batched, attention_mask_batched, position_ids_batched), labels + + def __iter__(self): + try: + for (input_ids, attention_mask, position_ids), labels in self.dataloader: + # Inputs for decoder_model.onnx + inputs = { + "input_ids": input_ids[:, :-1].detach().cpu().numpy().astype(np.int64), + "attention_mask": attention_mask[:, :-1].detach().cpu().numpy().astype(np.int64), + "position_ids": position_ids[:, :-1].detach().cpu().numpy().astype(np.int64), + } + label = labels.detach().cpu().numpy() + + if self.decoder_model is not None: + # Run decoder_model.onnx to get inputs for decoder_with_past_model.onnx + outputs = self.decoder_model.run(None, inputs) + + for i in range(int((len(outputs) - 1) / 2)): + inputs[f"past_key_values.{i}.key"] = outputs[i * 2 + 1] + inputs[f"past_key_values.{i}.value"] = outputs[i * 2 + 2] + past_sequence_length = inputs["past_key_values.0.key"].shape[2] + + inputs["input_ids"] = input_ids[:, -1].unsqueeze(0).detach().cpu().numpy().astype(np.int64) + attn_mask_torch = torch.ones((self.batch_size, past_sequence_length + 1), dtype=torch.int64) + inputs["attention_mask"] = attn_mask_torch.detach().cpu().numpy().astype(np.int64) + inputs["position_ids"] = ( + get_position_ids(attn_mask_torch, use_past_kv=True).detach().cpu().numpy().astype(np.int64) + ) + + # Yield (inputs, label) tuple for Intel's Neural Compressor: + # https://github.com/intel/neural-compressor/blob/d4baed9ea11614e1f0dc8a1f4f55b73ed3ed585c/neural_compressor/quantization.py#L55-L62 + yield (inputs, label) + + except StopIteration: + return diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/longformer/__init__.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/longformer/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5ef71ce9e355e17ea1c2ca9fb648951d917734b5 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/longformer/__init__.py @@ -0,0 +1,12 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +# -------------------------------------------------------------------------- +import os.path +import sys + +sys.path.append(os.path.dirname(__file__)) + +transformers_dir = os.path.normpath(os.path.join(os.path.dirname(__file__), "..", "..")) +if transformers_dir not in sys.path: + sys.path.append(transformers_dir) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/longformer/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/longformer/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bf1adfef03ba4e7de55e9ea0bd21a6d3dc7c741b Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/longformer/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/longformer/__pycache__/benchmark_longformer.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/longformer/__pycache__/benchmark_longformer.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ae907ab651e739653640541b2f263217bea6de8c Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/longformer/__pycache__/benchmark_longformer.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/longformer/__pycache__/convert_to_onnx.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/longformer/__pycache__/convert_to_onnx.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c4b0c26e8ce303fbcdf2460d4bd8d791d117cbc7 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/longformer/__pycache__/convert_to_onnx.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/longformer/__pycache__/generate_test_data.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/longformer/__pycache__/generate_test_data.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1ad77fbeb89c915d9ed5ccc67ff084fae7802eca Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/longformer/__pycache__/generate_test_data.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/longformer/__pycache__/longformer_helper.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/longformer/__pycache__/longformer_helper.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cad31f53cb138f5c6cc2c536050f76edba2bf74b Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/longformer/__pycache__/longformer_helper.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/longformer/benchmark_longformer.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/longformer/benchmark_longformer.py new file mode 100644 index 0000000000000000000000000000000000000000..7e6700dbaf08ef913bf5ee125b0f4b2150573245 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/longformer/benchmark_longformer.py @@ -0,0 +1,821 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- +# +# This script run benchmark of latency or peak memory usage of Longformer model inference. +# Please run convert_to_onnx.py to get onnx model before running benchmark. +# +# It is tested with python 3.8, onnxruntime-gpu 1.11.0, PyTorch 1.11.0, transformers 4.18.0, CUDA 11.3 like: +# conda create -n gpu_env python=3.8 +# conda activate gpu_env +# pip3 install torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/cu113 +# pip3 install onnx transformers onnxruntime-gpu numpy sympy psutil py3nvml +# python benchmark_longformer.py +# +# When there is no parameter, pre-defined tests will run on the longformer-base-4096 model. + +# Benchmark the latency: +# python benchmark_longformer.py --model longformer-base-4096 --batch_sizes 1 --sequence_lengths 512 1024 2048 4096 \ +# --global_lengths 8 --onnx ./longformer-base-4096_fp16.onnx -t 100 +# +# Benchmark GPU peak memory: +# export ORT_LONGFORMER_COMPACT_MEMORY=0 +# python benchmark_longformer.py --model longformer-base-4096 --batch_sizes 1 --sequence_lengths 4096 \ +# --global_lengths 8 --onnx ./longformer-base-4096_fp32.onnx --memory -t 10 --engine onnxruntime +# export ORT_LONGFORMER_COMPACT_MEMORY=1 +# python benchmark_longformer.py --model longformer-base-4096 --batch_sizes 1 --sequence_lengths 4096 \ +# --global_lengths 8 --onnx ./longformer-base-4096_fp32.onnx --memory -t 10 --engine onnxruntime +# +# By default, compact memory kernel is enabled. To disable it, set environment variable ORT_LONGFORMER_COMPACT_MEMORY=0. + +import argparse +import csv +import logging +import math +import os +import re +import sys +import timeit +import traceback +from concurrent.futures import ProcessPoolExecutor +from datetime import datetime +from typing import Any + +import benchmark_helper +import numpy as np +import torch +from longformer_helper import PRETRAINED_LONGFORMER_MODELS, LongformerHelper, LongformerInputs +from transformers import LongformerModel + +import onnxruntime + +logger = logging.getLogger("") + + +def test_torch_latency( + device, + model, + model_name, + batch_sizes, + sequence_lengths, + global_lengths, + test_times, + num_threads, +) -> list[dict[str, Any]]: + if num_threads > 0: + torch.set_num_threads(num_threads) + + results = [] + for batch_size in batch_sizes: + for sequence_length in sequence_lengths: + for global_length in global_lengths: + logger.info(f"batch_size={batch_size} sequence_length={sequence_length} global_length={global_length}") + inputs: LongformerInputs = LongformerHelper.get_dummy_inputs( + batch_size, sequence_length, global_length, device + ) + input_list = inputs.to_list() + + _ = model(*input_list) + runtimes = timeit.repeat(lambda: model(*input_list), repeat=test_times, number=1) # noqa: B023 + result = { + "engine": "torch", # TODO: test torchscript + "version": torch.__version__, + "device": "cuda", + "optimizer": "", + "precision": "fp32", + "io_binding": "", + "model_name": model_name, + "description": model_name + " [torch]", + "inputs": 3, + "threads": num_threads, + "batch_size": batch_size, + "sequence_length": sequence_length, + "global_length": global_length, + "datetime": str(datetime.now()), + "memory": "NA", + "diff_max": 0, + "diff_90_percentile": 0, + "diff_95_percentile": 0, + "diff_99_percentile": 0, + "use_compact_memory": "NA", + } + result.update(benchmark_helper.get_latency_result(runtimes, batch_size)) + logger.info("%s", result) + results.append(result) + return results + + +def test_parity(device, model, ort_session, batch_size, sequence_length, global_length, verbose=True): + parameters = f"batch_size={batch_size} sequence_length={sequence_length} global_length={global_length}" + logger.info(f"Comparing Torch and ORT outputs for {parameters}...") + dummy_inputs: LongformerInputs = LongformerHelper.get_dummy_inputs( + batch_size, sequence_length, global_length, device + ) + ort_inputs = dummy_inputs.get_ort_inputs() + ort_outputs = ort_session.run(None, ort_inputs) + input_list = dummy_inputs.to_list() + torch_outputs = model(*input_list) + max_diff = np.amax(torch_outputs[0].cpu().numpy() - ort_outputs[0]) + logger.info(f"last_state max diff = {max_diff}") + if verbose and (math.isnan(max_diff) or max_diff > 0.001): + print("torch last_state:", torch_outputs[0]) + print("ort last_state:", ort_outputs[0]) + return float(max_diff) + + +def test_ort_latency( + device, + model, + model_name, + description, + ort_session, + batch_sizes, + sequence_lengths, + global_lengths, + test_times, + num_threads, + optimizer=False, + precision="fp32", + disable_io_binding=False, + verbose=True, + use_compact_memory=False, + use_half4=False, + disable_parity=False, +) -> list[dict[str, Any]]: + results = [] + for batch_size in batch_sizes: + for sequence_length in sequence_lengths: + for global_length in global_lengths: + assert global_length <= model.config.attention_window[0], ( + "Limitation of current implementation: number of global token <= attention_window" + ) + + logger.info( + f"Testing batch_size={batch_size} sequence_length={sequence_length} global_length={global_length} " + f"optimizer={optimizer}, precision={precision} io_binding={not disable_io_binding}..." + ) + dummy_inputs: LongformerInputs = LongformerHelper.get_dummy_inputs( + batch_size, sequence_length, global_length, device + ) + + # Run OnnxRuntime + ort_inputs = dummy_inputs.get_ort_inputs() + + if verbose: + print(ort_inputs) + + # run one query for warm up + ort_outputs = ort_session.run(None, ort_inputs) + + result_template = { + "model_name": model_name, + "description": description, + "inputs": 3, + "engine": "OnnxRuntime", + "version": str(onnxruntime.__version__), + "device": "cuda", + "precision": str(precision), + "optimizer": int(optimizer), + "threads": int(num_threads), + "batch_size": int(batch_size), + "sequence_length": int(sequence_length), + "global_length": int(global_length), + "test_times": int(test_times), + "datetime": str(datetime.now()), + "memory": "", + "diff_max": None, + "diff_90_percentile": None, + "diff_95_percentile": None, + "diff_99_percentile": None, + "use_compact_memory": use_compact_memory, + "use_half4": use_half4, + } + + if not disable_io_binding: + max_last_state_size = max(batch_sizes) * max(sequence_lengths) * model.config.hidden_size + max_pooler_size = max(batch_sizes) * max(sequence_lengths) + result = benchmark_helper.inference_ort_with_io_binding( + ort_session, + ort_inputs, + result_template=result_template, + repeat_times=test_times, + ort_output_names=["last_state", "pooler"], + ort_outputs=ort_outputs, + output_buffers=[], + output_buffer_max_sizes=[max_last_state_size, max_pooler_size], + batch_size=batch_size, + device=device, + data_type=np.longlong, # input data type + ) + else: + result = benchmark_helper.inference_ort( + ort_session, + ort_inputs, + result_template=result_template, + repeat_times=test_times, + batch_size=batch_size, + ) + + # measure result difference between PyTorch and OnnxRuntime + if not disable_parity: + diff_results = [ + test_parity( + device, + model, + ort_session, + batch_size, + sequence_length, + global_length, + verbose, + ) + for _ in range(test_times) + ] + + result["diff_max"] = max(diff_results) + result["diff_90_percentile"] = np.percentile(diff_results, 90) + result["diff_95_percentile"] = np.percentile(diff_results, 95) + result["diff_99_percentile"] = np.percentile(diff_results, 99) + + results.append(result) + return results + + +def test_ort_memory( + device, + onnx_model_path, + batch_size, + sequence_length, + global_length, + test_times, + num_threads, +) -> dict[str, Any]: + logger.info( + f"Testing memory for model={onnx_model_path}, batch_size={batch_size}, sequence_length={sequence_length}, " + f"global_length={global_length}, test_times={test_times}, num_threads={num_threads}" + ) + + def inference(): + # Update Arena strategy so that we can measure the minimum memory required + cuda_provider_options = {"arena_extend_strategy": "kSameAsRequested"} + provider_options = {"CUDAExecutionProvider": cuda_provider_options} + session = benchmark_helper.create_onnxruntime_session( + onnx_model_path, + use_gpu=True, + enable_all_optimization=True, + num_threads=num_threads, + provider_options=provider_options, + ) + + dummy_inputs: LongformerInputs = LongformerHelper.get_dummy_inputs( + batch_size, sequence_length, global_length, device + ) + ort_inputs = dummy_inputs.get_ort_inputs() + for _ in range(test_times): + _ = session.run(None, ort_inputs) + + memory_used = benchmark_helper.measure_memory(is_gpu=True, func=inference) + + return { + "onnx_model": onnx_model_path, + "batch_size": batch_size, + "sequence_length": sequence_length, + "global_length": global_length, + "test_times": test_times, + "num_threads": num_threads, + "memory": memory_used, + } + + +def load_torch_model(model_name, device): + torch_model_name_or_dir = PRETRAINED_LONGFORMER_MODELS.get(model_name, model_name) + model = LongformerModel.from_pretrained(torch_model_name_or_dir) + model.to(device) + return model + + +def find_onnx_model(model_name, onnx_dir="."): + # Search onnx model in the following order: optimized fp16 model, optimized fp32 model, raw model + onnx_model_path = os.path.join(onnx_dir, model_name + ".onnx") + optimized_fp32_model = os.path.join(onnx_dir, model_name + "_fp32.onnx") + optimized_fp16_model = os.path.join(onnx_dir, model_name + "_fp16.onnx") + if os.path.isfile(optimized_fp16_model): + onnx_model_path = optimized_fp16_model + elif os.path.isfile(optimized_fp32_model): + onnx_model_path = optimized_fp32_model + return onnx_model_path + + +def test_memory(args, device) -> dict[str, Any]: + if len(args.batch_sizes) > 1: + raise RuntimeError("For memory test, only one batch_size (-b) is allowed.") + if len(args.sequence_lengths) > 1: + raise RuntimeError("For memory test, only one sequence_length (-s) is allowed.") + if len(args.global_lengths) > 1: + raise RuntimeError("For memory test, only one global_length (-g) is allowed.") + + model_name = args.model + onnx_model_path = find_onnx_model(model_name) if not args.onnx else args.onnx + + torch.cuda.empty_cache() + return test_ort_memory( + device, + onnx_model_path, + args.batch_sizes[0], + args.sequence_lengths[0], + args.global_lengths[0], + args.test_times, + args.num_threads, + ) + + +def test_ort(args, device) -> list[dict[str, Any]]: + model_name = args.model + + onnx_model_path = find_onnx_model(model_name) if not args.onnx else args.onnx + + optimized = onnx_model_path.endswith("_fp16.onnx") or onnx_model_path.endswith("_fp32.onnx") # noqa: PIE810 + precision = "fp32" if not onnx_model_path.endswith("_fp16.onnx") else "fp16" + + model = load_torch_model(model_name, device) + + num_threads = args.num_threads + + cuda_provider_options = {"arena_extend_strategy": "kSameAsRequested"} + provider_options = {"CUDAExecutionProvider": cuda_provider_options} + session = benchmark_helper.create_onnxruntime_session( + onnx_model_path, + use_gpu=True, + enable_all_optimization=True, + num_threads=num_threads, + provider_options=provider_options, + ) + if session is None: + raise RuntimeError(f"Failed to create ORT session from ONNX file {onnx_model_path}") + + use_compact_memory = os.environ.get("ORT_LONGFORMER_COMPACT_MEMORY", "1") == "1" + description = onnx_model_path + if not use_compact_memory: + description += "[non_compact_memory]" + + if args.use_half4: + description += "[half4]" if precision == "fp16" else "[float4]" + else: + description += "[half2]" if precision == "fp16" else "[float4]" + + return test_ort_latency( + device, + model, + model_name, + description, + session, + args.batch_sizes, + args.sequence_lengths, + args.global_lengths, + args.test_times, + num_threads, + optimized, + precision, + args.disable_io_binding, + args.verbose, + use_compact_memory, + args.use_half4, + args.disable_parity, + ) + + +def test_torch(args, device) -> list[dict[str, Any]]: + model = load_torch_model(args.model, device) + return test_torch_latency( + device, + model, + args.model, + args.batch_sizes, + args.sequence_lengths, + args.global_lengths, + args.test_times, + args.num_threads, + ) + + +def test_latency(args, device) -> list[dict[str, Any]]: + if args.engine == "onnxruntime": + return test_ort(args, device) + + return test_torch(args, device) + + +def parse_arguments(argv=None): + parser = argparse.ArgumentParser() + + parser.add_argument( + "-m", + "--model", + required=False, + type=str, + default="longformer-base-4096", + help="Checkpoint directory or pre-trained model names in the list: " + + ", ".join(PRETRAINED_LONGFORMER_MODELS.keys()), + ) + + parser.add_argument( + "-e", + "--engine", + required=False, + type=str, + default="onnxruntime", + choices=["onnxruntime", "torch"], + help="Engine to benchmark.", + ) + + parser.add_argument( + "-t", + "--test_times", + required=False, + default=1000, + type=int, + help="Number of repeat times to get average inference latency.", + ) + + parser.add_argument("-b", "--batch_sizes", nargs="+", type=int, default=[1]) + + # If --export_padding is not used in exporting onnx model, there is no padding in ONNX model, + # and you will need padding inputs by yourself before running onnx model. + # Here, we only test sequence length that is multiple of attention window size. + parser.add_argument( + "-s", + "--sequence_lengths", + nargs="+", + type=int, + default=[512, 1024, 2048, 4096], + help="Sequence lengths. It could have multiple values in latency test." + "If --export_padding is not used, sequence length shall be multiple of window size.", + ) + + parser.add_argument("--onnx", required=False, type=str, default=None, help="Onnx model path") + + parser.add_argument( + "-g", + "--global_lengths", + nargs="+", + type=int, + default=[0], + help="Number of global tokens. It could have multiple values in latency test.", + ) + + parser.add_argument( + "-n", + "--num_threads", + required=False, + type=int, + default=0, + help="Threads to use.", + ) + + parser.add_argument( + "--disable_io_binding", + required=False, + action="store_true", + help="Do not use IO Binding.", + ) + + parser.add_argument( + "--memory", + required=False, + action="store_true", + help="Test memory usage instead of latency.", + ) + + parser.add_argument("--verbose", required=False, action="store_true", help="Print more information.") + parser.set_defaults(verbose=False) + + parser.add_argument("--use_half4", required=False, action="store_true", help="Use half4 kernel.") + parser.set_defaults(use_half4=False) + + parser.add_argument("--disable_parity", required=False, action="store_true", help="Do not run parity test.") + parser.set_defaults(disable_parity=False) + + args = parser.parse_args(argv) + + return args + + +def output_details(results, csv_filename): + latency_results = [result for result in results if "average_latency_ms" in result] + if len(latency_results) == 0: + print("No latency results for output.") + return + + with open(csv_filename, mode="a", newline="", encoding="ascii") as csv_file: + column_names = [ + "engine", + "version", + "device", + "precision", + "optimizer", + "io_binding", + "model_name", + "inputs", + "threads", + "datetime", + "test_times", + "description", + "batch_size", + "sequence_length", + "global_length", + "use_compact_memory", + "use_half4", + "diff_max", + "diff_90_percentile", + "diff_95_percentile", + "diff_99_percentile", + "memory", + "QPS", + "average_latency_ms", + "latency_variance", + "latency_90_percentile", + "latency_95_percentile", + "latency_99_percentile", + ] + + csv_writer = csv.DictWriter(csv_file, fieldnames=column_names) + csv_writer.writeheader() + for result in latency_results: + print(result) + csv_writer.writerow(result) + + csv_file.flush() + + print(f"Detail results are saved to csv file: {csv_filename}") + + +def run(args) -> list[dict[str, Any]]: + torch.set_grad_enabled(False) + + # set random seed manually to get deterministic results + benchmark_helper.set_random_seed(123) + + # Currently, the longformer attention operator could only run in GPU (no CPU implementation yet). + device = torch.device("cuda:0") + + if args.memory: + return [test_memory(args, device)] # Convert to List so that return type is same as test_latency + + return test_latency(args, device) + + +def launch_test(arguments) -> list[dict[str, Any]]: + if not torch.cuda.is_available(): + raise RuntimeError("Please install PyTorch with Cuda, and use a machine with GPU for testing gpu performance.") + + with ProcessPoolExecutor() as executor: + results = list(executor.map(run, [arguments])) + assert len(results) == 1 + return results[0] + + +def run_tests( + use_compact_memory=True, + run_torch=False, + run_memory=True, + use_io_binding=True, + use_fp16=True, + use_merged_qkv_weights=True, + use_half4=True, + batch_size=1, +): + compact_memory = "1" if use_compact_memory else "0" + os.environ["ORT_LONGFORMER_COMPACT_MEMORY"] = compact_memory + logger.info(f"ORT_LONGFORMER_COMPACT_MEMORY={compact_memory}") + + os.environ["ORT_LONGFORMER_USE_HALF4"] = "1" if use_half4 else "0" + logger.info("ORT_LONGFORMER_USE_HALF4={}".format("1" if use_half4 else "0")) # noqa: G001 + + results = [] + test_times = 1000 + sequence_lengths = [4096, 2048, 1024, 512] + batch_sizes = [batch_size] + for model_name in ["longformer-base-4096"]: + for batch_size in batch_sizes: + for sequence_length in sequence_lengths: + for global_length in [16]: + if run_torch: + engine_name = "torch" + args = parse_arguments( + f"-e {engine_name} -t {test_times} -b {batch_size} -s {sequence_length} -g {global_length} " + f"-t {test_times} -m {model_name}".split(" ") + ) + results += run(args) + + engine_name = "onnxruntime" + file_format = 1 if use_merged_qkv_weights else 0 + onnx_path = ( + f"{model_name}_f{file_format}_fp16.onnx" + if use_fp16 + else f"{model_name}_f{file_format}_fp32.onnx" + ) + if not os.path.exists(onnx_path): + raise RuntimeError(f"onnx file not exists:{onnx_path}") + + arguments = ( + f"-e {engine_name} --onnx {onnx_path} " + f"-b {batch_size} -s {sequence_length} -g {global_length} -m {model_name}" + ) + + if not use_io_binding: + arguments += " --disable_io_binding" + + if use_half4: + arguments += " --use_half4" + + # Disable parity test to avoid out of memory for large batch size + if batch_size >= 4: + arguments += " --disable_parity" + + memory_results = None + try: + if run_memory: + args = parse_arguments(f"{arguments} -t 10 --memory".split(" ")) + memory_results = launch_test(args) + + args = parse_arguments(f"{arguments} -t {test_times}".split(" ")) + latency_results = launch_test(args) + except KeyboardInterrupt as exc: + raise RuntimeError("Keyboard Interrupted") from exc + except Exception: + traceback.print_exc() + continue + + if len(latency_results) == 1: + latency_results[0]["memory"] = memory_results[0]["memory"] if memory_results else "N/A" + else: + raise RuntimeError("length of latency_results should be 1") + + logger.info("%s", latency_results) + + results += latency_results + return results + + +def output_summary(results, csv_filename, data_field="average_latency_ms"): + with open(csv_filename, mode="a", newline="", encoding="ascii") as csv_file: + header_names = [ + "model_name", + "precision", + "engine", + "version", + "global_length", + "use_compact_memory", + "use_half4", + "description", + ] + + description_list = list({result["description"] for result in results}) + description_list.sort() + + batch_sizes = list({result["batch_size"] for result in results}) + batch_sizes.sort() + + sequence_lengths = list({result["sequence_length"] for result in results}) + sequence_lengths.sort() + + data_names = [] + for sequence_length in sequence_lengths: + for batch_size in batch_sizes: + data_names.append(f"b{batch_size}_s{sequence_length}") + + csv_writer = csv.DictWriter(csv_file, fieldnames=header_names + data_names) + csv_writer.writeheader() + + for description in description_list: + row = {} + + sum_latency = {} + sum_latency.update(dict.fromkeys(data_names, 0)) + + count_latency = {} + count_latency.update(dict.fromkeys(data_names, 0)) + + for result in results: + if result["description"] == description and result[data_field]: + headers = {k: v for k, v in result.items() if k in header_names} + if not row: + row.update(headers) + else: + for k in header_names: + if row[k] != headers[k]: + raise RuntimeError("Description shall be unique") + + batch_size = result["batch_size"] + sequence_length = result["sequence_length"] + key = f"b{batch_size}_s{sequence_length}" + + try: + latency = float(result[data_field]) + except ValueError: + continue + + sum_latency[key] += latency + count_latency[key] += 1 + + if row: + for key in data_names: + if key in count_latency and count_latency[key] > 0: + row[key] = sum_latency[key] / count_latency[key] + else: + row[key] = "" + + csv_writer.writerow(row) + + csv_file.flush() + + +def run_experiments(use_fp16, batch_size, is_baseline=False): + """Run experiments to compare different algorithms on one batch size""" + test_results = run_tests( + use_fp16=use_fp16, + use_merged_qkv_weights=True, + use_half4=False, + batch_size=batch_size, + ) + + if is_baseline: + return test_results + + if use_fp16: + test_results += run_tests( + use_fp16=use_fp16, + use_merged_qkv_weights=True, + use_half4=True, + batch_size=batch_size, + ) + + test_results += run_tests( + use_fp16=use_fp16, + use_merged_qkv_weights=False, + use_half4=True, + batch_size=batch_size, + ) + + test_results += run_tests( + use_fp16=use_fp16, + use_merged_qkv_weights=False, + use_half4=False, + batch_size=batch_size, + ) + + return test_results + + +def main(): + torch.multiprocessing.set_start_method("spawn") + + args = parse_arguments() + + benchmark_helper.setup_logger(args.verbose) + + if len(sys.argv) > 1: + test_results = launch_test(args) + time_stamp = datetime.now().strftime("%Y%m%d-%H%M%S") + csv_filename = f"benchmark_detail_{time_stamp}.csv" + output_details(test_results, csv_filename) + return + + gpu_list = benchmark_helper.get_gpu_info() + logger.info("GPU info: %s", gpu_list) + fp16_batch_sizes = [16, 8, 4, 2, 1] + fp32_batch_sizes = [4, 2, 1] + if gpu_list and gpu_list[0]["total"] >= 32 * 1024 * 1024 * 1024: # 32 GB + fp16_batch_sizes = [64, 32, 16, 8, 4, 2, 1] + fp32_batch_sizes = [16, 8, 4, 2, 1] + + gpu_name = re.sub(r"(?u)[^-\w.]", "_", gpu_list[0]["name"]) if gpu_list else "gpu" + is_baseline = os.environ.get("ORT_LONGFORMER_BASELINE", "0") == "1" + experiment_name = f"longformer_base_{gpu_name}" + ("_baseline" if is_baseline else "") + logger.info( + f"experiment_name={experiment_name}, fp16_batch_sizes={fp16_batch_sizes}, fp32_batch_sizes={fp32_batch_sizes}" + ) + + total_runs = 1 + all_results = [] + for _ in range(total_runs): + for batch_size in fp16_batch_sizes: + fp16_results = run_experiments(use_fp16=True, batch_size=batch_size, is_baseline=is_baseline) + output_details(fp16_results, "longformer_base_fp16.csv") + all_results += fp16_results + for metric_name in ["average_latency_ms", "QPS", "memory", "diff_90_percentile"]: + output_summary(all_results, f"{experiment_name}_{metric_name}.csv", metric_name) + + all_results = [] + for _ in range(total_runs): + for batch_size in fp32_batch_sizes: + fp32_results = run_experiments(use_fp16=False, batch_size=batch_size, is_baseline=is_baseline) + output_details(fp32_results, "longformer_base_fp32.csv") + all_results += fp32_results + for metric_name in ["average_latency_ms", "QPS", "memory", "diff_90_percentile"]: + output_summary(all_results, f"{experiment_name}_{metric_name}.csv", metric_name) + + +if __name__ == "__main__": + main() diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/longformer/convert_to_onnx.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/longformer/convert_to_onnx.py new file mode 100644 index 0000000000000000000000000000000000000000..f4c4f401123090b22143c051cc69380e255d331e --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/longformer/convert_to_onnx.py @@ -0,0 +1,413 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +# This script converts Longformer model from huggingface transformers 4.0 or later to ONNX. +# It translates LongformerSelfAttention to the LongformerAttention operator in ONNX Runtime. +# +# Before running this script, prepare a python environment in Linux with PyTorch 1.9.0 and other packages installed. +# Then run "python setup.py install" in ./torch_extensions directory. If your python version is not 3.8, you will need +# update this script with correct name of longformer_attention.cpython-*.so (search TODO below). +# +# It is tested in Ubuntu 18.04 with python 3.8, onnxruntime-gpu 1.11.0, PyTorch 1.9.0, transformers 4.18.0. +# Warning: Using PyTorch 1.10 or newer version might encounter issue in exporting, but they are fine for benchmarking. +# +# Example commands to export longformer base model in Linux: +# conda create -n longformer python=3.8 +# conda activate longformer +# python3 -m pip install torch==1.9.0+cu111 torchvision==0.10.0+cu111 torchaudio==0.9.0 -f https://download.pytorch.org/whl/torch_stable.html +# python3 -m pip install flatbuffers numpy packaging sympy protobuf==3.20.1 onnx==1.12.0 transformers==4.18.0 +# python3 -m pip install -i https://test.pypi.org/simple/ ort-nightly-gpu +# cd ./torch_extensions +# rm -rf build +# python setup.py install +# cd .. +# python convert_to_onnx.py --model longformer-base-4096 --precision fp16 --optimize_onnx +# python convert_to_onnx.py --model longformer-base-4096 --precision fp16 --optimize_onnx --no_merge_qkv +# +# GPU is not needed for this script. You can run it in CPU. For --optimize_onnx, you can use either onnxruntime or onnxruntime-gpu package. +# +# For inference of the onnx model, you will need onnxruntime-gpu 1.7.0 or newer version. + +import argparse +import inspect +from pathlib import Path + +import torch +import transformers +from longformer_helper import PRETRAINED_LONGFORMER_MODELS +from onnx import load_model +from onnx_model_bert import BertOnnxModel +from packaging import version +from torch.onnx import register_custom_op_symbolic +from torch.onnx.symbolic_helper import parse_args +from torch_onnx_export_helper import torch_onnx_export +from transformers import LongformerModel, LongformerSelfAttention + +# Supports format 0 or 1 +weight_bias_format = 0 + + +@parse_args("v", "v", "v", "v", "v", "v", "v", "i", "i") +def my_longformer_attention( + g, + input, + weight, + bias, + mask, + global_weight, + global_bias, + global_mask, + num_heads, + window, +): + return g.op( + "com.microsoft::LongformerAttention", + input, + weight, + bias, + mask, + global_weight, + global_bias, + global_mask, + num_heads_i=num_heads, + window_i=window, + ) + + +# namespace is onnxruntime which is registered in longformer_attention.cpp +register_custom_op_symbolic("onnxruntime::LongformerAttention", my_longformer_attention, 9) + +# TODO: search the directory to find correct output filename of "python setup.py install" when python version is not 3.8 +torch.ops.load_library( + r"./torch_extensions/build/lib.linux-x86_64-3.8/longformer_attention.cpython-38-x86_64-linux-gnu.so" +) + + +def parse_arguments(): + """Parse arguments + + Returns: + args: Namespace + """ + parser = argparse.ArgumentParser() + + parser.add_argument( + "-m", + "--model", + required=False, + type=str, + default="longformer-base-4096", + help="Checkpoint directory or pre-trained model names in the list: " + + ", ".join(PRETRAINED_LONGFORMER_MODELS.keys()), + ) + + parser.add_argument( + "--export_padding", + required=False, + action="store_true", + help="Export padding logic to ONNX graph. If not enabled, user need pad input so that sequence length is multiple of window size.", + ) + parser.set_defaults(export_padding=False) + + parser.add_argument( + "--no_merge_qkv", + required=False, + action="store_true", + help="Stack the weights of q, k and v on dimension 0 instead of dimension 1.", + ) + parser.set_defaults(no_merge_qkv=False) + + parser.add_argument( + "-o", + "--optimize_onnx", + required=False, + action="store_true", + help="Use optimizer.py to optimize onnx model.", + ) + parser.set_defaults(optimize_onnx=False) + + parser.add_argument( + "-p", + "--precision", + required=False, + type=str, + default="fp32", + choices=["fp32", "fp16"], + help="Precision of model to run: fp32 for full precision, fp16 for mixed precision", + ) + + args = parser.parse_args() + return args + + +# Create a dummy input for ONNX export. +def get_dummy_inputs(config, export_padding, device): + # When sequence length is multiple of windows size, there is no padding logic in ONNX graph + sequence_length = config.attention_window[0] + 1 if export_padding else config.attention_window[0] + + # Create dummy inputs + input_ids = torch.arange(sequence_length).unsqueeze(0).to(device) + + attention_mask = torch.ones(input_ids.shape, dtype=torch.long, device=device) + attention_mask[:, sequence_length - 1] = 0 # last token is masked + + global_attention_mask = torch.zeros(input_ids.shape, dtype=torch.long, device=device) + global_attention_mask[:, 0] = 1 # first token is global token + + return input_ids, attention_mask, global_attention_mask + + +# A new function to replace LongformerSelfAttention.forward +# For transformers 4.0.0 +def my_longformer_self_attention_forward_4( + self, + hidden_states, + attention_mask=None, + is_index_masked=None, + is_index_global_attn=None, + is_global_attn=None, +): + global_mask = is_index_global_attn.int() + # The following check is based on the dummy inputs (only the first token is global). + assert ( + len(global_mask.shape) == 2 + and global_mask.shape[0] == 1 + and global_mask.count_nonzero().item() == 1 + and global_mask.tolist()[0][0] == 1 + ) + + input_mask = is_index_masked.float() + # TODO: The filtering value may be -10000.0 or -inf. Check the huggingface implementation. + input_mask = input_mask.masked_fill(is_index_masked, -10000.0) + # Yet another way to generate input_mask = torch.masked_fill(attention_mask, is_index_global_attn, 0.0) + + # TODO: add postprocessing of ONNX model to calculate based on graph input: input_mask = (attention_mask - 1) * 10000.0 + # TODO: add postprocessing of ONNX model to use graph input directly: global_mask = global_attention_mask + + # The following check is based on the dummy inputs (only the last token is masked). + assert ( + len(input_mask.shape) == 2 + and input_mask.shape[0] == 1 + and input_mask.count_nonzero().item() == 1 + and input_mask.tolist()[0][-1] == -10000.0 + ) + + weight = torch.stack( + ( + self.query.weight.transpose(0, 1), + self.key.weight.transpose(0, 1), + self.value.weight.transpose(0, 1), + ), + dim=weight_bias_format, + ) + + if weight_bias_format == 1: + # shape is (hidden_size, 3*hidden_size) for format 1, otherwise (3, hidden_size, hidden_size) by default + weight = weight.reshape(self.embed_dim, 3 * self.embed_dim) + + global_weight = torch.stack( + ( + self.query_global.weight.transpose(0, 1), + self.key_global.weight.transpose(0, 1), + self.value_global.weight.transpose(0, 1), + ), + dim=weight_bias_format, + ) + + if weight_bias_format == 1: + global_weight = global_weight.reshape(self.embed_dim, 3 * self.embed_dim) + + if weight_bias_format == 1: + bias = torch.stack((self.query.bias, self.key.bias, self.value.bias), dim=0) + bias = bias.reshape(3 * self.embed_dim) + global_bias = torch.stack((self.query_global.bias, self.key_global.bias, self.value_global.bias), dim=0) + global_bias = global_bias.reshape(3 * self.embed_dim) + else: + bias = torch.stack( + (self.query.bias, self.key.bias, self.value.bias, self.key_global.bias, self.value_global.bias), dim=0 + ) + bias = bias.reshape(5 * self.embed_dim) + global_bias = self.query_global.bias + global_bias = global_bias.reshape(1 * self.embed_dim) + + attn_output = torch.ops.onnxruntime.LongformerAttention( + hidden_states, + weight, + bias, + input_mask, + global_weight, + global_bias, + global_mask, + self.num_heads, + self.one_sided_attn_window_size, + ) + + assert attn_output.size() == hidden_states.size(), "Unexpected size" + + outputs = (attn_output,) + return outputs + + +# For transformers 4.3.0 +def my_longformer_self_attention_forward_4_3( + self, + hidden_states, + attention_mask=None, + is_index_masked=None, + is_index_global_attn=None, + is_global_attn=None, + output_attentions=False, +): + assert output_attentions is False + return my_longformer_self_attention_forward_4( + self, + hidden_states, + attention_mask, + is_index_masked, + is_index_global_attn, + is_global_attn, + ) + + +# For transformers 4.3.2 or later versions +def my_longformer_self_attention_forward_4_3_2( + self, + hidden_states, + attention_mask=None, + layer_head_mask=None, + is_index_masked=None, + is_index_global_attn=None, + is_global_attn=None, + output_attentions=False, +): + assert output_attentions is False + assert layer_head_mask is None + return my_longformer_self_attention_forward_4( + self, + hidden_states, + attention_mask, + is_index_masked, + is_index_global_attn, + is_global_attn, + ) + + +def export_longformer(model: LongformerModel, onnx_model_path: str, export_padding: bool): + """Export longformer model to ONNX + + Args: + model (LongformerModel): longformer model + onnx_model_path (str): output onnx path + export_padding (bool): whether export padding logic to ONNX so that input string can be any length. + + Raises: + RuntimeError: This tool requires transformers 4.0.0 or later. + RuntimeError: LongformerSelfAttention.forward arguments are different. + """ + input_ids, attention_mask, global_attention_mask = get_dummy_inputs( + model.config, export_padding, device=torch.device("cpu") + ) + + _ = model( + input_ids, + attention_mask=attention_mask, + global_attention_mask=global_attention_mask, + ) + + if version.parse(transformers.__version__) < version.parse("4.0.0"): + raise RuntimeError("This tool requires transformers 4.0.0 or later.") + + # Here we replace LongformerSelfAttention.forward using our implementation for exporting ONNX model + key = " ".join(inspect.getfullargspec(LongformerSelfAttention.forward).args) + args_to_func = { + "self hidden_states attention_mask layer_head_mask is_index_masked is_index_global_attn is_global_attn output_attentions": my_longformer_self_attention_forward_4_3_2, + "self hidden_states attention_mask is_index_masked is_index_global_attn is_global_attn output_attentions": my_longformer_self_attention_forward_4_3, + "self hidden_states attention_mask is_index_masked is_index_global_attn is_global_attn": my_longformer_self_attention_forward_4, + } + + if key not in args_to_func: + print( + "Current arguments", + inspect.getfullargspec(LongformerSelfAttention.forward).args, + ) + raise RuntimeError( + "LongformerSelfAttention.forward arguments are different. Please install supported version (like transformers 4.3.0)." + ) + + # Store for restoring later + original_forward = LongformerSelfAttention.forward + + LongformerSelfAttention.forward = args_to_func[key] + + example_inputs = (input_ids, attention_mask, global_attention_mask) + + Path(onnx_model_path).parent.mkdir(parents=True, exist_ok=True) + + torch_onnx_export( + model, + example_inputs, + onnx_model_path, + opset_version=12, + input_names=["input_ids", "attention_mask", "global_attention_mask"], + output_names=["last_state", "pooler"], + dynamic_axes={ + "input_ids": {0: "batch_size", 1: "sequence_length"}, + "attention_mask": {0: "batch_size", 1: "sequence_length"}, + "global_attention_mask": {0: "batch_size", 1: "sequence_length"}, + "last_state": {0: "batch_size", 1: "sequence_length"}, + "pooler": {0: "batch_size", 1: "sequence_length"}, + }, + custom_opsets={"com.microsoft": 1}, + ) + print(f"ONNX model exported to {onnx_model_path}") + + # Restore original implementation: + LongformerSelfAttention.forward = original_forward + + +def optimize_longformer(onnx_model_path: str, fp32_model_path: str, fp16_model_path=None): + """Optimize longformer onnx model + + Args: + onnx_model_path (str): path of original ONNX model. + fp32_model_path (str): path of optimized fp32 model. + fp16_model_path (str, optional): path of optimized fp16 model. Defaults to None. + """ + model = load_model(onnx_model_path, format=None, load_external_data=True) + optimizer = BertOnnxModel(model) + optimizer.optimize() + + use_external_data_format = False + if fp32_model_path: + optimizer.save_model_to_file(fp32_model_path, use_external_data_format) + print(f"optimized fp32 model saved to {fp32_model_path}") + + if fp16_model_path: + optimizer.convert_float_to_float16(keep_io_types=True) + optimizer.save_model_to_file(fp16_model_path, use_external_data_format) + print(f"optimized fp16 model saved to {fp16_model_path}") + + +def main(args): + model_name = args.model + onnx_model_path = model_name + ".onnx" + + global weight_bias_format # noqa: PLW0603 + weight_bias_format = 0 if args.no_merge_qkv else 1 + + model = LongformerModel.from_pretrained(PRETRAINED_LONGFORMER_MODELS[model_name]) + + export_longformer(model, onnx_model_path, args.export_padding) + + if args.optimize_onnx or args.precision != "fp32": + fp32_model_path = model_name + f"_f{weight_bias_format}" + "_fp32.onnx" + fp16_model_path = model_name + f"_f{weight_bias_format}" + "_fp16.onnx" if args.precision == "fp16" else None + optimize_longformer(onnx_model_path, fp32_model_path, fp16_model_path) + + +if __name__ == "__main__": + args = parse_arguments() + main(args) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/longformer/generate_test_data.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/longformer/generate_test_data.py new file mode 100644 index 0000000000000000000000000000000000000000..0955973264d6412c3960e2954009ca742e5f3590 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/longformer/generate_test_data.py @@ -0,0 +1,347 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +# -------------------------------------------------------------------------- + +# Generate test data for a longformer model, so that we can use onnxruntime_perf_test.exe to evaluate the inference latency. + +import argparse +import os +import random +from pathlib import Path + +import numpy as np +from bert_test_data import fake_input_ids_data, fake_input_mask_data, output_test_data +from onnx import ModelProto, TensorProto +from onnx_model import OnnxModel + + +def parse_arguments(): + parser = argparse.ArgumentParser() + + parser.add_argument("--model", required=True, type=str, help="bert onnx model path.") + + parser.add_argument( + "--output_dir", + required=False, + type=str, + default=None, + help="output test data path. If not specified, .", + ) + + parser.add_argument("--batch_size", required=False, type=int, default=1, help="batch size of input") + + parser.add_argument( + "--sequence_length", + required=False, + type=int, + default=128, + help="maximum sequence length of input", + ) + + parser.add_argument( + "-a", + "--average_sequence_length", + default=-1, + type=int, + help="average sequence length excluding padding", + ) + + parser.add_argument( + "-r", + "--random_sequence_length", + required=False, + action="store_true", + help="use uniform random instead of fixed sequence length", + ) + parser.set_defaults(random_sequence_length=False) + + parser.add_argument( + "--global_tokens", + required=False, + type=int, + default=10, + help="number of global tokens", + ) + + parser.add_argument( + "--input_ids_name", + required=False, + type=str, + default=None, + help="input name for input ids", + ) + + parser.add_argument( + "--input_mask_name", + required=False, + type=str, + default=None, + help="input name for attention mask", + ) + + parser.add_argument( + "--global_mask_name", + required=False, + type=str, + default=None, + help="input name for global attention mask", + ) + + parser.add_argument( + "--samples", + required=False, + type=int, + default=1, + help="number of test cases to be generated", + ) + + parser.add_argument("--seed", required=False, type=int, default=3, help="random seed") + + parser.add_argument( + "--verbose", + required=False, + action="store_true", + help="print verbose information", + ) + parser.set_defaults(verbose=False) + + args = parser.parse_args() + return args + + +def get_longformer_inputs(onnx_file, input_ids_name=None, input_mask_name=None, global_mask_name=None): + """ + Get graph inputs for longformer model. + """ + model = ModelProto() + with open(onnx_file, "rb") as f: + model.ParseFromString(f.read()) + + onnx_model = OnnxModel(model) + graph_inputs = onnx_model.get_graph_inputs_excluding_initializers() + + if input_ids_name is not None: + input_ids = onnx_model.find_graph_input(input_ids_name) + if input_ids is None: + raise ValueError(f"Graph does not have input named {input_ids_name}") + + input_mask = None + if input_mask_name: + input_mask = onnx_model.find_graph_input(input_mask_name) + if input_mask is None: + raise ValueError(f"Graph does not have input named {input_mask_name}") + + global_mask = None + if global_mask_name: + global_mask = onnx_model.find_graph_input(global_mask_name) + if global_mask is None: + raise ValueError(f"Graph does not have input named {global_mask_name}") + + expected_inputs = 1 + (1 if input_mask else 0) + (1 if global_mask else 0) + if len(graph_inputs) != expected_inputs: + raise ValueError(f"Expect the graph to have {expected_inputs} inputs. Got {len(graph_inputs)}") + + return input_ids, input_mask, global_mask + + if len(graph_inputs) != 3: + raise ValueError(f"Expect the graph to have 3 inputs. Got {len(graph_inputs)}") + + # Try guess the inputs based on naming. + input_ids = None + input_mask = None + global_mask = None + for input in graph_inputs: + input_name_lower = input.name.lower() + if "global" in input_name_lower: + global_mask = input + elif "mask" in input_name_lower: + input_mask = input + else: + input_ids = input + + if input_ids and input_mask and global_mask: + return input_ids, input_mask, global_mask + + raise ValueError("Fail to assign 3 inputs. You might try rename the graph inputs.") + + +def fake_global_mask_data(global_mask, batch_size, sequence_length, num_global_tokens): + """ + Fake data based on the graph input of segment_ids. + Args: + segment_ids (TensorProto): graph input of input tensor. + Returns: + data (np.array): the data for input tensor + """ + data_type = global_mask.type.tensor_type.elem_type + assert data_type in [TensorProto.FLOAT, TensorProto.INT32, TensorProto.INT64] + + if num_global_tokens > 0: + assert num_global_tokens <= sequence_length + data = np.zeros((batch_size, sequence_length), dtype=np.int32) + temp = np.ones((batch_size, num_global_tokens), dtype=np.int32) + data[: temp.shape[0], : temp.shape[1]] = temp + else: + data = np.zeros((batch_size, sequence_length), dtype=np.int32) + + if data_type == TensorProto.FLOAT: + data = np.float32(data) + elif data_type == TensorProto.INT64: + data = np.int64(data) + + return data + + +def fake_test_data( + batch_size, + sequence_length, + test_cases, + dictionary_size, + verbose, + random_seed, + input_ids, + input_mask, + global_mask, + num_global_tokens, + average_sequence_length, + random_sequence_length, +): + """ + Generate fake input data for test. + """ + assert input_ids is not None + + np.random.seed(random_seed) + random.seed(random_seed) + + all_inputs = [] + for _ in range(test_cases): + input_1 = fake_input_ids_data(input_ids, batch_size, sequence_length, dictionary_size) + inputs = {input_ids.name: input_1} + + if input_mask: + inputs[input_mask.name] = fake_input_mask_data( + input_mask, batch_size, sequence_length, average_sequence_length, random_sequence_length + ) + + if global_mask: + inputs[global_mask.name] = fake_global_mask_data( + global_mask, batch_size, sequence_length, num_global_tokens + ) + + if verbose and len(all_inputs) == 0: + print("Example inputs", inputs) + all_inputs.append(inputs) + + return all_inputs + + +def generate_test_data( + batch_size, + sequence_length, + test_cases, + seed, + verbose, + input_ids, + input_mask, + global_mask, + num_global_tokens, + average_sequence_length, + random_sequence_length, +): + dictionary_size = 10000 + all_inputs = fake_test_data( + batch_size, + sequence_length, + test_cases, + dictionary_size, + verbose, + seed, + input_ids, + input_mask, + global_mask, + num_global_tokens, + average_sequence_length, + random_sequence_length, + ) + if len(all_inputs) != test_cases: + print("Failed to create test data for test.") + return all_inputs + + +def create_longformer_test_data( + model, + output_dir, + batch_size, + sequence_length, + test_cases, + seed, + verbose, + input_ids_name, + input_mask_name, + global_mask_name, + num_global_tokens, + average_sequence_length, + random_sequence_length, +): + input_ids, input_mask, global_mask = get_longformer_inputs(model, input_ids_name, input_mask_name, global_mask_name) + all_inputs = generate_test_data( + batch_size, + sequence_length, + test_cases, + seed, + verbose, + input_ids, + input_mask, + global_mask, + num_global_tokens, + average_sequence_length, + random_sequence_length, + ) + + for i, inputs in enumerate(all_inputs): + output_test_data(output_dir, i, inputs) + + +def main(): + args = parse_arguments() + + output_dir = args.output_dir + if output_dir is None: + # Default output directory is a sub-directory under the directory of model. + output_dir = os.path.join( + Path(args.model).parent, + f"b{args.batch_size}_s{args.sequence_length}_g{args.global_tokens}", + ) + + if output_dir is not None: + # create the output directory if not existed + path = Path(output_dir) + path.mkdir(parents=True, exist_ok=True) + else: + print("Directory existed. test data files will be overwritten.") + + if args.average_sequence_length <= 0: + args.average_sequence_length = args.sequence_length + + create_longformer_test_data( + args.model, + output_dir, + args.batch_size, + args.sequence_length, + args.samples, + args.seed, + args.verbose, + args.input_ids_name, + args.input_mask_name, + args.global_mask_name, + args.global_tokens, + args.average_sequence_length, + ) + + print("Test data is saved to directory:", output_dir) + + +if __name__ == "__main__": + main() diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/longformer/longformer_helper.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/longformer/longformer_helper.py new file mode 100644 index 0000000000000000000000000000000000000000..074fa098e6a096ea0c08ca518c3221efda849658 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/longformer/longformer_helper.py @@ -0,0 +1,76 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- +# This script helps creating dummy inputs for Longformer model. + +import logging + +import numpy +import torch + +logger = logging.getLogger(__name__) + +PRETRAINED_LONGFORMER_MODELS = { + "longformer-base-4096": "allenai/longformer-base-4096", + "longformer-large-4096": "allenai/longformer-large-4096", + "longformer-random-tiny": "patrickvonplaten/longformer-random-tiny", # A tiny model for debugging +} + + +class LongformerInputs: + def __init__(self, input_ids, attention_mask, global_attention_mask): + self.input_ids: torch.LongTensor = input_ids + self.attention_mask: torch.FloatTensor | torch.HalfTensor = attention_mask + self.global_attention_mask: torch.FloatTensor | torch.HalfTensor = global_attention_mask + + def to_list(self) -> list: + return [v for v in [self.input_ids, self.attention_mask, self.global_attention_mask] if v is not None] + + def to_tuple(self) -> tuple: + return tuple(v for v in self.to_list()) + + def get_ort_inputs(self) -> dict: + return { + "input_ids": numpy.ascontiguousarray(self.input_ids.cpu().numpy()), + "attention_mask": numpy.ascontiguousarray(self.attention_mask.cpu().numpy()), + "global_attention_mask": numpy.ascontiguousarray(self.global_attention_mask.cpu().numpy()), + } + + +class LongformerHelper: + """A helper class for Longformer model conversion, inference and verification.""" + + @staticmethod + def get_dummy_inputs( + batch_size: int, + sequence_length: int, + num_global_tokens: int, + device: torch.device, + vocab_size: int = 100, + ) -> LongformerInputs: + """Create random inputs for Longformer model. + Returns torch tensors of input_ids, attention_mask and global_attention_mask tensors. + """ + + input_ids = torch.randint( + low=0, + high=vocab_size - 1, + size=(batch_size, sequence_length), + dtype=torch.long, + device=device, + ) + attention_mask = torch.ones(input_ids.shape, dtype=torch.long, device=device) + global_attention_mask = torch.zeros(input_ids.shape, dtype=torch.long, device=device) + global_token_index = list(range(num_global_tokens)) + global_attention_mask[:, global_token_index] = 1 + return LongformerInputs(input_ids, attention_mask, global_attention_mask) + + @staticmethod + def get_output_shapes(batch_size: int, sequence_length: int, hidden_size: int) -> dict[str, list[int]]: + """Returns a dictionary with output name as key, and shape as value.""" + return { + "last_state": [batch_size, sequence_length, hidden_size], + "pooler": [batch_size, sequence_length], + } diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/phi2/__init__.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/phi2/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8f9a57c902589567201d260a9248c59309a74576 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/phi2/__init__.py @@ -0,0 +1,12 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +# -------------------------------------------------------------------------- +import os +import sys + +sys.path.append(os.path.dirname(__file__)) + +transformers_dir = os.path.normpath(os.path.join(os.path.dirname(__file__), "..", "..")) +if transformers_dir not in sys.path: + sys.path.append(transformers_dir) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/phi2/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/phi2/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0d4ccd74b5cf013598c40d531fde1d596d067d83 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/phi2/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/phi2/__pycache__/convert_to_onnx.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/phi2/__pycache__/convert_to_onnx.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..05f1d57329f566500c1964cd2d57177c4abda623 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/phi2/__pycache__/convert_to_onnx.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/phi2/__pycache__/inference_example.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/phi2/__pycache__/inference_example.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3c01e04e4f95dc0c5bbad427a819b7fc2caf6c35 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/phi2/__pycache__/inference_example.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/phi2/convert_to_onnx.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/phi2/convert_to_onnx.py new file mode 100644 index 0000000000000000000000000000000000000000..b45b732b194bb9db041cc40d6d0393bbe95c6a0d --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/phi2/convert_to_onnx.py @@ -0,0 +1,590 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +# -------------------------------------------------------------------------- +from __future__ import annotations + +import argparse +import logging +import os +import warnings +from pathlib import Path + +import onnx +import torch +from benchmark_helper import Precision +from fusion_options import AttentionOpType +from onnx_model import OnnxModel +from packaging import version +from transformers import AutoConfig, AutoModelForCausalLM + +from onnxruntime import __version__ as ort_version + +if version.parse(ort_version) < version.parse("1.22.0"): + from onnxruntime.quantization.matmul_4bits_quantizer import MatMul4BitsQuantizer as MatMulNBitsQuantizer +else: + from onnxruntime.quantization.matmul_nbits_quantizer import MatMulNBitsQuantizer + + +class ConvertPhi2ToONNX: + def __init__( + self, + device: torch.device, + model_class: str = "microsoft/phi-2", + cache_dir: str = "./cache", + ): + self.model_class = model_class + self.device = device + self.cache_dir = cache_dir + self.phi_config = AutoConfig.from_pretrained(self.model_class, trust_remote_code=True, cache_dir=self.cache_dir) + self.phi_model = None + self.batch_size = 2 + self.sequence_length = 8 + self.attn_op_type = None + self.precision = None + self.block_size = 16 + self.accuracy_level = None + + def set_quantization_params(self, block_size: int, accuracy_level: int | None): + self.block_size = block_size + self.accuracy_level = accuracy_level + + def init_attn_type_and_precision(self, attn_op_type: AttentionOpType, precision: Precision): + self.attn_op_type = attn_op_type + self.precision = precision + + def erase_onnx_model(self, onnx_path: str) -> None: + assert onnx_path.endswith(".onnx") + if not os.path.exists(onnx_path): + return + + model = onnx.load_model(onnx_path, load_external_data=False) + onnx_data_path = None + for initializer in model.graph.initializer: + if initializer.data_location == 1 and initializer.external_data[0].key == "location": + onnx_data_path = "./" + initializer.external_data[0].value + break + logging.info(f"Erasing {onnx_path}...") + os.remove(onnx_path) + if onnx_data_path is not None: + onnx_data_path = os.path.join(Path(onnx_path).parent, onnx_data_path) + logging.info(f"Erasing {onnx_data_path}...") + os.remove(onnx_data_path) + + def get_phi2_torch_model(self): + logging.info("Loading phi2 torch model...") + if self.phi_model is not None: + return + self.phi_model = AutoModelForCausalLM.from_pretrained( + self.model_class, trust_remote_code=True, cache_dir=self.cache_dir + ) + self.phi_model.eval() + self.phi_model.to(self.device) + + def get_phi2_torch_inputs(self, batch_size: int, sequence_length: int): + input_ids = torch.randint( + low=0, + high=self.phi_config.vocab_size, + size=(batch_size, sequence_length), + dtype=torch.int64, + device=self.device, + ) + self.get_phi2_torch_model() + torch_inputs = self.phi_model.prepare_inputs_for_generation( + input_ids, past_key_values=self.phi_model(input_ids, use_cache=True)["past_key_values"] + ) + return torch_inputs["input_ids"], torch_inputs["attention_mask"], torch_inputs["past_key_values"] + + def dynamo_export(self, onnx_path: str): + input_ids, attention_mask, past_key_values = self.get_phi2_torch_inputs(self.batch_size, self.sequence_length) + self.phi_model(input_ids, attention_mask=attention_mask, past_key_values=past_key_values) + + from torch._dynamo import config # noqa: PLC0415 + + config.capture_scalar_outputs = True + + logging.info("Exporting Phi2 torch model to ONNX...") + torch.onnx.dynamo_export( + self.phi_model, + input_ids, + attention_mask=attention_mask, + past_key_values=past_key_values, + export_options=torch.onnx.ExportOptions(dynamic_shapes=True), + ).save(onnx_path) + onnx.checker.check_model(onnx_path) + onnx.shape_inference.infer_shapes_path(onnx_path) + + def optimize_phi2_onnx(self, onnx_path: str, onnx_path_opt: str): + from fusion_options import FusionOptions # noqa: PLC0415 + from optimizer import optimize_model # noqa: PLC0415 + + optimization_options = FusionOptions("phi") + optimization_options.set_attention_op_type(self.attn_op_type) + optimizer = optimize_model( + onnx_path, + model_type="phi", + num_heads=self.phi_config.num_attention_heads, + hidden_size=self.phi_config.hidden_size, + opt_level=0, + optimization_options=optimization_options, + only_onnxruntime=False, + ) + + fused_op_count = optimizer.get_fused_operator_statistics() + if optimizer.is_fully_optimized(fused_op_count): + logging.info("Model is fully optimized.") + else: + logging.info("Model is not fully optimized.") + + if self.precision == Precision.FLOAT32: + optimizer.save_model_to_file(onnx_path_opt, use_external_data_format=True) + return + + if ( + self.precision == Precision.FLOAT16 or self.precision == Precision.INT4 + ) and self.attn_op_type != AttentionOpType.MultiHeadAttention: + # We keep last three layers of Attention as float32 or bfloat16 to avoid overflow. + node_block_list = ( + [ + "Attention_29", + "Attention_30", + "Attention_31", + ] + if self.attn_op_type != AttentionOpType.PagedAttention + else [] + ) # TODO: temp setting for paged attention + logging.info("Converting onnx model to float16/bfloat16...") + optimizer.convert_float_to_float16( + keep_io_types=False, + node_block_list=node_block_list, + use_symbolic_shape_infer=True, + use_bfloat16_as_blocked_nodes_dtype=self.attn_op_type == AttentionOpType.GroupQueryAttention, + ) + logging.info("Converting onnx model to float16/bfloat16 done.") + + if self.precision == Precision.FLOAT16: + optimizer.save_model_to_file(onnx_path_opt, use_external_data_format=True) + return + else: + assert self.precision == Precision.INT4 + quant = MatMulNBitsQuantizer( + model=optimizer.model, + bits=4, + block_size=self.block_size, + is_symmetric=True, + accuracy_level=self.accuracy_level, + ) + quant.process() + quant.model.save_model_to_file(onnx_path_opt, use_external_data_format=True) + + # This function currently only works for phi2 model + def convert_to_use_cuda_graph(self, in_onnx_path: str, out_onnx_path: str): + onnx_model = OnnxModel(onnx.load(in_onnx_path, load_external_data=True)) + + from onnx import TensorProto, helper # noqa: PLC0415 + + graph = onnx_model.graph() + new_inputs = [] + for vi in graph.input: + if "attention_mask" in vi.name: + vi_seqlen_k = helper.make_tensor_value_info( + "seqlens_k", + elem_type=TensorProto.INT32, + shape=["batch_size"], + ) + vi_total_seq_len = helper.make_tensor_value_info( + "total_sequence_length", + elem_type=TensorProto.INT32, + shape=[1], + ) + new_inputs.extend([vi_seqlen_k, vi_total_seq_len]) + else: + new_inputs.append(vi) + + graph.ClearField("input") + graph.input.extend(new_inputs) + + gqas = onnx_model.get_nodes_by_op_type("GroupQueryAttention") + gqa = gqas[0] + seqlens_path = onnx_model.match_parent_path( + gqa, + ["Cast", "Sub", "ReduceSum", "Cast"], + [5, 0, 0, 0], + ) + if seqlens_path is None: + raise RuntimeError("Failed to find seqlens path for GroupQueryAttention node.") + total_seq_len_path = onnx_model.match_parent_path( + gqa, + ["Cast", "Gather", "Shape"], + [6, 0, 0], + ) + if total_seq_len_path is None: + raise RuntimeError("Failed to find total_seq_len path for GroupQueryAttention node.") + onnx_model.remove_nodes(seqlens_path) + onnx_model.remove_nodes(total_seq_len_path) + + for gqa in gqas: + gqa.input[5] = "seqlens_k" + gqa.input[6] = "total_sequence_length" + + onnx_model.save(onnx_model.model, out_onnx_path, save_as_external_data=True) + + +def parse_arguments(): + parser = argparse.ArgumentParser() + + parser.add_argument( + "--fp32_cpu", + required=False, + action="store_true", + help="Generate fp32 ONNX model for CPU", + ) + + parser.add_argument( + "--int4_cpu", + required=False, + action="store_true", + help="Generate int4 ONNX model for CPU", + ) + + parser.add_argument( + "--fp32_gpu", + required=False, + action="store_true", + help="Generate fp32 ONNX model for Nvidia GPUs", + ) + + parser.add_argument( + "--fp16_gpu", + required=False, + action="store_true", + help="Generate fp16 ONNX model for Nvidia GPUs", + ) + + parser.add_argument( + "--int4_gpu", + required=False, + action="store_true", + help="Generate int4 ONNX model for Nvidia GPUs", + ) + + parser.add_argument( + "--fp16_gpu_sm8x", + required=False, + action="store_true", + help="Generate fp16 ONNX model for Nvidia GPUs with CUDA architecture SM=80~89", + ) + + parser.add_argument( + "--int4_gpu_sm8x", + required=False, + action="store_true", + help="Generate int4 ONNX model for Nvidia GPUs with CUDA architecture SM=80~89", + ) + + parser.add_argument( + "--fp16_vllm", + required=False, + action="store_true", + help="Generate fp16 ONNX model for ORT VLLM", + ) + + parser.add_argument( + "--int4_vllm", + required=False, + action="store_true", + help="Generate int4 ONNX model for ORT VLLM", + ) + + parser.add_argument( + "--use_cuda_graph", + required=False, + action="store_true", + help="Use CUDA Graph in decoding process", + ) + + parser.add_argument( + "--overwrite", + required=False, + action="store_true", + help="Overwrite existing ONNX models", + ) + + parser.add_argument( + "--cache_dir", + required=False, + type=str, + default="./cache", + help="The cache directory for the pytorch model", + ) + + parser.add_argument( + "--device_id", + required=False, + type=int, + default=0, + help="The device id for the pytorch model", + ) + + parser.add_argument( + "--run_example", + required=False, + action="store_true", + help="Run ORT inference example", + ) + + parser.add_argument( + "--run_benchmark", + required=False, + action="store_true", + help="Run ORT benchmark", + ) + + parser.add_argument( + "--skip_export", + required=False, + action="store_true", + help="Skip exporting ONNX model", + ) + + parser.add_argument( + "--output_dir", + type=str, + help="The output directory for the ONNX models", + default="phi2_onnx_models", + ) + + parser.add_argument( + "--block_size", + required=False, + default=16, + type=int, + help="Block size to quantize with. See https://github.com/microsoft/onnxruntime/blob/main/onnxruntime/python/tools/quantization/matmul_nbits_quantizer.py for details.", + ) + + parser.add_argument( + "--int4_accuracy_level", + required=False, + type=int, + help="Accuracy level of the 4-bit quantized MatMul computation. " + "Refer to the MatMulNBits contrib op's 'accuracy_level' attribute for details " + "(https://github.com/microsoft/onnxruntime/blob/main/docs/ContribOperators.md#commicrosoftmatmulnbits).", + ) + + args = parser.parse_args() + return args + + +def main(): + warnings.warn( + "This example is deprecated. Use the Olive recipe instead: " + "https://github.com/microsoft/olive-recipes/tree/main", + DeprecationWarning, + stacklevel=2, + ) + args = parse_arguments() + + device = torch.device("cuda", args.device_id) if torch.cuda.is_available() else torch.device("cpu") + + converter = ConvertPhi2ToONNX(device, cache_dir=args.cache_dir) + converter.set_quantization_params(args.block_size, args.int4_accuracy_level) + + output_dir = args.output_dir + + if not os.path.exists(output_dir): + os.makedirs(output_dir) + + original_onnx_path = os.path.join(output_dir, "phi2_original.onnx") + + if not args.skip_export: + if not os.path.exists(original_onnx_path) or args.overwrite: + converter.dynamo_export(original_onnx_path) + + model_type_to_args = { + "fp32_cpu": ( + AttentionOpType.MultiHeadAttention, + Precision.FLOAT32, + os.path.join(output_dir, "phi2_decoder_fp32_cpu.onnx"), + ), + "int4_cpu": ( + AttentionOpType.MultiHeadAttention, + Precision.INT4, + os.path.join(output_dir, "phi2_decoder_int4_cpu.onnx"), + ), + "fp32_gpu": ( + AttentionOpType.Attention, + Precision.FLOAT32, + os.path.join(output_dir, "phi2_decoder_fp32_gpu.onnx"), + ), + "fp16_gpu": ( + AttentionOpType.Attention, + Precision.FLOAT16, + os.path.join(output_dir, "phi2_decoder_fp16_gpu.onnx"), + ), + "int4_gpu": (AttentionOpType.Attention, Precision.INT4, os.path.join(output_dir, "phi2_decoder_int4_gpu.onnx")), + "fp16_gpu_sm8x": ( + AttentionOpType.GroupQueryAttention, + Precision.FLOAT16, + os.path.join(output_dir, "phi2_decoder_fp16_gpu_sm8x.onnx"), + ), + "int4_gpu_sm8x": ( + AttentionOpType.GroupQueryAttention, + Precision.INT4, + os.path.join(output_dir, "phi2_decoder_int4_gpu_sm8x.onnx"), + ), + "fp16_vllm": ( + AttentionOpType.PagedAttention, + Precision.FLOAT16, + os.path.join(output_dir, "phi2_decoder_fp16_vllm.onnx"), + ), + "int4_vllm": ( + AttentionOpType.PagedAttention, + Precision.INT4, + os.path.join(output_dir, "phi2_decoder_int4_vllm.onnx"), + ), + } + + if not args.skip_export: + from multiprocessing import Process # noqa: PLC0415 + + def run_optimize_phi2_onnx( + converter: ConvertPhi2ToONNX, + original_onnx_path: str, + attention_type: AttentionOpType, + precision: Precision, + optimized_onnx_path: str, + ): + converter.init_attn_type_and_precision(attention_type, precision) + converter.optimize_phi2_onnx(original_onnx_path, optimized_onnx_path) + if args.use_cuda_graph: + assert args.fp16_gpu_sm8x or args.int4_gpu_sm8x + converter.convert_to_use_cuda_graph(optimized_onnx_path, optimized_onnx_path) + + processes = [] + if args.fp32_cpu: + processes.append( + Process( + target=run_optimize_phi2_onnx, args=(converter, original_onnx_path, *model_type_to_args["fp32_cpu"]) + ) + ) + + if args.int4_cpu: + processes.append( + Process( + target=run_optimize_phi2_onnx, args=(converter, original_onnx_path, *model_type_to_args["int4_cpu"]) + ) + ) + + if args.fp32_gpu: + processes.append( + Process( + target=run_optimize_phi2_onnx, args=(converter, original_onnx_path, *model_type_to_args["fp32_gpu"]) + ) + ) + + if args.fp16_gpu: + processes.append( + Process( + target=run_optimize_phi2_onnx, args=(converter, original_onnx_path, *model_type_to_args["fp16_gpu"]) + ) + ) + + if args.int4_gpu: + processes.append( + Process( + target=run_optimize_phi2_onnx, args=(converter, original_onnx_path, *model_type_to_args["int4_gpu"]) + ) + ) + + if args.fp16_gpu_sm8x: + processes.append( + Process( + target=run_optimize_phi2_onnx, + args=(converter, original_onnx_path, *model_type_to_args["fp16_gpu_sm8x"]), + ) + ) + + if args.int4_gpu_sm8x: + processes.append( + Process( + target=run_optimize_phi2_onnx, + args=(converter, original_onnx_path, *model_type_to_args["int4_gpu_sm8x"]), + ) + ) + + if args.fp16_vllm: + processes.append( + Process( + target=run_optimize_phi2_onnx, + args=(converter, original_onnx_path, *model_type_to_args["fp16_vllm"]), + ) + ) + + if args.int4_vllm: + processes.append( + Process( + target=run_optimize_phi2_onnx, + args=(converter, original_onnx_path, *model_type_to_args["int4_vllm"]), + ) + ) + + [p.start() for p in processes] + [p.join() for p in processes] + + if args.run_example or args.run_benchmark: + from inference_example import run_phi2 # noqa: PLC0415 + + if args.fp16_gpu_sm8x: + logging.info("Running fp16_gpu_sm8x example...") + run_phi2( + onnx_model_path=model_type_to_args["fp16_gpu_sm8x"][2], + use_buffer_share=True, + device_id=args.device_id, + use_step=True, + use_cuda_graph=args.use_cuda_graph, + run_benchmark=args.run_benchmark, + ) + if args.int4_gpu_sm8x: + logging.info("Running int4_gpu_sm8x example...") + run_phi2( + onnx_model_path=model_type_to_args["int4_gpu_sm8x"][2], + use_buffer_share=True, + device_id=args.device_id, + use_step=True, + use_cuda_graph=args.use_cuda_graph, + run_benchmark=args.run_benchmark, + ) + if args.fp32_gpu: + logging.info("Running fp32_gpu example...") + run_phi2( + onnx_model_path=model_type_to_args["fp32_gpu"][2], + use_buffer_share=False, + device_id=args.device_id, + packed_kv=True, + use_fp16=False, + run_benchmark=args.run_benchmark, + ) + if args.fp16_gpu: + logging.info("Running fp16_gpu example...") + run_phi2( + onnx_model_path=model_type_to_args["fp16_gpu"][2], + use_buffer_share=False, + device_id=args.device_id, + packed_kv=True, + run_benchmark=args.run_benchmark, + ) + if args.int4_gpu: + logging.info("Running int4_gpu example...") + run_phi2( + onnx_model_path=model_type_to_args["int4_gpu"][2], + use_buffer_share=False, + device_id=args.device_id, + packed_kv=True, + run_benchmark=args.run_benchmark, + ) + if args.fp32_cpu or args.int4_cpu or args.fp16_vllm or args.int4_vllm: + raise NotImplementedError("CPU/vllm inference example is not implemented yet.") + + +if __name__ == "__main__": + main() diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/phi2/inference_example.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/phi2/inference_example.py new file mode 100644 index 0000000000000000000000000000000000000000..3dadd28d7ee4e74f34c24e5e61f531832e9b6811 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/phi2/inference_example.py @@ -0,0 +1,414 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +# -------------------------------------------------------------------------- + +import time + +import numpy as np +import torch +from transformers import AutoTokenizer + +import onnxruntime as ort + +pt_to_np = { + "torch.int32": np.int32, + "torch.int64": np.int64, + "torch.float32": np.float32, + "torch.float16": np.float16, +} + + +def cuda_memcpy(dst, src): + from cuda import cudart # noqa: PLC0415 + + cudart.cudaMemcpy( + dst.data_ptr(), + src.data_ptr(), + src.element_size() * src.nelement(), + cudart.cudaMemcpyKind.cudaMemcpyDeviceToDevice, + ) + + +class ORTGenerator: + def __init__(self, decoder_path): + self.onnx_decoder_path = decoder_path + self.num_heads = 32 + self.head_size = 80 + self.num_layers = 32 + self.max_sequence_length = 2048 + self.device_id = 0 + self.use_cuda_graph = False + self.use_traced_inputs = False + self.static_inputs_map = {} + + def append_static_inputs(self, batch_size): + # Only use this function with GQA and with use_cuda_graph=True + if batch_size in self.static_inputs_map: + return + + cpu_device = torch.device("cpu") + cuda_device = torch.device("cuda", self.device_id) + + static_io = {} + static_io["input_ids"] = torch.zeros((batch_size, 1), dtype=torch.int32, device=cuda_device) + static_io["step"] = torch.tensor([0], dtype=torch.int64, device=cuda_device) + static_io["seqlens_k"] = torch.tensor(batch_size * [0], dtype=torch.int32, device=cuda_device) + static_io["total_sequence_length"] = torch.tensor([0], dtype=torch.int32, device=cpu_device) + + cache_shape = (batch_size, self.num_heads, self.max_sequence_length, self.head_size) + for i in range(self.num_layers): + cache = torch.zeros(cache_shape, device=cuda_device, dtype=torch.float16) + static_io.update({f"past_key_{i}": cache.contiguous(), f"past_value_{i}": cache.clone().contiguous()}) + + static_io["logits"] = torch.zeros((batch_size, 1, 51200), dtype=torch.float16, device=cuda_device) + + self.static_inputs_map[batch_size] = static_io + + def get_initial_inputs_and_outputs(self, encodings_dict): + self.torch_dtype = torch.float16 if self.use_fp16 else torch.float32 + + input_ids = torch.tensor(encodings_dict["input_ids"], device=self.device, dtype=torch.int32) + attention_mask = torch.tensor(encodings_dict["attention_mask"], device=self.device, dtype=torch.int32) + + batch_size, sequence_length = input_ids.shape + + self.use_traced_inputs = ( + self.use_cuda_graph + and (batch_size in self.static_inputs_map) + and self.use_buffer_share + and not self.packed_kv + ) + + step = ( + torch.tensor([0], device=self.device, dtype=torch.int64) + if not self.use_traced_inputs + else self.static_inputs_map[batch_size]["step"] + ) + + seqlens_k = ( + torch.tensor(batch_size * [0], device=self.device, dtype=torch.int32) + if not self.use_traced_inputs + else self.static_inputs_map[batch_size]["seqlens_k"] + ) + cuda_memcpy(seqlens_k, attention_mask.sum(1).sub(1).to(torch.int32)) + + total_seq_length = ( + torch.tensor([0], device=torch.device("cpu"), dtype=torch.int32) + if not self.use_traced_inputs + else self.static_inputs_map[batch_size]["total_sequence_length"] + ) + total_seq_length[0] = sequence_length + + inputs = { + "input_ids": input_ids.contiguous(), + "attention_mask": attention_mask.contiguous(), + } + + if self.use_step: + inputs["step"] = step.contiguous() + + if self.use_cuda_graph: + inputs["seqlens_k"] = seqlens_k.contiguous() + inputs["total_sequence_length"] = total_seq_length.contiguous() + del inputs["attention_mask"] + + past_seq_length = self.max_sequence_length if self.use_buffer_share else 0 + past_shape = ( + (2, batch_size, self.num_heads, past_seq_length, self.head_size) + if self.packed_kv + else (batch_size, self.num_heads, past_seq_length, self.head_size) + ) + + if not self.use_traced_inputs: + for i in range(self.num_layers): + past = torch.zeros(past_shape, device=self.device, dtype=self.torch_dtype) + ( + inputs.update({f"past_key_{i}": past.contiguous(), f"past_value_{i}": past.clone().contiguous()}) + if not self.packed_kv + else inputs.update({f"past_{i}": past.contiguous()}) + ) + else: + for i in range(self.num_layers): + inputs.update( + { + f"past_key_{i}": self.static_inputs_map[batch_size][f"past_key_{i}"].contiguous(), + f"past_value_{i}": self.static_inputs_map[batch_size][f"past_value_{i}"].contiguous(), + } + ) + + logits = torch.zeros(batch_size, sequence_length, 51200, device=self.device, dtype=self.torch_dtype) + outputs = {"logits": logits.contiguous()} + + if not self.use_buffer_share: + present_shape = ( + (2, batch_size, self.num_heads, sequence_length, self.head_size) + if self.packed_kv + else (batch_size, self.num_heads, sequence_length, self.head_size) + ) + for i in range(self.num_layers): + present = torch.zeros(present_shape, device=self.device, dtype=self.torch_dtype) + ( + outputs.update( + {f"present_key_{i}": present.contiguous(), f"present_value_{i}": present.contiguous()} + ) + if not self.packed_kv + else outputs.update({f"present_{i}": present.contiguous()}) + ) + + return inputs, outputs + + def apply_io_binding(self, model: ort.InferenceSession, inputs: dict, outputs: dict): + io_binding = model.io_binding() + device = None + + for k, v in inputs.items(): + io_binding.bind_input( + name=k, + device_type=v.device.type, + device_id=0 if v.device.type == "cpu" else v.device.index, + element_type=pt_to_np[repr(v.dtype)], + shape=tuple(v.shape), + buffer_ptr=v.data_ptr(), + ) + device = v.device + + for output in model.get_outputs(): + name = output.name + if self.use_buffer_share and "present" in name: + v = inputs[name.replace("present", "past")] + io_binding.bind_output( + name=name, + device_type=v.device.type, + device_id=v.device.index, + element_type=(np.float16 if self.use_fp16 else np.float32), + shape=tuple(v.shape), + buffer_ptr=v.data_ptr(), + ) + else: + v = outputs[name] + io_binding.bind_output( + name=name, + device_type=device.type, + device_id=0 if device.type == "cpu" else device.index, + element_type=(np.float16 if self.use_fp16 else np.float32), + shape=tuple(v.shape), + buffer_ptr=v.data_ptr(), + ) + + return io_binding + + def create_session( + self, device_id, use_fp16=True, use_buffer_share=True, packed_kv=False, use_step=False, use_cuda_graph=False + ): + self.device_id = device_id + sess_options = ort.SessionOptions() + sess_options.log_verbosity_level = 4 + sess_options.log_severity_level = 4 + self.use_cuda_graph = use_cuda_graph + ep = ( + ("CUDAExecutionProvider", {"device_id": self.device_id, "enable_cuda_graph": self.use_cuda_graph}) + if self.device_id >= 0 + else "CPUExecutionProvider" + ) + self.sess = ort.InferenceSession(self.onnx_decoder_path, sess_options=sess_options, providers=[ep]) + self.ro = ort.RunOptions() + + self.device = torch.device("cuda", self.device_id) if torch.cuda.is_available() else torch.device("cpu") + self.use_fp16 = use_fp16 + self.use_buffer_share = use_buffer_share + self.packed_kv = packed_kv + self.use_step = use_step + + self.tokenizer = AutoTokenizer.from_pretrained("microsoft/phi-2", trust_remote_code=True) + self.tokenizer.pad_token = "[PAD]" + + def generate_impl(self, encodings_dict, max_length, cuda_graph_annotation, benchmark=False): + inputs, outputs = self.get_initial_inputs_and_outputs(encodings_dict) + + all_token_ids = inputs["input_ids"].clone() + batch_size, sequence_length = all_token_ids.shape + + current_length = sequence_length + has_eos = torch.zeros(batch_size, device=self.device, dtype=torch.bool) + + if benchmark: + latency = [] + + prompt_run = True + while current_length < max_length: + io_binding = self.apply_io_binding(self.sess, inputs, outputs) + + if benchmark: + start = time.time() + + io_binding.synchronize_inputs() + if prompt_run: + if self.use_cuda_graph: + # Disable CUDA graph for the prompt run + self.ro.add_run_config_entry("gpu_graph_id", "-1") + self.sess.run_with_iobinding(io_binding, self.ro) + if self.use_cuda_graph: + # Enable CUDA graph for the decoding run + self.ro.add_run_config_entry( + "gpu_graph_id", str(cuda_graph_annotation) if self.use_traced_inputs else "-1" + ) + prompt_run = False + else: + self.sess.run_with_iobinding(io_binding, self.ro) + io_binding.synchronize_outputs() + + if benchmark: + end = time.time() + latency.append(end - start) + + # Sample with argmax (greedy search) + next_token_logits = outputs["logits"][:, -1, :] + next_tokens = torch.argmax(next_token_logits, dim=-1) + + # Check if we previously reached EOS token id or if generated token id is EOS token id + has_eos = has_eos | next_tokens == self.tokenizer.eos_token_id + + # Determine which new tokens to add to list of all token ids + # Add EOS token ids for batch entries that ended early (ragged batching scenario where some batch entries ended early and some haven't) + tokens_to_add = next_tokens.masked_fill(has_eos, self.tokenizer.eos_token_id).reshape([batch_size, 1]) + all_token_ids = torch.cat([all_token_ids, tokens_to_add], dim=-1) + + # Return early if all batch entries have reached EOS token id + if torch.all(has_eos): + break + + # Update inputs for next inference run + current_length += 1 + + inputs["input_ids"] = tokens_to_add.to(torch.int32) + if self.use_traced_inputs: + cuda_memcpy(self.static_inputs_map[batch_size]["input_ids"], inputs["input_ids"]) + inputs["input_ids"] = self.static_inputs_map[batch_size]["input_ids"] + + if self.use_step: + inputs["step"] = torch.tensor([current_length - 1], device=self.device, dtype=torch.int64) + if self.use_traced_inputs: + cuda_memcpy(self.static_inputs_map[batch_size]["step"], inputs["step"]) + inputs["step"] = self.static_inputs_map[batch_size]["step"] + + if self.use_cuda_graph: + previous_seqlens_k = inputs["seqlens_k"] + inputs["seqlens_k"] = (previous_seqlens_k + (~has_eos).reshape(batch_size, 1)).to(torch.int32) + inputs["total_sequence_length"][0] = current_length + if self.use_traced_inputs: + cuda_memcpy(self.static_inputs_map[batch_size]["seqlens_k"], inputs["seqlens_k"]) + inputs["seqlens_k"] = self.static_inputs_map[batch_size]["seqlens_k"] + self.static_inputs_map[batch_size]["total_sequence_length"][0] = inputs["total_sequence_length"][0] + inputs["total_sequence_length"] = self.static_inputs_map[batch_size]["total_sequence_length"] + else: + inputs["attention_mask"] = torch.cat( + [inputs["attention_mask"], (~has_eos).reshape(batch_size, 1)], 1 + ).to(torch.int32) + + # Set logits to zeros for next inference run and re-use memory buffer + if outputs["logits"].shape[1] != 1: + outputs["logits"] = outputs["logits"][:, :1, :].contiguous() + if self.use_traced_inputs: + outputs["logits"] = self.static_inputs_map[batch_size]["logits"] + outputs["logits"].zero_() + + if not self.use_buffer_share: + for i in range(self.num_layers): + if not self.packed_kv: + inputs[f"past_key_{i}"] = outputs[f"present_key_{i}"] + inputs[f"past_value_{i}"] = outputs[f"present_value_{i}"] + else: + inputs[f"past_{i}"] = outputs[f"present_{i}"] + + new_sequence_length = inputs["attention_mask"].shape[1] + present_shape = ( + (2, batch_size, self.num_heads, new_sequence_length, self.head_size) + if self.packed_kv + else (batch_size, self.num_heads, new_sequence_length, self.head_size) + ) + for i in range(self.num_layers): + present = torch.zeros(present_shape, device=self.device, dtype=self.torch_dtype) + ( + outputs.update( + { + f"present_key_{i}": present.contiguous(), + f"present_value_{i}": present.clone().contiguous(), + } + ) + if not self.packed_kv + else outputs.update({f"present_{i}": present.contiguous()}) + ) + + if benchmark: + print( + f"Batch size: {batch_size}, Sequence length: {sequence_length}, Token num: {max_length - sequence_length}" + ) + print(f"Prompt letency: {1000 * latency[0]}ms, Token latency: {1000 * np.mean(latency[1:])}ms") + return + + texts = self.tokenizer.batch_decode(all_token_ids, skip_special_tokens=True) + return texts + + def generate(self, prompt, max_length, cuda_graph_annotation): + encodings_dict = self.tokenizer.batch_encode_plus(prompt, padding=True) + + return self.generate_impl(encodings_dict, max_length, cuda_graph_annotation) + + def generate_benchmark(self, prompt_shape, token_num, cuda_graph_annotation): + batch_size, sequence_length = prompt_shape + max_length = sequence_length + token_num + + encodings_dict = {} + encodings_dict["input_ids"] = torch.randint(0, 50264, (batch_size, sequence_length), dtype=torch.int32).tolist() + encodings_dict["attention_mask"] = torch.ones((batch_size, sequence_length), dtype=torch.int32).tolist() + + # Warm up run + self.generate_impl(encodings_dict, max_length, cuda_graph_annotation, benchmark=False) + + # Benchmark run + self.generate_impl(encodings_dict, max_length, cuda_graph_annotation, benchmark=True) + + +def run_phi2( + onnx_model_path, + use_buffer_share, + device_id, + packed_kv=False, + use_fp16=True, + use_step=False, + use_cuda_graph=False, + run_benchmark=False, +): + generator = ORTGenerator(onnx_model_path) + generator.create_session(device_id, use_fp16, use_buffer_share, packed_kv, use_step, use_cuda_graph) + + def simple_run(prompt): + example_batch_size = len(prompt) + if use_cuda_graph: + generator.append_static_inputs(batch_size=example_batch_size) + texts = generator.generate(prompt, max_length=210, cuda_graph_annotation=example_batch_size) + + for i in range(len(texts)): + print("Prompt: ", prompt[i]) + print("Texts: ", texts[i]) + + prompt = [ + '''```python + def print_prime(n): + """ + Print all primes between 1 and n + """''' + ] + + if not run_benchmark: + simple_run(prompt) + + # Run simple benchmark. Time the decoder only. + if run_benchmark: + token_num = 32 + for batch_size in [1, 2, 4, 8]: + generator.append_static_inputs(batch_size) + for sequence_length in [16, 512]: + prompt_shape = (batch_size, sequence_length) + generator.generate_benchmark(prompt_shape, token_num, cuda_graph_annotation=batch_size) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/sam2/__init__.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/sam2/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5ef71ce9e355e17ea1c2ca9fb648951d917734b5 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/sam2/__init__.py @@ -0,0 +1,12 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +# -------------------------------------------------------------------------- +import os.path +import sys + +sys.path.append(os.path.dirname(__file__)) + +transformers_dir = os.path.normpath(os.path.join(os.path.dirname(__file__), "..", "..")) +if transformers_dir not in sys.path: + sys.path.append(transformers_dir) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/sam2/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/sam2/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..126ff57f1db83864bebc7ddb6c5ceb14381cb72d Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/sam2/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/sam2/__pycache__/benchmark_sam2.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/sam2/__pycache__/benchmark_sam2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ca45b425dccc050d9f96952ccb160688626458e5 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/sam2/__pycache__/benchmark_sam2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/sam2/__pycache__/convert_to_onnx.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/sam2/__pycache__/convert_to_onnx.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5c4e7ce19504c352ed9496007e563a2cb9a3645a Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/sam2/__pycache__/convert_to_onnx.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/sam2/__pycache__/image_decoder.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/sam2/__pycache__/image_decoder.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fcc30d0e4edcc8dd8c0eeef38d18a27fdaa1f9ef Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/sam2/__pycache__/image_decoder.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/sam2/__pycache__/image_encoder.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/sam2/__pycache__/image_encoder.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f373a2b5497056301d5cf2197f1d40e56443d630 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/sam2/__pycache__/image_encoder.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/sam2/__pycache__/mask_decoder.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/sam2/__pycache__/mask_decoder.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4e66df1b94b8bf9d74cbefcc79ccd9cabaa16189 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/sam2/__pycache__/mask_decoder.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/sam2/__pycache__/nvtx_helper.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/sam2/__pycache__/nvtx_helper.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..257671eb60288b4ec6325e17c5d440c6d2252864 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/sam2/__pycache__/nvtx_helper.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/sam2/__pycache__/prompt_encoder.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/sam2/__pycache__/prompt_encoder.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5594c07ca1b90feae7cebfe07c492f78563d49ed Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/sam2/__pycache__/prompt_encoder.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/sam2/__pycache__/sam2_demo.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/sam2/__pycache__/sam2_demo.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dfae753c9c20ad2cdc8545668ce211446da56517 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/sam2/__pycache__/sam2_demo.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/sam2/__pycache__/sam2_image_onnx_predictor.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/sam2/__pycache__/sam2_image_onnx_predictor.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e29235385cf6c5945e1a4f0af2e16eca7663ae86 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/sam2/__pycache__/sam2_image_onnx_predictor.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/sam2/__pycache__/sam2_utils.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/sam2/__pycache__/sam2_utils.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c8b58474f7f6265cffa0975f439c908c659146ec Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/sam2/__pycache__/sam2_utils.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/sam2/benchmark_sam2.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/sam2/benchmark_sam2.py new file mode 100644 index 0000000000000000000000000000000000000000..99b00dd5bbf61fd40d748feeeb6874509f419ec4 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/sam2/benchmark_sam2.py @@ -0,0 +1,638 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +# -------------------------------------------------------------------------- + +""" +Benchmark performance of SAM2 encoder with ORT or PyTorch. See benchmark_sam2.sh for usage. +""" + +import argparse +import csv +import statistics +import time +from collections.abc import Mapping +from datetime import datetime + +import torch +from image_decoder import SAM2ImageDecoder +from image_encoder import SAM2ImageEncoder +from sam2_utils import decoder_shape_dict, encoder_shape_dict, load_sam2_model + +from onnxruntime import InferenceSession, SessionOptions, get_available_providers +from onnxruntime.transformers.io_binding_helper import CudaSession + + +class TestConfig: + def __init__( + self, + model_type: str, + onnx_path: str, + sam2_dir: str, + device: torch.device, + component: str = "image_encoder", + provider="CPUExecutionProvider", + torch_compile_mode="max-autotune", + batch_size: int = 1, + height: int = 1024, + width: int = 1024, + num_labels: int = 1, + num_points: int = 1, + num_masks: int = 1, + multi_mask_output: bool = False, + use_tf32: bool = True, + enable_cuda_graph: bool = False, + dtype=torch.float32, + prefer_nhwc: bool = False, + warm_up: int = 5, + enable_nvtx_profile: bool = False, + enable_ort_profile: bool = False, + enable_torch_profile: bool = False, + repeats: int = 1000, + verbose: bool = False, + ): + assert model_type in ["sam2_hiera_tiny", "sam2_hiera_small", "sam2_hiera_large", "sam2_hiera_base_plus"] + assert height >= 160 and height <= 4096 + assert width >= 160 and width <= 4096 + + self.model_type = model_type + self.onnx_path = onnx_path + self.sam2_dir = sam2_dir + self.component = component + self.provider = provider + self.torch_compile_mode = torch_compile_mode + self.batch_size = batch_size + self.height = height + self.width = width + self.num_labels = num_labels + self.num_points = num_points + self.num_masks = num_masks + self.multi_mask_output = multi_mask_output + self.device = device + self.use_tf32 = use_tf32 + self.enable_cuda_graph = enable_cuda_graph + self.dtype = dtype + self.prefer_nhwc = prefer_nhwc + self.warm_up = warm_up + self.enable_nvtx_profile = enable_nvtx_profile + self.enable_ort_profile = enable_ort_profile + self.enable_torch_profile = enable_torch_profile + self.repeats = repeats + self.verbose = verbose + + if self.component == "image_encoder": + assert self.height == 1024 and self.width == 1024, "Only image size 1024x1024 is allowed for image encoder." + + def __repr__(self): + return f"{vars(self)}" + + def shape_dict(self) -> Mapping[str, list[int]]: + if self.component == "image_encoder": + return encoder_shape_dict(self.batch_size, self.height, self.width) + else: + return decoder_shape_dict(self.height, self.width, self.num_labels, self.num_points, self.num_masks) + + def random_inputs(self) -> Mapping[str, torch.Tensor]: + dtype = self.dtype + if self.component == "image_encoder": + return {"image": torch.randn(self.batch_size, 3, self.height, self.width, dtype=dtype, device=self.device)} + else: + return { + "image_features_0": torch.rand(1, 32, 256, 256, dtype=dtype, device=self.device), + "image_features_1": torch.rand(1, 64, 128, 128, dtype=dtype, device=self.device), + "image_embeddings": torch.rand(1, 256, 64, 64, dtype=dtype, device=self.device), + "point_coords": torch.randint( + 0, 1024, (self.num_labels, self.num_points, 2), dtype=dtype, device=self.device + ), + "point_labels": torch.randint( + 0, 1, (self.num_labels, self.num_points), dtype=torch.int32, device=self.device + ), + "input_masks": torch.zeros(self.num_labels, 1, 256, 256, dtype=dtype, device=self.device), + "has_input_masks": torch.ones(self.num_labels, dtype=dtype, device=self.device), + "original_image_size": torch.tensor([self.height, self.width], dtype=torch.int32, device=self.device), + } + + +def create_ort_session(config: TestConfig, session_options=None) -> InferenceSession: + if config.verbose: + print(f"create session for {vars(config)}") + + if config.provider == "CUDAExecutionProvider": + device_id = torch.cuda.current_device() if isinstance(config.device, str) else config.device.index + provider_options = CudaSession.get_cuda_provider_options(device_id, config.enable_cuda_graph) + provider_options["use_tf32"] = int(config.use_tf32) + if config.prefer_nhwc: + provider_options["prefer_nhwc"] = 1 + providers = [(config.provider, provider_options), "CPUExecutionProvider"] + else: + providers = ["CPUExecutionProvider"] + + ort_session = InferenceSession(config.onnx_path, session_options, providers=providers) + return ort_session + + +def create_session(config: TestConfig, session_options=None) -> CudaSession: + ort_session = create_ort_session(config, session_options) + cuda_session = CudaSession(ort_session, config.device, config.enable_cuda_graph) + cuda_session.allocate_buffers(config.shape_dict()) + return cuda_session + + +class OrtTestSession: + """A wrapper of ORT session to test relevance and performance.""" + + def __init__(self, config: TestConfig, session_options=None): + self.ort_session = create_session(config, session_options) + self.feed_dict = config.random_inputs() + + def infer(self): + return self.ort_session.infer(self.feed_dict) + + +def measure_latency(cuda_session: CudaSession, input_dict): + start = time.time() + _ = cuda_session.infer(input_dict) + end = time.time() + return end - start + + +def run_torch(config: TestConfig): + device_type = config.device.type + is_cuda = device_type == "cuda" + + # Turn on TF32 for Ampere GPUs which could help when data type is float32. + if is_cuda and torch.cuda.get_device_properties(0).major >= 8 and config.use_tf32: + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + + enabled_auto_cast = is_cuda and config.dtype != torch.float32 + ort_inputs = config.random_inputs() + + with torch.inference_mode(), torch.autocast(device_type=device_type, dtype=config.dtype, enabled=enabled_auto_cast): + sam2_model = load_sam2_model(config.sam2_dir, config.model_type, device=config.device) + if config.component == "image_encoder": + if is_cuda and config.torch_compile_mode != "none": + sam2_model.image_encoder.forward = torch.compile( + sam2_model.image_encoder.forward, + mode=config.torch_compile_mode, # "reduce-overhead" if you want to reduce latency of first run. + fullgraph=True, + dynamic=False, + ) + + image_shape = config.shape_dict()["image"] + img = torch.randn(image_shape).to(device=config.device, dtype=config.dtype) + sam2_encoder = SAM2ImageEncoder(sam2_model) + + if is_cuda and config.torch_compile_mode != "none": + print(f"Running warm up. It will take a while since torch compile mode is {config.torch_compile_mode}.") + + for _ in range(config.warm_up): + _image_features_0, _image_features_1, _image_embeddings = sam2_encoder(img) + + if is_cuda and config.enable_nvtx_profile: + import nvtx # noqa: PLC0415 + from cuda import cudart # noqa: PLC0415 + + cudart.cudaProfilerStart() + print("Start nvtx profiling on encoder ...") + with nvtx.annotate("one_run"): + sam2_encoder(img, enable_nvtx_profile=True) + cudart.cudaProfilerStop() + + if is_cuda and config.enable_torch_profile: + with torch.profiler.profile( + activities=[torch.profiler.ProfilerActivity.CPU, torch.profiler.ProfilerActivity.CUDA], + record_shapes=True, + ) as prof: + print("Start torch profiling on encoder ...") + with torch.profiler.record_function("encoder"): + sam2_encoder(img) + print(prof.key_averages().table(sort_by="cuda_time_total", row_limit=10)) + prof.export_chrome_trace("torch_image_encoder.json") + + if config.repeats == 0: + return + + print(f"Start {config.repeats} runs of performance tests...") + start = time.time() + for _ in range(config.repeats): + _image_features_0, _image_features_1, _image_embeddings = sam2_encoder(img) + if is_cuda: + torch.cuda.synchronize() + else: + torch_inputs = ( + ort_inputs["image_features_0"], + ort_inputs["image_features_1"], + ort_inputs["image_embeddings"], + ort_inputs["point_coords"], + ort_inputs["point_labels"], + ort_inputs["input_masks"], + ort_inputs["has_input_masks"], + ort_inputs["original_image_size"], + ) + + sam2_decoder = SAM2ImageDecoder( + sam2_model, + multimask_output=config.multi_mask_output, + ) + + if is_cuda and config.torch_compile_mode != "none": + sam2_decoder.forward = torch.compile( + sam2_decoder.forward, + mode=config.torch_compile_mode, + fullgraph=True, + dynamic=False, + ) + + # warm up + for _ in range(config.warm_up): + _masks, _iou_predictions, _low_res_masks = sam2_decoder(*torch_inputs) + + if is_cuda and config.enable_nvtx_profile: + import nvtx # noqa: PLC0415 + from cuda import cudart # noqa: PLC0415 + + cudart.cudaProfilerStart() + print("Start nvtx profiling on decoder...") + with nvtx.annotate("one_run"): + sam2_decoder(*torch_inputs, enable_nvtx_profile=True) + cudart.cudaProfilerStop() + + if is_cuda and config.enable_torch_profile: + with torch.profiler.profile( + activities=[torch.profiler.ProfilerActivity.CPU, torch.profiler.ProfilerActivity.CUDA], + record_shapes=True, + ) as prof: + print("Start torch profiling on decoder ...") + with torch.profiler.record_function("decoder"): + sam2_decoder(*torch_inputs) + print(prof.key_averages().table(sort_by="cuda_time_total", row_limit=10)) + prof.export_chrome_trace("torch_image_decoder.json") + + if config.repeats == 0: + return + + print(f"Start {config.repeats} runs of performance tests...") + start = time.time() + for _ in range(config.repeats): + _masks, _iou_predictions, _low_res_masks = sam2_decoder(*torch_inputs) + if is_cuda: + torch.cuda.synchronize() + + end = time.time() + return (end - start) / config.repeats + + +def run_test( + args: argparse.Namespace, + csv_writer: csv.DictWriter | None = None, +): + use_gpu: bool = args.use_gpu + enable_cuda_graph: bool = args.use_cuda_graph + repeats: int = args.repeats + + if use_gpu: + device_id = torch.cuda.current_device() + device = torch.device("cuda", device_id) + provider = "CUDAExecutionProvider" + else: + device_id = 0 + device = torch.device("cpu") + enable_cuda_graph = False + provider = "CPUExecutionProvider" + + dtypes = {"fp32": torch.float32, "fp16": torch.float16, "bf16": torch.bfloat16} + config = TestConfig( + model_type=args.model_type, + onnx_path=args.onnx_path, + sam2_dir=args.sam2_dir, + component=args.component, + provider=provider, + batch_size=args.batch_size, + height=args.height, + width=args.width, + device=device, + use_tf32=True, + enable_cuda_graph=enable_cuda_graph, + dtype=dtypes[args.dtype], + prefer_nhwc=args.prefer_nhwc, + repeats=args.repeats, + warm_up=args.warm_up, + enable_nvtx_profile=args.enable_nvtx_profile, + enable_ort_profile=args.enable_ort_profile, + enable_torch_profile=args.enable_torch_profile, + torch_compile_mode=args.torch_compile_mode, + verbose=False, + ) + + if args.engine == "ort": + sess_options = SessionOptions() + sess_options.intra_op_num_threads = args.intra_op_num_threads + if config.enable_ort_profile: + sess_options.enable_profiling = True + sess_options.log_severity_level = 4 + sess_options.log_verbosity_level = 0 + + session = create_session(config, sess_options) + input_dict = config.random_inputs() + + # warm up session + try: + for _ in range(config.warm_up): + _ = measure_latency(session, input_dict) + except Exception as e: + print(f"Failed to run {config=}. Exception: {e}") + return + + if config.enable_nvtx_profile: + import nvtx # noqa: PLC0415 + from cuda import cudart # noqa: PLC0415 + + cudart.cudaProfilerStart() + with nvtx.annotate("one_run"): + _ = session.infer(input_dict) + cudart.cudaProfilerStop() + + if config.enable_ort_profile: + session.ort_session.end_profiling() + + if repeats == 0: + return + + latency_list = [] + for _ in range(repeats): + latency = measure_latency(session, input_dict) + latency_list.append(latency) + average_latency = statistics.mean(latency_list) + + del session + else: # torch + with torch.no_grad(): + try: + average_latency = run_torch(config) + except Exception as e: + print(f"Failed to run {config=}. Exception: {e}") + return + + if repeats == 0: + return + + engine = args.engine + ":" + ("cuda" if use_gpu else "cpu") + row = { + "model_type": args.model_type, + "component": args.component, + "dtype": args.dtype, + "use_gpu": use_gpu, + "enable_cuda_graph": enable_cuda_graph, + "prefer_nhwc": config.prefer_nhwc, + "use_tf32": config.use_tf32, + "batch_size": args.batch_size, + "height": args.height, + "width": args.width, + "multi_mask_output": args.multimask_output, + "num_labels": config.num_labels, + "num_points": config.num_points, + "num_masks": config.num_masks, + "intra_op_num_threads": args.intra_op_num_threads, + "warm_up": config.warm_up, + "repeats": repeats, + "enable_nvtx_profile": args.enable_nvtx_profile, + "torch_compile_mode": args.torch_compile_mode, + "engine": engine, + "average_latency": average_latency, + } + + if csv_writer is not None: + csv_writer.writerow(row) + + print(f"{vars(config)}") + print(f"{row}") + + +def run_perf_test(args): + features = "gpu" if args.use_gpu else "cpu" + csv_filename = "benchmark_sam_{}_{}_{}.csv".format( + features, + args.engine, + datetime.now().strftime("%Y%m%d-%H%M%S"), + ) + with open(csv_filename, mode="a", newline="") as csv_file: + column_names = [ + "model_type", + "component", + "dtype", + "use_gpu", + "enable_cuda_graph", + "prefer_nhwc", + "use_tf32", + "batch_size", + "height", + "width", + "multi_mask_output", + "num_labels", + "num_points", + "num_masks", + "intra_op_num_threads", + "warm_up", + "repeats", + "enable_nvtx_profile", + "torch_compile_mode", + "engine", + "average_latency", + ] + csv_writer = csv.DictWriter(csv_file, fieldnames=column_names) + csv_writer.writeheader() + + run_test(args, csv_writer) + + +def _parse_arguments(): + parser = argparse.ArgumentParser(description="Benchmark SMA2 for ONNX Runtime and PyTorch.") + + parser.add_argument( + "--component", + required=False, + choices=["image_encoder", "image_decoder"], + default="image_encoder", + help="component to benchmark. Choices are image_encoder and image_decoder.", + ) + + parser.add_argument( + "--dtype", required=False, choices=["fp32", "fp16", "bf16"], default="fp32", help="Data type for inference." + ) + + parser.add_argument( + "--use_gpu", + required=False, + action="store_true", + help="Use GPU for inference.", + ) + parser.set_defaults(use_gpu=False) + + parser.add_argument( + "--use_cuda_graph", + required=False, + action="store_true", + help="Use cuda graph in onnxruntime.", + ) + parser.set_defaults(use_cuda_graph=False) + + parser.add_argument( + "--intra_op_num_threads", + required=False, + type=int, + choices=[0, 1, 2, 4, 8, 16], + default=0, + help="intra_op_num_threads for onnxruntime. ", + ) + + parser.add_argument( + "--batch_size", + required=False, + type=int, + default=1, + help="batch size", + ) + + parser.add_argument( + "--height", + required=False, + type=int, + default=1024, + help="image height", + ) + + parser.add_argument( + "--width", + required=False, + type=int, + default=1024, + help="image width", + ) + + parser.add_argument( + "--repeats", + required=False, + type=int, + default=1000, + help="number of repeats for performance test. Default is 1000.", + ) + + parser.add_argument( + "--warm_up", + required=False, + type=int, + default=5, + help="number of runs for warm up. Default is 5.", + ) + + parser.add_argument( + "--engine", + required=False, + type=str, + default="ort", + choices=["ort", "torch"], + help="engine for inference", + ) + + parser.add_argument( + "--multimask_output", + required=False, + default=False, + action="store_true", + help="Export mask_decoder or image_decoder with multimask_output", + ) + + parser.add_argument( + "--prefer_nhwc", + required=False, + default=False, + action="store_true", + help="Use prefer_nhwc=1 provider option for CUDAExecutionProvider", + ) + + parser.add_argument( + "--enable_nvtx_profile", + required=False, + default=False, + action="store_true", + help="Enable nvtx profiling. It will add an extra run for profiling before performance test.", + ) + + parser.add_argument( + "--enable_ort_profile", + required=False, + default=False, + action="store_true", + help="Enable ORT profiling.", + ) + + parser.add_argument( + "--enable_torch_profile", + required=False, + default=False, + action="store_true", + help="Enable PyTorch profiling. It will add an extra run for profiling before performance test.", + ) + + parser.add_argument( + "--model_type", + required=False, + type=str, + default="sam2_hiera_large", + choices=["sam2_hiera_tiny", "sam2_hiera_small", "sam2_hiera_large", "sam2_hiera_base_plus"], + help="sam2 model name", + ) + + parser.add_argument( + "--sam2_dir", + required=False, + type=str, + default="./segment-anything-2", + help="The directory of segment-anything-2 git root directory", + ) + + parser.add_argument( + "--onnx_path", + required=False, + type=str, + default="./sam2_onnx_models/sam2_hiera_large_image_encoder.onnx", + help="path of onnx model", + ) + + parser.add_argument( + "--torch_compile_mode", + required=False, + type=str, + default=None, + choices=["reduce-overhead", "max-autotune", "max-autotune-no-cudagraphs", "none"], + help="torch compile mode. none will disable torch compile.", + ) + + args = parser.parse_args() + + return args + + +if __name__ == "__main__": + args = _parse_arguments() + print(f"arguments:{args}") + + if args.torch_compile_mode is None: + # image decoder will fail with compile modes other than "none". + args.torch_compile_mode = "max-autotune" if args.component == "image_encoder" else "none" + + if args.use_gpu: + assert torch.cuda.is_available() + if args.engine == "ort": + assert "CUDAExecutionProvider" in get_available_providers() + args.enable_torch_profile = False + else: + # Only support cuda profiling for now. + assert not args.enable_nvtx_profile + assert not args.enable_torch_profile + + if args.enable_nvtx_profile or args.enable_torch_profile: + run_test(args) + else: + run_perf_test(args) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/sam2/convert_to_onnx.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/sam2/convert_to_onnx.py new file mode 100644 index 0000000000000000000000000000000000000000..bca091ae91a7599691f63498d6b517f1fc8d6376 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/sam2/convert_to_onnx.py @@ -0,0 +1,270 @@ +# ------------------------------------------------------------------------- +# Copyright (R) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +# -------------------------------------------------------------------------- +import argparse +import os +import pathlib +import sys + +import torch +from image_decoder import export_decoder_onnx, test_decoder_onnx +from image_encoder import export_image_encoder_onnx, test_image_encoder_onnx +from mask_decoder import export_mask_decoder_onnx, test_mask_decoder_onnx +from prompt_encoder import export_prompt_encoder_onnx, test_prompt_encoder_onnx +from sam2_demo import run_demo, show_all_images +from sam2_utils import load_sam2_model, sam2_onnx_path, setup_logger + + +def parse_arguments(): + parser = argparse.ArgumentParser(description="Export SAM2 models to ONNX") + + parser.add_argument( + "--model_type", + required=False, + type=str, + choices=["sam2_hiera_tiny", "sam2_hiera_small", "sam2_hiera_large", "sam2_hiera_base_plus"], + default="sam2_hiera_large", + help="The model type to export", + ) + + parser.add_argument( + "--components", + required=False, + nargs="+", + choices=["image_encoder", "mask_decoder", "prompt_encoder", "image_decoder"], + default=["image_encoder", "image_decoder"], + help="Type of ONNX models to export. " + "Note that image_decoder is a combination of prompt_encoder and mask_decoder", + ) + + parser.add_argument( + "--output_dir", + type=str, + help="The output directory for the ONNX models", + default="sam2_onnx_models", + ) + + parser.add_argument( + "--dynamic_batch_axes", + required=False, + default=False, + action="store_true", + help="Export image_encoder with dynamic batch axes", + ) + + parser.add_argument( + "--multimask_output", + required=False, + default=False, + action="store_true", + help="Export mask_decoder or image_decoder with multimask_output", + ) + + parser.add_argument( + "--disable_dynamic_multimask_via_stability", + required=False, + action="store_true", + help="Disable mask_decoder dynamic_multimask_via_stability, and output first mask only." + "This option will be ignored when multimask_output is True", + ) + + parser.add_argument( + "--sam2_dir", + required=False, + type=str, + default="./segment-anything-2", + help="The directory of segment-anything-2 git repository", + ) + + parser.add_argument( + "--overwrite", + required=False, + default=False, + action="store_true", + help="Overwrite onnx model file if exists.", + ) + + parser.add_argument( + "--demo", + required=False, + default=False, + action="store_true", + help="Run demo with the exported ONNX models.", + ) + + parser.add_argument( + "--optimize", + required=False, + default=False, + action="store_true", + help="Optimize onnx models", + ) + + parser.add_argument( + "--dtype", required=False, choices=["fp32", "fp16"], default="fp32", help="Data type for inference." + ) + + parser.add_argument( + "--use_gpu", + required=False, + default=False, + action="store_true", + help="Optimize onnx models for GPU", + ) + + parser.add_argument( + "--dynamo", + required=False, + default=False, + action="store_true", + help="Use dynamo for exporting onnx model. Only image_encoder supports dynamo right now.", + ) + + parser.add_argument( + "--verbose", + required=False, + default=False, + action="store_true", + help="Print verbose information", + ) + + args = parser.parse_args() + return args + + +def optimize_sam2_model(onnx_model_path, optimized_model_path, float16: bool, use_gpu: bool): + print(f"Optimizing {onnx_model_path} to {optimized_model_path} with float16={float16} and use_gpu={use_gpu}...") + + # Import from source directory. + transformers_dir = os.path.normpath(os.path.join(os.path.dirname(__file__), "..", "..")) + if transformers_dir not in sys.path: + sys.path.insert(0, transformers_dir) + from optimizer import optimize_model # noqa: PLC0415 + + optimized_model = optimize_model(onnx_model_path, model_type="sam2", opt_level=1, use_gpu=use_gpu) + if float16: + optimized_model.convert_float_to_float16(keep_io_types=False) + optimized_model.save_model_to_file(optimized_model_path) + + +def main(): + args = parse_arguments() + + sam2_model = load_sam2_model(args.sam2_dir, args.model_type, device="cpu") + + pathlib.Path(args.output_dir).mkdir(parents=True, exist_ok=True) + + for component in args.components: + onnx_model_path = sam2_onnx_path(args.output_dir, args.model_type, component, args.multimask_output) + if component == "image_encoder": + if args.overwrite or not os.path.exists(onnx_model_path): + export_image_encoder_onnx( + sam2_model, onnx_model_path, args.dynamic_batch_axes, args.verbose, args.dynamo + ) + test_image_encoder_onnx(sam2_model, onnx_model_path, dynamic_batch_axes=args.dynamic_batch_axes) + + elif component == "mask_decoder": + if args.overwrite or not os.path.exists(onnx_model_path): + export_mask_decoder_onnx( + sam2_model, + onnx_model_path, + args.multimask_output, + not args.disable_dynamic_multimask_via_stability, + args.verbose, + ) + test_mask_decoder_onnx( + sam2_model, + onnx_model_path, + args.multimask_output, + not args.disable_dynamic_multimask_via_stability, + ) + elif component == "prompt_encoder": + if args.overwrite or not os.path.exists(onnx_model_path): + export_prompt_encoder_onnx(sam2_model, onnx_model_path) + test_prompt_encoder_onnx(sam2_model, onnx_model_path) + else: + assert component == "image_decoder" + if args.overwrite or not os.path.exists(onnx_model_path): + export_decoder_onnx(sam2_model, onnx_model_path, args.multimask_output) + test_decoder_onnx(sam2_model, onnx_model_path, args.multimask_output) + + suffix = "" + convert_to_fp16 = args.dtype == "fp16" + if args.optimize: + suffix = f"_{args.dtype}_" + ("gpu" if args.use_gpu else "cpu") + for component in args.components: + onnx_model_path = sam2_onnx_path(args.output_dir, args.model_type, component, args.multimask_output) + optimized_model_path = sam2_onnx_path( + args.output_dir, args.model_type, component, args.multimask_output, suffix + ) + optimize_sam2_model(onnx_model_path, optimized_model_path, convert_to_fp16, args.use_gpu) + + if args.demo: + # Export required ONNX models for demo if not already exported. + image_encoder_onnx_path = sam2_onnx_path( + args.output_dir, args.model_type, "image_encoder", args.multimask_output + ) + if not os.path.exists(image_encoder_onnx_path): + export_image_encoder_onnx(sam2_model, image_encoder_onnx_path, args.dynamic_batch_axes, args.verbose) + + image_decoder_onnx_path = sam2_onnx_path(args.output_dir, args.model_type, "image_decoder", False) + if not os.path.exists(image_decoder_onnx_path): + export_decoder_onnx(sam2_model, image_decoder_onnx_path, False) + + image_decoder_multi_onnx_path = sam2_onnx_path(args.output_dir, args.model_type, "image_decoder", True) + if not os.path.exists(image_decoder_multi_onnx_path): + export_decoder_onnx(sam2_model, image_decoder_multi_onnx_path, True) + + dtype = torch.float32 if args.dtype == "fp32" else torch.float16 + if suffix: + optimized_image_encoder_onnx_path = image_encoder_onnx_path.replace(".onnx", f"{suffix}.onnx") + if not os.path.exists(optimized_image_encoder_onnx_path): + optimize_sam2_model( + image_encoder_onnx_path, optimized_image_encoder_onnx_path, convert_to_fp16, args.use_gpu + ) + + optimized_image_decoder_onnx_path = image_decoder_onnx_path.replace(".onnx", f"{suffix}.onnx") + if not os.path.exists(optimized_image_decoder_onnx_path): + optimize_sam2_model( + image_decoder_onnx_path, optimized_image_decoder_onnx_path, convert_to_fp16, args.use_gpu + ) + + optimized_image_decoder_multi_onnx_path = image_decoder_multi_onnx_path.replace(".onnx", f"{suffix}.onnx") + if not os.path.exists(optimized_image_decoder_multi_onnx_path): + optimize_sam2_model( + image_decoder_multi_onnx_path, + optimized_image_decoder_multi_onnx_path, + convert_to_fp16, + args.use_gpu, + ) + + # Use optimized models to run demo. + image_encoder_onnx_path = optimized_image_encoder_onnx_path + image_decoder_onnx_path = optimized_image_decoder_onnx_path + image_decoder_multi_onnx_path = optimized_image_decoder_multi_onnx_path + + ort_image_files = run_demo( + args.sam2_dir, + args.model_type, + engine="ort", + dtype=dtype, + image_encoder_onnx_path=image_encoder_onnx_path, + image_decoder_onnx_path=image_decoder_onnx_path, + image_decoder_multi_onnx_path=image_decoder_multi_onnx_path, + use_gpu=args.use_gpu, + ) + print("demo output files for ONNX Runtime:", ort_image_files) + + # Get results from torch engine to compare. + torch_image_files = run_demo(args.sam2_dir, args.model_type, engine="torch", dtype=dtype, use_gpu=args.use_gpu) + print("demo output files for PyTorch:", torch_image_files) + + show_all_images(ort_image_files, torch_image_files, suffix) + print(f"Combined demo output: sam2_demo{suffix}.png") + + +if __name__ == "__main__": + setup_logger(verbose=False) + with torch.no_grad(): + main() diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/sam2/image_decoder.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/sam2/image_decoder.py new file mode 100644 index 0000000000000000000000000000000000000000..b5e0ceea90e87b7fdd36d9b2f55b390f5d5347fc --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/sam2/image_decoder.py @@ -0,0 +1,272 @@ +# ------------------------------------------------------------------------- +# Copyright (R) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +# -------------------------------------------------------------------------- +import logging +import warnings + +import torch +import torch.nn.functional as F +from image_encoder import SAM2ImageEncoder, random_sam2_input_image +from mask_decoder import SAM2MaskDecoder +from prompt_encoder import SAM2PromptEncoder +from sam2.modeling.sam2_base import SAM2Base +from sam2_utils import compare_tensors_with_tolerance +from torch import nn + +logger = logging.getLogger(__name__) + + +class SAM2ImageDecoder(nn.Module): + def __init__( + self, + sam_model: SAM2Base, + multimask_output: bool, + dynamic_multimask_via_stability: bool = True, + return_logits: bool = False, + mask_threshold: float = 0.0, + ) -> None: + super().__init__() + self.prompt_encoder = SAM2PromptEncoder(sam_model) + self.mask_decoder = SAM2MaskDecoder(sam_model, multimask_output, dynamic_multimask_via_stability) + self.return_logits = return_logits + self.mask_threshold = mask_threshold + + @torch.no_grad() + def forward( + self, + image_features_0: torch.Tensor, + image_features_1: torch.Tensor, + image_embeddings: torch.Tensor, + point_coords: torch.Tensor, + point_labels: torch.Tensor, + input_masks: torch.Tensor, + has_input_masks: torch.Tensor, + original_image_size: torch.Tensor, + enable_nvtx_profile: bool = False, + ): + """ + Decode masks from image features and prompts. Batched images are not supported. H=W=1024. + + Args: + image_features_0 (torch.Tensor): [1, 32, H/4, W/4]. high resolution features of level 0 from image encoder. + image_features_1 (torch.Tensor): [1, 64, H/8, W/8]. high resolution features of level 1 from image encoder. + image_embeddings (torch.Tensor): [1, 256, H/16, W/16]. image embedding from image encoder. + point_coords (torch.Tensor): [L, P, 2] shape and float32 dtype and contains the absolute pixel + coordinate in (x, y) format of the P input points in image of size 1024x1024. + point_labels (torch.Tensor): shape [L, P] and int32 dtype, where 1 means + positive (foreground), 0 means negative (background), -1 means padding, + 2 (box left upper corner), 3 (box right bottom corner). + input_masks (torch.Tensor): [L, 1, H/4, W/4]. Low resolution mask input to the model. + Typically coming from a previous iteration. + has_input_masks (torch.Tensor): [L]. 1.0 if input_masks is used, 0.0 otherwise. + original_image_size(torch.Tensor): [2]. original image size H_o, W_o. + enable_nvtx_profile (bool): enable NVTX profiling. + + Returns: + masks (torch.Tensor): [1, M, H_o, W_o] where M=3 or 1. Masks of original image size. + iou_predictions (torch.Tensor): [1, M]. scores for M masks. + low_res_masks (torch.Tensor, optional): [1, M, H/4, W/4]. low resolution masks. + """ + nvtx_helper = None + if enable_nvtx_profile: + from nvtx_helper import NvtxHelper # noqa: PLC0415 + + nvtx_helper = NvtxHelper(["prompt_encoder", "mask_decoder", "post_process"]) + + if nvtx_helper is not None: + nvtx_helper.start_profile("prompt_encoder", color="blue") + + sparse_embeddings, dense_embeddings, image_pe = self.prompt_encoder( + point_coords, point_labels, input_masks, has_input_masks + ) + + if nvtx_helper is not None: + nvtx_helper.stop_profile("prompt_encoder") + nvtx_helper.start_profile("mask_decoder", color="red") + + low_res_masks, iou_predictions = self.mask_decoder( + image_features_0, image_features_1, image_embeddings, image_pe, sparse_embeddings, dense_embeddings + ) + + if nvtx_helper is not None: + nvtx_helper.stop_profile("mask_decoder") + nvtx_helper.start_profile("post_process", color="green") + + # Interpolate the low resolution masks back to the original image size. + masks = F.interpolate( + low_res_masks, + (original_image_size[0], original_image_size[1]), + mode="bilinear", + align_corners=False, # Note that align_corners=True has less mismatches during comparing ORT and PyTorch. + ) + + low_res_masks = torch.clamp(low_res_masks, -32.0, 32.0) + if not self.return_logits: + masks = masks > self.mask_threshold + + if nvtx_helper is not None: + nvtx_helper.stop_profile("post_process") + nvtx_helper.print_latency() + + return masks, iou_predictions, low_res_masks + + +def export_decoder_onnx( + sam2_model: SAM2Base, + onnx_model_path: str, + multimask_output: bool = False, + verbose: bool = False, +): + batch_size = 1 + image = random_sam2_input_image(batch_size) + sam2_encoder = SAM2ImageEncoder(sam2_model).cpu() + image_features_0, image_features_1, image_embeddings = sam2_encoder(image) + + logger.info("image_features_0.shape: %s", image_features_0.shape) + logger.info("image_features_1.shape: %s", image_features_1.shape) + logger.info("image_embeddings.shape: %s", image_embeddings.shape) + + sam2_decoder = SAM2ImageDecoder( + sam2_model, + multimask_output=multimask_output, + dynamic_multimask_via_stability=True, + ).cpu() + + num_labels = 2 + num_points = 3 + point_coords = torch.randint(low=0, high=1024, size=(num_labels, num_points, 2), dtype=torch.float) + point_labels = torch.randint(low=0, high=1, size=(num_labels, num_points), dtype=torch.int32) + input_masks = torch.zeros(num_labels, 1, 256, 256, dtype=torch.float) + has_input_masks = torch.ones(1, dtype=torch.float) + original_image_size = torch.tensor([1200, 1800], dtype=torch.int32) + + example_inputs = ( + image_features_0, + image_features_1, + image_embeddings, + point_coords, + point_labels, + input_masks, + has_input_masks, + original_image_size, + ) + + logger.info("point_coords.shape: %s", point_coords.shape) + logger.info("point_labels.shape: %s", point_labels.shape) + logger.info("input_masks.shape: %s", input_masks.shape) + logger.info("has_input_masks.shape: %s", has_input_masks.shape) + logger.info("original_image_size.shape: %s", original_image_size.shape) + + if verbose: + masks, iou_predictions, low_res_masks = sam2_decoder(*example_inputs) + logger.info("masks.shape: %s", masks.shape) + logger.info("iou_predictions.shape: %s", iou_predictions.shape) + logger.info("low_res_masks.shape: %s", low_res_masks.shape) + + input_names = [ + "image_features_0", + "image_features_1", + "image_embeddings", + "point_coords", + "point_labels", + "input_masks", + "has_input_masks", + "original_image_size", + ] + + output_names = ["masks", "iou_predictions", "low_res_masks"] + + dynamic_axes = { + "point_coords": {0: "num_labels", 1: "num_points"}, + "point_labels": {0: "num_labels", 1: "num_points"}, + "input_masks": {0: "num_labels"}, + "has_input_masks": {0: "num_labels"}, + "masks": {0: "num_labels", 2: "original_image_height", 3: "original_image_width"}, + "low_res_masks": {0: "num_labels"}, + "iou_predictions": {0: "num_labels"}, + } + + with warnings.catch_warnings(): + if not verbose: + warnings.filterwarnings("ignore", category=torch.jit.TracerWarning) + warnings.filterwarnings("ignore", category=UserWarning) + + torch.onnx.export( + sam2_decoder, + example_inputs, + onnx_model_path, + export_params=True, + opset_version=16, + do_constant_folding=True, + input_names=input_names, + output_names=output_names, + dynamic_axes=dynamic_axes, + ) + + logger.info("decoder onnx model saved to %s", onnx_model_path) + + +def test_decoder_onnx( + sam2_model: SAM2Base, + onnx_model_path: str, + multimask_output=False, +): + batch_size = 1 + image = random_sam2_input_image(batch_size) + sam2_encoder = SAM2ImageEncoder(sam2_model).cpu() + image_features_0, image_features_1, image_embeddings = sam2_encoder(image) + + sam2_image_decoder = SAM2ImageDecoder( + sam2_model, + multimask_output=multimask_output, + dynamic_multimask_via_stability=True, + ).cpu() + + num_labels = 1 + num_points = 5 + point_coords = torch.randint(low=0, high=1024, size=(num_labels, num_points, 2), dtype=torch.float) + point_labels = torch.randint(low=0, high=1, size=(num_labels, num_points), dtype=torch.int32) + input_masks = torch.zeros(num_labels, 1, 256, 256, dtype=torch.float) + has_input_masks = torch.zeros(1, dtype=torch.float) + original_image_size = torch.tensor([1500, 1500], dtype=torch.int32) + + example_inputs = ( + image_features_0, + image_features_1, + image_embeddings, + point_coords, + point_labels, + input_masks, + has_input_masks, + original_image_size, + ) + + masks, iou_predictions, low_res_masks = sam2_image_decoder(*example_inputs) + + import onnxruntime # noqa: PLC0415 + + ort_session = onnxruntime.InferenceSession(onnx_model_path, providers=["CPUExecutionProvider"]) + + model_inputs = ort_session.get_inputs() + input_names = [model_inputs[i].name for i in range(len(model_inputs))] + logger.info("input_names: %s", input_names) + + model_outputs = ort_session.get_outputs() + output_names = [model_outputs[i].name for i in range(len(model_outputs))] + logger.info("output_names: %s", output_names) + inputs = {model_inputs[i].name: example_inputs[i].numpy() for i in range(len(model_inputs))} + outputs = ort_session.run(output_names, inputs) + + for i, output_name in enumerate(output_names): + logger.info(f"{output_name}.shape: %s", outputs[i].shape) + + ort_masks, ort_iou_predictions, ort_low_res_masks = outputs + if ( + compare_tensors_with_tolerance("masks", masks.float(), torch.tensor(ort_masks).float()) + and compare_tensors_with_tolerance("iou_predictions", iou_predictions, torch.tensor(ort_iou_predictions)) + and compare_tensors_with_tolerance("low_res_masks", low_res_masks, torch.tensor(ort_low_res_masks)) + ): + print("onnx model has been verified:", onnx_model_path) + else: + print("onnx model verification failed:", onnx_model_path) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/sam2/image_encoder.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/sam2/image_encoder.py new file mode 100644 index 0000000000000000000000000000000000000000..7dc9226fbcc4a9945d59e4bf60046e21c055587a --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/sam2/image_encoder.py @@ -0,0 +1,236 @@ +# ------------------------------------------------------------------------- +# Copyright (R) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +# -------------------------------------------------------------------------- +import logging +import warnings + +import torch +from sam2.modeling.sam2_base import SAM2Base +from sam2_utils import compare_tensors_with_tolerance, random_sam2_input_image +from torch import nn + +import onnxruntime + +logger = logging.getLogger(__name__) + + +class SAM2ImageEncoder(nn.Module): + def __init__(self, sam_model: SAM2Base) -> None: + super().__init__() + self.model = sam_model + self.image_encoder = sam_model.image_encoder + self.no_mem_embed = sam_model.no_mem_embed + + def forward( + self, + image: torch.Tensor, + enable_nvtx_profile: bool = False, + ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """ + Encodes images into features. + + Only supports H=W=1024. If you want to use different image sizes like 512x512, + see https://github.com/facebookresearch/segment-anything-2/issues/138. + + Args: + image (torch.Tensor): images of shape [B, 3, H, W], B is batch size, H and W are height and width. + enable_nvtx_profile (bool): enable NVTX profiling. + + Returns: + image_features_0: image features of shape [B, 32, H/4, W/4] - high resolution features of level 0 + image_features_1: image features of shape [B, 64, H/8, W/8] - high resolution features of level 1 + image_embeddings: image features of shape [B, 256, H/16, W/16] - 16 is the backbone_stride + """ + nvtx_helper = None + if enable_nvtx_profile: + from nvtx_helper import NvtxHelper # noqa: PLC0415 + + nvtx_helper = NvtxHelper(["image_encoder", "post_process"]) + + if nvtx_helper is not None: + nvtx_helper.start_profile("image_encoder") + + backbone_out = self.image_encoder(image) + + if nvtx_helper is not None: + nvtx_helper.stop_profile("image_encoder") + nvtx_helper.start_profile("post_process") + + # precompute projected level 0 and level 1 features in SAM decoder + # to avoid running it again on every SAM click + backbone_out["backbone_fpn"][0] = self.model.sam_mask_decoder.conv_s0(backbone_out["backbone_fpn"][0]) + backbone_out["backbone_fpn"][1] = self.model.sam_mask_decoder.conv_s1(backbone_out["backbone_fpn"][1]) + + # Prepare and flatten visual features. + feature_maps = backbone_out["backbone_fpn"][-self.model.num_feature_levels :] + vision_pos_embeds = backbone_out["vision_pos_enc"][-self.model.num_feature_levels :] + feat_sizes = [(x.shape[-2], x.shape[-1]) for x in vision_pos_embeds] + + # flatten NxCxHxW to HWxNxC + # TODO: we should avoid this transpose since it will be transposed back to NCHW later. + vision_feats = [x.flatten(2).permute(2, 0, 1) for x in feature_maps] + + vision_feats[-1] = vision_feats[-1] + self.no_mem_embed + + feats = [ + feat.permute(1, 2, 0).reshape(1, -1, *feat_size) + for feat, feat_size in zip(vision_feats[::-1], feat_sizes[::-1], strict=False) + ][::-1] + + if nvtx_helper is not None: + nvtx_helper.stop_profile("post_process") + nvtx_helper.print_latency() + + return feats[0], feats[1], feats[2] + + +def export_image_encoder_onnx( + sam2_model: SAM2Base, + onnx_model_path: str, + dynamic_batch_axes: bool = False, + verbose: bool = False, + dynamo: bool = False, + clear_dynamo_metadata: bool = False, +): + image = random_sam2_input_image() + + sam2_encoder = SAM2ImageEncoder(sam2_model).cpu() + image_features_0, image_features_1, image_embeddings = sam2_encoder(image) + logger.info("image.shape: %s", image.shape) + logger.info("image_features_0.shape: %s", image_features_0.shape) + logger.info("image_features_1.shape: %s", image_features_1.shape) + logger.info("image_embeddings.shape: %s", image_embeddings.shape) + + dynamic_axes = None + if dynamic_batch_axes: + dynamic_axes = { + "image": {0: "batch_size"}, + "image_features_0": {0: "batch_size"}, + "image_features_1": {0: "batch_size"}, + "image_embeddings": {0: "batch_size"}, + } + + with warnings.catch_warnings(): + if not verbose: + warnings.filterwarnings("ignore", category=torch.jit.TracerWarning) + warnings.filterwarnings("ignore", category=UserWarning) + + if not dynamo: + torch.onnx.export( + sam2_encoder, + image, + onnx_model_path, + export_params=True, + opset_version=17, + do_constant_folding=True, + input_names=["image"], + output_names=["image_features_0", "image_features_1", "image_embeddings"], + dynamic_axes=dynamic_axes, + ) + else: + torch._dynamo.config.capture_scalar_outputs = True + ep = torch.export.export( + sam2_encoder, + args=(image,), + strict=False, + dynamic_shapes=[ + {0: torch.export.Dim.AUTO}, + ], + ) + + onnx_program = torch.onnx.export( + ep, + (), + opset_version=17, + input_names=["image"], + output_names=["image_features_0", "image_features_1", "image_embeddings"], + dynamo=True, + ) + onnx_program.optimize() + onnx_program.save(onnx_model_path + ".dynamo.onnx", external_data=False) + import onnx # noqa: PLC0415 + + from onnxruntime.transformers.dynamo_onnx_helper import DynamoOnnxHelper # noqa: PLC0415 + + onnx_model = onnx.load_model(onnx_model_path + ".dynamo.onnx", load_external_data=True) + if dynamic_batch_axes: + # Fix labels of dynamic axes since they can't be specified during Dynamo export currently + onnx_model.graph.input[0].type.tensor_type.shape.dim[0].dim_param = "batch_size" + for i in range(3): + onnx_model.graph.output[i].type.tensor_type.shape.dim[0].dim_param = "batch_size" + + onnx_model_helper = DynamoOnnxHelper(onnx_model) + onnx_model_helper.convert_constants_to_initializers() + if clear_dynamo_metadata: + onnx_model_helper.clear_metadata() + + import os # noqa: PLC0415 + + if os.path.exists(onnx_model_path): + os.remove(onnx_model_path) + if os.path.exists(onnx_model_path + ".data"): + os.remove(onnx_model_path + ".data") + onnx_model_helper.model.save_model_to_file( + onnx_model_path, use_external_data_format=True, all_tensors_to_one_file=True, convert_attribute=True + ) + + print("encoder onnx model saved to", onnx_model_path) + + +def test_image_encoder_onnx( + sam2_model: SAM2Base, + onnx_model_path: str, + dynamic_batch_axes=False, +): + ort_session = onnxruntime.InferenceSession(onnx_model_path, providers=["CPUExecutionProvider"]) + + model_inputs = ort_session.get_inputs() + input_names = [model_inputs[i].name for i in range(len(model_inputs))] + logger.info("input_names: %s", input_names) + + model_outputs = ort_session.get_outputs() + output_names = [model_outputs[i].name for i in range(len(model_outputs))] + logger.info("output_names: %s", output_names) + + batch_sizes = [1, 2] if dynamic_batch_axes else [1] + for batch_size in batch_sizes: + image = random_sam2_input_image(batch_size) + + sam2_encoder = SAM2ImageEncoder(sam2_model).cpu() + image_features_0, image_features_1, image_embeddings = sam2_encoder(image.clone()) + + logger.info("image.shape: %s", image.shape) + logger.info("image_features_0.shape: %s", image_features_0.shape) + logger.info("image_features_1.shape: %s", image_features_1.shape) + logger.info("image_embeddings.shape: %s", image_embeddings.shape) + + outputs = ort_session.run(output_names, {"image": image.numpy()}) + for i, output_name in enumerate(output_names): + logger.info("output %s shape %s", output_name, outputs[i].shape) + ort_image_features_0, ort_image_features_1, ort_image_embeddings = outputs + + # ONNXRuntime and PyTorch has about 0.75% mismatched elements, but seems not impacting segmentation results. + if ( + compare_tensors_with_tolerance( + "image_features_0", + image_features_0, + torch.tensor(ort_image_features_0), + mismatch_percentage_tolerance=1, + ) + and compare_tensors_with_tolerance( + "image_features_1", + image_features_1, + torch.tensor(ort_image_features_1), + mismatch_percentage_tolerance=1, + ) + and compare_tensors_with_tolerance( + "image_embeddings", + image_embeddings, + torch.tensor(ort_image_embeddings), + mismatch_percentage_tolerance=1, + ) + ): + print(f"onnx model has been verified for batch_size={batch_size}: {onnx_model_path}") + else: + print(f"onnx model verification failed for batch_size={batch_size}: {onnx_model_path}") diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/sam2/mask_decoder.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/sam2/mask_decoder.py new file mode 100644 index 0000000000000000000000000000000000000000..5fab016b8ae79ae4bf6b0a41d12dee03e0443f0f --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/sam2/mask_decoder.py @@ -0,0 +1,208 @@ +# ------------------------------------------------------------------------- +# Copyright (R) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +# -------------------------------------------------------------------------- +import logging +import warnings + +import torch +from image_encoder import SAM2ImageEncoder, random_sam2_input_image +from prompt_encoder import SAM2PromptEncoder +from sam2.modeling.sam2_base import SAM2Base +from torch import nn + +logger = logging.getLogger(__name__) + + +class SAM2MaskDecoder(nn.Module): + def __init__( + self, + sam_model: SAM2Base, + multimask_output: bool, + dynamic_multimask_via_stability: bool = True, + ) -> None: + super().__init__() + self.mask_decoder = sam_model.sam_mask_decoder + self.prompt_encoder = sam_model.sam_prompt_encoder + self.model = sam_model + self.multimask_output = multimask_output + self.dynamic_multimask_via_stability = dynamic_multimask_via_stability + + @torch.no_grad() + def forward( + self, + image_features_0: torch.Tensor, + image_features_1: torch.Tensor, + image_embeddings: torch.Tensor, + image_pe: torch.Tensor, + sparse_embeddings: torch.Tensor, + dense_embeddings: torch.Tensor, + ): + """ + Decode masks from image and prompt embeddings. Only support H=W=1024. + + Args: + image_features_0 (torch.Tensor): [1, 32, H/4, W/4]. high resolution features of level 0 from image encoder. + image_features_1 (torch.Tensor): [1, 64, H/8, W/8]. high resolution features of level 1 from image encoder. + image_embeddings (torch.Tensor): [1, 256, H/16, W/16]. image embedding from image encoder. + image_pe (torch.Tensor): [1, 256, H/16, W/16]. image positional encoding. + sparse_embeddings (torch.Tensor): [L, P+1, 256], embedding for points and boxes. + dense_embeddings (torch.Tensor): [L, 256, H/16, W/16]. embedding for input masks. + + Returns: + low_res_masks (torch.Tensor, optional): [1, M, H/4, W/4]. low resolution masks. + iou_predictions (torch.Tensor): [1, M]. scores for M masks. + """ + low_res_masks, iou_predictions, _, _ = self.mask_decoder.predict_masks( + image_embeddings=image_embeddings, + image_pe=image_pe, + sparse_prompt_embeddings=sparse_embeddings, + dense_prompt_embeddings=dense_embeddings, + repeat_image=sparse_embeddings.shape[0] > 1, # batch mode + high_res_features=[image_features_0, image_features_1], + ) + + if self.multimask_output: + low_res_masks = low_res_masks[:, 1:, :, :] + iou_predictions = iou_predictions[:, 1:] + elif self.dynamic_multimask_via_stability: + # When outputting a single mask, if the stability score from the current single-mask + # output (based on output token 0) falls below a threshold, we instead select from + # multi-mask outputs (based on output token 1~3) the mask with the highest predicted IoU score. + low_res_masks, iou_predictions = self.mask_decoder._dynamic_multimask_via_stability( + low_res_masks, iou_predictions + ) + else: + low_res_masks = low_res_masks[:, 0:1, :, :] + iou_predictions = iou_predictions[:, 0:1] + + return low_res_masks, iou_predictions + + +def export_mask_decoder_onnx( + sam2_model: SAM2Base, + onnx_model_path: str, + multimask_output: bool, + dynamic_multimask_via_stability: bool = True, + verbose=False, +): + sam2_prompt_encoder = SAM2PromptEncoder(sam2_model).cpu() + + image = random_sam2_input_image() + sam2_encoder = SAM2ImageEncoder(sam2_model).cpu() + image_features_0, image_features_1, image_embeddings = sam2_encoder(image) + logger.info("image_features_0.shape: %s", image_features_0.shape) + logger.info("image_features_1.shape: %s", image_features_1.shape) + logger.info("image_embeddings.shape: %s", image_embeddings.shape) + + # encode an random prompt + num_labels = 2 + num_points = 3 + point_coords = torch.randint(low=0, high=1024, size=(num_labels, num_points, 2), dtype=torch.float) + point_labels = torch.randint(low=0, high=1, size=(num_labels, num_points), dtype=torch.float) + input_masks = torch.zeros(num_labels, 1, 256, 256, dtype=torch.float) + has_input_masks = torch.ones(1, dtype=torch.float) + + sparse_embeddings, dense_embeddings, image_pe = sam2_prompt_encoder( + point_coords, point_labels, input_masks, has_input_masks + ) + + logger.info("sparse_embeddings.shape: %s", sparse_embeddings.shape) + logger.info("dense_embeddings.shape: %s", dense_embeddings.shape) + logger.info("image_pe.shape: %s", image_pe.shape) + + sam2_mask_decoder = SAM2MaskDecoder(sam2_model, multimask_output, dynamic_multimask_via_stability) + inputs = (image_features_0, image_features_1, image_embeddings, image_pe, sparse_embeddings, dense_embeddings) + low_res_masks, iou_predictions = sam2_mask_decoder(*inputs) + logger.info("low_res_masks.shape: %s", low_res_masks.shape) + logger.info("iou_predictions.shape: %s", iou_predictions.shape) + + with warnings.catch_warnings(): + if not verbose: + warnings.filterwarnings("ignore", category=torch.jit.TracerWarning) + warnings.filterwarnings("ignore", category=UserWarning) + torch.onnx.export( + sam2_mask_decoder, + inputs, + onnx_model_path, + export_params=True, + opset_version=18, + do_constant_folding=True, + input_names=[ + "image_features_0", + "image_features_1", + "image_embeddings", + "image_pe", + "sparse_embeddings", + "dense_embeddings", + ], + output_names=["low_res_masks", "iou_predictions"], + dynamic_axes={ + "sparse_embeddings": {0: "num_labels", 1: "num_points+1"}, + "dense_embeddings": {0: "num_labels"}, + "low_res_masks": {0: "num_labels"}, + "iou_predictions": {0: "num_labels"}, + }, + ) + + print("mask decoder onnx model saved to", onnx_model_path) + + +def test_mask_decoder_onnx( + sam2_model: SAM2Base, + onnx_model_path: str, + multimask_output: bool, + dynamic_multimask_via_stability: bool, +): + sam2_prompt_encoder = SAM2PromptEncoder(sam2_model).cpu() + + image = random_sam2_input_image() + sam2_encoder = SAM2ImageEncoder(sam2_model).cpu() + image_features_0, image_features_1, image_embeddings = sam2_encoder(image) + + num_labels = 1 + num_points = 5 + point_coords = torch.randint(low=0, high=1024, size=(num_labels, num_points, 2), dtype=torch.float) + point_labels = torch.randint(low=0, high=1, size=(num_labels, num_points), dtype=torch.float) + input_masks = torch.rand(num_labels, 1, 256, 256, dtype=torch.float) + has_input_masks = torch.ones(1, dtype=torch.float) + + sparse_embeddings, dense_embeddings, image_pe = sam2_prompt_encoder( + point_coords, point_labels, input_masks, has_input_masks + ) + + sam2_mask_decoder = SAM2MaskDecoder(sam2_model, multimask_output, dynamic_multimask_via_stability) + inputs = (image_features_0, image_features_1, image_embeddings, image_pe, sparse_embeddings, dense_embeddings) + low_res_masks, iou_predictions = sam2_mask_decoder(*inputs) + + import onnxruntime # noqa: PLC0415 + + ort_session = onnxruntime.InferenceSession(onnx_model_path, providers=["CPUExecutionProvider"]) + + model_inputs = ort_session.get_inputs() + input_names = [model_inputs[i].name for i in range(len(model_inputs))] + logger.info("input_names: %s", input_names) + + model_outputs = ort_session.get_outputs() + output_names = [model_outputs[i].name for i in range(len(model_outputs))] + logger.info("output_names: %s", output_names) + + outputs = ort_session.run( + output_names, + { + "image_features_0": image_features_0.numpy(), + "image_features_1": image_features_1.numpy(), + "image_embeddings": image_embeddings.numpy(), + "image_pe": image_pe.numpy(), + "sparse_embeddings": sparse_embeddings.numpy(), + "dense_embeddings": dense_embeddings.numpy(), + }, + ) + + for i, output_name in enumerate(output_names): + logger.info("output %s shape: %s", output_name, outputs[i].shape) + + ort_low_res_masks, ort_iou_predictions = outputs + torch.testing.assert_close(low_res_masks, torch.tensor(ort_low_res_masks), atol=5e-3, rtol=1e-4) + torch.testing.assert_close(iou_predictions, torch.tensor(ort_iou_predictions), atol=5e-3, rtol=1e-4) + print(f"onnx model has been verified: {onnx_model_path}") diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/sam2/nvtx_helper.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/sam2/nvtx_helper.py new file mode 100644 index 0000000000000000000000000000000000000000..9f561564050edc4782615e2703ac4dc76c20d648 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/sam2/nvtx_helper.py @@ -0,0 +1,33 @@ +# ------------------------------------------------------------------------- +# Copyright (R) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +# -------------------------------------------------------------------------- +import nvtx +from cuda import cudart + + +class NvtxHelper: + def __init__(self, stages): + self.stages = stages + self.events = {} + for stage in stages: + for marker in ["start", "stop"]: + self.events[stage + "-" + marker] = cudart.cudaEventCreate()[1] + self.markers = {} + + def start_profile(self, stage, color="blue"): + self.markers[stage] = nvtx.start_range(message=stage, color=color) + event_name = stage + "-start" + if event_name in self.events: + cudart.cudaEventRecord(self.events[event_name], 0) + + def stop_profile(self, stage): + event_name = stage + "-stop" + if event_name in self.events: + cudart.cudaEventRecord(self.events[event_name], 0) + nvtx.end_range(self.markers[stage]) + + def print_latency(self): + for stage in self.stages: + latency = cudart.cudaEventElapsedTime(self.events[f"{stage}-start"], self.events[f"{stage}-stop"])[1] + print(f"{stage}: {latency:.2f} ms") diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/sam2/prompt_encoder.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/sam2/prompt_encoder.py new file mode 100644 index 0000000000000000000000000000000000000000..8bec00b0d5a9f08d95fa169dc90031d34137ac96 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/sam2/prompt_encoder.py @@ -0,0 +1,189 @@ +# ------------------------------------------------------------------------- +# Copyright (R) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +# -------------------------------------------------------------------------- +import logging + +import torch +from sam2.modeling.sam2_base import SAM2Base +from sam2_utils import compare_tensors_with_tolerance +from torch import nn + +logger = logging.getLogger(__name__) + + +class SAM2PromptEncoder(nn.Module): + def __init__(self, sam_model: SAM2Base): + super().__init__() + self.prompt_encoder = sam_model.sam_prompt_encoder + self.model = sam_model + + @torch.no_grad() + def forward( + self, + point_coords: torch.Tensor, + point_labels: torch.Tensor, + input_masks: torch.Tensor, + has_input_masks: torch.Tensor, + ): + """Encode prompts. + + Args: + point_coords (torch.Tensor): [L, P, 2] shape and float32 dtype and contains the absolute pixel + coordinate in (x, y) format of the P input points in image of size 1024x1024. + point_labels (torch.Tensor): shape [L, P] and int32 dtype, where 1 means + positive (foreground), 0 means negative (background), -1 means padding, + 2 (box left upper corner), 3 (box right bottom corner). + input_masks (torch.Tensor): [L, 1, H/4, W/4]. Low resolution mask input to the model. + Typically coming from a previous iteration. + has_input_masks (torch.Tensor): [L]. 1.0 if input_masks is used, 0.0 otherwise. + Returns: + sparse_embeddings (torch.Tensor): [L, P+1, 256], embedding for points and boxes. + dense_embeddings (torch.Tensor): [L, 256, 64, 64]. embedding for input masks. + image_pe (torch.Tensor, optional): [1, 256, 64, 64]. image positional encoding. + """ + sparse_embeddings = self._embed_points(point_coords, point_labels) + dense_embeddings = self._embed_masks(input_masks, has_input_masks) + image_pe = self.prompt_encoder.get_dense_pe() + + return sparse_embeddings, dense_embeddings, image_pe + + def _embed_points(self, point_coords: torch.Tensor, point_labels: torch.Tensor) -> torch.Tensor: + point_coords = point_coords + 0.5 + + padding_point = torch.zeros((point_coords.shape[0], 1, 2), device=point_coords.device) + padding_label = -torch.ones((point_labels.shape[0], 1), device=point_labels.device) + point_coords = torch.cat([point_coords, padding_point], dim=1) + point_labels = torch.cat([point_labels, padding_label], dim=1) + + # Note that the input coordinates are based on image size 1024x1024. Here we normalize it to [0.0, 1.0). + point_coords[:, :, 0] = point_coords[:, :, 0] / self.model.image_size + point_coords[:, :, 1] = point_coords[:, :, 1] / self.model.image_size + + point_embedding = self.prompt_encoder.pe_layer._pe_encoding(point_coords) + point_labels = point_labels.unsqueeze(-1).expand_as(point_embedding) + + point_embedding = point_embedding * (point_labels != -1) + point_embedding = point_embedding + self.prompt_encoder.not_a_point_embed.weight * (point_labels == -1) + + for i in range(self.prompt_encoder.num_point_embeddings): + point_embedding = point_embedding + self.prompt_encoder.point_embeddings[i].weight * (point_labels == i) + + return point_embedding + + def _embed_masks(self, input_masks: torch.Tensor, has_input_masks: torch.Tensor) -> torch.Tensor: + mask_embedding = self.prompt_encoder.mask_downscaling(input_masks) + no_mask_embedding = self.prompt_encoder.no_mask_embed.weight.reshape(1, -1, 1, 1) + logger.info("no_mask_embedding.shape: %s", no_mask_embedding.shape) + mask_embedding = has_input_masks * mask_embedding + (1.0 - has_input_masks) * no_mask_embedding + logger.info("mask_embedding.shape: %s", mask_embedding.shape) + return mask_embedding + + +def export_prompt_encoder_onnx( + sam2_model: SAM2Base, + onnx_model_path: str, +): + sam2_prompt_encoder = SAM2PromptEncoder(sam2_model).cpu() + + num_labels = 2 + num_points = 3 + point_coords = torch.randint(low=0, high=1024, size=(num_labels, num_points, 2), dtype=torch.float) + point_labels = torch.randint(low=0, high=1, size=(num_labels, num_points), dtype=torch.int32) + input_masks = torch.zeros(num_labels, 1, 256, 256, dtype=torch.float) + has_input_masks = torch.ones(1, dtype=torch.float) + + sparse_embeddings, dense_embeddings, image_pe = sam2_prompt_encoder( + point_coords, point_labels, input_masks, has_input_masks + ) + + logger.info("point_coords.shape: %s", point_coords.shape) + logger.info("point_labels.shape: %s", point_labels.shape) + logger.info("input_masks.shape: %s", input_masks.shape) + logger.info("has_input_masks.shape: %s", has_input_masks.shape) + + logger.info("sparse_embeddings.shape: %s", sparse_embeddings.shape) + logger.info("dense_embeddings.shape: %s", dense_embeddings.shape) + logger.info("image_pe.shape: %s", image_pe.shape) + + torch.onnx.export( + sam2_prompt_encoder, + (point_coords, point_labels, input_masks, has_input_masks), + onnx_model_path, + export_params=True, + opset_version=18, + do_constant_folding=True, + input_names=["point_coords", "point_labels", "input_masks", "has_input_masks"], + output_names=["sparse_embeddings", "dense_embeddings", "image_pe"], + dynamic_axes={ + "point_coords": {0: "num_labels", 1: "num_points"}, + "point_labels": {0: "num_labels", 1: "num_points"}, + "input_masks": {0: "num_labels"}, + "sparse_embeddings": {0: "num_labels", 1: "num_points+1"}, + "dense_embeddings": {0: "num_labels"}, + }, + ) + + print("prompt encoder onnx model saved to ", onnx_model_path) + + +def test_prompt_encoder_onnx( + sam2_model: SAM2Base, + onnx_model_path: str, +): + sam2_prompt_encoder = SAM2PromptEncoder(sam2_model).cpu() + + num_labels = 1 + num_points = 5 + point_coords = torch.randint(low=0, high=1024, size=(num_labels, num_points, 2), dtype=torch.float) + point_labels = torch.randint(low=0, high=1, size=(num_labels, num_points), dtype=torch.int32) + input_masks = torch.rand(num_labels, 1, 256, 256, dtype=torch.float) + has_input_masks = torch.ones(1, dtype=torch.float) + + sparse_embeddings, dense_embeddings, image_pe = sam2_prompt_encoder( + point_coords, point_labels, input_masks, has_input_masks + ) + + import onnxruntime # noqa: PLC0415 + + ort_session = onnxruntime.InferenceSession(onnx_model_path, providers=["CPUExecutionProvider"]) + + model_inputs = ort_session.get_inputs() + input_names = [model_inputs[i].name for i in range(len(model_inputs))] + logger.info("input_names: %s", input_names) + + model_outputs = ort_session.get_outputs() + output_names = [model_outputs[i].name for i in range(len(model_outputs))] + logger.info("output_names: %s", output_names) + + outputs = ort_session.run( + output_names, + { + "point_coords": point_coords.numpy(), + "point_labels": point_labels.numpy(), + "input_masks": input_masks.numpy(), + "has_input_masks": has_input_masks.numpy(), + }, + ) + + for i, output_name in enumerate(output_names): + logger.info("output %s shape: %s", output_name, outputs[i].shape) + + ort_sparse_embeddings, ort_dense_embeddings, ort_image_pe = outputs + if ( + compare_tensors_with_tolerance( + "sparse_embeddings", + sparse_embeddings, + torch.tensor(ort_sparse_embeddings), + mismatch_percentage_tolerance=0.2, + ) + and compare_tensors_with_tolerance( + "dense_embeddings", dense_embeddings, torch.tensor(ort_dense_embeddings), mismatch_percentage_tolerance=0.2 + ) + and compare_tensors_with_tolerance( + "image_pe", image_pe, torch.tensor(ort_image_pe), mismatch_percentage_tolerance=0.2 + ) + ): + print(f"onnx model has been verified: {onnx_model_path}") + else: + print(f"onnx model verification failed: {onnx_model_path}") diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/sam2/sam2_demo.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/sam2/sam2_demo.py new file mode 100644 index 0000000000000000000000000000000000000000..20ee0274ade3632fb155a0037c7e34383149dba1 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/sam2/sam2_demo.py @@ -0,0 +1,321 @@ +# ------------------------------------------------------------------------- +# Copyright (R) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +# -------------------------------------------------------------------------- +import os + +import matplotlib.image as mpimg +import matplotlib.pyplot as plt +import numpy as np +import torch +from matplotlib.patches import Rectangle +from PIL import Image +from sam2.sam2_image_predictor import SAM2ImagePredictor +from sam2_image_onnx_predictor import SAM2ImageOnnxPredictor +from sam2_utils import load_sam2_model + +import onnxruntime + + +def show_mask(mask, ax, random_color=False, borders=True): + if random_color: + color = np.concatenate([np.random.random(3), np.array([0.6])], axis=0) + else: + color = np.array([30 / 255, 144 / 255, 255 / 255, 0.6]) + h, w = mask.shape[-2:] + mask = mask.astype(np.uint8) + mask_image = mask.reshape(h, w, 1) * color.reshape(1, 1, -1) + if borders: + import cv2 # noqa: PLC0415 + + contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) + # Try to smooth contours + contours = [cv2.approxPolyDP(contour, epsilon=0.01, closed=True) for contour in contours] + mask_image = cv2.drawContours(mask_image, contours, -1, (1, 1, 1, 0.5), thickness=2) + ax.imshow(mask_image) + + +def show_points(coords, labels, ax, marker_size=375): + pos_points = coords[labels == 1] + neg_points = coords[labels == 0] + ax.scatter( + pos_points[:, 0], pos_points[:, 1], color="green", marker="*", s=marker_size, edgecolor="white", linewidth=1.25 + ) + ax.scatter( + neg_points[:, 0], neg_points[:, 1], color="red", marker="*", s=marker_size, edgecolor="white", linewidth=1.25 + ) + + +def show_box(box, ax): + x0, y0 = box[0], box[1] + w, h = box[2] - box[0], box[3] - box[1] + ax.add_patch(Rectangle((x0, y0), w, h, edgecolor="green", facecolor=(0, 0, 0, 0), lw=2)) + + +def show_masks( + image, + masks, + scores, + point_coords=None, + box_coords=None, + input_labels=None, + borders=True, + output_image_file_prefix=None, + image_files=None, +): + for i, (mask, score) in enumerate(zip(masks, scores, strict=False)): + plt.figure(figsize=(10, 10)) + plt.imshow(image) + show_mask(mask, plt.gca(), borders=borders) + if point_coords is not None: + assert input_labels is not None + show_points(point_coords, input_labels, plt.gca()) + + if box_coords is not None: + show_box(box_coords, plt.gca()) + + if len(scores) > 1: + plt.title(f"Mask {i + 1}, Score: {score:.3f}", fontsize=18) + + plt.axis("off") + if output_image_file_prefix: + filename = f"{output_image_file_prefix}_{i}.png" + if os.path.exists(filename): + os.remove(filename) + plt.savefig(filename, format="png", bbox_inches="tight", pad_inches=0) + if isinstance(image_files, list): + image_files.append(filename) + plt.show(block=False) + plt.close() + + +def get_predictor( + sam2_dir: str, + device: str | torch.device, + dtype: torch.dtype, + model_type="sam2_hiera_large", + engine="torch", + image_encoder_onnx_path: str = "", + image_decoder_onnx_path: str = "", + image_decoder_multi_onnx_path: str = "", + provider: str = "CUDAExecutionProvider", +): + sam2_model = load_sam2_model(sam2_dir, model_type, device=device) + if engine == "torch": + predictor = SAM2ImagePredictor(sam2_model) + else: + predictor = SAM2ImageOnnxPredictor( + sam2_model, + image_encoder_onnx_path=image_encoder_onnx_path, + image_decoder_onnx_path=image_decoder_onnx_path, + image_decoder_multi_onnx_path=image_decoder_multi_onnx_path, + provider=provider, + device=device, + onnx_dtype=dtype, + ) + return predictor + + +def run_demo( + sam2_dir: str, + model_type: str = "sam2_hiera_large", + engine: str = "torch", + dtype: torch.dtype = torch.float32, + image_encoder_onnx_path: str = "", + image_decoder_onnx_path: str = "", + image_decoder_multi_onnx_path: str = "", + use_gpu: bool = True, + enable_batch: bool = False, +): + if use_gpu: + assert torch.cuda.is_available() + assert "CUDAExecutionProvider" in onnxruntime.get_available_providers() + provider = "CUDAExecutionProvider" + else: + provider = "CPUExecutionProvider" + + device = torch.device("cuda" if use_gpu else "cpu") + + if use_gpu and engine == "torch" and torch.cuda.get_device_properties(0).major >= 8: + # Turn on tfloat32 for Ampere GPUs. + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + + np.random.seed(3) + image = Image.open("truck.jpg") + image = np.array(image.convert("RGB")) + + predictor = get_predictor( + sam2_dir, + device, + dtype, + model_type, + engine, + image_encoder_onnx_path, + image_decoder_onnx_path, + image_decoder_multi_onnx_path, + provider=provider, + ) + + predictor.set_image(image) + prefix = f"sam2_demo_{engine}_" + + # The model returns masks, quality predictions for those masks, + # and low resolution mask logits that can be passed to the next iteration of prediction. + # With multimask_output=True (the default setting), SAM 2 outputs 3 masks, where + # scores gives the model's own estimation of the quality of these masks. + # For ambiguous prompts such as a single point, it is recommended to use multimask_output=True + # even if only a single mask is desired; + input_point = np.array([[500, 375]]) + input_label = np.array([1]) + masks, scores, logits = predictor.predict( + point_coords=input_point, + point_labels=input_label, + multimask_output=True, + ) + + sorted_ind = np.argsort(scores)[::-1] + masks = masks[sorted_ind] + scores = scores[sorted_ind] + logits = logits[sorted_ind] + + image_files = [] + show_masks( + image, + masks, + scores, + point_coords=input_point, + input_labels=input_label, + borders=True, + output_image_file_prefix=prefix + "multimask", + image_files=image_files, + ) + + # Multiple points. + input_point = np.array([[500, 375], [1125, 625]]) + input_label = np.array([1, 1]) + mask_input = logits[np.argmax(scores), :, :] # Choose the model's best mask + masks, scores, _ = predictor.predict( + point_coords=input_point, + point_labels=input_label, + mask_input=mask_input[None, :, :], + multimask_output=False, + ) + show_masks( + image, + masks, + scores, + point_coords=input_point, + input_labels=input_label, + output_image_file_prefix=prefix + "multi_points", + image_files=image_files, + ) + + # Specify a window and a background point. + input_point = np.array([[500, 375], [1125, 625]]) + input_label = np.array([1, 0]) + mask_input = logits[np.argmax(scores), :, :] # Choose the model's best mask + masks, scores, _ = predictor.predict( + point_coords=input_point, + point_labels=input_label, + mask_input=mask_input[None, :, :], + multimask_output=False, + ) + show_masks( + image, + masks, + scores, + point_coords=input_point, + input_labels=input_label, + output_image_file_prefix=prefix + "background_point", + image_files=image_files, + ) + + # Take a box as input + input_box = np.array([425, 600, 700, 875]) + masks, scores, _ = predictor.predict( + point_coords=None, + point_labels=None, + box=input_box[None, :], + multimask_output=False, + ) + show_masks( + image, + masks, + scores, + box_coords=input_box, + output_image_file_prefix=prefix + "box", + image_files=image_files, + ) + + # Combining points and boxes + input_box = np.array([425, 600, 700, 875]) + input_point = np.array([[575, 750]]) + input_label = np.array([0]) + + masks, scores, logits = predictor.predict( + point_coords=input_point, + point_labels=input_label, + box=input_box, + multimask_output=False, + ) + show_masks( + image, + masks, + scores, + box_coords=input_box, + point_coords=input_point, + input_labels=input_label, + output_image_file_prefix=prefix + "box_and_point", + image_files=image_files, + ) + + # TODO: support batched prompt inputs + if enable_batch: + input_boxes = np.array( + [ + [75, 275, 1725, 850], + [425, 600, 700, 875], + [1375, 550, 1650, 800], + [1240, 675, 1400, 750], + ] + ) + masks, scores, _ = predictor.predict( + point_coords=None, + point_labels=None, + box=input_boxes, + multimask_output=False, + ) + plt.figure(figsize=(10, 10)) + plt.imshow(image) + for mask in masks: + show_mask(mask.squeeze(0), plt.gca(), random_color=True) + for box in input_boxes: + show_box(box, plt.gca()) + plt.axis("off") + plt.show() + plt.savefig(prefix + "batch_prompt.png") + image_files.append(prefix + "batch_prompt.png") + return image_files + + +def show_all_images(left_images, right_images, suffix=""): + # Show images in two rows since display screen is horizontal in most cases. + fig, axes = plt.subplots(nrows=2, ncols=len(left_images), figsize=(19.20, 10.80)) + for i, (left_img_path, right_img_path) in enumerate(zip(left_images, right_images, strict=False)): + left_img = mpimg.imread(left_img_path) + right_img = mpimg.imread(right_img_path) + + axes[0, i].imshow(left_img) + axes[0, i].set_title(left_img_path.replace("sam2_demo_", "").replace(".png", ""), fontsize=10) + axes[0, i].axis("off") + axes[0, i].set_aspect(left_img.shape[1] / left_img.shape[0]) + + axes[1, i].imshow(right_img) + axes[1, i].set_title(right_img_path.replace("sam2_demo_", "").replace(".png", ""), fontsize=10) + axes[1, i].axis("off") + axes[1, i].set_aspect(right_img.shape[1] / right_img.shape[0]) + + plt.tight_layout() + plt.savefig(f"sam2_demo{suffix}.png", format="png", bbox_inches="tight", dpi=1000) + plt.show() diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/sam2/sam2_image_onnx_predictor.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/sam2/sam2_image_onnx_predictor.py new file mode 100644 index 0000000000000000000000000000000000000000..c497e2b22e0fd621671dd108224c5dcc7f0248aa --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/sam2/sam2_image_onnx_predictor.py @@ -0,0 +1,279 @@ +# ------------------------------------------------------------------------- +# Copyright (R) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +# -------------------------------------------------------------------------- + +import logging + +import numpy as np +import torch +from PIL.Image import Image +from sam2.modeling.sam2_base import SAM2Base +from sam2.sam2_image_predictor import SAM2ImagePredictor +from sam2_utils import decoder_shape_dict, encoder_shape_dict + +from onnxruntime import InferenceSession +from onnxruntime.transformers.io_binding_helper import CudaSession + +logger = logging.getLogger(__name__) + + +def create_ort_session( + onnx_path: str, + session_options=None, + provider="CUDAExecutionProvider", + enable_cuda_graph=False, + use_tf32=True, +) -> InferenceSession: + if provider == "CUDAExecutionProvider": + device_id = torch.cuda.current_device() + provider_options = CudaSession.get_cuda_provider_options(device_id, enable_cuda_graph) + provider_options["use_tf32"] = int(use_tf32) + providers = [(provider, provider_options), "CPUExecutionProvider"] + else: + providers = ["CPUExecutionProvider"] + logger.info("Using providers: %s", providers) + return InferenceSession(onnx_path, session_options, providers=providers) + + +def create_session( + onnx_path: str, + session_options=None, + provider="CUDAExecutionProvider", + device: str | torch.device = "cuda", + enable_cuda_graph=False, +) -> CudaSession: + ort_session = create_ort_session( + onnx_path, session_options, provider, enable_cuda_graph=enable_cuda_graph, use_tf32=True + ) + cuda_session = CudaSession(ort_session, device=torch.device(device), enable_cuda_graph=enable_cuda_graph) + return cuda_session + + +class SAM2ImageOnnxPredictor(SAM2ImagePredictor): + def __init__( + self, + sam_model: SAM2Base, + image_encoder_onnx_path: str = "", + image_decoder_onnx_path: str = "", + image_decoder_multi_onnx_path: str = "", + provider: str = "CUDAExecutionProvider", + device: str | torch.device = "cuda", + onnx_dtype: torch.dtype = torch.float32, + mask_threshold=0.0, + max_hole_area=0.0, + max_sprinkle_area=0.0, + **kwargs, + ) -> None: + """ + Uses SAM-2 to compute the image embedding for an image, and then allow mask prediction given prompts. + + Arguments: + sam_model (SAM2Base): The model to use for mask prediction. + onnx_directory (str): The path of the directory that contains encoder and decoder onnx models. + onnx_dtype (torch.dtype): The data type to use for ONNX inputs. + mask_threshold (float): The threshold to convert mask logits to binary masks. Default is 0.0. + max_hole_area (float): If max_hole_area > 0, we fill small holes in up to + the maximum area of max_hole_area in low_res_masks. + max_sprinkle_area (float): If max_sprinkle_area > 0, we remove small sprinkles up to + the maximum area of max_sprinkle_area in low_res_masks. + """ + super().__init__( + sam_model, mask_threshold=mask_threshold, max_hole_area=max_hole_area, max_sprinkle_area=max_sprinkle_area + ) + + logger.debug("self.device=%s, device=%s", self.device, device) + + # This model is exported by image_encoder.py. + self.encoder_session = create_session( + image_encoder_onnx_path, + session_options=None, + provider=provider, + device=device, + enable_cuda_graph=False, + ) + self.onnx_dtype = onnx_dtype + + # This model is exported by image_decoder.py. It outputs only one mask. + self.decoder_session = create_session( + image_decoder_onnx_path, + session_options=None, + provider=provider, + device=device, + enable_cuda_graph=False, + ) + + # This model is exported by image_decoder.py. It outputs multiple (3) masks. + self.decoder_session_multi_out = create_session( + image_decoder_multi_onnx_path, + session_options=None, + provider=provider, + device=device, + enable_cuda_graph=False, + ) + + @torch.no_grad() + def set_image(self, image: np.ndarray | Image): + """ + Calculates the image embeddings for the provided image. + + Arguments: + image (np.ndarray or PIL Image): The input image to embed in RGB format. + The image should be in HWC format if np.ndarray, or WHC format if PIL Image with pixel values in [0, 255]. + """ + self.reset_predictor() + # Transform the image to the form expected by the model + if isinstance(image, np.ndarray): + # For numpy array image, we assume (HxWxC) format. + self._orig_hw = [image.shape[:2]] + elif isinstance(image, Image): + w, h = image.size + self._orig_hw = [(h, w)] + else: + raise NotImplementedError("Image format not supported") + + input_image = self._transforms(image) + input_image = input_image[None, ...].to(self.device) + + assert len(input_image.shape) == 4 and input_image.shape[1] == 3, ( + f"input_image must be of size 1x3xHxW, got {input_image.shape}" + ) + + # Computing image embeddings for the provided image + io_shapes = encoder_shape_dict(batch_size=1, height=input_image.shape[2], width=input_image.shape[3]) + self.encoder_session.allocate_buffers(io_shapes) + + feed_dict = {"image": input_image.to(self.onnx_dtype).to(self.device)} + + for key, value in feed_dict.items(): + logger.debug(f"{key}: {value.shape}, {value.dtype}") + logger.debug(f"encoder onnx: {self.encoder_session.ort_session._model_path}") + + ort_outputs = self.encoder_session.infer(feed_dict) + + self._features = { + "image_embed": ort_outputs["image_embeddings"], + "high_res_feats": [ort_outputs[f"image_features_{i}"] for i in range(2)], + } + self._is_image_set = True + logging.info("Image embeddings computed.") + + @torch.no_grad() + def _predict( + self, + point_coords: torch.Tensor | None, + point_labels: torch.Tensor | None, + boxes: torch.Tensor | None = None, + mask_input: torch.Tensor | None = None, + multimask_output: bool = True, + return_logits: bool = False, + img_idx: int = -1, + ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """ + Predict masks for the given input prompts, using the currently set image. + Input prompts are batched torch tensors and are expected to already be + transformed to the input frame using SAM2Transforms. + + Arguments: + point_coords (torch.Tensor or None): A BxNx2 array of point prompts to the + model. Each point is in (X,Y) in pixels. + point_labels (torch.Tensor or None): A BxN array of labels for the + point prompts. 1 indicates a foreground point and 0 indicates a + background point. + boxes (np.ndarray or None): A Bx4 array given a box prompt to the + model, in XYXY format. + mask_input (np.ndarray): A low resolution mask input to the model, typically + coming from a previous prediction iteration. Has form Bx1xHxW, where + for SAM, H=W=256. Masks returned by a previous iteration of the + predict method do not need further transformation. + multimask_output (bool): If true, the model will return three masks. + For ambiguous input prompts (such as a single click), this will often + produce better masks than a single prediction. If only a single + mask is needed, the model's predicted quality score can be used + to select the best mask. For non-ambiguous prompts, such as multiple + input prompts, multimask_output=False can give better results. + return_logits (bool): If true, returns un-thresholded masks logits + instead of a binary mask. + + Returns: + (torch.Tensor): The output masks in BxCxHxW format, where C is the + number of masks, and (H, W) is the original image size. + (torch.Tensor): An array of shape BxC containing the model's + predictions for the quality of each mask. + (torch.Tensor): An array of shape BxCxHxW, where C is the number + of masks and H=W=256. These low res logits can be passed to + a subsequent iteration as mask input. + """ + assert not return_logits # onnx model is exported for returning bool masks. + + if not self._is_image_set: + raise RuntimeError("An image must be set with .set_image(...) before mask prediction.") + + if point_coords is not None: + concat_points = (point_coords, point_labels) + else: + concat_points = None + + # Embed prompts + if boxes is not None: + box_coords = boxes.reshape(-1, 2, 2) + box_labels = torch.tensor([[2, 3]], dtype=torch.int, device=boxes.device) + box_labels = box_labels.repeat(boxes.size(0), 1) + # we merge "boxes" and "points" into a single "concat_points" input (where + # boxes are added at the beginning) to sam_prompt_encoder + if concat_points is not None: + concat_coords = torch.cat([box_coords, concat_points[0]], dim=1) + concat_labels = torch.cat([box_labels, concat_points[1]], dim=1) + concat_points = (concat_coords, concat_labels) + else: + concat_points = (box_coords, box_labels) + + assert concat_points is not None + num_labels = concat_points[0].shape[0] + shape_dict = decoder_shape_dict( + original_image_height=self._orig_hw[img_idx][0], + original_image_width=self._orig_hw[img_idx][1], + num_labels=num_labels, + max_points=concat_points[0].shape[1], + num_masks=3 if multimask_output else 1, + ) + if multimask_output: + decoder_session = self.decoder_session_multi_out + else: + decoder_session = self.decoder_session + + decoder_session.allocate_buffers(shape_dict) + + image_features_0 = self._features["high_res_feats"][0][img_idx].unsqueeze(0) + image_features_1 = self._features["high_res_feats"][1][img_idx].unsqueeze(0) + image_embeddings = self._features["image_embed"][img_idx].unsqueeze(0) + + if mask_input is None: + input_masks = torch.zeros(num_labels, 1, 256, 256, dtype=self.onnx_dtype, device=self.device) + has_input_masks = torch.zeros(num_labels, dtype=self.onnx_dtype, device=self.device) + else: + input_masks = mask_input[img_idx].unsqueeze(0).repeat(num_labels, 1, 1, 1) + has_input_masks = torch.ones(num_labels, dtype=self.onnx_dtype, device=self.device) + + feed_dict = { + "image_embeddings": image_embeddings.contiguous().to(dtype=self.onnx_dtype).to(self.device), + "image_features_0": image_features_0.contiguous().to(dtype=self.onnx_dtype).to(self.device), + "image_features_1": image_features_1.contiguous().to(dtype=self.onnx_dtype).to(self.device), + "point_coords": concat_points[0].to(dtype=self.onnx_dtype).to(self.device), + "point_labels": concat_points[1].to(dtype=torch.int32).to(self.device), + "input_masks": input_masks.to(dtype=self.onnx_dtype).to(self.device), + "has_input_masks": has_input_masks.to(dtype=self.onnx_dtype).to(self.device), + "original_image_size": torch.tensor(self._orig_hw[img_idx], dtype=torch.int32, device=self.device), + } + + for key, value in feed_dict.items(): + logger.debug(f"{key}: {value.shape}, {value.dtype}") + logger.debug(f"decoder onnx: {self.decoder_session.ort_session._model_path}") + + ort_outputs = decoder_session.infer(feed_dict) + + masks = ort_outputs["masks"] + iou_predictions = ort_outputs["iou_predictions"] + low_res_masks = ort_outputs["low_res_masks"] + + return torch.Tensor(masks), torch.Tensor(iou_predictions), torch.Tensor(low_res_masks) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/sam2/sam2_utils.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/sam2/sam2_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..3bf9df4dab03e0d9da5b604cf2c7c99f3a94121a --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/sam2/sam2_utils.py @@ -0,0 +1,147 @@ +# ------------------------------------------------------------------------- +# Copyright (R) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +# -------------------------------------------------------------------------- +import logging +import os +import sys +from collections.abc import Mapping + +import torch +from sam2.build_sam import build_sam2 +from sam2.modeling.sam2_base import SAM2Base + +logger = logging.getLogger(__name__) + + +def _get_model_cfg(model_type) -> str: + assert model_type in ["sam2_hiera_tiny", "sam2_hiera_small", "sam2_hiera_large", "sam2_hiera_base_plus"] + if model_type == "sam2_hiera_tiny": + model_cfg = "sam2_hiera_t.yaml" + elif model_type == "sam2_hiera_small": + model_cfg = "sam2_hiera_s.yaml" + elif model_type == "sam2_hiera_base_plus": + model_cfg = "sam2_hiera_b+.yaml" + else: + model_cfg = "sam2_hiera_l.yaml" + return model_cfg + + +def load_sam2_model(sam2_dir, model_type, device: str | torch.device = "cpu") -> SAM2Base: + checkpoints_dir = os.path.join(sam2_dir, "checkpoints") + sam2_config_dir = os.path.join(sam2_dir, "sam2_configs") + if not os.path.exists(sam2_dir): + raise FileNotFoundError(f"{sam2_dir} does not exist. Please specify --sam2_dir correctly.") + + if not os.path.exists(checkpoints_dir): + raise FileNotFoundError(f"{checkpoints_dir} does not exist. Please specify --sam2_dir correctly.") + + if not os.path.exists(sam2_config_dir): + raise FileNotFoundError(f"{sam2_config_dir} does not exist. Please specify --sam2_dir correctly.") + + checkpoint_path = os.path.join(checkpoints_dir, f"{model_type}.pt") + if not os.path.exists(checkpoint_path): + raise FileNotFoundError(f"{checkpoint_path} does not exist. Please download checkpoints under the directory.") + + if sam2_dir not in sys.path: + sys.path.append(sam2_dir) + + model_cfg = _get_model_cfg(model_type) + sam2_model = build_sam2(model_cfg, checkpoint_path, device=device) + return sam2_model + + +def sam2_onnx_path(output_dir, model_type, component, multimask_output=False, suffix=""): + if component == "image_encoder": + return os.path.join(output_dir, f"{model_type}_image_encoder{suffix}.onnx") + elif component == "mask_decoder": + return os.path.join(output_dir, f"{model_type}_mask_decoder{suffix}.onnx") + elif component == "prompt_encoder": + return os.path.join(output_dir, f"{model_type}_prompt_encoder{suffix}.onnx") + else: + assert component == "image_decoder" + return os.path.join( + output_dir, f"{model_type}_image_decoder" + ("_multi" if multimask_output else "") + f"{suffix}.onnx" + ) + + +def encoder_shape_dict(batch_size: int, height: int, width: int) -> Mapping[str, list[int]]: + assert height == 1024 and width == 1024, "Only 1024x1024 images are supported." + return { + "image": [batch_size, 3, height, width], + "image_features_0": [batch_size, 32, height // 4, width // 4], + "image_features_1": [batch_size, 64, height // 8, width // 8], + "image_embeddings": [batch_size, 256, height // 16, width // 16], + } + + +def decoder_shape_dict( + original_image_height: int, + original_image_width: int, + num_labels: int = 1, + max_points: int = 16, + num_masks: int = 1, +) -> dict: + height: int = 1024 + width: int = 1024 + return { + "image_features_0": [1, 32, height // 4, width // 4], + "image_features_1": [1, 64, height // 8, width // 8], + "image_embeddings": [1, 256, height // 16, width // 16], + "point_coords": [num_labels, max_points, 2], + "point_labels": [num_labels, max_points], + "input_masks": [num_labels, 1, height // 4, width // 4], + "has_input_masks": [num_labels], + "original_image_size": [2], + "masks": [num_labels, num_masks, original_image_height, original_image_width], + "iou_predictions": [num_labels, num_masks], + "low_res_masks": [num_labels, num_masks, height // 4, width // 4], + } + + +def compare_tensors_with_tolerance( + name: str, + tensor1: torch.Tensor, + tensor2: torch.Tensor, + atol=5e-3, + rtol=1e-4, + mismatch_percentage_tolerance=0.1, +) -> bool: + assert tensor1.shape == tensor2.shape + a = tensor1.clone().float() + b = tensor2.clone().float() + + differences = torch.abs(a - b) + mismatch_count = (differences > (rtol * torch.max(torch.abs(a), torch.abs(b)) + atol)).sum().item() + + total_elements = a.numel() + mismatch_percentage = (mismatch_count / total_elements) * 100 + + passed = mismatch_percentage < mismatch_percentage_tolerance + + log_func = logger.error if not passed else logger.info + log_func( + "%s: mismatched elements percentage %.2f (%d/%d). Verification %s (threshold=%.2f).", + name, + mismatch_percentage, + mismatch_count, + total_elements, + "passed" if passed else "failed", + mismatch_percentage_tolerance, + ) + + return passed + + +def random_sam2_input_image(batch_size=1, image_height=1024, image_width=1024) -> torch.Tensor: + image = torch.randn(batch_size, 3, image_height, image_width, dtype=torch.float32).cpu() + return image + + +def setup_logger(verbose=True): + if verbose: + logging.basicConfig(format="[%(filename)s:%(lineno)s - %(funcName)20s()] %(message)s") + logging.getLogger().setLevel(logging.INFO) + else: + logging.basicConfig(format="[%(message)s") + logging.getLogger().setLevel(logging.WARNING) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/__init__.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5ef71ce9e355e17ea1c2ca9fb648951d917734b5 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/__init__.py @@ -0,0 +1,12 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +# -------------------------------------------------------------------------- +import os.path +import sys + +sys.path.append(os.path.dirname(__file__)) + +transformers_dir = os.path.normpath(os.path.join(os.path.dirname(__file__), "..", "..")) +if transformers_dir not in sys.path: + sys.path.append(transformers_dir) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dd122499848c25e48c67897f5e9035e8c3445123 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/__pycache__/benchmark.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/__pycache__/benchmark.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fea7b3379065952b468d2cebe4ce928949e3a099 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/__pycache__/benchmark.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/__pycache__/benchmark_controlnet.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/__pycache__/benchmark_controlnet.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..62515b6310431c62bbb8736ba4759a7e433445db Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/__pycache__/benchmark_controlnet.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/__pycache__/demo_txt2img.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/__pycache__/demo_txt2img.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..61409a062d0862bd33a6320e28da778c1d8b68b2 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/__pycache__/demo_txt2img.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/__pycache__/demo_txt2img_xl.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/__pycache__/demo_txt2img_xl.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e5d7f8c1e70b44e6a20cabf908cefd1918834a37 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/__pycache__/demo_txt2img_xl.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/__pycache__/demo_utils.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/__pycache__/demo_utils.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..821524a3ed0741ff6048df99d2b344d6a5eb7c98 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/__pycache__/demo_utils.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/__pycache__/diffusion_models.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/__pycache__/diffusion_models.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c8e5586e2c14b6fbaa4a61c6d59553e8ee8f7e54 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/__pycache__/diffusion_models.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/__pycache__/diffusion_schedulers.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/__pycache__/diffusion_schedulers.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f5deb1664059bb6bf6e6f0b8b76db0b69e30244c Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/__pycache__/diffusion_schedulers.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/__pycache__/engine_builder.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/__pycache__/engine_builder.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2dffe658ac4905d1a9af4d3be44cca0f3781c7bf Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/__pycache__/engine_builder.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/__pycache__/engine_builder_ort_cuda.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/__pycache__/engine_builder_ort_cuda.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..344e65ce0a092804232df205118e30d12277be07 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/__pycache__/engine_builder_ort_cuda.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/__pycache__/engine_builder_ort_trt.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/__pycache__/engine_builder_ort_trt.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..01e51eaa8ebbb9571246cbc09e1acfdfc8ca20f4 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/__pycache__/engine_builder_ort_trt.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/__pycache__/engine_builder_tensorrt.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/__pycache__/engine_builder_tensorrt.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b3489019df4e330e5b5c7d3fce24005bc9a979f7 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/__pycache__/engine_builder_tensorrt.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/__pycache__/engine_builder_torch.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/__pycache__/engine_builder_torch.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..76c8b83c1e11c16b9d574b0b95fff655c39db691 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/__pycache__/engine_builder_torch.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/__pycache__/optimize_pipeline.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/__pycache__/optimize_pipeline.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..413666513d500fae6df2fafd535cc8e5e2dd6a9b Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/__pycache__/optimize_pipeline.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/__pycache__/ort_optimizer.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/__pycache__/ort_optimizer.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f09e4d430695be47c84d187b0c8d144e38965940 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/__pycache__/ort_optimizer.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/__pycache__/pipeline_stable_diffusion.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/__pycache__/pipeline_stable_diffusion.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..38d1e7615acbb27a993116f8cb7e1f3724d96b8a Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/__pycache__/pipeline_stable_diffusion.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/__pycache__/trt_utilities.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/__pycache__/trt_utilities.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ab997c0d2829dd673ba563dee582c2f3f9b092ee Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/__pycache__/trt_utilities.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/benchmark.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/benchmark.py new file mode 100644 index 0000000000000000000000000000000000000000..2db5e3c68534e2443539cded84a4a380fd9898ff --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/benchmark.py @@ -0,0 +1,1519 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +# -------------------------------------------------------------------------- + +import argparse +import csv +import logging +import os +import statistics +import sys +import time +from pathlib import Path + +# import torch before onnxruntime so that onnxruntime uses the cuDNN in the torch package. +import torch +from benchmark_helper import measure_memory + +SD_MODELS = { + "1.5": "runwayml/stable-diffusion-v1-5", + "2.0": "stabilityai/stable-diffusion-2", + "2.1": "stabilityai/stable-diffusion-2-1", + "xl-1.0": "stabilityai/stable-diffusion-xl-refiner-1.0", + "3.0M": "stabilityai/stable-diffusion-3-medium-diffusers", + "3.5M": "stabilityai/stable-diffusion-3.5-medium", + "3.5L": "stabilityai/stable-diffusion-3.5-large", + "Flux.1S": "black-forest-labs/FLUX.1-schnell", + "Flux.1D": "black-forest-labs/FLUX.1-dev", +} + +PROVIDERS = { + "cuda": "CUDAExecutionProvider", + "migraphx": "MIGraphXExecutionProvider", + "tensorrt": "TensorrtExecutionProvider", +} + + +def example_prompts(): + prompts = [ + "a photo of an astronaut riding a horse on mars", + "cute grey cat with blue eyes, wearing a bowtie, acrylic painting", + "a cute magical flying dog, fantasy art drawn by disney concept artists, highly detailed, digital painting", + "an illustration of a house with large barn with many cute flower pots and beautiful blue sky scenery", + "one apple sitting on a table, still life, reflective, full color photograph, centered, close-up product", + "background texture of stones, masterpiece, artistic, stunning photo, award winner photo", + "new international organic style house, tropical surroundings, architecture, 8k, hdr", + "beautiful Renaissance Revival Estate, Hobbit-House, detailed painting, warm colors, 8k, trending on Artstation", + "blue owl, big green eyes, portrait, intricate metal design, unreal engine, octane render, realistic", + "delicate elvish moonstone necklace on a velvet background, symmetrical intricate motifs, leaves, flowers, 8k", + ] + + negative_prompt = "bad composition, ugly, abnormal, malformed" + + return prompts, negative_prompt + + +def warmup_prompts(): + return "warm up", "bad" + + +def measure_gpu_memory(monitor_type, func, start_memory=None): + return measure_memory(is_gpu=True, func=func, monitor_type=monitor_type, start_memory=start_memory) + + +def get_ort_pipeline(model_name: str, directory: str, provider, disable_safety_checker: bool): + from diffusers import DDIMScheduler, OnnxStableDiffusionPipeline # noqa: PLC0415 + + import onnxruntime # noqa: PLC0415 + + if directory is not None: + assert os.path.exists(directory) + session_options = onnxruntime.SessionOptions() + pipe = OnnxStableDiffusionPipeline.from_pretrained( + directory, + provider=provider, + sess_options=session_options, + ) + else: + pipe = OnnxStableDiffusionPipeline.from_pretrained( + model_name, + revision="onnx", + provider=provider, + use_auth_token=True, + ) + pipe.scheduler = DDIMScheduler.from_config(pipe.scheduler.config) + pipe.set_progress_bar_config(disable=True) + + if disable_safety_checker: + pipe.safety_checker = None + pipe.feature_extractor = None + + return pipe + + +def get_torch_pipeline(model_name: str, disable_safety_checker: bool, enable_torch_compile: bool, use_xformers: bool): + if "FLUX" in model_name: + from diffusers import FluxPipeline # noqa: PLC0415 + + pipe = FluxPipeline.from_pretrained(model_name, torch_dtype=torch.bfloat16).to("cuda") + if enable_torch_compile: + pipe.transformer.to(memory_format=torch.channels_last) + pipe.transformer = torch.compile(pipe.transformer, mode="max-autotune", fullgraph=True) + return pipe + + if "stable-diffusion-3" in model_name: + from diffusers import StableDiffusion3Pipeline # noqa: PLC0415 + + pipe = StableDiffusion3Pipeline.from_pretrained(model_name, torch_dtype=torch.bfloat16).to("cuda") + if enable_torch_compile: + pipe.transformer.to(memory_format=torch.channels_last) + pipe.transformer = torch.compile(pipe.transformer, mode="max-autotune", fullgraph=True) + return pipe + + from diffusers import DDIMScheduler, StableDiffusionPipeline # noqa: PLC0415 + from torch import channels_last, float16 # noqa: PLC0415 + + pipe = StableDiffusionPipeline.from_pretrained(model_name, torch_dtype=float16).to("cuda") + + pipe.unet.to(memory_format=channels_last) # in-place operation + + if use_xformers: + pipe.enable_xformers_memory_efficient_attention() + + if enable_torch_compile: + pipe.unet = torch.compile(pipe.unet) + pipe.vae = torch.compile(pipe.vae) + pipe.text_encoder = torch.compile(pipe.text_encoder) + print("Torch compiled unet, vae and text_encoder") + + pipe.scheduler = DDIMScheduler.from_config(pipe.scheduler.config) + pipe.set_progress_bar_config(disable=True) + + if disable_safety_checker: + pipe.safety_checker = None + pipe.feature_extractor = None + + return pipe + + +def get_image_filename_prefix(engine: str, model_name: str, batch_size: int, steps: int, disable_safety_checker: bool): + short_model_name = model_name.split("/")[-1].replace("stable-diffusion-", "sd") + return f"{engine}_{short_model_name}_b{batch_size}_s{steps}" + ("" if disable_safety_checker else "_safe") + + +def run_ort_pipeline( + pipe, + batch_size: int, + image_filename_prefix: str, + height, + width, + steps, + num_prompts, + batch_count, + start_memory, + memory_monitor_type, + skip_warmup: bool = False, +): + from diffusers import OnnxStableDiffusionPipeline # noqa: PLC0415 + + assert isinstance(pipe, OnnxStableDiffusionPipeline) + + prompts, negative_prompt = example_prompts() + + def warmup(): + if skip_warmup: + return + prompt, negative = warmup_prompts() + pipe( + prompt=[prompt] * batch_size, + height=height, + width=width, + num_inference_steps=steps, + negative_prompt=[negative] * batch_size, + ) + + # Run warm up, and measure GPU memory of two runs + # cuDNN/MIOpen The first run has algo search so it might need more memory) + first_run_memory = measure_gpu_memory(memory_monitor_type, warmup, start_memory) + second_run_memory = measure_gpu_memory(memory_monitor_type, warmup, start_memory) + + warmup() + + latency_list = [] + for i, prompt in enumerate(prompts): + if i >= num_prompts: + break + inference_start = time.time() + images = pipe( + prompt=[prompt] * batch_size, + height=height, + width=width, + num_inference_steps=steps, + negative_prompt=[negative_prompt] * batch_size, + ).images + inference_end = time.time() + latency = inference_end - inference_start + latency_list.append(latency) + print(f"Inference took {latency:.3f} seconds") + for k, image in enumerate(images): + image.save(f"{image_filename_prefix}_{i}_{k}.jpg") + + from onnxruntime import __version__ as ort_version # noqa: PLC0415 + + return { + "engine": "onnxruntime", + "version": ort_version, + "height": height, + "width": width, + "steps": steps, + "batch_size": batch_size, + "batch_count": batch_count, + "num_prompts": num_prompts, + "average_latency": sum(latency_list) / len(latency_list), + "median_latency": statistics.median(latency_list), + "first_run_memory_MB": first_run_memory, + "second_run_memory_MB": second_run_memory, + } + + +def get_negative_prompt_kwargs(negative_prompt, use_num_images_per_prompt, is_flux, batch_size) -> dict: + # Flux does not support negative prompt + kwargs = ( + ( + {"negative_prompt": negative_prompt} + if use_num_images_per_prompt + else {"negative_prompt": [negative_prompt] * batch_size} + ) + if not is_flux + else {} + ) + + # Fix the random seed so that we can inspect the output quality easily. + if torch.cuda.is_available(): + kwargs["generator"] = torch.Generator(device="cuda").manual_seed(123) + + return kwargs + + +def run_torch_pipeline( + pipe, + batch_size: int, + image_filename_prefix: str, + height, + width, + steps, + num_prompts, + batch_count, + start_memory, + memory_monitor_type, + skip_warmup=False, +): + prompts, negative_prompt = example_prompts() + + import diffusers # noqa: PLC0415 + + is_flux = isinstance(pipe, diffusers.FluxPipeline) + + def warmup(): + if skip_warmup: + return + prompt, negative = warmup_prompts() + extra_kwargs = get_negative_prompt_kwargs(negative, False, is_flux, batch_size) + pipe(prompt=[prompt] * batch_size, height=height, width=width, num_inference_steps=steps, **extra_kwargs) + + # Run warm up, and measure GPU memory of two runs (The first run has cuDNN algo search so it might need more memory) + first_run_memory = measure_gpu_memory(memory_monitor_type, warmup, start_memory) + second_run_memory = measure_gpu_memory(memory_monitor_type, warmup, start_memory) + + warmup() + + torch.set_grad_enabled(False) + + latency_list = [] + for i, prompt in enumerate(prompts): + if i >= num_prompts: + break + torch.cuda.synchronize() + inference_start = time.time() + extra_kwargs = get_negative_prompt_kwargs(negative_prompt, False, is_flux, batch_size) + images = pipe( + prompt=[prompt] * batch_size, + height=height, + width=width, + num_inference_steps=steps, + **extra_kwargs, + ).images + + torch.cuda.synchronize() + inference_end = time.time() + latency = inference_end - inference_start + latency_list.append(latency) + print(f"Inference took {latency:.3f} seconds") + for k, image in enumerate(images): + image.save(f"{image_filename_prefix}_{i}_{k}.jpg") + + return { + "engine": "torch", + "version": torch.__version__, + "height": height, + "width": width, + "steps": steps, + "batch_size": batch_size, + "batch_count": batch_count, + "num_prompts": num_prompts, + "average_latency": sum(latency_list) / len(latency_list), + "median_latency": statistics.median(latency_list), + "first_run_memory_MB": first_run_memory, + "second_run_memory_MB": second_run_memory, + } + + +def run_ort( + model_name: str, + directory: str, + provider: str, + batch_size: int, + disable_safety_checker: bool, + height: int, + width: int, + steps: int, + num_prompts: int, + batch_count: int, + start_memory, + memory_monitor_type, + tuning: bool, + skip_warmup: bool = False, +): + provider_and_options = provider + if tuning and provider in ["CUDAExecutionProvider"]: + provider_and_options = (provider, {"tunable_op_enable": 1, "tunable_op_tuning_enable": 1}) + + load_start = time.time() + pipe = get_ort_pipeline(model_name, directory, provider_and_options, disable_safety_checker) + load_end = time.time() + print(f"Model loading took {load_end - load_start} seconds") + + image_filename_prefix = get_image_filename_prefix("ort", model_name, batch_size, steps, disable_safety_checker) + result = run_ort_pipeline( + pipe, + batch_size, + image_filename_prefix, + height, + width, + steps, + num_prompts, + batch_count, + start_memory, + memory_monitor_type, + skip_warmup=skip_warmup, + ) + + result.update( + { + "model_name": model_name, + "directory": directory, + "provider": provider.replace("ExecutionProvider", ""), + "disable_safety_checker": disable_safety_checker, + "enable_cuda_graph": False, + } + ) + return result + + +def get_optimum_ort_pipeline( + model_name: str, + directory: str, + provider="CUDAExecutionProvider", + disable_safety_checker: bool = True, + use_io_binding: bool = False, +): + from optimum.onnxruntime import ORTPipelineForText2Image # noqa: PLC0415 + + if directory is not None and os.path.exists(directory): + pipeline = ORTPipelineForText2Image.from_pretrained(directory, provider=provider, use_io_binding=use_io_binding) + else: + pipeline = ORTPipelineForText2Image.from_pretrained( + model_name, + export=True, + provider=provider, + use_io_binding=use_io_binding, + ) + pipeline.save_pretrained(directory) + + if disable_safety_checker: + pipeline.safety_checker = None + pipeline.feature_extractor = None + + return pipeline + + +def run_optimum_ort_pipeline( + pipe, + batch_size: int, + image_filename_prefix: str, + height, + width, + steps, + num_prompts, + batch_count, + start_memory, + memory_monitor_type, + use_num_images_per_prompt=False, + skip_warmup=False, +): + print("Pipeline type", type(pipe)) + from optimum.onnxruntime.modeling_diffusion import ORTFluxPipeline # noqa: PLC0415 + + is_flux = isinstance(pipe, ORTFluxPipeline) + + prompts, negative_prompt = example_prompts() + + def warmup(): + if skip_warmup: + return + prompt, negative = warmup_prompts() + extra_kwargs = get_negative_prompt_kwargs(negative, use_num_images_per_prompt, is_flux, batch_size) + if use_num_images_per_prompt: + pipe( + prompt=prompt, + height=height, + width=width, + num_inference_steps=steps, + num_images_per_prompt=batch_count, + **extra_kwargs, + ) + else: + pipe(prompt=[prompt] * batch_size, height=height, width=width, num_inference_steps=steps, **extra_kwargs) + + # Run warm up, and measure GPU memory of two runs. + # The first run has algo search for cuDNN/MIOpen, so it might need more memory. + first_run_memory = measure_gpu_memory(memory_monitor_type, warmup, start_memory) + second_run_memory = measure_gpu_memory(memory_monitor_type, warmup, start_memory) + + warmup() + + extra_kwargs = get_negative_prompt_kwargs(negative_prompt, use_num_images_per_prompt, is_flux, batch_size) + + latency_list = [] + for i, prompt in enumerate(prompts): + if i >= num_prompts: + break + inference_start = time.time() + if use_num_images_per_prompt: + images = pipe( + prompt=prompt, + height=height, + width=width, + num_inference_steps=steps, + num_images_per_prompt=batch_size, + **extra_kwargs, + ).images + else: + images = pipe( + prompt=[prompt] * batch_size, height=height, width=width, num_inference_steps=steps, **extra_kwargs + ).images + inference_end = time.time() + latency = inference_end - inference_start + latency_list.append(latency) + print(f"Inference took {latency:.3f} seconds") + for k, image in enumerate(images): + image.save(f"{image_filename_prefix}_{i}_{k}.jpg") + + from onnxruntime import __version__ as ort_version # noqa: PLC0415 + + return { + "engine": "optimum_ort", + "version": ort_version, + "height": height, + "width": width, + "steps": steps, + "batch_size": batch_size, + "batch_count": batch_count, + "num_prompts": num_prompts, + "average_latency": sum(latency_list) / len(latency_list), + "median_latency": statistics.median(latency_list), + "first_run_memory_MB": first_run_memory, + "second_run_memory_MB": second_run_memory, + } + + +def run_optimum_ort( + model_name: str, + directory: str, + provider: str, + batch_size: int, + disable_safety_checker: bool, + height: int, + width: int, + steps: int, + num_prompts: int, + batch_count: int, + start_memory, + memory_monitor_type, + use_io_binding: bool = False, + skip_warmup: bool = False, +): + load_start = time.time() + pipe = get_optimum_ort_pipeline( + model_name, directory, provider, disable_safety_checker, use_io_binding=use_io_binding + ) + load_end = time.time() + print(f"Model loading took {load_end - load_start} seconds") + + full_model_name = model_name + "_" + Path(directory).name if directory else model_name + image_filename_prefix = get_image_filename_prefix( + "optimum", full_model_name, batch_size, steps, disable_safety_checker + ) + result = run_optimum_ort_pipeline( + pipe, + batch_size, + image_filename_prefix, + height, + width, + steps, + num_prompts, + batch_count, + start_memory, + memory_monitor_type, + skip_warmup=skip_warmup, + ) + + result.update( + { + "model_name": model_name, + "directory": directory, + "provider": provider.replace("ExecutionProvider", ""), + "disable_safety_checker": disable_safety_checker, + "enable_cuda_graph": False, + } + ) + return result + + +def run_ort_trt_static( + work_dir: str, + version: str, + batch_size: int, + disable_safety_checker: bool, + height: int, + width: int, + steps: int, + num_prompts: int, + batch_count: int, + start_memory, + memory_monitor_type, + max_batch_size: int, + nvtx_profile: bool = False, + use_cuda_graph: bool = True, +): + print("[I] Initializing ORT TensorRT EP accelerated StableDiffusionXL txt2img pipeline (static input shape)") + + # Register TensorRT plugins + from trt_utilities import init_trt_plugins # noqa: PLC0415 + + init_trt_plugins() + + assert batch_size <= max_batch_size + + from diffusion_models import PipelineInfo # noqa: PLC0415 + + pipeline_info = PipelineInfo(version) + short_name = pipeline_info.short_name() + + from engine_builder import EngineType, get_engine_paths # noqa: PLC0415 + from pipeline_stable_diffusion import StableDiffusionPipeline # noqa: PLC0415 + + engine_type = EngineType.ORT_TRT + onnx_dir, engine_dir, output_dir, framework_model_dir, _ = get_engine_paths(work_dir, pipeline_info, engine_type) + + # Initialize pipeline + pipeline = StableDiffusionPipeline( + pipeline_info, + scheduler="DDIM", + output_dir=output_dir, + verbose=False, + nvtx_profile=nvtx_profile, + max_batch_size=max_batch_size, + use_cuda_graph=use_cuda_graph, + framework_model_dir=framework_model_dir, + engine_type=engine_type, + ) + + # Load TensorRT engines and pytorch modules + pipeline.backend.build_engines( + engine_dir, + framework_model_dir, + onnx_dir, + 17, + opt_image_height=height, + opt_image_width=width, + opt_batch_size=batch_size, + static_batch=True, + static_image_shape=True, + max_workspace_size=0, + device_id=torch.cuda.current_device(), + ) + + # Here we use static batch and image size, so the resource allocation only need done once. + # For dynamic batch and image size, some cost (like memory allocation) shall be included in latency. + pipeline.load_resources(height, width, batch_size) + + def warmup(): + prompt, negative = warmup_prompts() + pipeline.run([prompt] * batch_size, [negative] * batch_size, height, width, denoising_steps=steps) + + # Run warm up, and measure GPU memory of two runs + # The first run has algo search so it might need more memory + first_run_memory = measure_gpu_memory(memory_monitor_type, warmup, start_memory) + second_run_memory = measure_gpu_memory(memory_monitor_type, warmup, start_memory) + + warmup() + + image_filename_prefix = get_image_filename_prefix("ort_trt", short_name, batch_size, steps, disable_safety_checker) + + latency_list = [] + prompts, negative_prompt = example_prompts() + for i, prompt in enumerate(prompts): + if i >= num_prompts: + break + inference_start = time.time() + # Use warmup mode here since non-warmup mode will save image to disk. + images, pipeline_time = pipeline.run( + [prompt] * batch_size, + [negative_prompt] * batch_size, + height, + width, + denoising_steps=steps, + guidance=7.5, + seed=123, + ) + inference_end = time.time() + latency = inference_end - inference_start + latency_list.append(latency) + print(f"End2End took {latency:.3f} seconds. Inference latency: {pipeline_time}") + for k, image in enumerate(images): + image.save(f"{image_filename_prefix}_{i}_{k}.jpg") + + pipeline.teardown() + + from tensorrt import __version__ as trt_version # noqa: PLC0415 + + from onnxruntime import __version__ as ort_version # noqa: PLC0415 + + return { + "model_name": pipeline_info.name(), + "engine": "onnxruntime", + "version": ort_version, + "provider": f"tensorrt({trt_version})", + "directory": engine_dir, + "height": height, + "width": width, + "steps": steps, + "batch_size": batch_size, + "batch_count": batch_count, + "num_prompts": num_prompts, + "average_latency": sum(latency_list) / len(latency_list), + "median_latency": statistics.median(latency_list), + "first_run_memory_MB": first_run_memory, + "second_run_memory_MB": second_run_memory, + "disable_safety_checker": disable_safety_checker, + "enable_cuda_graph": use_cuda_graph, + } + + +def run_tensorrt_static( + work_dir: str, + version: str, + model_name: str, + batch_size: int, + disable_safety_checker: bool, + height: int, + width: int, + steps: int, + num_prompts: int, + batch_count: int, + start_memory, + memory_monitor_type, + max_batch_size: int, + nvtx_profile: bool = False, + use_cuda_graph: bool = True, + skip_warmup: bool = False, +): + print("[I] Initializing TensorRT accelerated StableDiffusionXL txt2img pipeline (static input shape)") + + from cuda import cudart # noqa: PLC0415 + + # Register TensorRT plugins + from trt_utilities import init_trt_plugins # noqa: PLC0415 + + init_trt_plugins() + + assert batch_size <= max_batch_size + + from diffusion_models import PipelineInfo # noqa: PLC0415 + + pipeline_info = PipelineInfo(version) + + from engine_builder import EngineType, get_engine_paths # noqa: PLC0415 + from pipeline_stable_diffusion import StableDiffusionPipeline # noqa: PLC0415 + + engine_type = EngineType.TRT + onnx_dir, engine_dir, output_dir, framework_model_dir, timing_cache = get_engine_paths( + work_dir, pipeline_info, engine_type + ) + + # Initialize pipeline + pipeline = StableDiffusionPipeline( + pipeline_info, + scheduler="DDIM", + output_dir=output_dir, + verbose=False, + nvtx_profile=nvtx_profile, + max_batch_size=max_batch_size, + use_cuda_graph=True, + engine_type=engine_type, + ) + + # Load TensorRT engines and pytorch modules + pipeline.backend.load_engines( + engine_dir=engine_dir, + framework_model_dir=framework_model_dir, + onnx_dir=onnx_dir, + onnx_opset=17, + opt_batch_size=batch_size, + opt_image_height=height, + opt_image_width=width, + static_batch=True, + static_shape=True, + enable_all_tactics=False, + timing_cache=timing_cache, + ) + + # activate engines + max_device_memory = max(pipeline.backend.max_device_memory(), pipeline.backend.max_device_memory()) + _, shared_device_memory = cudart.cudaMalloc(max_device_memory) + pipeline.backend.activate_engines(shared_device_memory) + + # Here we use static batch and image size, so the resource allocation only need done once. + # For dynamic batch and image size, some cost (like memory allocation) shall be included in latency. + pipeline.load_resources(height, width, batch_size) + + def warmup(): + if skip_warmup: + return + prompt, negative = warmup_prompts() + pipeline.run([prompt] * batch_size, [negative] * batch_size, height, width, denoising_steps=steps) + + # Run warm up, and measure GPU memory of two runs + # The first run has algo search so it might need more memory + first_run_memory = measure_gpu_memory(memory_monitor_type, warmup, start_memory) + second_run_memory = measure_gpu_memory(memory_monitor_type, warmup, start_memory) + + warmup() + + image_filename_prefix = get_image_filename_prefix("trt", model_name, batch_size, steps, disable_safety_checker) + + latency_list = [] + prompts, negative_prompt = example_prompts() + for i, prompt in enumerate(prompts): + if i >= num_prompts: + break + inference_start = time.time() + # Use warmup mode here since non-warmup mode will save image to disk. + images, pipeline_time = pipeline.run( + [prompt] * batch_size, + [negative_prompt] * batch_size, + height, + width, + denoising_steps=steps, + seed=123, + ) + inference_end = time.time() + latency = inference_end - inference_start + latency_list.append(latency) + print(f"End2End took {latency:.3f} seconds. Inference latency: {pipeline_time}") + for k, image in enumerate(images): + image.save(f"{image_filename_prefix}_{i}_{k}.jpg") + + pipeline.teardown() + + import tensorrt as trt # noqa: PLC0415 + + return { + "engine": "tensorrt", + "version": trt.__version__, + "provider": "default", + "height": height, + "width": width, + "steps": steps, + "batch_size": batch_size, + "batch_count": batch_count, + "num_prompts": num_prompts, + "average_latency": sum(latency_list) / len(latency_list), + "median_latency": statistics.median(latency_list), + "first_run_memory_MB": first_run_memory, + "second_run_memory_MB": second_run_memory, + "enable_cuda_graph": use_cuda_graph, + } + + +def run_tensorrt_static_xl( + work_dir: str, + version: str, + batch_size: int, + disable_safety_checker: bool, + height: int, + width: int, + steps: int, + num_prompts: int, + batch_count: int, + start_memory, + memory_monitor_type, + max_batch_size: int, + nvtx_profile: bool = False, + use_cuda_graph=True, + skip_warmup: bool = False, +): + print("[I] Initializing TensorRT accelerated StableDiffusionXL txt2img pipeline (static input shape)") + + import tensorrt as trt # noqa: PLC0415 + from cuda import cudart # noqa: PLC0415 + from trt_utilities import init_trt_plugins # noqa: PLC0415 + + # Validate image dimensions + image_height = height + image_width = width + if image_height % 8 != 0 or image_width % 8 != 0: + raise ValueError( + f"Image height and width have to be divisible by 8 but specified as: {image_height} and {image_width}." + ) + + # Register TensorRT plugins + init_trt_plugins() + + assert batch_size <= max_batch_size + + from diffusion_models import PipelineInfo # noqa: PLC0415 + from engine_builder import EngineType, get_engine_paths # noqa: PLC0415 + + def init_pipeline(pipeline_class, pipeline_info): + engine_type = EngineType.TRT + + onnx_dir, engine_dir, output_dir, framework_model_dir, timing_cache = get_engine_paths( + work_dir, pipeline_info, engine_type + ) + + # Initialize pipeline + pipeline = pipeline_class( + pipeline_info, + scheduler="DDIM", + output_dir=output_dir, + verbose=False, + nvtx_profile=nvtx_profile, + max_batch_size=max_batch_size, + use_cuda_graph=use_cuda_graph, + framework_model_dir=framework_model_dir, + engine_type=engine_type, + ) + + pipeline.backend.load_engines( + engine_dir=engine_dir, + framework_model_dir=framework_model_dir, + onnx_dir=onnx_dir, + onnx_opset=17, + opt_batch_size=batch_size, + opt_image_height=height, + opt_image_width=width, + static_batch=True, + static_shape=True, + enable_all_tactics=False, + timing_cache=timing_cache, + ) + return pipeline + + from pipeline_stable_diffusion import StableDiffusionPipeline # noqa: PLC0415 + + pipeline_info = PipelineInfo(version) + pipeline = init_pipeline(StableDiffusionPipeline, pipeline_info) + + max_device_memory = max(pipeline.backend.max_device_memory(), pipeline.backend.max_device_memory()) + _, shared_device_memory = cudart.cudaMalloc(max_device_memory) + pipeline.backend.activate_engines(shared_device_memory) + + # Here we use static batch and image size, so the resource allocation only need done once. + # For dynamic batch and image size, some cost (like memory allocation) shall be included in latency. + pipeline.load_resources(image_height, image_width, batch_size) + + def run_sd_xl_inference(prompt, negative_prompt, seed=None): + return pipeline.run( + prompt, + negative_prompt, + image_height, + image_width, + denoising_steps=steps, + guidance=5.0, + seed=seed, + ) + + def warmup(): + if skip_warmup: + return + prompt, negative = warmup_prompts() + run_sd_xl_inference([prompt] * batch_size, [negative] * batch_size) + + # Run warm up, and measure GPU memory of two runs + # The first run has algo search so it might need more memory + first_run_memory = measure_gpu_memory(memory_monitor_type, warmup, start_memory) + second_run_memory = measure_gpu_memory(memory_monitor_type, warmup, start_memory) + + warmup() + + model_name = pipeline_info.name() + image_filename_prefix = get_image_filename_prefix("trt", model_name, batch_size, steps, disable_safety_checker) + + latency_list = [] + prompts, negative_prompt = example_prompts() + for i, prompt in enumerate(prompts): + if i >= num_prompts: + break + inference_start = time.time() + # Use warmup mode here since non-warmup mode will save image to disk. + images, pipeline_time = run_sd_xl_inference([prompt] * batch_size, [negative_prompt] * batch_size, seed=123) + inference_end = time.time() + latency = inference_end - inference_start + latency_list.append(latency) + print(f"End2End took {latency:.3f} seconds. Inference latency: {pipeline_time}") + for k, image in enumerate(images): + image.save(f"{image_filename_prefix}_{i}_{k}.png") + + pipeline.teardown() + + return { + "model_name": model_name, + "engine": "tensorrt", + "version": trt.__version__, + "provider": "default", + "height": height, + "width": width, + "steps": steps, + "batch_size": batch_size, + "batch_count": batch_count, + "num_prompts": num_prompts, + "average_latency": sum(latency_list) / len(latency_list), + "median_latency": statistics.median(latency_list), + "first_run_memory_MB": first_run_memory, + "second_run_memory_MB": second_run_memory, + "enable_cuda_graph": use_cuda_graph, + } + + +def run_ort_trt_xl( + work_dir: str, + version: str, + batch_size: int, + disable_safety_checker: bool, + height: int, + width: int, + steps: int, + num_prompts: int, + batch_count: int, + start_memory, + memory_monitor_type, + max_batch_size: int, + nvtx_profile: bool = False, + use_cuda_graph=True, + skip_warmup: bool = False, +): + from demo_utils import initialize_pipeline # noqa: PLC0415 + from engine_builder import EngineType # noqa: PLC0415 + + pipeline = initialize_pipeline( + version=version, + engine_type=EngineType.ORT_TRT, + work_dir=work_dir, + height=height, + width=width, + use_cuda_graph=use_cuda_graph, + max_batch_size=max_batch_size, + opt_batch_size=batch_size, + ) + + assert batch_size <= max_batch_size + + pipeline.load_resources(height, width, batch_size) + + def run_sd_xl_inference(prompt, negative_prompt, seed=None): + return pipeline.run( + prompt, + negative_prompt, + height, + width, + denoising_steps=steps, + guidance=5.0, + seed=seed, + ) + + def warmup(): + if skip_warmup: + return + prompt, negative = warmup_prompts() + run_sd_xl_inference([prompt] * batch_size, [negative] * batch_size) + + # Run warm up, and measure GPU memory of two runs + # The first run has algo search so it might need more memory + first_run_memory = measure_gpu_memory(memory_monitor_type, warmup, start_memory) + second_run_memory = measure_gpu_memory(memory_monitor_type, warmup, start_memory) + + warmup() + + model_name = pipeline.pipeline_info.name() + image_filename_prefix = get_image_filename_prefix("ort_trt", model_name, batch_size, steps, disable_safety_checker) + + latency_list = [] + prompts, negative_prompt = example_prompts() + for i, prompt in enumerate(prompts): + if i >= num_prompts: + break + inference_start = time.time() + # Use warmup mode here since non-warmup mode will save image to disk. + images, pipeline_time = run_sd_xl_inference([prompt] * batch_size, [negative_prompt] * batch_size, seed=123) + inference_end = time.time() + latency = inference_end - inference_start + latency_list.append(latency) + print(f"End2End took {latency:.3f} seconds. Inference latency: {pipeline_time}") + for k, image in enumerate(images): + filename = f"{image_filename_prefix}_{i}_{k}.png" + image.save(filename) + print("Image saved to", filename) + + pipeline.teardown() + + from tensorrt import __version__ as trt_version # noqa: PLC0415 + + from onnxruntime import __version__ as ort_version # noqa: PLC0415 + + return { + "model_name": model_name, + "engine": "onnxruntime", + "version": ort_version, + "provider": f"tensorrt{trt_version})", + "height": height, + "width": width, + "steps": steps, + "batch_size": batch_size, + "batch_count": batch_count, + "num_prompts": num_prompts, + "average_latency": sum(latency_list) / len(latency_list), + "median_latency": statistics.median(latency_list), + "first_run_memory_MB": first_run_memory, + "second_run_memory_MB": second_run_memory, + "enable_cuda_graph": use_cuda_graph, + } + + +def run_torch( + model_name: str, + batch_size: int, + disable_safety_checker: bool, + enable_torch_compile: bool, + use_xformers: bool, + height: int, + width: int, + steps: int, + num_prompts: int, + batch_count: int, + start_memory, + memory_monitor_type, + skip_warmup: bool = True, +): + torch.backends.cudnn.enabled = True + torch.backends.cudnn.benchmark = True + + torch.set_grad_enabled(False) + + load_start = time.time() + pipe = get_torch_pipeline(model_name, disable_safety_checker, enable_torch_compile, use_xformers) + load_end = time.time() + print(f"Model loading took {load_end - load_start} seconds") + + image_filename_prefix = get_image_filename_prefix("torch", model_name, batch_size, steps, disable_safety_checker) + + if not enable_torch_compile: + with torch.inference_mode(): + result = run_torch_pipeline( + pipe, + batch_size, + image_filename_prefix, + height, + width, + steps, + num_prompts, + batch_count, + start_memory, + memory_monitor_type, + skip_warmup=skip_warmup, + ) + else: + result = run_torch_pipeline( + pipe, + batch_size, + image_filename_prefix, + height, + width, + steps, + num_prompts, + batch_count, + start_memory, + memory_monitor_type, + skip_warmup=skip_warmup, + ) + + result.update( + { + "model_name": model_name, + "directory": None, + "provider": "compile" if enable_torch_compile else "xformers" if use_xformers else "default", + "disable_safety_checker": disable_safety_checker, + "enable_cuda_graph": False, + } + ) + return result + + +def parse_arguments(): + parser = argparse.ArgumentParser() + + parser.add_argument( + "-e", + "--engine", + required=False, + type=str, + default="onnxruntime", + choices=["onnxruntime", "optimum", "torch", "tensorrt"], + help="Engines to benchmark. Default is onnxruntime.", + ) + + parser.add_argument( + "-r", + "--provider", + required=False, + type=str, + default="cuda", + choices=list(PROVIDERS.keys()), + help="Provider to benchmark. Default is CUDAExecutionProvider.", + ) + + parser.add_argument( + "-t", + "--tuning", + action="store_true", + help="Enable TunableOp and tuning. This will incur longer warmup latency.", + ) + + parser.add_argument( + "-v", + "--version", + required=False, + type=str, + choices=list(SD_MODELS.keys()), + default="1.5", + help="Stable diffusion version like 1.5, 2.0 or 2.1. Default is 1.5.", + ) + + parser.add_argument( + "-p", + "--pipeline", + required=False, + type=str, + default=None, + help="Directory of saved onnx pipeline. It could be the output directory of optimize_pipeline.py.", + ) + + parser.add_argument( + "-w", + "--work_dir", + required=False, + type=str, + default=".", + help="Root directory to save exported onnx models, built engines etc.", + ) + + parser.add_argument( + "--enable_safety_checker", + required=False, + action="store_true", + help="Enable safety checker", + ) + parser.set_defaults(enable_safety_checker=False) + + parser.add_argument( + "--enable_torch_compile", + required=False, + action="store_true", + help="Enable compile unet for PyTorch 2.0", + ) + parser.set_defaults(enable_torch_compile=False) + + parser.add_argument( + "--use_xformers", + required=False, + action="store_true", + help="Use xformers for PyTorch", + ) + parser.set_defaults(use_xformers=False) + + parser.add_argument( + "--use_io_binding", + required=False, + action="store_true", + help="Use I/O Binding for Optimum.", + ) + parser.set_defaults(use_io_binding=False) + + parser.add_argument( + "--skip_warmup", + required=False, + action="store_true", + help="No warmup.", + ) + parser.set_defaults(skip_warmup=False) + + parser.add_argument( + "-b", + "--batch_size", + type=int, + default=1, + choices=[1, 2, 3, 4, 8, 10, 16, 32], + help="Number of images per batch. Default is 1.", + ) + + parser.add_argument( + "--height", + required=False, + type=int, + default=512, + help="Output image height. Default is 512.", + ) + + parser.add_argument( + "--width", + required=False, + type=int, + default=512, + help="Output image width. Default is 512.", + ) + + parser.add_argument( + "-s", + "--steps", + required=False, + type=int, + default=50, + help="Number of steps. Default is 50.", + ) + + parser.add_argument( + "-n", + "--num_prompts", + required=False, + type=int, + default=10, + help="Number of prompts. Default is 10.", + ) + + parser.add_argument( + "-c", + "--batch_count", + required=False, + type=int, + choices=range(1, 11), + default=5, + help="Number of batches to test. Default is 5.", + ) + + parser.add_argument( + "-m", + "--max_trt_batch_size", + required=False, + type=int, + choices=range(1, 16), + default=4, + help="Maximum batch size for TensorRT. Change the value may trigger TensorRT engine rebuild. Default is 4.", + ) + + parser.add_argument( + "-g", + "--enable_cuda_graph", + required=False, + action="store_true", + help="Enable Cuda Graph. Requires onnxruntime >= 1.16", + ) + parser.set_defaults(enable_cuda_graph=False) + + args = parser.parse_args() + + return args + + +def print_loaded_libraries(cuda_related_only=True): + import psutil # noqa: PLC0415 + + p = psutil.Process(os.getpid()) + for lib in p.memory_maps(): + if (not cuda_related_only) or any(x in lib.path for x in ("libcu", "libnv", "tensorrt")): + print(lib.path) + + +def main(): + args = parse_arguments() + print(args) + + if args.engine == "onnxruntime": + if args.version in ["2.1"]: + # Set a flag to avoid overflow in attention, which causes black image output in SD 2.1 model. + # The environment variables shall be set before the first run of Attention or MultiHeadAttention operator. + os.environ["ORT_DISABLE_TRT_FLASH_ATTENTION"] = "1" + + from packaging import version # noqa: PLC0415 + + from onnxruntime import __version__ as ort_version # noqa: PLC0415 + + if version.parse(ort_version) == version.parse("1.16.0"): + # ORT 1.16 has a bug that might trigger Attention RuntimeError when latest fusion script is applied on clip model. + # The walkaround is to enable fused causal attention, or disable Attention fusion for clip model. + os.environ["ORT_ENABLE_FUSED_CAUSAL_ATTENTION"] = "1" + + if args.enable_cuda_graph: + if not (args.engine == "onnxruntime" and args.provider in ["cuda", "tensorrt"] and args.pipeline is None): + raise ValueError("The stable diffusion pipeline does not support CUDA graph.") + + if version.parse(ort_version) < version.parse("1.16"): + raise ValueError("CUDA graph requires ONNX Runtime 1.16 or later") + + logging.basicConfig(format="%(funcName)20s: %(message)s", level=logging.INFO, force=True) + + memory_monitor_type = "cuda" + + start_memory = measure_gpu_memory(memory_monitor_type, None) + print("GPU memory used before loading models:", start_memory) + + sd_model = SD_MODELS[args.version] + provider = PROVIDERS[args.provider] + if args.engine == "onnxruntime" and args.provider == "tensorrt": + if "xl" in args.version: + print("Testing Txt2ImgXLPipeline with static input shape. Backend is ORT TensorRT EP.") + result = run_ort_trt_xl( + work_dir=args.work_dir, + version=args.version, + batch_size=args.batch_size, + disable_safety_checker=True, + height=args.height, + width=args.width, + steps=args.steps, + num_prompts=args.num_prompts, + batch_count=args.batch_count, + start_memory=start_memory, + memory_monitor_type=memory_monitor_type, + max_batch_size=args.max_trt_batch_size, + nvtx_profile=False, + use_cuda_graph=args.enable_cuda_graph, + skip_warmup=args.skip_warmup, + ) + else: + print("Testing Txt2ImgPipeline with static input shape. Backend is ORT TensorRT EP.") + result = run_ort_trt_static( + work_dir=args.work_dir, + version=args.version, + batch_size=args.batch_size, + disable_safety_checker=not args.enable_safety_checker, + height=args.height, + width=args.width, + steps=args.steps, + num_prompts=args.num_prompts, + batch_count=args.batch_count, + start_memory=start_memory, + memory_monitor_type=memory_monitor_type, + max_batch_size=args.max_trt_batch_size, + nvtx_profile=False, + use_cuda_graph=args.enable_cuda_graph, + skip_warmup=args.skip_warmup, + ) + elif args.engine == "optimum" and provider == "CUDAExecutionProvider": + if "xl" in args.version: + os.environ["ORT_ENABLE_FUSED_CAUSAL_ATTENTION"] = "1" + + result = run_optimum_ort( + model_name=sd_model, + directory=args.pipeline, + provider=provider, + batch_size=args.batch_size, + disable_safety_checker=not args.enable_safety_checker, + height=args.height, + width=args.width, + steps=args.steps, + num_prompts=args.num_prompts, + batch_count=args.batch_count, + start_memory=start_memory, + memory_monitor_type=memory_monitor_type, + use_io_binding=args.use_io_binding, + skip_warmup=args.skip_warmup, + ) + elif args.engine == "onnxruntime": + assert args.pipeline and os.path.isdir(args.pipeline), ( + "--pipeline should be specified for the directory of ONNX models" + ) + print(f"Testing diffusers StableDiffusionPipeline with {provider} provider and tuning={args.tuning}") + result = run_ort( + model_name=sd_model, + directory=args.pipeline, + provider=provider, + batch_size=args.batch_size, + disable_safety_checker=not args.enable_safety_checker, + height=args.height, + width=args.width, + steps=args.steps, + num_prompts=args.num_prompts, + batch_count=args.batch_count, + start_memory=start_memory, + memory_monitor_type=memory_monitor_type, + tuning=args.tuning, + skip_warmup=args.skip_warmup, + ) + elif args.engine == "tensorrt" and "xl" in args.version: + print("Testing Txt2ImgXLPipeline with static input shape. Backend is TensorRT.") + result = run_tensorrt_static_xl( + work_dir=args.work_dir, + version=args.version, + batch_size=args.batch_size, + disable_safety_checker=True, + height=args.height, + width=args.width, + steps=args.steps, + num_prompts=args.num_prompts, + batch_count=args.batch_count, + start_memory=start_memory, + memory_monitor_type=memory_monitor_type, + max_batch_size=args.max_trt_batch_size, + nvtx_profile=False, + use_cuda_graph=args.enable_cuda_graph, + skip_warmup=args.skip_warmup, + ) + elif args.engine == "tensorrt": + print("Testing Txt2ImgPipeline with static input shape. Backend is TensorRT.") + result = run_tensorrt_static( + work_dir=args.work_dir, + version=args.version, + model_name=sd_model, + batch_size=args.batch_size, + disable_safety_checker=True, + height=args.height, + width=args.width, + steps=args.steps, + num_prompts=args.num_prompts, + batch_count=args.batch_count, + start_memory=start_memory, + memory_monitor_type=memory_monitor_type, + max_batch_size=args.max_trt_batch_size, + nvtx_profile=False, + use_cuda_graph=args.enable_cuda_graph, + skip_warmup=args.skip_warmup, + ) + else: + print( + f"Testing Txt2ImgPipeline with dynamic input shape. Backend is PyTorch: compile={args.enable_torch_compile}, xformers={args.use_xformers}." + ) + result = run_torch( + model_name=sd_model, + batch_size=args.batch_size, + disable_safety_checker=not args.enable_safety_checker, + enable_torch_compile=args.enable_torch_compile, + use_xformers=args.use_xformers, + height=args.height, + width=args.width, + steps=args.steps, + num_prompts=args.num_prompts, + batch_count=args.batch_count, + start_memory=start_memory, + memory_monitor_type=memory_monitor_type, + skip_warmup=args.skip_warmup, + ) + + print(result) + + with open("benchmark_result.csv", mode="a", newline="") as csv_file: + column_names = [ + "model_name", + "directory", + "engine", + "version", + "provider", + "disable_safety_checker", + "height", + "width", + "steps", + "batch_size", + "batch_count", + "num_prompts", + "average_latency", + "median_latency", + "first_run_memory_MB", + "second_run_memory_MB", + "enable_cuda_graph", + ] + csv_writer = csv.DictWriter(csv_file, fieldnames=column_names) + csv_writer.writeheader() + csv_writer.writerow(result) + + # Show loaded DLLs when steps == 1 for debugging purpose. + if args.steps == 1: + print_loaded_libraries(args.provider in ["cuda", "tensorrt"]) + + +if __name__ == "__main__": + import traceback + + try: + main() + except Exception: + traceback.print_exception(*sys.exc_info()) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/benchmark_controlnet.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/benchmark_controlnet.py new file mode 100644 index 0000000000000000000000000000000000000000..5d6b1cc1aea9cb07a798c756bf393d72e2379a3f --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/benchmark_controlnet.py @@ -0,0 +1,426 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +# -------------------------------------------------------------------------- + +import gc +import importlib.util +import time +from statistics import mean + +import torch +from demo_utils import PipelineInfo +from diffusers import ( + AutoencoderKL, + ControlNetModel, + DiffusionPipeline, + EulerAncestralDiscreteScheduler, + StableDiffusionXLControlNetPipeline, +) +from engine_builder import EngineType, get_engine_paths +from pipeline_stable_diffusion import StableDiffusionPipeline + +""" +Benchmark script for SDXL-Turbo with control net for engines like PyTorch or Stable Fast. + +Setup for Stable Fast (see https://github.com/chengzeyi/stable-fast/blob/main/README.md for more info): + git clone https://github.com/chengzeyi/stable-fast.git + cd stable-fast + git submodule update --init + pip3 install torch torchvision torchaudio ninja + pip3 install -e '.[dev,xformers,triton,transformers,diffusers]' -v + sudo apt install libgoogle-perftools-dev + export LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libtcmalloc.so +""" + + +def get_canny_image(): + import cv2 # noqa: PLC0415 + import numpy as np # noqa: PLC0415 + from PIL import Image # noqa: PLC0415 + + # Test Image can be downloaded from https://hf.co/datasets/huggingface/documentation-images/resolve/main/diffusers/input_image_vermeer.png + image = Image.open("input_image_vermeer.png").convert("RGB") + + image = np.array(image) + image = cv2.Canny(image, 100, 200) + image = image[:, :, None] + image = np.concatenate([image, image, image], axis=2) + return Image.fromarray(image) + + +def compile_stable_fast(pipeline, enable_cuda_graph=True): + from sfast.compilers.stable_diffusion_pipeline_compiler import CompilationConfig, compile # noqa: PLC0415 + + config = CompilationConfig.Default() + + if importlib.util.find_spec("xformers") is not None: + config.enable_xformers = True + + if importlib.util.find_spec("triton") is not None: + config.enable_triton = True + + config.enable_cuda_graph = enable_cuda_graph + + pipeline = compile(pipeline, config) + return pipeline + + +def compile_torch(pipeline, use_nhwc=False): + if use_nhwc: + pipeline.unet.to(memory_format=torch.channels_last) + + pipeline.unet = torch.compile(pipeline.unet, mode="reduce-overhead", fullgraph=True) + + if hasattr(pipeline, "controlnet"): + if use_nhwc: + pipeline.controlnet.to(memory_format=torch.channels_last) + pipeline.controlnet = torch.compile(pipeline.controlnet, mode="reduce-overhead", fullgraph=True) + return pipeline + + +def load_pipeline(name, engine, use_control_net=False, use_nhwc=False, enable_cuda_graph=True): + gc.collect() + torch.cuda.empty_cache() + before_memory = torch.cuda.memory_allocated() + + scheduler = EulerAncestralDiscreteScheduler.from_pretrained(name, subfolder="scheduler") + vae = AutoencoderKL.from_pretrained("madebyollin/sdxl-vae-fp16-fix", torch_dtype=torch.float16).to("cuda") + + if use_control_net: + assert "xl" in name + controlnet = ControlNetModel.from_pretrained("diffusers/controlnet-canny-sdxl-1.0", torch_dtype=torch.float16) + pipeline = StableDiffusionXLControlNetPipeline.from_pretrained( + name, + controlnet=controlnet, + vae=vae, + scheduler=scheduler, + variant="fp16", + use_safetensors=True, + torch_dtype=torch.float16, + ).to("cuda") + else: + pipeline = DiffusionPipeline.from_pretrained( + name, + vae=vae, + scheduler=scheduler, + variant="fp16", + use_safetensors=True, + torch_dtype=torch.float16, + ).to("cuda") + pipeline.safety_checker = None + + gc.collect() + after_memory = torch.cuda.memory_allocated() + print(f"Loaded model with {after_memory - before_memory} bytes allocated") + + if engine == "stable_fast": + pipeline = compile_stable_fast(pipeline, enable_cuda_graph=enable_cuda_graph) + elif engine == "torch": + pipeline = compile_torch(pipeline, use_nhwc=use_nhwc) + + pipeline.set_progress_bar_config(disable=True) + return pipeline + + +def get_prompt(): + return "little cute gremlin wearing a jacket, cinematic, vivid colors, intricate masterpiece, golden ratio, highly detailed" + + +def load_ort_cuda_pipeline(name, engine, use_control_net=False, enable_cuda_graph=True, work_dir="."): + version = PipelineInfo.supported_models()[name] + guidance_scale = 0.0 + pipeline_info = PipelineInfo( + version, + use_vae=True, + use_fp16_vae=True, + do_classifier_free_guidance=(guidance_scale > 1.0), + controlnet=["canny"] if use_control_net else [], + ) + + engine_type = EngineType.ORT_CUDA if engine == "ort_cuda" else EngineType.ORT_TRT + onnx_dir, engine_dir, output_dir, framework_model_dir, _ = get_engine_paths( + work_dir=work_dir, pipeline_info=pipeline_info, engine_type=engine_type + ) + + pipeline = StableDiffusionPipeline( + pipeline_info, + scheduler="EulerA", + max_batch_size=32, + use_cuda_graph=enable_cuda_graph, + framework_model_dir=framework_model_dir, + output_dir=output_dir, + engine_type=engine_type, + ) + + pipeline.backend.build_engines( + engine_dir=engine_dir, + framework_model_dir=framework_model_dir, + onnx_dir=onnx_dir, + device_id=torch.cuda.current_device(), + ) + + return pipeline + + +def test_ort_cuda( + pipeline, + batch_size=1, + steps=4, + control_image=None, + warmup_runs=3, + test_runs=10, + seed=123, + verbose=False, + image_height=512, + image_width=512, +): + if batch_size > 4 and pipeline.pipeline_info.version == "xl-1.0": + pipeline.backend.enable_vae_slicing() + + pipeline.load_resources(image_height, image_width, batch_size) + + warmup_prompt = "warm up" + for _ in range(warmup_runs): + images, _ = pipeline.run( + [warmup_prompt] * batch_size, + [""] * batch_size, + image_height=image_height, + image_width=image_width, + denoising_steps=steps, + guidance=0.0, + seed=seed, + controlnet_images=[control_image], + controlnet_scales=torch.FloatTensor([0.5]), + output_type="image", + ) + assert len(images) == batch_size + + generator = torch.Generator(device="cuda") + generator.manual_seed(seed) + + prompt = get_prompt() + + latency_list = [] + images = None + for _ in range(test_runs): + torch.cuda.synchronize() + start_time = time.perf_counter() + images, _ = pipeline.run( + [prompt] * batch_size, + [""] * batch_size, + image_height=image_height, + image_width=image_width, + denoising_steps=steps, + guidance=0.0, + seed=seed, + controlnet_images=[control_image], + controlnet_scales=torch.FloatTensor([0.5]), + output_type="pil", + ) + torch.cuda.synchronize() + seconds = time.perf_counter() - start_time + latency_list.append(seconds) + + if verbose: + print(latency_list) + + return images, latency_list + + +def test(pipeline, batch_size=1, steps=4, control_image=None, warmup_runs=3, test_runs=10, seed=123, verbose=False): + control_net_args = {} + if hasattr(pipeline, "controlnet"): + control_net_args = { + "image": control_image, + "controlnet_conditioning_scale": 0.5, + } + + warmup_prompt = "warm up" + for _ in range(warmup_runs): + images = pipeline( + prompt=warmup_prompt, + num_inference_steps=steps, + num_images_per_prompt=batch_size, + guidance_scale=0.0, + **control_net_args, + ).images + assert len(images) == batch_size + + generator = torch.Generator(device="cuda") + generator.manual_seed(seed) + + prompt = get_prompt() + + latency_list = [] + images = None + for _ in range(test_runs): + torch.cuda.synchronize() + start_time = time.perf_counter() + images = pipeline( + prompt=prompt, + num_inference_steps=steps, + num_images_per_prompt=batch_size, + guidance_scale=0.0, + generator=generator, + **control_net_args, + ).images + torch.cuda.synchronize() + seconds = time.perf_counter() - start_time + latency_list.append(seconds) + + if verbose: + print(latency_list) + + return images, latency_list + + +def arguments(): + import argparse # noqa: PLC0415 + + parser = argparse.ArgumentParser(description="Benchmark Stable Diffusion pipeline (optional control net for SDXL)") + parser.add_argument( + "--engine", + type=str, + default="torch", + choices=["torch", "stable_fast", "ort_cuda", "ort_trt"], + help="Backend engine: torch, stable_fast or ort_cuda", + ) + + parser.add_argument( + "--name", + type=str, + choices=list(PipelineInfo.supported_models().keys()), + default="stabilityai/sdxl-turbo", + help="Stable diffusion model name. Default is stabilityai/sdxl-turbo", + ) + + parser.add_argument( + "--work-dir", + type=str, + default=".", + help="working directory for ort_cuda or ort_trt", + ) + + parser.add_argument( + "--use_control_net", + action="store_true", + help="Use control net diffusers/controlnet-canny-sdxl-1.0", + ) + + parser.add_argument( + "--batch_size", + type=int, + default=1, + help="Batch size", + ) + + parser.add_argument( + "--steps", + type=int, + default=1, + help="Denoising steps", + ) + + parser.add_argument( + "--warmup_runs", + type=int, + default=3, + help="Number of warmup runs before measurement", + ) + + parser.add_argument( + "--use_nhwc", + action="store_true", + help="use channel last format for torch compile", + ) + + parser.add_argument( + "--enable_cuda_graph", + action="store_true", + help="enable cuda graph for stable fast", + ) + + parser.add_argument( + "--verbose", + action="store_true", + help="print more information", + ) + + args = parser.parse_args() + return args + + +def main(): + args = arguments() + + with torch.no_grad(): + if args.engine == "ort_cuda": + pipeline = load_ort_cuda_pipeline( + args.name, + args.engine, + use_control_net=args.use_control_net, + enable_cuda_graph=args.enable_cuda_graph, + work_dir=args.work_dir, + ) + else: + pipeline = load_pipeline( + args.name, + args.engine, + use_control_net=args.use_control_net, + use_nhwc=args.use_nhwc, + enable_cuda_graph=args.enable_cuda_graph, + ) + + canny_image = get_canny_image() + + if args.engine == "ort_cuda": + images, latency_list = test_ort_cuda( + pipeline, + args.batch_size, + args.steps, + control_image=canny_image, + warmup_runs=args.warmup_runs, + verbose=args.verbose, + ) + elif args.engine == "stable_fast": + from sfast.utils.compute_precision import low_compute_precision # noqa: PLC0415 + + with low_compute_precision(): + images, latency_list = test( + pipeline, + args.batch_size, + args.steps, + control_image=canny_image, + warmup_runs=args.warmup_runs, + verbose=args.verbose, + ) + else: + images, latency_list = test( + pipeline, + args.batch_size, + args.steps, + control_image=canny_image, + warmup_runs=args.warmup_runs, + verbose=args.verbose, + ) + + # Save the first output image to inspect the result. + if images: + images[0].save( + f"{args.engine}_{args.name.replace('/', '_')}_{args.batch_size}_{args.steps}_c{int(args.use_control_net)}.png" + ) + + result = { + "engine": args.engine, + "batch_size": args.batch_size, + "steps": args.steps, + "control_net": args.use_control_net, + "nhwc": args.use_nhwc, + "enable_cuda_graph": args.enable_cuda_graph, + "average_latency_in_ms": mean(latency_list) * 1000, + } + print(result) + + +main() diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/demo_txt2img.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/demo_txt2img.py new file mode 100644 index 0000000000000000000000000000000000000000..9db4eb0016c5a937c9cf2ce035d9f7074d2600ae --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/demo_txt2img.py @@ -0,0 +1,103 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +# -------------------------------------------------------------------------- +# Modified from TensorRT demo diffusion, which has the following license: +# +# SPDX-FileCopyrightText: Copyright (c) 1993-2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# -------------------------------------------------------------------------- + +import logging + +from cuda import cudart +from demo_utils import ( + add_controlnet_arguments, + arg_parser, + get_metadata, + load_pipelines, + parse_arguments, + process_controlnet_arguments, + repeat_prompt, +) + + +def main(args): + controlnet_images, controlnet_scale = process_controlnet_arguments(args) + + pipeline, refiner = load_pipelines(args) + assert refiner is None + + prompt, negative_prompt = repeat_prompt(args) + batch_size = len(prompt) + pipeline.load_resources(args.height, args.width, batch_size) + + def run_inference(warmup=False): + return pipeline.run( + prompt, + negative_prompt, + args.height, + args.width, + denoising_steps=args.denoising_steps, + guidance=args.guidance, + seed=args.seed, + controlnet_images=controlnet_images, + controlnet_scales=controlnet_scale, + show_latency=not warmup, + output_type="pil", + deterministic=args.deterministic, + ) + + if not args.disable_cuda_graph: + # inference once to get cuda graph + _, _ = run_inference(warmup=True) + + print("[I] Warming up ..") + for _ in range(args.num_warmup_runs): + _, _ = run_inference(warmup=True) + + print("[I] Running StableDiffusion pipeline") + if args.nvtx_profile: + cudart.cudaProfilerStart() + images, perf_data = run_inference(warmup=False) + if args.nvtx_profile: + cudart.cudaProfilerStop() + + metadata = get_metadata(args, False) + metadata.update(pipeline.metadata()) + if perf_data: + metadata.update(perf_data) + metadata["images"] = len(images) + print(metadata) + pipeline.save_images(images, prompt, negative_prompt, metadata) + + pipeline.teardown() + + +if __name__ == "__main__": + logging.basicConfig(format="%(funcName)20s: %(message)s", level=logging.INFO) + + parser = arg_parser("Options for Stable Diffusion Demo") + add_controlnet_arguments(parser) + args = parse_arguments(is_xl=False, parser=parser) + + if args.user_compute_stream: + import torch + + s = torch.cuda.Stream() + with torch.cuda.stream(s): + main(args) + else: + main(args) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/demo_txt2img_xl.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/demo_txt2img_xl.py new file mode 100644 index 0000000000000000000000000000000000000000..4c550923766545204fcb6b0874279334e77bcfc5 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/demo_txt2img_xl.py @@ -0,0 +1,269 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +# -------------------------------------------------------------------------- +# Modified from TensorRT demo diffusion, which has the following license: +# +# SPDX-FileCopyrightText: Copyright (c) 1993-2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# -------------------------------------------------------------------------- + +import logging + +from cuda import cudart +from demo_utils import ( + add_controlnet_arguments, + arg_parser, + get_metadata, + load_pipelines, + parse_arguments, + process_controlnet_arguments, + repeat_prompt, +) + + +def run_pipelines( + args, base, refiner, prompt, negative_prompt, controlnet_image=None, controlnet_scale=None, is_warm_up=False +): + image_height = args.height + image_width = args.width + batch_size = len(prompt) + base.load_resources(image_height, image_width, batch_size) + if refiner: + refiner.load_resources(image_height, image_width, batch_size) + + def run_base_and_refiner(warmup=False): + images, base_perf = base.run( + prompt, + negative_prompt, + image_height, + image_width, + denoising_steps=args.denoising_steps, + guidance=args.guidance, + seed=args.seed, + controlnet_images=controlnet_image, + controlnet_scales=controlnet_scale, + show_latency=not warmup, + output_type="latent" if refiner else "pil", + ) + if refiner is None: + return images, base_perf + + # Use same seed in base and refiner. + seed = base.get_current_seed() + + images, refiner_perf = refiner.run( + prompt, + negative_prompt, + image_height, + image_width, + denoising_steps=args.refiner_denoising_steps, + image=images, + strength=args.strength, + guidance=args.refiner_guidance, + seed=seed, + show_latency=not warmup, + ) + + perf_data = None + if base_perf and refiner_perf: + perf_data = {"latency": base_perf["latency"] + refiner_perf["latency"]} + perf_data.update({"base." + key: val for key, val in base_perf.items()}) + perf_data.update({"refiner." + key: val for key, val in refiner_perf.items()}) + + return images, perf_data + + if not args.disable_cuda_graph: + # inference once to get cuda graph + _, _ = run_base_and_refiner(warmup=True) + + if args.num_warmup_runs > 0: + print("[I] Warming up ..") + for _ in range(args.num_warmup_runs): + _, _ = run_base_and_refiner(warmup=True) + + if is_warm_up: + return + + print("[I] Running StableDiffusion XL pipeline") + if args.nvtx_profile: + cudart.cudaProfilerStart() + images, perf_data = run_base_and_refiner(warmup=False) + if args.nvtx_profile: + cudart.cudaProfilerStop() + + if refiner: + print("|----------------|--------------|") + print("| {:^14} | {:>9.2f} ms |".format("e2e", perf_data["latency"])) + print("|----------------|--------------|") + + metadata = get_metadata(args, True) + metadata.update({"base." + key: val for key, val in base.metadata().items()}) + if refiner: + metadata.update({"refiner." + key: val for key, val in refiner.metadata().items()}) + if perf_data: + metadata.update(perf_data) + metadata["images"] = len(images) + print(metadata) + (refiner or base).save_images(images, prompt, negative_prompt, metadata) + + +def run_demo(args): + """Run Stable Diffusion XL Base + Refiner together (known as ensemble of expert denoisers) to generate an image.""" + controlnet_image, controlnet_scale = process_controlnet_arguments(args) + prompt, negative_prompt = repeat_prompt(args) + batch_size = len(prompt) + base, refiner = load_pipelines(args, batch_size) + run_pipelines(args, base, refiner, prompt, negative_prompt, controlnet_image, controlnet_scale) + base.teardown() + if refiner: + refiner.teardown() + + +def run_dynamic_shape_demo(args): + """ + Run demo of generating images with different settings with ORT CUDA provider. + Try "python demo_txt2img_xl.py --max-cuda-graphs 3 --user-compute-stream" to see the effect of multiple CUDA graphs. + """ + args.engine = "ORT_CUDA" + base, refiner = load_pipelines(args, 1) + + prompts = [ + "starry night over Golden Gate Bridge by van gogh", + "beautiful photograph of Mt. Fuji during cherry blossom", + "little cute gremlin sitting on a bed, cinematic", + "cute grey cat with blue eyes, wearing a bowtie, acrylic painting", + "beautiful Renaissance Revival Estate, Hobbit-House, detailed painting, warm colors, 8k, trending on Artstation", + "blue owl, big green eyes, portrait, intricate metal design, unreal engine, octane render, realistic", + "An astronaut riding a rainbow unicorn, cinematic, dramatic", + "close-up photography of old man standing in the rain at night, in a street lit by lamps, leica 35mm", + ] + + # batch size, height, width, scheduler, steps, prompt, seed, guidance, refiner scheduler, refiner steps, refiner strength + configs = [ + (1, 832, 1216, "UniPC", 8, prompts[0], None, 5.0, "UniPC", 10, 0.3), + (1, 1024, 1024, "DDIM", 24, prompts[1], None, 5.0, "DDIM", 30, 0.3), + (1, 1216, 832, "EulerA", 16, prompts[2], 1716921396712843, 5.0, "EulerA", 10, 0.3), + (1, 1344, 768, "EulerA", 24, prompts[3], 123698071912362, 5.0, "EulerA", 20, 0.3), + (2, 640, 1536, "UniPC", 16, prompts[4], 4312973633252712, 5.0, "UniPC", 10, 0.3), + (2, 1152, 896, "DDIM", 24, prompts[5], 1964684802882906, 5.0, "UniPC", 20, 0.3), + ] + + # In testing LCM, refiner is disabled so the settings of refiner is not used. + if args.lcm: + configs = [ + (1, 1024, 1024, "LCM", 8, prompts[6], None, 1.0, "UniPC", 20, 0.3), + (1, 1216, 832, "LCM", 6, prompts[7], 1337, 1.0, "UniPC", 20, 0.3), + ] + + # Warm up each combination of (batch size, height, width) once before serving. + args.prompt = ["warm up"] + args.num_warmup_runs = 1 + for batch_size, height, width, _, _, _, _, _, _, _, _ in configs: + args.batch_size = batch_size + args.height = height + args.width = width + print(f"\nWarm up batch_size={batch_size}, height={height}, width={width}") + prompt, negative_prompt = repeat_prompt(args) + run_pipelines(args, base, refiner, prompt, negative_prompt, is_warm_up=True) + + # Run pipeline on a list of prompts. + args.num_warmup_runs = 0 + for ( + batch_size, + height, + width, + scheduler, + steps, + example_prompt, + seed, + guidance, + refiner_scheduler, + refiner_denoising_steps, + strength, + ) in configs: + args.prompt = [example_prompt] + args.batch_size = batch_size + args.height = height + args.width = width + args.scheduler = scheduler + args.denoising_steps = steps + args.seed = seed + args.guidance = guidance + args.refiner_scheduler = refiner_scheduler + args.refiner_denoising_steps = refiner_denoising_steps + args.strength = strength + base.set_scheduler(scheduler) + if refiner: + refiner.set_scheduler(refiner_scheduler) + prompt, negative_prompt = repeat_prompt(args) + run_pipelines(args, base, refiner, prompt, negative_prompt, is_warm_up=False) + + base.teardown() + if refiner: + refiner.teardown() + + +def run_turbo_demo(args): + """Run demo of generating images with test prompts with ORT CUDA provider.""" + args.engine = "ORT_CUDA" + base, refiner = load_pipelines(args, 1) + + from datasets import load_dataset # noqa: PLC0415 + + dataset = load_dataset("Gustavosta/Stable-Diffusion-Prompts") + num_rows = dataset["test"].num_rows + batch_size = args.batch_size + num_batch = int(num_rows / batch_size) + args.batch_size = 1 + for i in range(num_batch): + args.prompt = [dataset["test"][i]["Prompt"] for i in range(i * batch_size, (i + 1) * batch_size)] + base.set_scheduler(args.scheduler) + if refiner: + refiner.set_scheduler(args.refiner_scheduler) + prompt, negative_prompt = repeat_prompt(args) + run_pipelines(args, base, refiner, prompt, negative_prompt, is_warm_up=False) + + base.teardown() + if refiner: + refiner.teardown() + + +def main(args): + no_prompt = isinstance(args.prompt, list) and len(args.prompt) == 1 and not args.prompt[0] + if no_prompt: + if args.version == "xl-turbo": + run_turbo_demo(args) + else: + run_dynamic_shape_demo(args) + else: + run_demo(args) + + +if __name__ == "__main__": + logging.basicConfig(format="%(funcName)20s: %(message)s", level=logging.INFO) + + parser = arg_parser("Options for Stable Diffusion XL Demo") + add_controlnet_arguments(parser) + args = parse_arguments(is_xl=True, parser=parser) + + if args.user_compute_stream: + import torch + + s = torch.cuda.Stream() + with torch.cuda.stream(s): + main(args) + else: + main(args) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/demo_utils.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/demo_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..b7df106649fe04c8782e39bd2c943f952fff6cf6 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/demo_utils.py @@ -0,0 +1,778 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +# -------------------------------------------------------------------------- +# Modified from TensorRT demo diffusion, which has the following license: +# +# SPDX-FileCopyrightText: Copyright (c) 1993-2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# -------------------------------------------------------------------------- +import argparse +import os +import sys +from importlib.metadata import PackageNotFoundError, version +from typing import Any + +import controlnet_aux +import cv2 +import numpy as np +import torch +from cuda import cudart +from diffusion_models import PipelineInfo +from engine_builder import EngineType, get_engine_paths, get_engine_type +from PIL import Image +from pipeline_stable_diffusion import StableDiffusionPipeline + + +class RawTextArgumentDefaultsHelpFormatter(argparse.ArgumentDefaultsHelpFormatter, argparse.RawTextHelpFormatter): + pass + + +def arg_parser(description: str): + return argparse.ArgumentParser( + description=description, + formatter_class=RawTextArgumentDefaultsHelpFormatter, + ) + + +def set_default_arguments(args): + # set default value for some arguments if not provided + if args.height is None: + args.height = PipelineInfo.default_resolution(args.version) + + if args.width is None: + args.width = PipelineInfo.default_resolution(args.version) + + is_lcm = (args.version == "xl-1.0" and args.lcm) or "lcm" in args.lora_weights + is_turbo = args.version in ["sd-turbo", "xl-turbo"] + if args.denoising_steps is None: + args.denoising_steps = 4 if is_turbo else 8 if is_lcm else (30 if args.version == "xl-1.0" else 50) + + if args.scheduler is None: + args.scheduler = "LCM" if (is_lcm or is_turbo) else ("EulerA" if args.version == "xl-1.0" else "DDIM") + + if args.guidance is None: + args.guidance = 0.0 if (is_lcm or is_turbo) else (5.0 if args.version == "xl-1.0" else 7.5) + + +def parse_arguments(is_xl: bool, parser): + engines = ["ORT_CUDA", "ORT_TRT", "TRT", "TORCH"] + + parser.add_argument( + "-e", + "--engine", + type=str, + default=engines[0], + choices=engines, + help="Backend engine in {engines}. " + "ORT_CUDA is CUDA execution provider; ORT_TRT is Tensorrt execution provider; TRT is TensorRT", + ) + + supported_versions = PipelineInfo.supported_versions(is_xl) + parser.add_argument( + "-v", + "--version", + type=str, + default="xl-1.0" if is_xl else "1.5", + choices=supported_versions, + help="Version of Stable Diffusion" + (" XL." if is_xl else "."), + ) + + parser.add_argument( + "-y", + "--height", + type=int, + default=None, + help="Height of image to generate (must be multiple of 8).", + ) + parser.add_argument( + "-x", "--width", type=int, default=None, help="Height of image to generate (must be multiple of 8)." + ) + + parser.add_argument( + "-s", + "--scheduler", + type=str, + default=None, + choices=["DDIM", "EulerA", "UniPC", "LCM"], + help="Scheduler for diffusion process" + " of base" if is_xl else "", + ) + + parser.add_argument( + "-wd", + "--work-dir", + default=".", + help="Root Directory to store torch or ONNX models, built engines and output images etc.", + ) + + parser.add_argument( + "-i", + "--engine-dir", + default=None, + help="Root Directory to store built engines or optimized ONNX models etc.", + ) + + parser.add_argument("prompt", nargs="*", default=[""], help="Text prompt(s) to guide image generation.") + + parser.add_argument( + "-n", + "--negative-prompt", + nargs="*", + default=[""], + help="Optional negative prompt(s) to guide the image generation.", + ) + parser.add_argument( + "-b", + "--batch-size", + type=int, + default=1, + choices=[1, 2, 4, 8, 16], + help="Number of times to repeat the prompt (batch size multiplier).", + ) + + parser.add_argument( + "-d", + "--denoising-steps", + type=int, + default=None, + help="Number of denoising steps" + (" in base." if is_xl else "."), + ) + + parser.add_argument( + "-g", + "--guidance", + type=float, + default=None, + help="Higher guidance scale encourages to generate images that are closely linked to the text prompt.", + ) + + parser.add_argument( + "-ls", "--lora-scale", type=float, default=1, help="Scale of LoRA weights, default 1 (must between 0 and 1)" + ) + parser.add_argument("-lw", "--lora-weights", type=str, default="", help="LoRA weights to apply in the base model") + + if is_xl: + parser.add_argument( + "--lcm", + action="store_true", + help="Use fine-tuned latent consistency model to replace the UNet in base.", + ) + + parser.add_argument( + "-rs", + "--refiner-scheduler", + type=str, + default="EulerA", + choices=["DDIM", "EulerA", "UniPC"], + help="Scheduler for diffusion process of refiner.", + ) + + parser.add_argument( + "-rg", + "--refiner-guidance", + type=float, + default=5.0, + help="Guidance scale used in refiner.", + ) + + parser.add_argument( + "-rd", + "--refiner-denoising-steps", + type=int, + default=30, + help="Number of denoising steps in refiner. Note that actual steps is refiner_denoising_steps * strength.", + ) + + parser.add_argument( + "--strength", + type=float, + default=0.3, + help="A value between 0 and 1. The higher the value less the final image similar to the seed image.", + ) + + parser.add_argument( + "-r", + "--enable-refiner", + action="store_true", + help="Enable SDXL refiner to refine image from base pipeline.", + ) + + # ONNX export + parser.add_argument( + "--onnx-opset", + type=int, + default=None, + choices=range(14, 18), + help="Select ONNX opset version to target for exported models.", + ) + + # Engine build options. + parser.add_argument( + "-db", + "--build-dynamic-batch", + action="store_true", + help="Build TensorRT engines to support dynamic batch size.", + ) + parser.add_argument( + "-ds", + "--build-dynamic-shape", + action="store_true", + help="Build TensorRT engines to support dynamic image sizes.", + ) + parser.add_argument("--max-batch-size", type=int, default=None, choices=[1, 2, 4, 8, 16, 32], help="Max batch size") + + # Inference related options + parser.add_argument( + "-nw", "--num-warmup-runs", type=int, default=5, help="Number of warmup runs before benchmarking performance." + ) + parser.add_argument("--nvtx-profile", action="store_true", help="Enable NVTX markers for performance profiling.") + parser.add_argument("--seed", type=int, default=None, help="Seed for random generator to get consistent results.") + parser.add_argument("--deterministic", action="store_true", help="use deterministic algorithms.") + parser.add_argument("-dc", "--disable-cuda-graph", action="store_true", help="Disable cuda graph.") + + parser.add_argument("--framework-model-dir", default=None, help="framework model directory") + + group = parser.add_argument_group("Options for ORT_CUDA engine only") + group.add_argument("--enable-vae-slicing", action="store_true", help="True will feed only one image to VAE once.") + group.add_argument("--max-cuda-graphs", type=int, default=1, help="Max number of cuda graphs to use. Default 1.") + group.add_argument("--user-compute-stream", action="store_true", help="Use user compute stream.") + + # TensorRT only options + group = parser.add_argument_group("Options for TensorRT (--engine=TRT) only") + group.add_argument( + "--build-all-tactics", action="store_true", help="Build TensorRT engines using all tactic sources." + ) + + args = parser.parse_args() + + set_default_arguments(args) + + # Validate image dimensions + if args.height % 64 != 0 or args.width % 64 != 0: + raise ValueError( + f"Image height and width have to be divisible by 64 but specified as: {args.height} and {args.width}." + ) + + if (args.build_dynamic_batch or args.build_dynamic_shape) and not args.disable_cuda_graph: + print("[I] CUDA Graph is disabled since dynamic input shape is configured.") + args.disable_cuda_graph = True + + if args.onnx_opset is None: + args.onnx_opset = 14 if args.engine == "ORT_CUDA" else 17 + + if is_xl: + if args.version == "xl-turbo": + if args.lcm: + print("[I] sdxl-turbo cannot use with LCM.") + args.lcm = False + + assert args.strength > 0.0 and args.strength < 1.0 + + assert not (args.lcm and args.lora_weights), "it is not supported to use both lcm unet and Lora together" + + if args.scheduler == "LCM": + if args.guidance > 2.0: + print("[I] Use --guidance=0.0 (no more than 2.0) when LCM scheduler is used.") + args.guidance = 0.0 + if args.denoising_steps > 16: + print("[I] Use --denoising_steps=8 (no more than 16) when LCM scheduler is used.") + args.denoising_steps = 8 + + print(args) + + return args + + +def max_batch(args): + if args.max_batch_size: + max_batch_size = args.max_batch_size + else: + do_classifier_free_guidance = args.guidance > 1.0 + batch_multiplier = 2 if do_classifier_free_guidance else 1 + max_batch_size = 32 // batch_multiplier + if args.engine != "ORT_CUDA" and (args.build_dynamic_shape or args.height > 512 or args.width > 512): + max_batch_size = 8 // batch_multiplier + return max_batch_size + + +def get_metadata(args, is_xl: bool = False) -> dict[str, Any]: + metadata = { + "command": " ".join(['"' + x + '"' if " " in x else x for x in sys.argv]), + "args.prompt": args.prompt, + "args.negative_prompt": args.negative_prompt, + "args.batch_size": args.batch_size, + "height": args.height, + "width": args.width, + "cuda_graph": not args.disable_cuda_graph, + "vae_slicing": args.enable_vae_slicing, + "engine": args.engine, + } + + if args.lora_weights: + metadata["lora_weights"] = args.lora_weights + metadata["lora_scale"] = args.lora_scale + + if args.controlnet_type: + metadata["controlnet_type"] = args.controlnet_type + metadata["controlnet_scale"] = args.controlnet_scale + + if is_xl and args.enable_refiner: + metadata["base.scheduler"] = args.scheduler + metadata["base.denoising_steps"] = args.denoising_steps + metadata["base.guidance"] = args.guidance + metadata["refiner.strength"] = args.strength + metadata["refiner.scheduler"] = args.refiner_scheduler + metadata["refiner.denoising_steps"] = args.refiner_denoising_steps + metadata["refiner.guidance"] = args.refiner_guidance + else: + metadata["scheduler"] = args.scheduler + metadata["denoising_steps"] = args.denoising_steps + metadata["guidance"] = args.guidance + + # Version of installed python packages + packages = "" + for name in [ + "onnxruntime-gpu", + "torch", + "tensorrt", + "transformers", + "diffusers", + "onnx", + "onnx-graphsurgeon", + "polygraphy", + "controlnet_aux", + ]: + try: + packages += (" " if packages else "") + f"{name}=={version(name)}" + except PackageNotFoundError: + continue + metadata["packages"] = packages + metadata["device"] = torch.cuda.get_device_name() + metadata["torch.version.cuda"] = torch.version.cuda + + return metadata + + +def repeat_prompt(args): + if not isinstance(args.prompt, list): + raise ValueError(f"`prompt` must be of type `str` or `str` list, but is {type(args.prompt)}") + prompt = args.prompt * args.batch_size + + if not isinstance(args.negative_prompt, list): + raise ValueError( + f"`--negative-prompt` must be of type `str` or `str` list, but is {type(args.negative_prompt)}" + ) + + if len(args.negative_prompt) == 1: + negative_prompt = args.negative_prompt * len(prompt) + else: + negative_prompt = args.negative_prompt + + return prompt, negative_prompt + + +def initialize_pipeline( + version="xl-turbo", + is_refiner: bool = False, + is_inpaint: bool = False, + engine_type=EngineType.ORT_CUDA, + work_dir: str = ".", + engine_dir=None, + onnx_opset: int = 17, + scheduler="EulerA", + height=512, + width=512, + nvtx_profile=False, + use_cuda_graph=True, + build_dynamic_batch=False, + build_dynamic_shape=False, + min_image_size: int = 512, + max_image_size: int = 1024, + max_batch_size: int = 16, + opt_batch_size: int = 1, + build_all_tactics: bool = False, + do_classifier_free_guidance: bool = False, + lcm: bool = False, + controlnet=None, + lora_weights=None, + lora_scale: float = 1.0, + use_fp16_vae: bool = True, + use_vae: bool = True, + framework_model_dir: str | None = None, + max_cuda_graphs: int = 1, +): + pipeline_info = PipelineInfo( + version, + is_refiner=is_refiner, + is_inpaint=is_inpaint, + use_vae=use_vae, + min_image_size=min_image_size, + max_image_size=max_image_size, + use_fp16_vae=use_fp16_vae, + use_lcm=lcm, + do_classifier_free_guidance=do_classifier_free_guidance, + controlnet=controlnet, + lora_weights=lora_weights, + lora_scale=lora_scale, + ) + + input_engine_dir = engine_dir + + onnx_dir, engine_dir, output_dir, framework_model_dir, timing_cache = get_engine_paths( + work_dir=work_dir, pipeline_info=pipeline_info, engine_type=engine_type, framework_model_dir=framework_model_dir + ) + + pipeline = StableDiffusionPipeline( + pipeline_info, + scheduler=scheduler, + output_dir=output_dir, + verbose=False, + nvtx_profile=nvtx_profile, + max_batch_size=max_batch_size, + use_cuda_graph=use_cuda_graph, + framework_model_dir=framework_model_dir, + engine_type=engine_type, + ) + + import_engine_dir = None + if input_engine_dir: + if not os.path.exists(input_engine_dir): + raise RuntimeError(f"--engine_dir directory does not exist: {input_engine_dir}") + + # Support importing from optimized diffusers onnx pipeline + if engine_type == EngineType.ORT_CUDA and os.path.exists(os.path.join(input_engine_dir, "model_index.json")): + import_engine_dir = input_engine_dir + else: + engine_dir = input_engine_dir + + opt_image_height = pipeline_info.default_image_size() if build_dynamic_shape else height + opt_image_width = pipeline_info.default_image_size() if build_dynamic_shape else width + + if engine_type == EngineType.ORT_CUDA: + pipeline.backend.build_engines( + engine_dir=engine_dir, + framework_model_dir=framework_model_dir, + onnx_dir=onnx_dir, + tmp_dir=os.path.join(work_dir or ".", engine_type.name, pipeline_info.short_name(), "tmp"), + device_id=torch.cuda.current_device(), + import_engine_dir=import_engine_dir, + max_cuda_graphs=max_cuda_graphs, + ) + elif engine_type == EngineType.ORT_TRT: + pipeline.backend.build_engines( + engine_dir, + framework_model_dir, + onnx_dir, + onnx_opset, + opt_image_height=opt_image_height, + opt_image_width=opt_image_width, + opt_batch_size=opt_batch_size, + static_batch=not build_dynamic_batch, + static_image_shape=not build_dynamic_shape, + max_workspace_size=0, + device_id=torch.cuda.current_device(), + timing_cache=timing_cache, + ) + elif engine_type == EngineType.TRT: + pipeline.backend.load_engines( + engine_dir, + framework_model_dir, + onnx_dir, + onnx_opset, + opt_batch_size=opt_batch_size, + opt_image_height=opt_image_height, + opt_image_width=opt_image_width, + static_batch=not build_dynamic_batch, + static_shape=not build_dynamic_shape, + enable_all_tactics=build_all_tactics, + timing_cache=timing_cache, + ) + elif engine_type == EngineType.TORCH: + pipeline.backend.build_engines(framework_model_dir) + else: + raise RuntimeError("invalid engine type") + + return pipeline + + +def load_pipelines(args, batch_size=None): + engine_type = get_engine_type(args.engine) + + # Register TensorRT plugins + if engine_type == EngineType.TRT: + from trt_utilities import init_trt_plugins # noqa: PLC0415 + + init_trt_plugins() + + max_batch_size = max_batch(args) + + if batch_size is None: + assert isinstance(args.prompt, list) + batch_size = len(args.prompt) * args.batch_size + + if batch_size > max_batch_size: + raise ValueError(f"Batch size {batch_size} is larger than allowed {max_batch_size}.") + + # For TensorRT, performance of engine built with dynamic shape is very sensitive to the range of image size. + # Here, we reduce the range of image size for TensorRT to trade-off flexibility and performance. + # This range can cover most frequent shape of landscape (832x1216), portrait (1216x832) or square (1024x1024). + if args.version == "xl-turbo": + min_image_size = 512 + max_image_size = 768 if args.engine != "ORT_CUDA" else 1024 + elif args.version == "xl-1.0": + min_image_size = 832 if args.engine != "ORT_CUDA" else 512 + max_image_size = 1216 if args.engine != "ORT_CUDA" else 2048 + else: + # This range can cover common used shape of landscape 512x768, portrait 768x512, or square 512x512 and 768x768. + min_image_size = 512 if args.engine != "ORT_CUDA" else 256 + max_image_size = 768 if args.engine != "ORT_CUDA" else 1024 + + params = { + "version": args.version, + "is_refiner": False, + "is_inpaint": False, + "engine_type": engine_type, + "work_dir": args.work_dir, + "engine_dir": args.engine_dir, + "onnx_opset": args.onnx_opset, + "scheduler": args.scheduler, + "height": args.height, + "width": args.width, + "nvtx_profile": args.nvtx_profile, + "use_cuda_graph": not args.disable_cuda_graph, + "build_dynamic_batch": args.build_dynamic_batch, + "build_dynamic_shape": args.build_dynamic_shape, + "min_image_size": min_image_size, + "max_image_size": max_image_size, + "max_batch_size": max_batch_size, + "opt_batch_size": 1 if args.build_dynamic_batch else batch_size, + "build_all_tactics": args.build_all_tactics, + "do_classifier_free_guidance": args.guidance > 1.0, + "controlnet": args.controlnet_type, + "lora_weights": args.lora_weights, + "lora_scale": args.lora_scale, + "use_fp16_vae": "xl" in args.version, + "use_vae": True, + "framework_model_dir": args.framework_model_dir, + "max_cuda_graphs": args.max_cuda_graphs, + } + + if "xl" in args.version: + params["lcm"] = args.lcm + params["use_vae"] = not args.enable_refiner + base = initialize_pipeline(**params) + + refiner = None + if "xl" in args.version and args.enable_refiner: + params["version"] = "xl-1.0" # Allow SDXL Turbo to use refiner. + params["is_refiner"] = True + params["scheduler"] = args.refiner_scheduler + params["do_classifier_free_guidance"] = args.refiner_guidance > 1.0 + params["lcm"] = False + params["controlnet"] = None + params["lora_weights"] = None + params["use_vae"] = True + params["use_fp16_vae"] = True + refiner = initialize_pipeline(**params) + + if engine_type == EngineType.TRT: + max_device_memory = max(base.backend.max_device_memory(), (refiner or base).backend.max_device_memory()) + _, shared_device_memory = cudart.cudaMalloc(max_device_memory) + base.backend.activate_engines(shared_device_memory) + if refiner: + refiner.backend.activate_engines(shared_device_memory) + + if engine_type == EngineType.ORT_CUDA: + enable_vae_slicing = args.enable_vae_slicing + if batch_size > 4 and not enable_vae_slicing and (args.height >= 1024 and args.width >= 1024): + print( + "Updating enable_vae_slicing to be True to avoid cuDNN error for batch size > 4 and resolution >= 1024." + ) + enable_vae_slicing = True + if enable_vae_slicing: + (refiner or base).backend.enable_vae_slicing() + return base, refiner + + +def get_depth_image(image): + """ + Create depth map for SDXL depth control net. + """ + from transformers import DPTFeatureExtractor, DPTForDepthEstimation # noqa: PLC0415 + + depth_estimator = DPTForDepthEstimation.from_pretrained("Intel/dpt-hybrid-midas").to("cuda") + feature_extractor = DPTFeatureExtractor.from_pretrained("Intel/dpt-hybrid-midas") + + image = feature_extractor(images=image, return_tensors="pt").pixel_values.to("cuda") + with torch.no_grad(), torch.autocast("cuda"): + depth_map = depth_estimator(image).predicted_depth + + # The depth map is 384x384 by default, here we interpolate to the default output size. + # Note that it will be resized to output image size later. May change the size here to avoid interpolate twice. + depth_map = torch.nn.functional.interpolate( + depth_map.unsqueeze(1), + size=(1024, 1024), + mode="bicubic", + align_corners=False, + ) + depth_min = torch.amin(depth_map, dim=[1, 2, 3], keepdim=True) + depth_max = torch.amax(depth_map, dim=[1, 2, 3], keepdim=True) + depth_map = (depth_map - depth_min) / (depth_max - depth_min) + image = torch.cat([depth_map] * 3, dim=1) + + image = image.permute(0, 2, 3, 1).cpu().numpy()[0] + image = Image.fromarray((image * 255.0).clip(0, 255).astype(np.uint8)) + return image + + +def get_canny_image(image) -> Image.Image: + """ + Create canny image for SDXL control net. + """ + image = np.array(image) + image = cv2.Canny(image, 100, 200) + image = image[:, :, None] + image = np.concatenate([image, image, image], axis=2) + image = Image.fromarray(image) + return image + + +def process_controlnet_images_xl(args) -> list[Image.Image]: + """ + Process control image for SDXL control net. + """ + assert len(args.controlnet_image) == 1 + image = Image.open(args.controlnet_image[0]).convert("RGB") + + controlnet_images = [] + if args.controlnet_type[0] == "canny": + controlnet_images.append(get_canny_image(image)) + elif args.controlnet_type[0] == "depth": + controlnet_images.append(get_depth_image(image)) + else: + raise ValueError(f"This controlnet type is not supported for SDXL or Turbo: {args.controlnet_type}.") + + return controlnet_images + + +def add_controlnet_arguments(parser, is_xl: bool = False): + """ + Add control net related arguments. + """ + group = parser.add_argument_group("Options for ControlNet (supports 1.5, sd-turbo, xl-turbo, xl-1.0).") + + group.add_argument( + "-ci", + "--controlnet-image", + nargs="*", + type=str, + default=[], + help="Path to the input regular RGB image/images for controlnet", + ) + group.add_argument( + "-ct", + "--controlnet-type", + nargs="*", + type=str, + default=[], + choices=list(PipelineInfo.supported_controlnet("xl-1.0" if is_xl else "1.5").keys()), + help="A list of controlnet type", + ) + group.add_argument( + "-cs", + "--controlnet-scale", + nargs="*", + type=float, + default=[], + help="The outputs of the controlnet are multiplied by `controlnet_scale` before they are added to the residual in the original unet. Default is 0.5 for SDXL, or 1.0 for SD 1.5", + ) + + +def process_controlnet_image(controlnet_type: str, image: Image.Image, height, width): + """ + Process control images of control net v1.1 for Stable Diffusion 1.5. + """ + control_image = None + shape = (height, width) + image = image.convert("RGB") + if controlnet_type == "canny": + canny_image = controlnet_aux.CannyDetector()(image) + control_image = canny_image.resize(shape) + elif controlnet_type == "normalbae": + normal_image = controlnet_aux.NormalBaeDetector.from_pretrained("lllyasviel/Annotators")(image) + control_image = normal_image.resize(shape) + elif controlnet_type == "depth": + depth_image = controlnet_aux.LeresDetector.from_pretrained("lllyasviel/Annotators")(image) + control_image = depth_image.resize(shape) + elif controlnet_type == "mlsd": + mlsd_image = controlnet_aux.MLSDdetector.from_pretrained("lllyasviel/Annotators")(image) + control_image = mlsd_image.resize(shape) + elif controlnet_type == "openpose": + openpose_image = controlnet_aux.OpenposeDetector.from_pretrained("lllyasviel/Annotators")(image) + control_image = openpose_image.resize(shape) + elif controlnet_type == "scribble": + scribble_image = controlnet_aux.HEDdetector.from_pretrained("lllyasviel/Annotators")(image, scribble=True) + control_image = scribble_image.resize(shape) + elif controlnet_type == "seg": + seg_image = controlnet_aux.SamDetector.from_pretrained("ybelkada/segment-anything", subfolder="checkpoints")( + image + ) + control_image = seg_image.resize(shape) + else: + raise ValueError(f"There is no demo image of this controlnet_type: {controlnet_type}") + return control_image + + +def process_controlnet_arguments(args): + """ + Process control net arguments, and returns a list of control images and a tensor of control net scales. + """ + assert isinstance(args.controlnet_type, list) + assert isinstance(args.controlnet_scale, list) + assert isinstance(args.controlnet_image, list) + + if len(args.controlnet_image) != len(args.controlnet_type): + raise ValueError( + f"Numbers of controlnet_image {len(args.controlnet_image)} should be equal to number of controlnet_type {len(args.controlnet_type)}." + ) + + if len(args.controlnet_type) == 0: + return None, None + + if args.version not in ["1.5", "xl-1.0", "xl-turbo", "sd-turbo"]: + raise ValueError("This demo only supports ControlNet in Stable Diffusion 1.5, XL or Turbo.") + + is_xl = "xl" in args.version + if is_xl and len(args.controlnet_type) > 1: + raise ValueError("This demo only support one ControlNet for Stable Diffusion XL or Turbo.") + + if len(args.controlnet_scale) == 0: + args.controlnet_scale = [0.5 if is_xl else 1.0] * len(args.controlnet_type) + elif len(args.controlnet_type) != len(args.controlnet_scale): + raise ValueError( + f"Numbers of controlnet_type {len(args.controlnet_type)} should be equal to number of controlnet_scale {len(args.controlnet_scale)}." + ) + + # Convert controlnet scales to tensor + controlnet_scale = torch.FloatTensor(args.controlnet_scale) + + if is_xl: + images = process_controlnet_images_xl(args) + else: + images = [] + for i, image in enumerate(args.controlnet_image): + images.append(process_controlnet_image(args.controlnet_type[i], Image.open(image), args.height, args.width)) + + return images, controlnet_scale diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/diffusion_models.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/diffusion_models.py new file mode 100644 index 0000000000000000000000000000000000000000..302c6fe980c3f6e8d98896015c138669769dc605 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/diffusion_models.py @@ -0,0 +1,1318 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +# -------------------------------------------------------------------------- +# Modified from stable_diffusion_tensorrt_txt2img.py in diffusers and TensorRT demo diffusion, +# which has the following license: +# +# Copyright 2023 The HuggingFace Inc. team. +# SPDX-FileCopyrightText: Copyright (c) 1993-2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import logging +import os +import tempfile + +import onnx +import onnx_graphsurgeon as gs +import torch +from diffusers.models import AutoencoderKL, ControlNetModel, UNet2DConditionModel +from onnx import GraphProto, ModelProto, shape_inference +from ort_optimizer import OrtStableDiffusionOptimizer +from polygraphy.backend.onnx.loader import fold_constants +from transformers import CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer + +from onnxruntime.transformers.onnx_model import OnnxModel + +logger = logging.getLogger(__name__) + + +class TrtOptimizer: + def __init__(self, onnx_graph): + self.graph = gs.import_onnx(onnx_graph) + + def cleanup(self): + self.graph.cleanup().toposort() + + def get_optimized_onnx_graph(self): + return gs.export_onnx(self.graph) + + def select_outputs(self, keep, names=None): + self.graph.outputs = [self.graph.outputs[o] for o in keep] + if names: + for i, name in enumerate(names): + self.graph.outputs[i].name = name + + def fold_constants(self): + onnx_graph = fold_constants(gs.export_onnx(self.graph), allow_onnxruntime_shape_inference=True) + self.graph = gs.import_onnx(onnx_graph) + + def infer_shapes(self): + onnx_graph = gs.export_onnx(self.graph) + if onnx_graph.ByteSize() >= onnx.checker.MAXIMUM_PROTOBUF: + with tempfile.TemporaryDirectory() as temp_dir: + input_onnx_path = os.path.join(temp_dir, "model.onnx") + onnx.save_model( + onnx_graph, + input_onnx_path, + save_as_external_data=True, + all_tensors_to_one_file=True, + convert_attribute=False, + ) + output_onnx_path = os.path.join(temp_dir, "model_with_shape.onnx") + onnx.shape_inference.infer_shapes_path(input_onnx_path, output_onnx_path) + onnx_graph = onnx.load(output_onnx_path) + else: + onnx_graph = shape_inference.infer_shapes(onnx_graph) + + self.graph = gs.import_onnx(onnx_graph) + + +class PipelineInfo: + def __init__( + self, + version: str, + is_inpaint: bool = False, + is_refiner: bool = False, + use_vae=True, # TODO: this has couple with output type of pipeline + min_image_size=256, + max_image_size=1024, + use_fp16_vae=True, + use_lcm=False, + do_classifier_free_guidance=True, + controlnet=None, + lora_weights=None, + lora_scale=1.0, + ): + self.version = version + self._is_inpaint = is_inpaint + self._is_refiner = is_refiner + self._use_vae = use_vae + self._min_image_size = min_image_size + self._max_image_size = max_image_size + self._use_fp16_vae = use_fp16_vae + self._use_lcm = use_lcm + self.do_classifier_free_guidance = do_classifier_free_guidance and not use_lcm + self.controlnet = controlnet # A list of control net type + self.lora_weights = lora_weights + self.lora_scale = lora_scale + + if is_refiner: + assert not use_lcm + assert self.is_xl() + + def is_inpaint(self) -> bool: + return self._is_inpaint + + def is_xl(self) -> bool: + return "xl" in self.version + + def is_xl_turbo(self) -> bool: + return self.version == "xl-turbo" + + def is_xl_base(self) -> bool: + return self.version == "xl-1.0" and not self._is_refiner + + def is_xl_base_or_turbo(self) -> bool: + return self.is_xl_base() or self.is_xl_turbo() + + def is_xl_refiner(self) -> bool: + return self.version == "xl-1.0" and self._is_refiner + + def use_safetensors(self) -> bool: + return self.is_xl() or self.version in ["sd-turbo"] + + def stages(self) -> list[str]: + if self.is_xl_base_or_turbo(): + return ["clip", "clip2", "unetxl"] + (["vae"] if self._use_vae else []) + + if self.is_xl_refiner(): + return ["clip2", "unetxl", "vae"] + + return ["clip", "unet", "vae"] + + def vae_scaling_factor(self) -> float: + return 0.13025 if self.is_xl() else 0.18215 + + def vae_torch_fallback(self) -> bool: + return self.is_xl() and not self._use_fp16_vae + + def custom_fp16_vae(self) -> str | None: + # For SD XL, use a VAE that fine-tuned to run in fp16 precision without generating NaNs + return "madebyollin/sdxl-vae-fp16-fix" if self._use_fp16_vae and self.is_xl() else None + + def custom_unet(self) -> str | None: + return "latent-consistency/lcm-sdxl" if self._use_lcm and self.is_xl_base() else None + + @staticmethod + def supported_versions(is_xl: bool): + return ["xl-1.0", "xl-turbo"] if is_xl else ["1.4", "1.5", "2.0-base", "2.0", "2.1", "2.1-base", "sd-turbo"] + + @staticmethod + def supported_models(): + return { + "CompVis/stable-diffusion-v1-4": "1.4", + "runwayml/stable-diffusion-v1-5": "1.5", + "stabilityai/stable-diffusion-2-base": "2.0-base", + "stabilityai/stable-diffusion-2": "2.0", + "stabilityai/stable-diffusion-2-1": "2.1", + "stabilityai/stable-diffusion-2-1-base": "2.1", + "stabilityai/stable-diffusion-xl-base-1.0": "xl-1.0", + "stabilityai/stable-diffusion-xl-refiner-1.0": "xl-1.0", + "stabilityai/sdxl-turbo": "xl-turbo", + "stabilityai/sd-turbo": "sd-turbo", + # "runwayml/stable-diffusion-inpainting": "1.5", + # "stabilityai/stable-diffusion-2-inpainting": "2.0", + } + + def name(self) -> str: + if self.version == "1.4": + if self.is_inpaint(): + return "runwayml/stable-diffusion-inpainting" + else: + return "CompVis/stable-diffusion-v1-4" + elif self.version == "1.5": + if self.is_inpaint(): + return "runwayml/stable-diffusion-inpainting" + else: + return "runwayml/stable-diffusion-v1-5" + elif self.version == "2.0-base": + if self.is_inpaint(): + return "stabilityai/stable-diffusion-2-inpainting" + else: + return "stabilityai/stable-diffusion-2-base" + elif self.version == "2.0": + if self.is_inpaint(): + return "stabilityai/stable-diffusion-2-inpainting" + else: + return "stabilityai/stable-diffusion-2" + elif self.version == "2.1": + return "stabilityai/stable-diffusion-2-1" + elif self.version == "2.1-base": + return "stabilityai/stable-diffusion-2-1-base" + elif self.version == "xl-1.0": + if self.is_xl_refiner(): + return "stabilityai/stable-diffusion-xl-refiner-1.0" + else: + return "stabilityai/stable-diffusion-xl-base-1.0" + elif self.version == "xl-turbo": + return "stabilityai/sdxl-turbo" + elif self.version == "sd-turbo": + return "stabilityai/sd-turbo" + + raise ValueError(f"Incorrect version {self.version}") + + def short_name(self) -> str: + return self.name().split("/")[-1].replace("stable-diffusion", "sd") + + def clip_embedding_dim(self): + # TODO: can we read from config instead + if self.version in ("1.4", "1.5"): + return 768 + elif self.version in ("2.0", "2.0-base", "2.1", "2.1-base", "sd-turbo"): + return 1024 + elif self.is_xl_base_or_turbo(): + return 768 + else: + raise ValueError(f"Invalid version {self.version}") + + def clipwithproj_embedding_dim(self): + if self.is_xl(): + return 1280 + else: + raise ValueError(f"Invalid version {self.version}") + + def unet_embedding_dim(self): + if self.version in ("1.4", "1.5"): + return 768 + elif self.version in ("2.0", "2.0-base", "2.1", "2.1-base", "sd-turbo"): + return 1024 + elif self.is_xl_base_or_turbo(): + return 2048 + elif self.is_xl_refiner(): + return 1280 + else: + raise ValueError(f"Invalid version {self.version}") + + def min_image_size(self): + return self._min_image_size + + def max_image_size(self): + return self._max_image_size + + @staticmethod + def default_resolution(version: str) -> int: + if version == "xl-1.0": + return 1024 + if version in ("2.0", "2.1"): + return 768 + return 512 + + def default_image_size(self) -> int: + return PipelineInfo.default_resolution(self.version) + + @staticmethod + def supported_controlnet(version="1.5"): + if version in ("xl-1.0", "xl-turbo"): + return { + "canny": "diffusers/controlnet-canny-sdxl-1.0", + "depth": "diffusers/controlnet-depth-sdxl-1.0", + } + elif version == "1.5": + return { + "canny": "lllyasviel/control_v11p_sd15_canny", + "depth": "lllyasviel/control_v11f1p_sd15_depth", + "openpose": "lllyasviel/control_v11p_sd15_openpose", + # "tile": "lllyasviel/control_v11f1e_sd15_tile", + # "lineart": "lllyasviel/control_v11p_sd15_lineart", + # "inpaint": "lllyasviel/control_v11p_sd15_inpaint", + # "softedge": "lllyasviel/control_v11p_sd15_softedge", + "mlsd": "lllyasviel/control_v11p_sd15_mlsd", + "scribble": "lllyasviel/control_v11p_sd15_scribble", + # "ip2p": "lllyasviel/control_v11e_sd15_ip2p", + "normalbae": "lllyasviel/control_v11p_sd15_normalbae", + "seg": "lllyasviel/control_v11p_sd15_seg", + # "shuffle": "lllyasviel/control_v11e_sd15_shuffle", + # "lineart_anime": "lllyasviel/control_v11p_sd15s2_lineart_anime", + } + return None + + def controlnet_name(self): + """Return a list of controlnet name""" + if not self.controlnet: + return None + controlnet_map = PipelineInfo.supported_controlnet(self.version) + if controlnet_map is None: + return None + return [controlnet_map[controlnet] for controlnet in self.controlnet] + + +class BaseModel: + def __init__( + self, + pipeline_info: PipelineInfo, + model, + device, + fp16: bool = False, + max_batch_size: int = 16, + embedding_dim: int = 768, + text_maxlen: int = 77, + ): + self.name = self.__class__.__name__ + + self.pipeline_info = pipeline_info + + self.model = model + self.fp16 = fp16 + self.device = device + + self.min_batch = 1 + self.max_batch = max_batch_size + self.min_image_shape = pipeline_info.min_image_size() + self.max_image_shape = pipeline_info.max_image_size() + self.min_latent_shape = self.min_image_shape // 8 + self.max_latent_shape = self.max_image_shape // 8 + + self.embedding_dim = embedding_dim + self.text_maxlen = text_maxlen + + def get_batch_multiplier(self): + return 2 if self.pipeline_info.do_classifier_free_guidance else 1 + + def get_ort_optimizer(self): + model_name_to_model_type = { + "CLIP": "clip", + "UNet": "unet", + "VAE": "vae", + "UNetXL": "unet", + "CLIPWithProj": "clip", + } + model_type = model_name_to_model_type[self.name] + return OrtStableDiffusionOptimizer(model_type) + + def get_model(self): + return self.model + + def from_pretrained(self, model_class, framework_model_dir, subfolder=None, model_name=None, **kwargs): + if model_name is None: + model_name = self.pipeline_info.name() + + if subfolder: + model_dir = os.path.join(framework_model_dir, model_name, subfolder) + else: + model_dir = os.path.join(framework_model_dir, model_name) + + if not os.path.exists(model_dir): + model = model_class.from_pretrained( + model_name, + subfolder=subfolder, + use_safetensors=self.pipeline_info.use_safetensors(), + **kwargs, + ).to(self.device) + model.save_pretrained(model_dir) + else: + print(f"Load {self.name} pytorch model from: {model_dir}") + + model = model_class.from_pretrained(model_dir).to(self.device) + return model + + def load_model(self, framework_model_dir: str, subfolder: str): + pass + + def get_input_names(self) -> list[str]: + pass + + def get_output_names(self) -> list[str]: + pass + + def get_dynamic_axes(self) -> dict[str, dict[int, str]]: + pass + + def get_sample_input(self, batch_size, image_height, image_width) -> tuple: + pass + + def get_profile_id(self, batch_size, image_height, image_width, static_batch, static_image_shape): + """For TensorRT EP""" + ( + min_batch, + max_batch, + min_image_height, + max_image_height, + min_image_width, + max_image_width, + _, + _, + _, + _, + ) = self.get_minmax_dims(batch_size, image_height, image_width, static_batch, static_image_shape) + + if (self.name in ["UNet", "UNetXL"]) and (self.get_batch_multiplier() == 1): + profile_id = f"_b1_{batch_size}" if static_batch else f"_b1_{min_batch}_{max_batch}" + else: + profile_id = f"_b_{batch_size}" if static_batch else f"_b_{min_batch}_{max_batch}" + + if self.name != "CLIP": + if static_image_shape: + profile_id += f"_h_{image_height}_w_{image_width}" + else: + profile_id += f"_h_{min_image_height}_{max_image_height}_w_{min_image_width}_{max_image_width}" + + return profile_id + + def get_input_profile(self, batch_size, image_height, image_width, static_batch, static_image_shape): + """For TensorRT""" + + def get_shape_dict(self, batch_size, image_height, image_width): + pass + + def fp32_input_output_names(self) -> list[str]: + """For CUDA EP, we export ONNX model with FP32 first, then convert it to mixed precision model. + This is a list of input or output names that are kept as float32 in optimized model. + """ + return [] + + def optimize_ort( + self, + input_onnx_path, + optimized_onnx_path, + to_fp16=True, + fp32_op_list=None, + optimize_by_ort=True, + optimize_by_fusion=True, + tmp_dir=None, + ): + optimizer = self.get_ort_optimizer() + optimizer.optimize( + input_onnx_path, + optimized_onnx_path, + float16=to_fp16, + keep_io_types=self.fp32_input_output_names(), + fp32_op_list=fp32_op_list, + optimize_by_ort=optimize_by_ort, + optimize_by_fusion=optimize_by_fusion, + tmp_dir=tmp_dir, + ) + + def optimize_trt(self, input_onnx_path, optimized_onnx_path): + onnx_graph = onnx.load(input_onnx_path) + opt = TrtOptimizer(onnx_graph) + opt.cleanup() + opt.fold_constants() + opt.infer_shapes() + opt.cleanup() + onnx_opt_graph = opt.get_optimized_onnx_graph() + + if onnx_opt_graph.ByteSize() > onnx.checker.MAXIMUM_PROTOBUF: + onnx.save_model( + onnx_opt_graph, + optimized_onnx_path, + save_as_external_data=True, + all_tensors_to_one_file=True, + convert_attribute=False, + ) + else: + onnx.save(onnx_opt_graph, optimized_onnx_path) + + def check_dims(self, batch_size, image_height, image_width): + assert batch_size >= self.min_batch and batch_size <= self.max_batch + assert image_height % 8 == 0 or image_width % 8 == 0 + latent_height = image_height // 8 + latent_width = image_width // 8 + assert latent_height >= self.min_latent_shape and latent_height <= self.max_latent_shape + assert latent_width >= self.min_latent_shape and latent_width <= self.max_latent_shape + return (latent_height, latent_width) + + def get_minmax_dims(self, batch_size, image_height, image_width, static_batch, static_image_shape): + min_batch = batch_size if static_batch else self.min_batch + max_batch = batch_size if static_batch else self.max_batch + latent_height = image_height // 8 + latent_width = image_width // 8 + min_image_height = image_height if static_image_shape else self.min_image_shape + max_image_height = image_height if static_image_shape else self.max_image_shape + min_image_width = image_width if static_image_shape else self.min_image_shape + max_image_width = image_width if static_image_shape else self.max_image_shape + min_latent_height = latent_height if static_image_shape else self.min_latent_shape + max_latent_height = latent_height if static_image_shape else self.max_latent_shape + min_latent_width = latent_width if static_image_shape else self.min_latent_shape + max_latent_width = latent_width if static_image_shape else self.max_latent_shape + return ( + min_batch, + max_batch, + min_image_height, + max_image_height, + min_image_width, + max_image_width, + min_latent_height, + max_latent_height, + min_latent_width, + max_latent_width, + ) + + +class CLIP(BaseModel): + def __init__( + self, + pipeline_info: PipelineInfo, + model, + device, + max_batch_size, + embedding_dim: int = 0, + clip_skip=0, + ): + super().__init__( + pipeline_info, + model=model, + device=device, + max_batch_size=max_batch_size, + embedding_dim=embedding_dim if embedding_dim > 0 else pipeline_info.clip_embedding_dim(), + ) + self.output_hidden_state = pipeline_info.is_xl() + + # see https://github.com/huggingface/diffusers/pull/5057 for more information of clip_skip. + # Clip_skip=1 means that the output of the pre-final layer will be used for computing the prompt embeddings. + self.clip_skip = clip_skip + + def get_input_names(self): + return ["input_ids"] + + def get_output_names(self): + # The exported onnx model has no hidden_state. For SD-XL, We will add hidden_state to optimized onnx model. + return ["text_embeddings"] + + def get_dynamic_axes(self): + return {"input_ids": {0: "B", 1: "S"}, "text_embeddings": {0: "B", 1: "S"}} + + def get_input_profile(self, batch_size, image_height, image_width, static_batch, static_image_shape): + self.check_dims(batch_size, image_height, image_width) + min_batch, max_batch, _, _, _, _, _, _, _, _ = self.get_minmax_dims( + batch_size, image_height, image_width, static_batch, static_image_shape + ) + return { + "input_ids": [(min_batch, self.text_maxlen), (batch_size, self.text_maxlen), (max_batch, self.text_maxlen)] + } + + def get_shape_dict(self, batch_size, image_height, image_width): + self.check_dims(batch_size, image_height, image_width) + output = { + "input_ids": (batch_size, self.text_maxlen), + "text_embeddings": (batch_size, self.text_maxlen, self.embedding_dim), + } + + if self.output_hidden_state: + output["hidden_states"] = (batch_size, self.text_maxlen, self.embedding_dim) + + return output + + def get_sample_input(self, batch_size, image_height, image_width): + self.check_dims(batch_size, image_height, image_width) + return (torch.zeros(batch_size, self.text_maxlen, dtype=torch.int32, device=self.device),) + + def add_hidden_states_graph_output(self, model: ModelProto, optimized_onnx_path, use_external_data_format=False): + graph: GraphProto = model.graph + hidden_layers = -1 + for i in range(len(graph.node)): + for j in range(len(graph.node[i].output)): + name = graph.node[i].output[j] + if "layers" in name: + hidden_layers = max(int(name.split(".")[1].split("/")[0]), hidden_layers) + + assert self.clip_skip >= 0 and self.clip_skip < hidden_layers + + node_output_name = f"/text_model/encoder/layers.{hidden_layers - 1 - self.clip_skip}/Add_1_output_0" + + # search the name in outputs of all node + found = False + for i in range(len(graph.node)): + for j in range(len(graph.node[i].output)): + if graph.node[i].output[j] == node_output_name: + found = True + break + if found: + break + if not found: + raise RuntimeError("Failed to find hidden_states graph output in clip") + + # Insert a Cast (fp32 -> fp16) node so that hidden_states has same data type as the first graph output. + graph_output_name = "hidden_states" + cast_node = onnx.helper.make_node("Cast", inputs=[node_output_name], outputs=[graph_output_name]) + cast_node.attribute.extend([onnx.helper.make_attribute("to", graph.output[0].type.tensor_type.elem_type)]) + + hidden_state = graph.output.add() + hidden_state.CopyFrom( + onnx.helper.make_tensor_value_info( + graph_output_name, + graph.output[0].type.tensor_type.elem_type, + ["B", "S", self.embedding_dim], + ) + ) + + onnx_model = OnnxModel(model) + onnx_model.add_node(cast_node) + onnx_model.save_model_to_file(optimized_onnx_path, use_external_data_format=use_external_data_format) + + def optimize_ort( + self, + input_onnx_path, + optimized_onnx_path, + to_fp16=True, + fp32_op_list=None, + optimize_by_ort=True, + optimize_by_fusion=True, + tmp_dir=None, + ): + optimizer = self.get_ort_optimizer() + + if not self.output_hidden_state: + optimizer.optimize( + input_onnx_path, + optimized_onnx_path, + float16=to_fp16, + keep_io_types=[], + fp32_op_list=fp32_op_list, + keep_outputs=["text_embeddings"], + optimize_by_ort=optimize_by_ort, + optimize_by_fusion=optimize_by_fusion, + tmp_dir=tmp_dir, + ) + elif optimize_by_fusion: + with tempfile.TemporaryDirectory() as tmp_dir: + # Save to a temporary file so that we can load it with Onnx Runtime. + logger.info("Saving a temporary model to add hidden_states to graph output ...") + tmp_model_path = os.path.join(tmp_dir, "model.onnx") + + model = onnx.load(input_onnx_path) + self.add_hidden_states_graph_output(model, tmp_model_path, use_external_data_format=True) + optimizer.optimize( + tmp_model_path, + optimized_onnx_path, + float16=to_fp16, + keep_io_types=[], + fp32_op_list=fp32_op_list, + keep_outputs=["text_embeddings", "hidden_states"], + optimize_by_ort=optimize_by_ort, + optimize_by_fusion=optimize_by_fusion, + tmp_dir=tmp_dir, + ) + else: # input is optimized model, there is no need to add hidden states. + optimizer.optimize( + input_onnx_path, + optimized_onnx_path, + float16=to_fp16, + keep_io_types=[], + fp32_op_list=fp32_op_list, + keep_outputs=["text_embeddings", "hidden_states"], + optimize_by_ort=optimize_by_ort, + optimize_by_fusion=optimize_by_fusion, + tmp_dir=tmp_dir, + ) + + def optimize_trt(self, input_onnx_path, optimized_onnx_path): + onnx_graph = onnx.load(input_onnx_path) + opt = TrtOptimizer(onnx_graph) + opt.select_outputs([0]) # delete graph output#1 + opt.cleanup() + opt.fold_constants() + opt.infer_shapes() + opt.select_outputs([0], names=["text_embeddings"]) # rename network output + opt.cleanup() + onnx_opt_graph = opt.get_optimized_onnx_graph() + if self.output_hidden_state: + self.add_hidden_states_graph_output(onnx_opt_graph, optimized_onnx_path) + else: + onnx.save(onnx_opt_graph, optimized_onnx_path) + + def load_model(self, framework_model_dir, subfolder="text_encoder"): + return self.from_pretrained(CLIPTextModel, framework_model_dir, subfolder) + + +class CLIPWithProj(CLIP): + def __init__( + self, + pipeline_info: PipelineInfo, + model, + device, + max_batch_size=16, + clip_skip=0, + ): + super().__init__( + pipeline_info, + model, + device=device, + max_batch_size=max_batch_size, + embedding_dim=pipeline_info.clipwithproj_embedding_dim(), + clip_skip=clip_skip, + ) + + def load_model(self, framework_model_dir, subfolder="text_encoder_2"): + return self.from_pretrained(CLIPTextModelWithProjection, framework_model_dir, subfolder) + + def get_shape_dict(self, batch_size, image_height, image_width): + self.check_dims(batch_size, image_height, image_width) + output = { + "input_ids": (batch_size, self.text_maxlen), + "text_embeddings": (batch_size, self.embedding_dim), + } + + if self.output_hidden_state: + output["hidden_states"] = (batch_size, self.text_maxlen, self.embedding_dim) + + return output + + +class UNet2DConditionControlNetModel(torch.nn.Module): + def __init__(self, unet, controlnets: ControlNetModel): + super().__init__() + self.unet = unet + self.controlnets = controlnets + + def forward(self, sample, timestep, encoder_hidden_states, controlnet_images, controlnet_scales): + for i, (controlnet_image, conditioning_scale, controlnet) in enumerate( + zip(controlnet_images, controlnet_scales, self.controlnets, strict=False) + ): + down_samples, mid_sample = controlnet( + sample, + timestep, + encoder_hidden_states=encoder_hidden_states, + controlnet_cond=controlnet_image, + return_dict=False, + ) + + down_samples = [down_sample * conditioning_scale for down_sample in down_samples] + mid_sample *= conditioning_scale + + # merge samples + if i == 0: + down_block_res_samples, mid_block_res_sample = down_samples, mid_sample + else: + down_block_res_samples = [ + samples_prev + samples_curr + for samples_prev, samples_curr in zip(down_block_res_samples, down_samples, strict=False) + ] + mid_block_res_sample += mid_sample + + noise_pred = self.unet( + sample, + timestep, + encoder_hidden_states=encoder_hidden_states, + down_block_additional_residuals=down_block_res_samples, + mid_block_additional_residual=mid_block_res_sample, + ) + return noise_pred[0] + + +# Modified from convert_stable_diffusion_controlnet_to_onnx.py in diffusers +class UNet2DConditionXLControlNetModel(torch.nn.Module): + def __init__(self, unet, controlnets: ControlNetModel): + super().__init__() + self.unet = unet + self.controlnets = controlnets + + def forward( + self, + sample, + timestep, + encoder_hidden_states, + text_embeds, + time_ids, + controlnet_images, + controlnet_scales, + ): + added_cond_kwargs = {"text_embeds": text_embeds, "time_ids": time_ids} + for i, (controlnet_image, conditioning_scale, controlnet) in enumerate( + zip(controlnet_images, controlnet_scales, self.controlnets, strict=False) + ): + down_samples, mid_sample = controlnet( + sample, + timestep, + encoder_hidden_states=encoder_hidden_states, + controlnet_cond=controlnet_image, + conditioning_scale=conditioning_scale, + added_cond_kwargs=added_cond_kwargs, + return_dict=False, + ) + + # merge samples + if i == 0: + down_block_res_samples, mid_block_res_sample = down_samples, mid_sample + else: + down_block_res_samples = [ + samples_prev + samples_curr + for samples_prev, samples_curr in zip(down_block_res_samples, down_samples, strict=False) + ] + mid_block_res_sample += mid_sample + + noise_pred = self.unet( + sample, + timestep, + encoder_hidden_states=encoder_hidden_states, + down_block_additional_residuals=down_block_res_samples, + mid_block_additional_residual=mid_block_res_sample, + added_cond_kwargs=added_cond_kwargs, + return_dict=False, + ) + return noise_pred[0] + + +class UNet(BaseModel): + def __init__( + self, + pipeline_info: PipelineInfo, + model, + device, + fp16=False, # used by TRT + max_batch_size=16, + text_maxlen=77, + unet_dim=4, + ): + super().__init__( + pipeline_info, + model=model, + device=device, + fp16=fp16, + max_batch_size=max_batch_size, + embedding_dim=pipeline_info.unet_embedding_dim(), + text_maxlen=text_maxlen, + ) + + self.unet_dim = unet_dim + self.controlnet = pipeline_info.controlnet_name() + + def load_model(self, framework_model_dir, subfolder="unet"): + options = {"variant": "fp16", "torch_dtype": torch.float16} + + model = self.from_pretrained(UNet2DConditionModel, framework_model_dir, subfolder, **options) + + if self.controlnet: + controlnet_list = [] + for name in self.controlnet: + controlnet = self.from_pretrained( + ControlNetModel, + framework_model_dir, + subfolder=None, + model_name=name, + torch_dtype=torch.float16, + ) + controlnet_list.append(controlnet) + + model = UNet2DConditionControlNetModel(model, torch.nn.ModuleList(controlnet_list)) + + if not self.fp16: + model = model.to(torch.float32) + + return model + + def get_input_names(self): + if not self.controlnet: + return ["sample", "timestep", "encoder_hidden_states"] + else: + return ["sample", "timestep", "encoder_hidden_states", "controlnet_images", "controlnet_scales"] + + def get_output_names(self): + return ["latent"] + + def get_dynamic_axes(self): + b = "2B" if self.get_batch_multiplier() == 2 else "B" + output = { + "sample": {0: b, 2: "H", 3: "W"}, + "encoder_hidden_states": {0: b}, + "latent": {0: b, 2: "H", 3: "W"}, + } + if self.controlnet: + output.update( + { + "controlnet_images": {1: b, 3: "8H", 4: "8W"}, + } + ) + return output + + def get_input_profile(self, batch_size, image_height, image_width, static_batch, static_image_shape): + latent_height, latent_width = self.check_dims(batch_size, image_height, image_width) + ( + min_batch, + max_batch, + min_image_height, + max_image_height, + min_image_width, + max_image_width, + min_latent_height, + max_latent_height, + min_latent_width, + max_latent_width, + ) = self.get_minmax_dims(batch_size, image_height, image_width, static_batch, static_image_shape) + m = self.get_batch_multiplier() + output = { + "sample": [ + (m * min_batch, self.unet_dim, min_latent_height, min_latent_width), + (m * batch_size, self.unet_dim, latent_height, latent_width), + (m * max_batch, self.unet_dim, max_latent_height, max_latent_width), + ], + "encoder_hidden_states": [ + (m * min_batch, self.text_maxlen, self.embedding_dim), + (m * batch_size, self.text_maxlen, self.embedding_dim), + (m * max_batch, self.text_maxlen, self.embedding_dim), + ], + } + + if self.controlnet: + output.update( + { + "controlnet_images": [ + (len(self.controlnet), m * min_batch, 3, min_image_height, min_image_width), + (len(self.controlnet), m * batch_size, 3, image_height, image_width), + (len(self.controlnet), m * max_batch, 3, max_image_height, max_image_width), + ] + } + ) + return output + + def get_shape_dict(self, batch_size, image_height, image_width): + latent_height, latent_width = self.check_dims(batch_size, image_height, image_width) + m = self.get_batch_multiplier() + output = { + "sample": (m * batch_size, self.unet_dim, latent_height, latent_width), + "timestep": [1], + "encoder_hidden_states": (m * batch_size, self.text_maxlen, self.embedding_dim), + "latent": (m * batch_size, 4, latent_height, latent_width), + } + + if self.controlnet: + output.update( + { + "controlnet_images": (len(self.controlnet), m * batch_size, 3, image_height, image_width), + "controlnet_scales": [len(self.controlnet)], + } + ) + return output + + def get_sample_input(self, batch_size, image_height, image_width): + latent_height, latent_width = self.check_dims(batch_size, image_height, image_width) + dtype = torch.float16 if self.fp16 else torch.float32 + m = self.get_batch_multiplier() + output = ( + torch.randn(m * batch_size, self.unet_dim, latent_height, latent_width, dtype=dtype, device=self.device), + torch.tensor([1.0], dtype=dtype, device=self.device), + torch.randn(m * batch_size, self.text_maxlen, self.embedding_dim, dtype=dtype, device=self.device), + ) + + if self.controlnet: + output = ( + *output, + torch.randn( + len(self.controlnet), m * batch_size, 3, image_height, image_width, dtype=dtype, device=self.device + ), + torch.randn(len(self.controlnet), dtype=dtype, device=self.device), + ) + return output + + +class UNetXL(BaseModel): + def __init__( + self, + pipeline_info: PipelineInfo, + model, + device, + fp16=False, # used by TRT + max_batch_size=16, + text_maxlen=77, + unet_dim=4, + time_dim=6, + ): + super().__init__( + pipeline_info, + model, + device=device, + fp16=fp16, + max_batch_size=max_batch_size, + embedding_dim=pipeline_info.unet_embedding_dim(), + text_maxlen=text_maxlen, + ) + self.unet_dim = unet_dim + self.time_dim = time_dim + + self.custom_unet = pipeline_info.custom_unet() + self.controlnet = pipeline_info.controlnet_name() + + def load_model(self, framework_model_dir, subfolder="unet", always_download_fp16=True): + options = {"variant": "fp16", "torch_dtype": torch.float16} if self.fp16 or always_download_fp16 else {} + + if self.custom_unet: + model_dir = os.path.join(framework_model_dir, self.custom_unet, subfolder) + if not os.path.exists(model_dir): + unet = UNet2DConditionModel.from_pretrained(self.custom_unet, **options) + unet.save_pretrained(model_dir) + else: + unet = UNet2DConditionModel.from_pretrained(model_dir, **options) + model = unet.to(self.device) + else: + model = self.from_pretrained(UNet2DConditionModel, framework_model_dir, subfolder, **options) + + if always_download_fp16 and not self.fp16: + model = model.to(torch.float32) + + if self.controlnet: + cnet_model_opts = {"torch_dtype": torch.float16} if self.fp16 or always_download_fp16 else {} + controlnets = torch.nn.ModuleList( + [ControlNetModel.from_pretrained(path, **cnet_model_opts).to(self.device) for path in self.controlnet] + ) + model = UNet2DConditionXLControlNetModel(model, controlnets) + + if always_download_fp16 and not self.fp16: + model = model.to(torch.float32) + + return model + + def get_input_names(self): + input_names = ["sample", "timestep", "encoder_hidden_states", "text_embeds", "time_ids"] + if self.controlnet: + return [*input_names, "controlnet_images", "controlnet_scales"] + return input_names + + def get_output_names(self): + return ["latent"] + + def get_dynamic_axes(self): + b = "2B" if self.get_batch_multiplier() == 2 else "B" + output = { + "sample": {0: b, 2: "H", 3: "W"}, + "encoder_hidden_states": {0: b}, + "text_embeds": {0: b}, + "time_ids": {0: b}, + "latent": {0: b, 2: "H", 3: "W"}, + } + + if self.controlnet: + output.update( + { + "controlnet_images": {1: b, 3: "8H", 4: "8W"}, + } + ) + return output + + def get_input_profile(self, batch_size, image_height, image_width, static_batch, static_image_shape): + latent_height, latent_width = self.check_dims(batch_size, image_height, image_width) + ( + min_batch, + max_batch, + min_image_height, + max_image_height, + min_image_width, + max_image_width, + min_latent_height, + max_latent_height, + min_latent_width, + max_latent_width, + ) = self.get_minmax_dims(batch_size, image_height, image_width, static_batch, static_image_shape) + m = self.get_batch_multiplier() + output = { + "sample": [ + (m * min_batch, self.unet_dim, min_latent_height, min_latent_width), + (m * batch_size, self.unet_dim, latent_height, latent_width), + (m * max_batch, self.unet_dim, max_latent_height, max_latent_width), + ], + "encoder_hidden_states": [ + (m * min_batch, self.text_maxlen, self.embedding_dim), + (m * batch_size, self.text_maxlen, self.embedding_dim), + (m * max_batch, self.text_maxlen, self.embedding_dim), + ], + "text_embeds": [(m * min_batch, 1280), (m * batch_size, 1280), (m * max_batch, 1280)], + "time_ids": [ + (m * min_batch, self.time_dim), + (m * batch_size, self.time_dim), + (m * max_batch, self.time_dim), + ], + } + + if self.controlnet: + output.update( + { + "controlnet_images": [ + (len(self.controlnet), m * min_batch, 3, min_image_height, min_image_width), + (len(self.controlnet), m * batch_size, 3, image_height, image_width), + (len(self.controlnet), m * max_batch, 3, max_image_height, max_image_width), + ], + } + ) + return output + + def get_shape_dict(self, batch_size, image_height, image_width): + latent_height, latent_width = self.check_dims(batch_size, image_height, image_width) + m = self.get_batch_multiplier() + output = { + "sample": (m * batch_size, self.unet_dim, latent_height, latent_width), + "timestep": (1,), + "encoder_hidden_states": (m * batch_size, self.text_maxlen, self.embedding_dim), + "text_embeds": (m * batch_size, 1280), + "time_ids": (m * batch_size, self.time_dim), + "latent": (m * batch_size, 4, latent_height, latent_width), + } + + if self.controlnet: + output.update( + { + "controlnet_images": (len(self.controlnet), m * batch_size, 3, image_height, image_width), + "controlnet_scales": [len(self.controlnet)], + } + ) + return output + + def get_sample_input(self, batch_size, image_height, image_width): + latent_height, latent_width = self.check_dims(batch_size, image_height, image_width) + dtype = torch.float16 if self.fp16 else torch.float32 + m = self.get_batch_multiplier() + if not self.controlnet: + return ( + torch.randn( + m * batch_size, self.unet_dim, latent_height, latent_width, dtype=dtype, device=self.device + ), + torch.tensor([1.0], dtype=dtype, device=self.device), + torch.randn(m * batch_size, self.text_maxlen, self.embedding_dim, dtype=dtype, device=self.device), + { + "added_cond_kwargs": { + "text_embeds": torch.randn(m * batch_size, 1280, dtype=dtype, device=self.device), + "time_ids": torch.randn(m * batch_size, self.time_dim, dtype=dtype, device=self.device), + } + }, + ) + else: + # sample, timestep, encoder_hidden_states, text_embeds, time_ids, controlnet_images, controlnet_scales, + return ( + torch.randn( + m * batch_size, self.unet_dim, latent_height, latent_width, dtype=dtype, device=self.device + ), + torch.tensor([1.0], dtype=dtype, device=self.device), + torch.randn(m * batch_size, self.text_maxlen, self.embedding_dim, dtype=dtype, device=self.device), + torch.randn(m * batch_size, 1280, dtype=dtype, device=self.device), + torch.randn(m * batch_size, self.time_dim, dtype=dtype, device=self.device), + torch.randn( + len(self.controlnet), m * batch_size, 3, image_height, image_width, dtype=dtype, device=self.device + ), + torch.randn(len(self.controlnet), dtype=dtype, device=self.device), + ) + + +# VAE Decoder +class VAE(BaseModel): + def __init__( + self, + pipeline_info: PipelineInfo, + model, + device, + max_batch_size, + fp16: bool = False, + custom_fp16_vae: str | None = None, + ): + super().__init__( + pipeline_info, + model=model, + device=device, + fp16=fp16, + max_batch_size=max_batch_size, + ) + + # For SD XL, need custom trained fp16 model to speed up, and avoid overflow at the same time. + self.custom_fp16_vae = custom_fp16_vae + + def load_model(self, framework_model_dir, subfolder: str = "vae_decoder"): + model_name = self.custom_fp16_vae or self.pipeline_info.name() + + model_dir = os.path.join(framework_model_dir, model_name, subfolder) + if not os.path.exists(model_dir): + if self.custom_fp16_vae: + vae = AutoencoderKL.from_pretrained(self.custom_fp16_vae, torch_dtype=torch.float16).to(self.device) + else: + vae = AutoencoderKL.from_pretrained( + self.pipeline_info.name(), + subfolder="vae", + use_safetensors=self.pipeline_info.use_safetensors(), + ).to(self.device) + vae.save_pretrained(model_dir) + else: + print(f"Load {self.name} pytorch model from: {model_dir}") + if self.custom_fp16_vae: + vae = AutoencoderKL.from_pretrained(model_dir, torch_dtype=torch.float16).to(self.device) + else: + vae = AutoencoderKL.from_pretrained(model_dir).to(self.device) + + vae.forward = vae.decode + return vae + + def get_input_names(self): + return ["latent"] + + def get_output_names(self): + return ["images"] + + def get_dynamic_axes(self): + return {"latent": {0: "B", 2: "H", 3: "W"}, "images": {0: "B", 2: "8H", 3: "8W"}} + + def get_input_profile(self, batch_size, image_height, image_width, static_batch, static_image_shape): + latent_height, latent_width = self.check_dims(batch_size, image_height, image_width) + ( + min_batch, + max_batch, + _, + _, + _, + _, + min_latent_height, + max_latent_height, + min_latent_width, + max_latent_width, + ) = self.get_minmax_dims(batch_size, image_height, image_width, static_batch, static_image_shape) + return { + "latent": [ + (min_batch, 4, min_latent_height, min_latent_width), + (batch_size, 4, latent_height, latent_width), + (max_batch, 4, max_latent_height, max_latent_width), + ] + } + + def get_shape_dict(self, batch_size, image_height, image_width): + latent_height, latent_width = self.check_dims(batch_size, image_height, image_width) + return { + "latent": (batch_size, 4, latent_height, latent_width), + "images": (batch_size, 3, image_height, image_width), + } + + def get_sample_input(self, batch_size, image_height, image_width): + latent_height, latent_width = self.check_dims(batch_size, image_height, image_width) + dtype = torch.float16 if self.fp16 else torch.float32 + return (torch.randn(batch_size, 4, latent_height, latent_width, dtype=dtype, device=self.device),) + + def fp32_input_output_names(self) -> list[str]: + return [] + + +def get_tokenizer(pipeline_info: PipelineInfo, framework_model_dir, subfolder="tokenizer"): + tokenizer_dir = os.path.join(framework_model_dir, pipeline_info.name(), subfolder) + + if not os.path.exists(tokenizer_dir): + model = CLIPTokenizer.from_pretrained( + pipeline_info.name(), + subfolder=subfolder, + use_safetensors=pipeline_info.is_xl(), + ) + model.save_pretrained(tokenizer_dir) + else: + print(f"[I] Load tokenizer pytorch model from: {tokenizer_dir}") + model = CLIPTokenizer.from_pretrained(tokenizer_dir) + return model + + +class TorchVAEEncoder(torch.nn.Module): + def __init__(self, vae_encoder): + super().__init__() + self.vae_encoder = vae_encoder + + def forward(self, x): + return self.vae_encoder.encode(x).latent_dist.sample() + + +class VAEEncoder(BaseModel): + def __init__(self, pipeline_info: PipelineInfo, model, device, max_batch_size): + super().__init__( + pipeline_info, + model=model, + device=device, + max_batch_size=max_batch_size, + ) + + def load_model(self, framework_model_dir, subfolder="vae_encoder"): + vae = self.from_pretrained(AutoencoderKL, framework_model_dir, subfolder) + return TorchVAEEncoder(vae) + + def get_input_names(self): + return ["images"] + + def get_output_names(self): + return ["latent"] + + def get_dynamic_axes(self): + return {"images": {0: "B", 2: "8H", 3: "8W"}, "latent": {0: "B", 2: "H", 3: "W"}} + + def get_input_profile(self, batch_size, image_height, image_width, static_batch, static_image_shape): + self.check_dims(batch_size, image_height, image_width) + + ( + min_batch, + max_batch, + min_image_height, + max_image_height, + min_image_width, + max_image_width, + _, + _, + _, + _, + ) = self.get_minmax_dims(batch_size, image_height, image_width, static_batch, static_image_shape) + + return { + "images": [ + (min_batch, 3, min_image_height, min_image_width), + (batch_size, 3, image_height, image_width), + (max_batch, 3, max_image_height, max_image_width), + ], + } + + def get_shape_dict(self, batch_size, image_height, image_width): + latent_height, latent_width = self.check_dims(batch_size, image_height, image_width) + return { + "images": (batch_size, 3, image_height, image_width), + "latent": (batch_size, 4, latent_height, latent_width), + } + + def get_sample_input(self, batch_size, image_height, image_width): + self.check_dims(batch_size, image_height, image_width) + return torch.randn(batch_size, 3, image_height, image_width, dtype=torch.float32, device=self.device) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/diffusion_schedulers.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/diffusion_schedulers.py new file mode 100644 index 0000000000000000000000000000000000000000..9e05ce4a677eff77e92f50b1365904363e9cea36 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/diffusion_schedulers.py @@ -0,0 +1,1179 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +# -------------------------------------------------------------------------- +# Modified from utilities.py of TensorRT demo diffusion, which has the following license: +# +# Copyright 2022 The HuggingFace Inc. team. +# SPDX-FileCopyrightText: Copyright (c) 1993-2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# -------------------------------------------------------------------------- + + +import numpy as np +import torch + + +class DDIMScheduler: + def __init__( + self, + device="cuda", + num_train_timesteps: int = 1000, + beta_start: float = 0.0001, + beta_end: float = 0.02, + clip_sample: bool = False, + set_alpha_to_one: bool = False, + steps_offset: int = 1, + prediction_type: str = "epsilon", + timestep_spacing: str = "leading", + ): + # this schedule is very specific to the latent diffusion model. + betas = torch.linspace(beta_start**0.5, beta_end**0.5, num_train_timesteps, dtype=torch.float32) ** 2 + + alphas = 1.0 - betas + self.alphas_cumprod = torch.cumprod(alphas, dim=0) + # standard deviation of the initial noise distribution + self.init_noise_sigma = 1.0 + + # At every step in ddim, we are looking into the previous alphas_cumprod + # For the final step, there is no previous alphas_cumprod because we are already at 0 + # `set_alpha_to_one` decides whether we set this parameter simply to one or + # whether we use the final alpha of the "non-previous" one. + self.final_alpha_cumprod = torch.tensor(1.0) if set_alpha_to_one else self.alphas_cumprod[0] + + # setable values + self.num_inference_steps = None + self.timesteps = torch.from_numpy(np.arange(0, num_train_timesteps)[::-1].copy().astype(np.int64)) + self.steps_offset = steps_offset + self.num_train_timesteps = num_train_timesteps + self.clip_sample = clip_sample + self.prediction_type = prediction_type + self.device = device + self.timestep_spacing = timestep_spacing + + def configure(self): + variance = np.zeros(self.num_inference_steps, dtype=np.float32) + for idx, timestep in enumerate(self.timesteps): + prev_timestep = timestep - self.num_train_timesteps // self.num_inference_steps + variance[idx] = self._get_variance(timestep, prev_timestep) + self.variance = torch.from_numpy(variance).to(self.device) + + timesteps = self.timesteps.long().cpu() + self.filtered_alphas_cumprod = self.alphas_cumprod[timesteps].to(self.device) + self.final_alpha_cumprod = self.final_alpha_cumprod.to(self.device) + + def scale_model_input(self, sample: torch.FloatTensor, idx, *args, **kwargs) -> torch.FloatTensor: + return sample + + def _get_variance(self, timestep, prev_timestep): + alpha_prod_t = self.alphas_cumprod[timestep] + alpha_prod_t_prev = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.final_alpha_cumprod + beta_prod_t = 1 - alpha_prod_t + beta_prod_t_prev = 1 - alpha_prod_t_prev + + variance = (beta_prod_t_prev / beta_prod_t) * (1 - alpha_prod_t / alpha_prod_t_prev) + + return variance + + def set_timesteps(self, num_inference_steps: int): + self.num_inference_steps = num_inference_steps + if self.timestep_spacing == "leading": + step_ratio = self.num_train_timesteps // self.num_inference_steps + # creates integer timesteps by multiplying by ratio + # casting to int to avoid issues when num_inference_step is power of 3 + timesteps = (np.arange(0, num_inference_steps) * step_ratio).round()[::-1].copy().astype(np.int64) + timesteps += self.steps_offset + elif self.timestep_spacing == "trailing": + step_ratio = self.num_train_timesteps / self.num_inference_steps + # creates integer timesteps by multiplying by ratio + # casting to int to avoid issues when num_inference_step is power of 3 + timesteps = np.round(np.arange(self.num_train_timesteps, 0, -step_ratio)).astype(np.int64) + timesteps -= 1 + else: + raise ValueError( + f"{self.timestep_spacing} is not supported. Please make sure to choose one of 'linspace', 'leading' or 'trailing'." + ) + + self.timesteps = torch.from_numpy(timesteps).to(self.device) + + def step( + self, + model_output, + sample, + idx, + timestep, + eta: float = 0.0, + use_clipped_model_output: bool = False, + generator=None, + variance_noise: torch.FloatTensor = None, + ): + if self.num_inference_steps is None: + raise ValueError( + "Number of inference steps is 'None', you need to run 'set_timesteps' after creating the scheduler" + ) + + # See formulas (12) and (16) of DDIM paper https://arxiv.org/pdf/2010.02502.pdf + # Ideally, read DDIM paper in-detail understanding + + # Notation ( -> + # - pred_noise_t -> e_theta(x_t, t) + # - pred_original_sample -> f_theta(x_t, t) or x_0 + # - std_dev_t -> sigma_t + # - eta -> η + # - pred_sample_direction -> "direction pointing to x_t" + # - pred_prev_sample -> "x_t-1" + + prev_idx = idx + 1 + alpha_prod_t = self.filtered_alphas_cumprod[idx] + alpha_prod_t_prev = ( + self.filtered_alphas_cumprod[prev_idx] if prev_idx < self.num_inference_steps else self.final_alpha_cumprod + ) + + beta_prod_t = 1 - alpha_prod_t + + # 3. compute predicted original sample from predicted noise also called + # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf + if self.prediction_type == "epsilon": + pred_original_sample = (sample - beta_prod_t ** (0.5) * model_output) / alpha_prod_t ** (0.5) + elif self.prediction_type == "sample": + pred_original_sample = model_output + elif self.prediction_type == "v_prediction": + pred_original_sample = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output + # predict V + model_output = (alpha_prod_t**0.5) * model_output + (beta_prod_t**0.5) * sample + else: + raise ValueError( + f"prediction_type given as {self.prediction_type} must be one of `epsilon`, `sample`, or `v_prediction`" + ) + + # 4. Clip "predicted x_0" + if self.clip_sample: + pred_original_sample = torch.clamp(pred_original_sample, -1, 1) + + # 5. compute variance: "sigma_t(η)" -> see formula (16) + # o_t = sqrt((1 - a_t-1)/(1 - a_t)) * sqrt(1 - a_t/a_t-1) + variance = self.variance[idx] + std_dev_t = eta * variance ** (0.5) + + if use_clipped_model_output: + # the model_output is always re-derived from the clipped x_0 in Glide + model_output = (sample - alpha_prod_t ** (0.5) * pred_original_sample) / beta_prod_t ** (0.5) + + # 6. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf + pred_sample_direction = (1 - alpha_prod_t_prev - std_dev_t**2) ** (0.5) * model_output + + # 7. compute x_t without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf + prev_sample = alpha_prod_t_prev ** (0.5) * pred_original_sample + pred_sample_direction + + if eta > 0: + # randn_like does not support generator https://github.com/pytorch/pytorch/issues/27072 + device = model_output.device + if variance_noise is not None and generator is not None: + raise ValueError( + "Cannot pass both generator and variance_noise. Please make sure that either `generator` or" + " `variance_noise` stays `None`." + ) + + if variance_noise is None: + variance_noise = torch.randn( + model_output.shape, generator=generator, device=device, dtype=model_output.dtype + ) + variance = std_dev_t * variance_noise + + prev_sample = prev_sample + variance + + return prev_sample + + def add_noise(self, init_latents, noise, idx, latent_timestep): + sqrt_alpha_prod = self.filtered_alphas_cumprod[idx] ** 0.5 + sqrt_one_minus_alpha_prod = (1 - self.filtered_alphas_cumprod[idx]) ** 0.5 + noisy_latents = sqrt_alpha_prod * init_latents + sqrt_one_minus_alpha_prod * noise + + return noisy_latents + + +class EulerAncestralDiscreteScheduler: + def __init__( + self, + num_train_timesteps: int = 1000, + beta_start: float = 0.0001, + beta_end: float = 0.02, + device="cuda", + steps_offset: int = 1, + prediction_type: str = "epsilon", + timestep_spacing: str = "trailing", # set default to trailing for SDXL Turbo + ): + betas = torch.linspace(beta_start**0.5, beta_end**0.5, num_train_timesteps, dtype=torch.float32) ** 2 + alphas = 1.0 - betas + self.alphas_cumprod = torch.cumprod(alphas, dim=0) + + sigmas = np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5) + sigmas = np.concatenate([sigmas[::-1], [0.0]]).astype(np.float32) + self.sigmas = torch.from_numpy(sigmas) + + # standard deviation of the initial noise distribution + self.init_noise_sigma = self.sigmas.max() + + # setable values + self.num_inference_steps = None + timesteps = np.linspace(0, num_train_timesteps - 1, num_train_timesteps, dtype=float)[::-1].copy() + self.timesteps = torch.from_numpy(timesteps) + self.is_scale_input_called = False + + self._step_index = None + + self.device = device + self.num_train_timesteps = num_train_timesteps + self.steps_offset = steps_offset + self.prediction_type = prediction_type + self.timestep_spacing = timestep_spacing + + # Copied from diffusers.schedulers.scheduling_euler_discrete.EulerDiscreteScheduler._init_step_index + def _init_step_index(self, timestep): + if isinstance(timestep, torch.Tensor): + timestep = timestep.to(self.timesteps.device) + + index_candidates = (self.timesteps == timestep).nonzero() + + # The sigma index that is taken for the **very** first `step` + # is always the second index (or the last index if there is only 1) + # This way we can ensure we don't accidentally skip a sigma in + # case we start in the middle of the denoising schedule (e.g. for image-to-image) + if len(index_candidates) > 1: + step_index = index_candidates[1] + else: + step_index = index_candidates[0] + + self._step_index = step_index.item() + + def scale_model_input(self, sample: torch.FloatTensor, idx, timestep, *args, **kwargs) -> torch.FloatTensor: + if self._step_index is None: + self._init_step_index(timestep) + + sigma = self.sigmas[self._step_index] + sample = sample / ((sigma**2 + 1) ** 0.5) + self.is_scale_input_called = True + return sample + + def set_timesteps(self, num_inference_steps: int): + self.num_inference_steps = num_inference_steps + + if self.timestep_spacing == "linspace": + timesteps = np.linspace(0, self.num_train_timesteps - 1, num_inference_steps, dtype=np.float32)[::-1].copy() + elif self.timestep_spacing == "leading": + step_ratio = self.num_train_timesteps // self.num_inference_steps + # creates integer timesteps by multiplying by ratio + # casting to int to avoid issues when num_inference_step is power of 3 + timesteps = (np.arange(0, num_inference_steps) * step_ratio).round()[::-1].copy().astype(np.float32) + timesteps += self.steps_offset + elif self.timestep_spacing == "trailing": + step_ratio = self.num_train_timesteps / self.num_inference_steps + # creates integer timesteps by multiplying by ratio + # casting to int to avoid issues when num_inference_step is power of 3 + timesteps = (np.arange(self.num_train_timesteps, 0, -step_ratio)).round().copy().astype(np.float32) + timesteps -= 1 + else: + raise ValueError( + f"{self.timestep_spacing} is not supported. Please make sure to choose one of 'linspace', 'leading' or 'trailing'." + ) + + sigmas = np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5) + sigmas = np.interp(timesteps, np.arange(0, len(sigmas)), sigmas) + sigmas = np.concatenate([sigmas, [0.0]]).astype(np.float32) + self.sigmas = torch.from_numpy(sigmas).to(device=self.device) + self.timesteps = torch.from_numpy(timesteps).to(device=self.device) + + self._step_index = None + + def configure(self): + dts = np.zeros(self.num_inference_steps, dtype=np.float32) + sigmas_up = np.zeros(self.num_inference_steps, dtype=np.float32) + for idx, timestep in enumerate(self.timesteps): + step_index = (self.timesteps == timestep).nonzero().item() + sigma = self.sigmas[step_index] + + sigma_from = self.sigmas[step_index] + sigma_to = self.sigmas[step_index + 1] + sigma_up = (sigma_to**2 * (sigma_from**2 - sigma_to**2) / sigma_from**2) ** 0.5 + sigma_down = (sigma_to**2 - sigma_up**2) ** 0.5 + dt = sigma_down - sigma + dts[idx] = dt + sigmas_up[idx] = sigma_up + + self.dts = torch.from_numpy(dts).to(self.device) + self.sigmas_up = torch.from_numpy(sigmas_up).to(self.device) + + def step( + self, + model_output, + sample, + idx, + timestep, + generator=None, + ): + if self._step_index is None: + self._init_step_index(timestep) + sigma = self.sigmas[self._step_index] + + # 1. compute predicted original sample (x_0) from sigma-scaled predicted noise + if self.prediction_type == "epsilon": + pred_original_sample = sample - sigma * model_output + elif self.prediction_type == "v_prediction": + # * c_out + input * c_skip + pred_original_sample = model_output * (-sigma / (sigma**2 + 1) ** 0.5) + (sample / (sigma**2 + 1)) + else: + raise ValueError( + f"prediction_type given as {self.prediction_type} must be one of `epsilon`, or `v_prediction`" + ) + + sigma_from = self.sigmas[self._step_index] + sigma_to = self.sigmas[self._step_index + 1] + sigma_up = (sigma_to**2 * (sigma_from**2 - sigma_to**2) / sigma_from**2) ** 0.5 + sigma_down = (sigma_to**2 - sigma_up**2) ** 0.5 + + # 2. Convert to an ODE derivative + derivative = (sample - pred_original_sample) / sigma + + dt = sigma_down - sigma + + prev_sample = sample + derivative * dt + + device = model_output.device + noise = torch.randn(model_output.shape, dtype=model_output.dtype, device=device, generator=generator).to(device) + + prev_sample = prev_sample + noise * sigma_up + + # upon completion increase step index by one + self._step_index += 1 + + return prev_sample + + def add_noise(self, original_samples, noise, idx, timestep=None): + sigmas = self.sigmas.to(device=original_samples.device, dtype=original_samples.dtype) + schedule_timesteps = self.timesteps.to(original_samples.device) + timesteps = timestep.to(original_samples.device) + + step_indices = [(schedule_timesteps == t).nonzero().item() for t in timesteps] + + sigma = sigmas[step_indices].flatten() + while len(sigma.shape) < len(original_samples.shape): + sigma = sigma.unsqueeze(-1) + + noisy_samples = original_samples + noise * sigma + return noisy_samples + + +class UniPCMultistepScheduler: + def __init__( + self, + device="cuda", + num_train_timesteps: int = 1000, + beta_start: float = 0.00085, + beta_end: float = 0.012, + solver_order: int = 2, + prediction_type: str = "epsilon", + thresholding: bool = False, + dynamic_thresholding_ratio: float = 0.995, + sample_max_value: float = 1.0, + predict_x0: bool = True, + solver_type: str = "bh2", + lower_order_final: bool = True, + disable_corrector: list[int] | None = None, + use_karras_sigmas: bool | None = False, + timestep_spacing: str = "linspace", + steps_offset: int = 0, + sigma_min=None, + sigma_max=None, + ): + self.device = device + self.betas = torch.linspace(beta_start**0.5, beta_end**0.5, num_train_timesteps, dtype=torch.float32) ** 2 + + self.alphas = 1.0 - self.betas + self.alphas_cumprod = torch.cumprod(self.alphas, dim=0) + # Currently we only support VP-type noise schedule + self.alpha_t = torch.sqrt(self.alphas_cumprod) + self.sigma_t = torch.sqrt(1 - self.alphas_cumprod) + self.lambda_t = torch.log(self.alpha_t) - torch.log(self.sigma_t) + + # standard deviation of the initial noise distribution + self.init_noise_sigma = 1.0 + + self.predict_x0 = predict_x0 + # setable values + self.num_inference_steps = None + timesteps = np.linspace(0, num_train_timesteps - 1, num_train_timesteps, dtype=np.float32)[::-1].copy() + self.timesteps = torch.from_numpy(timesteps) + self.model_outputs = [None] * solver_order + self.timestep_list = [None] * solver_order + self.lower_order_nums = 0 + self.disable_corrector = disable_corrector if disable_corrector else [] + self.last_sample = None + + self._step_index = None + + self.num_train_timesteps = num_train_timesteps + self.solver_order = solver_order + self.prediction_type = prediction_type + self.thresholding = thresholding + self.dynamic_thresholding_ratio = dynamic_thresholding_ratio + self.sample_max_value = sample_max_value + self.solver_type = solver_type + self.lower_order_final = lower_order_final + self.use_karras_sigmas = use_karras_sigmas + self.timestep_spacing = timestep_spacing + self.steps_offset = steps_offset + self.sigma_min = sigma_min + self.sigma_max = sigma_max + + @property + def step_index(self): + """ + The index counter for current timestep. It will increase 1 after each scheduler step. + """ + return self._step_index + + def set_timesteps(self, num_inference_steps: int): + if self.timestep_spacing == "linspace": + timesteps = ( + np.linspace(0, self.num_train_timesteps - 1, num_inference_steps + 1) + .round()[::-1][:-1] + .copy() + .astype(np.int64) + ) + elif self.timestep_spacing == "leading": + step_ratio = self.num_train_timesteps // (num_inference_steps + 1) + # creates integer timesteps by multiplying by ratio + # casting to int to avoid issues when num_inference_step is power of 3 + timesteps = (np.arange(0, num_inference_steps + 1) * step_ratio).round()[::-1][:-1].copy().astype(np.int64) + timesteps += self.steps_offset + elif self.timestep_spacing == "trailing": + step_ratio = self.num_train_timesteps / num_inference_steps + # creates integer timesteps by multiplying by ratio + # casting to int to avoid issues when num_inference_step is power of 3 + timesteps = np.arange(self.num_train_timesteps, 0, -step_ratio).round().copy().astype(np.int64) + timesteps -= 1 + else: + raise ValueError( + f"{self.timestep_spacing} is not supported. Please make sure to choose one of 'linspace', 'leading' or 'trailing'." + ) + + sigmas = np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5) + if self.use_karras_sigmas: + log_sigmas = np.log(sigmas) + sigmas = np.flip(sigmas).copy() + sigmas = self._convert_to_karras(in_sigmas=sigmas, num_inference_steps=num_inference_steps) + timesteps = np.array([self._sigma_to_t(sigma, log_sigmas) for sigma in sigmas]).round() + sigmas = np.concatenate([sigmas, sigmas[-1:]]).astype(np.float32) + else: + sigmas = np.interp(timesteps, np.arange(0, len(sigmas)), sigmas) + sigma_last = ((1 - self.alphas_cumprod[0]) / self.alphas_cumprod[0]) ** 0.5 + sigmas = np.concatenate([sigmas, [sigma_last]]).astype(np.float32) + + self.sigmas = torch.from_numpy(sigmas) + self.timesteps = torch.from_numpy(timesteps).to(device=self.device, dtype=torch.int64) + + self.num_inference_steps = len(timesteps) + + self.model_outputs = [ + None, + ] * self.solver_order + self.lower_order_nums = 0 + self.last_sample = None + + # add an index counter for schedulers that allow duplicated timesteps + self._step_index = None + + # Copied from diffusers.schedulers.scheduling_ddpm.DDPMScheduler._threshold_sample + def _threshold_sample(self, sample: torch.FloatTensor) -> torch.FloatTensor: + dtype = sample.dtype + batch_size, channels, *remaining_dims = sample.shape + + if dtype not in (torch.float32, torch.float64): + sample = sample.float() # upcast for quantile calculation, and clamp not implemented for cpu half + + # Flatten sample for doing quantile calculation along each image + sample = sample.reshape(batch_size, channels * np.prod(remaining_dims)) + + abs_sample = sample.abs() # "a certain percentile absolute pixel value" + + s = torch.quantile(abs_sample, self.dynamic_thresholding_ratio, dim=1) + s = torch.clamp( + s, min=1, max=self.sample_max_value + ) # When clamped to min=1, equivalent to standard clipping to [-1, 1] + s = s.unsqueeze(1) # (batch_size, 1) because clamp will broadcast along dim=0 + sample = torch.clamp(sample, -s, s) / s # "we threshold xt0 to the range [-s, s] and then divide by s" + + sample = sample.reshape(batch_size, channels, *remaining_dims) + sample = sample.to(dtype) + + return sample + + # Copied from diffusers.schedulers.scheduling_euler_discrete.EulerDiscreteScheduler._sigma_to_t + def _sigma_to_t(self, sigma, log_sigmas): + # get log sigma + log_sigma = np.log(np.maximum(sigma, 1e-10)) + + # get distribution + dists = log_sigma - log_sigmas[:, np.newaxis] + + # get sigmas range + low_idx = np.cumsum((dists >= 0), axis=0).argmax(axis=0).clip(max=log_sigmas.shape[0] - 2) + high_idx = low_idx + 1 + + low = log_sigmas[low_idx] + high = log_sigmas[high_idx] + + # interpolate sigmas + w = (low - log_sigma) / (low - high) + w = np.clip(w, 0, 1) + + # transform interpolation to time range + t = (1 - w) * low_idx + w * high_idx + t = t.reshape(sigma.shape) + return t + + # Copied from diffusers.schedulers.scheduling_dpmsolver_multistep.DPMSolverMultistepScheduler._sigma_to_alpha_sigma_t + def _sigma_to_alpha_sigma_t(self, sigma): + alpha_t = 1 / ((sigma**2 + 1) ** 0.5) + sigma_t = sigma * alpha_t + + return alpha_t, sigma_t + + # Copied from diffusers.schedulers.scheduling_euler_discrete.EulerDiscreteScheduler._convert_to_karras + def _convert_to_karras(self, in_sigmas: torch.FloatTensor, num_inference_steps) -> torch.FloatTensor: + """Constructs the noise schedule of Karras et al. (2022).""" + + sigma_min = self.sigma_min + sigma_max = self.sigma_max + + sigma_min = sigma_min if sigma_min is not None else in_sigmas[-1].item() + sigma_max = sigma_max if sigma_max is not None else in_sigmas[0].item() + + rho = 7.0 # 7.0 is the value used in the paper + ramp = np.linspace(0, 1, num_inference_steps) + min_inv_rho = sigma_min ** (1 / rho) + max_inv_rho = sigma_max ** (1 / rho) + sigmas = (max_inv_rho + ramp * (min_inv_rho - max_inv_rho)) ** rho + return sigmas + + def convert_model_output( + self, + model_output: torch.FloatTensor, + *args, + sample: torch.FloatTensor = None, + **kwargs, + ) -> torch.FloatTensor: + timestep = args[0] if len(args) > 0 else kwargs.pop("timestep", None) + if sample is None: + if len(args) > 1: + sample = args[1] + else: + raise ValueError("missing `sample` as a required keyword argument") + if timestep is not None: + print( + "Passing `timesteps` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`", + ) + + sigma = self.sigmas[self.step_index] + alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma) + + if self.predict_x0: + if self.prediction_type == "epsilon": + x0_pred = (sample - sigma_t * model_output) / alpha_t + elif self.prediction_type == "sample": + x0_pred = model_output + elif self.prediction_type == "v_prediction": + x0_pred = alpha_t * sample - sigma_t * model_output + else: + raise ValueError( + f"prediction_type given as {self.prediction_type} must be one of `epsilon`, `sample`, or" + " `v_prediction` for the UniPCMultistepScheduler." + ) + + if self.thresholding: + x0_pred = self._threshold_sample(x0_pred) + + return x0_pred + else: + if self.prediction_type == "epsilon": + return model_output + elif self.prediction_type == "sample": + epsilon = (sample - alpha_t * model_output) / sigma_t + return epsilon + elif self.prediction_type == "v_prediction": + epsilon = alpha_t * model_output + sigma_t * sample + return epsilon + else: + raise ValueError( + f"prediction_type given as {self.prediction_type} must be one of `epsilon`, `sample`, or" + " `v_prediction` for the UniPCMultistepScheduler." + ) + + def multistep_uni_p_bh_update( + self, + model_output: torch.FloatTensor, + *args, + sample: torch.FloatTensor = None, + order: int | None = None, + **kwargs, + ) -> torch.FloatTensor: + prev_timestep = args[0] if len(args) > 0 else kwargs.pop("prev_timestep", None) + if sample is None: + if len(args) > 1: + sample = args[1] + else: + raise ValueError(" missing `sample` as a required keyword argument") + if order is None: + if len(args) > 2: + order = args[2] + else: + raise ValueError(" missing `order` as a required keyword argument") + if prev_timestep is not None: + print( + "Passing `prev_timestep` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`", + ) + model_output_list = self.model_outputs + + # s0 = self.timestep_list[-1] + m0 = model_output_list[-1] + x = sample + + sigma_t, sigma_s0 = self.sigmas[self.step_index + 1], self.sigmas[self.step_index] + alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma_t) + alpha_s0, sigma_s0 = self._sigma_to_alpha_sigma_t(sigma_s0) + + lambda_t = torch.log(alpha_t) - torch.log(sigma_t) + lambda_s0 = torch.log(alpha_s0) - torch.log(sigma_s0) + + h = lambda_t - lambda_s0 + device = sample.device + + rks = [] + d1s = [] + for i in range(1, order): + si = self.step_index - i + mi = model_output_list[-(i + 1)] + alpha_si, sigma_si = self._sigma_to_alpha_sigma_t(self.sigmas[si]) + lambda_si = torch.log(alpha_si) - torch.log(sigma_si) + rk = (lambda_si - lambda_s0) / h + rks.append(rk) + d1s.append((mi - m0) / rk) + + rks.append(1.0) + rks = torch.tensor(rks, device=device) + + r = [] + b = [] + + hh = -h if self.predict_x0 else h + h_phi_1 = torch.expm1(hh) # h\phi_1(h) = e^h - 1 + h_phi_k = h_phi_1 / hh - 1 + + factorial_i = 1 + + if self.solver_type == "bh1": + b_h = hh + elif self.solver_type == "bh2": + b_h = torch.expm1(hh) + else: + raise NotImplementedError() + + for i in range(1, order + 1): + r.append(torch.pow(rks, i - 1)) + b.append(h_phi_k * factorial_i / b_h) + factorial_i *= i + 1 + h_phi_k = h_phi_k / hh - 1 / factorial_i + + r = torch.stack(r) + b = torch.tensor(b, device=device) + + if len(d1s) > 0: + d1s = torch.stack(d1s, dim=1) # (B, K) + # for order 2, we use a simplified version + if order == 2: + rhos_p = torch.tensor([0.5], dtype=x.dtype, device=device) + else: + rhos_p = torch.linalg.solve(r[:-1, :-1], b[:-1]) + else: + d1s = None + + if self.predict_x0: + x_t_ = sigma_t / sigma_s0 * x - alpha_t * h_phi_1 * m0 + if d1s is not None: + pred_res = torch.einsum("k,bkc...->bc...", rhos_p, d1s) + else: + pred_res = 0 + x_t = x_t_ - alpha_t * b_h * pred_res + else: + x_t_ = alpha_t / alpha_s0 * x - sigma_t * h_phi_1 * m0 + if d1s is not None: + pred_res = torch.einsum("k,bkc...->bc...", rhos_p, d1s) + else: + pred_res = 0 + x_t = x_t_ - sigma_t * b_h * pred_res + + x_t = x_t.to(x.dtype) + return x_t + + def multistep_uni_c_bh_update( + self, + this_model_output: torch.FloatTensor, + *args, + last_sample: torch.FloatTensor = None, + this_sample: torch.FloatTensor = None, + order: int | None = None, + **kwargs, + ) -> torch.FloatTensor: + this_timestep = args[0] if len(args) > 0 else kwargs.pop("this_timestep", None) + if last_sample is None: + if len(args) > 1: + last_sample = args[1] + else: + raise ValueError(" missing`last_sample` as a required keyword argument") + if this_sample is None: + if len(args) > 2: + this_sample = args[2] + else: + raise ValueError(" missing`this_sample` as a required keyword argument") + if order is None: + if len(args) > 3: + order = args[3] + else: + raise ValueError(" missing`order` as a required keyword argument") + if this_timestep is not None: + print( + "Passing `this_timestep` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`", + ) + + model_output_list = self.model_outputs + + m0 = model_output_list[-1] + x = last_sample + # x_t = this_sample + model_t = this_model_output + + sigma_t, sigma_s0 = self.sigmas[self.step_index], self.sigmas[self.step_index - 1] + alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma_t) + alpha_s0, sigma_s0 = self._sigma_to_alpha_sigma_t(sigma_s0) + + lambda_t = torch.log(alpha_t) - torch.log(sigma_t) + lambda_s0 = torch.log(alpha_s0) - torch.log(sigma_s0) + + h = lambda_t - lambda_s0 + device = this_sample.device + + rks = [] + d1s = [] + for i in range(1, order): + si = self.step_index - (i + 1) + mi = model_output_list[-(i + 1)] + alpha_si, sigma_si = self._sigma_to_alpha_sigma_t(self.sigmas[si]) + lambda_si = torch.log(alpha_si) - torch.log(sigma_si) + rk = (lambda_si - lambda_s0) / h + rks.append(rk) + d1s.append((mi - m0) / rk) + + rks.append(1.0) + rks = torch.tensor(rks, device=device) + + r = [] + b = [] + + hh = -h if self.predict_x0 else h + h_phi_1 = torch.expm1(hh) # h\phi_1(h) = e^h - 1 + h_phi_k = h_phi_1 / hh - 1 + + factorial_i = 1 + + if self.solver_type == "bh1": + b_h = hh + elif self.solver_type == "bh2": + b_h = torch.expm1(hh) + else: + raise NotImplementedError() + + for i in range(1, order + 1): + r.append(torch.pow(rks, i - 1)) + b.append(h_phi_k * factorial_i / b_h) + factorial_i *= i + 1 + h_phi_k = h_phi_k / hh - 1 / factorial_i + + r = torch.stack(r) + b = torch.tensor(b, device=device) + + if len(d1s) > 0: + d1s = torch.stack(d1s, dim=1) + else: + d1s = None + + # for order 1, we use a simplified version + if order == 1: + rhos_c = torch.tensor([0.5], dtype=x.dtype, device=device) + else: + rhos_c = torch.linalg.solve(r, b) + + if self.predict_x0: + x_t_ = sigma_t / sigma_s0 * x - alpha_t * h_phi_1 * m0 + if d1s is not None: + corr_res = torch.einsum("k,bkc...->bc...", rhos_c[:-1], d1s) + else: + corr_res = 0 + d1_t = model_t - m0 + x_t = x_t_ - alpha_t * b_h * (corr_res + rhos_c[-1] * d1_t) + else: + x_t_ = alpha_t / alpha_s0 * x - sigma_t * h_phi_1 * m0 + if d1s is not None: + corr_res = torch.einsum("k,bkc...->bc...", rhos_c[:-1], d1s) + else: + corr_res = 0 + d1_t = model_t - m0 + x_t = x_t_ - sigma_t * b_h * (corr_res + rhos_c[-1] * d1_t) + x_t = x_t.to(x.dtype) + return x_t + + def _init_step_index(self, timestep): + if isinstance(timestep, torch.Tensor): + timestep = timestep.to(self.timesteps.device) + + index_candidates = (self.timesteps == timestep).nonzero() + + if len(index_candidates) == 0: + step_index = len(self.timesteps) - 1 + # The sigma index that is taken for the **very** first `step` + # is always the second index (or the last index if there is only 1) + # This way we can ensure we don't accidentally skip a sigma in + # case we start in the middle of the denoising schedule (e.g. for image-to-image) + elif len(index_candidates) > 1: + step_index = index_candidates[1].item() + else: + step_index = index_candidates[0].item() + + self._step_index = step_index + + def step( + self, + model_output: torch.FloatTensor, + timestep: int, + sample: torch.FloatTensor, + return_dict: bool = True, + ): + if self.num_inference_steps is None: + raise ValueError( + "Number of inference steps is 'None', you need to run 'set_timesteps' after creating the scheduler" + ) + + if self.step_index is None: + self._init_step_index(timestep) + + use_corrector = ( + self.step_index > 0 and self.step_index - 1 not in self.disable_corrector and self.last_sample is not None + ) + + model_output_convert = self.convert_model_output(model_output, sample=sample) + if use_corrector: + sample = self.multistep_uni_c_bh_update( + this_model_output=model_output_convert, + last_sample=self.last_sample, + this_sample=sample, + order=self.this_order, + ) + + for i in range(self.solver_order - 1): + self.model_outputs[i] = self.model_outputs[i + 1] + self.timestep_list[i] = self.timestep_list[i + 1] + + self.model_outputs[-1] = model_output_convert + self.timestep_list[-1] = timestep + + if self.lower_order_final: + this_order = min(self.solver_order, len(self.timesteps) - self.step_index) + else: + this_order = self.solver_order + + self.this_order = min(this_order, self.lower_order_nums + 1) # warmup for multistep + assert self.this_order > 0 + + self.last_sample = sample + prev_sample = self.multistep_uni_p_bh_update( + model_output=model_output, # pass the original non-converted model output, in case solver-p is used + sample=sample, + order=self.this_order, + ) + + if self.lower_order_nums < self.solver_order: + self.lower_order_nums += 1 + + # upon completion increase step index by one + self._step_index += 1 + + if not return_dict: + return (prev_sample,) + + return prev_sample + + def scale_model_input(self, sample: torch.FloatTensor, *args, **kwargs) -> torch.FloatTensor: + return sample + + def add_noise( + self, + original_samples: torch.FloatTensor, + noise: torch.FloatTensor, + idx, + timesteps: torch.IntTensor, + ) -> torch.FloatTensor: + # Make sure sigmas and timesteps have the same device and dtype as original_samples + sigmas = self.sigmas.to(device=original_samples.device, dtype=original_samples.dtype) + schedule_timesteps = self.timesteps.to(original_samples.device) + timesteps = timesteps.to(original_samples.device) + + step_indices = [(schedule_timesteps == t).nonzero().item() for t in timesteps] + sigma = sigmas[step_indices].flatten() + while len(sigma.shape) < len(original_samples.shape): + sigma = sigma.unsqueeze(-1) + + alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma) + noisy_samples = alpha_t * original_samples + sigma_t * noise + return noisy_samples + + def configure(self): + pass + + def __len__(self): + return self.num_train_timesteps + + +# Modified from diffusers.schedulers.LCMScheduler +class LCMScheduler: + def __init__( + self, + device="cuda", + num_train_timesteps: int = 1000, + beta_start: float = 0.00085, + beta_end: float = 0.012, + original_inference_steps: int = 50, + clip_sample: bool = False, + clip_sample_range: float = 1.0, + steps_offset: int = 0, + prediction_type: str = "epsilon", + thresholding: bool = False, + dynamic_thresholding_ratio: float = 0.995, + sample_max_value: float = 1.0, + timestep_spacing: str = "leading", + timestep_scaling: float = 10.0, + ): + self.device = device + self.betas = torch.linspace(beta_start**0.5, beta_end**0.5, num_train_timesteps, dtype=torch.float32) ** 2 + self.alphas = 1.0 - self.betas + self.alphas_cumprod = torch.cumprod(self.alphas, dim=0) + self.final_alpha_cumprod = self.alphas_cumprod[0] + # standard deviation of the initial noise distribution + self.init_noise_sigma = 1.0 + # setable values + self.num_inference_steps = None + self.timesteps = torch.from_numpy(np.arange(0, num_train_timesteps)[::-1].copy().astype(np.int64)) + + self.num_train_timesteps = num_train_timesteps + self.clip_sample = clip_sample + self.clip_sample_range = clip_sample_range + self.steps_offset = steps_offset + self.prediction_type = prediction_type + self.thresholding = thresholding + self.timestep_spacing = timestep_spacing + self.timestep_scaling = timestep_scaling + self.original_inference_steps = original_inference_steps + self.dynamic_thresholding_ratio = dynamic_thresholding_ratio + self.sample_max_value = sample_max_value + + self._step_index = None + + # Copied from diffusers.schedulers.scheduling_euler_discrete.EulerDiscreteScheduler._init_step_index + def _init_step_index(self, timestep): + if isinstance(timestep, torch.Tensor): + timestep = timestep.to(self.timesteps.device) + + index_candidates = (self.timesteps == timestep).nonzero() + + if len(index_candidates) > 1: + step_index = index_candidates[1] + else: + step_index = index_candidates[0] + + self._step_index = step_index.item() + + @property + def step_index(self): + return self._step_index + + def scale_model_input(self, sample: torch.FloatTensor, *args, **kwargs) -> torch.FloatTensor: + return sample + + # Copied from diffusers.schedulers.scheduling_ddpm.DDPMScheduler._threshold_sample + def _threshold_sample(self, sample: torch.FloatTensor) -> torch.FloatTensor: + dtype = sample.dtype + batch_size, channels, *remaining_dims = sample.shape + + if dtype not in (torch.float32, torch.float64): + sample = sample.float() # upcast for quantile calculation, and clamp not implemented for cpu half + + # Flatten sample for doing quantile calculation along each image + sample = sample.reshape(batch_size, channels * np.prod(remaining_dims)) + + abs_sample = sample.abs() # "a certain percentile absolute pixel value" + + s = torch.quantile(abs_sample, self.dynamic_thresholding_ratio, dim=1) + s = torch.clamp( + s, min=1, max=self.sample_max_value + ) # When clamped to min=1, equivalent to standard clipping to [-1, 1] + s = s.unsqueeze(1) # (batch_size, 1) because clamp will broadcast along dim=0 + sample = torch.clamp(sample, -s, s) / s # "we threshold xt0 to the range [-s, s] and then divide by s" + + sample = sample.reshape(batch_size, channels, *remaining_dims) + sample = sample.to(dtype) + + return sample + + def set_timesteps( + self, + num_inference_steps: int, + strength: int = 1.0, + ): + assert num_inference_steps <= self.num_train_timesteps + + self.num_inference_steps = num_inference_steps + original_steps = self.original_inference_steps + + assert original_steps <= self.num_train_timesteps + assert num_inference_steps <= original_steps + + # LCM Timesteps Setting + # Currently, only linear spacing is supported. + c = self.num_train_timesteps // original_steps + # LCM Training Steps Schedule + lcm_origin_timesteps = np.asarray(list(range(1, int(original_steps * strength) + 1))) * c - 1 + skipping_step = len(lcm_origin_timesteps) // num_inference_steps + # LCM Inference Steps Schedule + timesteps = lcm_origin_timesteps[::-skipping_step][:num_inference_steps] + + self.timesteps = torch.from_numpy(timesteps.copy()).to(device=self.device, dtype=torch.long) + + self._step_index = None + + def get_scalings_for_boundary_condition_discrete(self, timestep): + self.sigma_data = 0.5 # Default: 0.5 + scaled_timestep = timestep * self.timestep_scaling + + c_skip = self.sigma_data**2 / (scaled_timestep**2 + self.sigma_data**2) + c_out = scaled_timestep / (scaled_timestep**2 + self.sigma_data**2) ** 0.5 + return c_skip, c_out + + def step( + self, + model_output: torch.FloatTensor, + timestep: int, + sample: torch.FloatTensor, + generator: torch.Generator | None = None, + ): + if self.num_inference_steps is None: + raise ValueError( + "Number of inference steps is 'None', you need to run 'set_timesteps' after creating the scheduler" + ) + + if self.step_index is None: + self._init_step_index(timestep) + + # 1. get previous step value + prev_step_index = self.step_index + 1 + if prev_step_index < len(self.timesteps): + prev_timestep = self.timesteps[prev_step_index] + else: + prev_timestep = timestep + + # 2. compute alphas, betas + alpha_prod_t = self.alphas_cumprod[timestep] + alpha_prod_t_prev = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.final_alpha_cumprod + + beta_prod_t = 1 - alpha_prod_t + beta_prod_t_prev = 1 - alpha_prod_t_prev + + # 3. Get scalings for boundary conditions + c_skip, c_out = self.get_scalings_for_boundary_condition_discrete(timestep) + + # 4. Compute the predicted original sample x_0 based on the model parameterization + if self.prediction_type == "epsilon": # noise-prediction + predicted_original_sample = (sample - beta_prod_t.sqrt() * model_output) / alpha_prod_t.sqrt() + elif self.prediction_type == "sample": # x-prediction + predicted_original_sample = model_output + elif self.prediction_type == "v_prediction": # v-prediction + predicted_original_sample = alpha_prod_t.sqrt() * sample - beta_prod_t.sqrt() * model_output + else: + raise ValueError( + f"prediction_type given as {self.prediction_type} must be one of `epsilon`, `sample` or" + " `v_prediction` for `LCMScheduler`." + ) + + # 5. Clip or threshold "predicted x_0" + if self.thresholding: + predicted_original_sample = self._threshold_sample(predicted_original_sample) + elif self.clip_sample: + predicted_original_sample = predicted_original_sample.clamp(-self.clip_sample_range, self.clip_sample_range) + + # 6. Denoise model output using boundary conditions + denoised = c_out * predicted_original_sample + c_skip * sample + + # 7. Sample and inject noise z ~ N(0, I) for MultiStep Inference + # Noise is not used on the final timestep of the timestep schedule. + # This also means that noise is not used for one-step sampling. + if self.step_index != self.num_inference_steps - 1: + noise = torch.randn( + model_output.shape, device=model_output.device, dtype=denoised.dtype, generator=generator + ) + prev_sample = alpha_prod_t_prev.sqrt() * denoised + beta_prod_t_prev.sqrt() * noise + else: + prev_sample = denoised + + # upon completion increase step index by one + self._step_index += 1 + + return (prev_sample,) + + # Copied from diffusers.schedulers.scheduling_ddpm.DDPMScheduler.add_noise + def add_noise( + self, + original_samples: torch.FloatTensor, + noise: torch.FloatTensor, + timesteps: torch.IntTensor, + ) -> torch.FloatTensor: + # Make sure alphas_cumprod and timestep have same device and dtype as original_samples + alphas_cumprod = self.alphas_cumprod.to(device=original_samples.device, dtype=original_samples.dtype) + timesteps = timesteps.to(original_samples.device) + + sqrt_alpha_prod = alphas_cumprod[timesteps] ** 0.5 + sqrt_alpha_prod = sqrt_alpha_prod.flatten() + while len(sqrt_alpha_prod.shape) < len(original_samples.shape): + sqrt_alpha_prod = sqrt_alpha_prod.unsqueeze(-1) + + sqrt_one_minus_alpha_prod = (1 - alphas_cumprod[timesteps]) ** 0.5 + sqrt_one_minus_alpha_prod = sqrt_one_minus_alpha_prod.flatten() + while len(sqrt_one_minus_alpha_prod.shape) < len(original_samples.shape): + sqrt_one_minus_alpha_prod = sqrt_one_minus_alpha_prod.unsqueeze(-1) + + noisy_samples = sqrt_alpha_prod * original_samples + sqrt_one_minus_alpha_prod * noise + return noisy_samples + + def configure(self): + pass + + def __len__(self): + return self.num_train_timesteps diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/engine_builder.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/engine_builder.py new file mode 100644 index 0000000000000000000000000000000000000000..248a00c49fed69d4b01f499a8b5570990437dd03 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/engine_builder.py @@ -0,0 +1,295 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +# -------------------------------------------------------------------------- +import hashlib +import os +from enum import Enum + +import torch +from diffusion_models import CLIP, VAE, CLIPWithProj, PipelineInfo, UNet, UNetXL + + +class EngineType(Enum): + ORT_CUDA = 0 # ONNX Runtime CUDA Execution Provider + ORT_TRT = 1 # ONNX Runtime TensorRT Execution Provider + TRT = 2 # TensorRT + TORCH = 3 # PyTorch + + +def get_engine_type(name: str) -> EngineType: + name_to_type = { + "ORT_CUDA": EngineType.ORT_CUDA, + "ORT_TRT": EngineType.ORT_TRT, + "TRT": EngineType.TRT, + "TORCH": EngineType.TORCH, + } + return name_to_type[name] + + +class EngineBuilder: + def __init__( + self, + engine_type: EngineType, + pipeline_info: PipelineInfo, + device="cuda", + max_batch_size=16, + use_cuda_graph=False, + ): + """ + Initializes the Engine Builder. + + Args: + pipeline_info (PipelineInfo): + Version and Type of pipeline. + device (str | torch.device): + device to run engine + max_batch_size (int): + Maximum batch size for dynamic batch engine. + use_cuda_graph (bool): + Use CUDA graph to capture engine execution and then launch inference + """ + self.engine_type = engine_type + self.pipeline_info = pipeline_info + self.max_batch_size = max_batch_size + self.use_cuda_graph = use_cuda_graph + self.device = torch.device(device) + self.torch_device = torch.device(device, torch.cuda.current_device()) + self.stages = pipeline_info.stages() + + self.vae_torch_fallback = self.pipeline_info.vae_torch_fallback() and self.engine_type != EngineType.TORCH + self.custom_fp16_vae = self.pipeline_info.custom_fp16_vae() + + self.models = {} + self.engines = {} + self.torch_models = {} + self.use_vae_slicing = False + + self.torch_sdpa = getattr(torch.nn.functional, "scaled_dot_product_attention", None) + + def enable_vae_slicing(self): + self.use_vae_slicing = True + + def disable_torch_spda(self): + if hasattr(torch.nn.functional, "scaled_dot_product_attention"): + delattr(torch.nn.functional, "scaled_dot_product_attention") + + def enable_torch_spda(self): + if (not hasattr(torch.nn.functional, "scaled_dot_product_attention")) and self.torch_sdpa: + torch.nn.functional.scaled_dot_product_attention = self.torch_sdpa + + def teardown(self): + for engine in self.engines.values(): + del engine + self.engines = {} + + def get_diffusers_module_name(self, model_name): + name_mapping = { + "clip": "text_encoder", + "clip2": "text_encoder_2", + "unet": "unet", + "unetxl": "unet", + "vae": "vae_decoder", + } + return name_mapping.get(model_name, model_name) + + def get_cached_model_name(self, model_name): + model_name = self.get_diffusers_module_name(model_name) + is_unet = model_name == "unet" + hash_source = [] + if model_name in ["text_encoder", "text_encoder_2", "unet"] and self.pipeline_info.lora_weights: + if self.pipeline_info.lora_weights in [ + "latent-consistency/lcm-lora-sdxl", + "latent-consistency/lcm-lora-sdv1-5", + ]: + if is_unet: + model_name = "unet_lcm-lora" + else: + model_name = model_name + "_lora" + hash_source.append(self.pipeline_info.lora_weights) + + # TODO(tianleiwu): save custom model to a directory named by its original model. + if is_unet and self.pipeline_info.custom_unet(): + model_name = model_name + "_lcm" + + if model_name in ["unet"] and self.pipeline_info.controlnet: + model_name = model_name + "_" + "_".join(self.pipeline_info.controlnet) + + if hash_source: + model_name += "_" + hashlib.sha256("\t".join(hash_source).encode("utf-8")).hexdigest()[:8] + + # TODO: When we support original VAE, we shall save custom VAE to another directory. + + if self.pipeline_info.is_inpaint(): + model_name += "_inpaint" + return model_name + + def get_model_dir(self, model_name, root_dir, opt=True, suffix="", create=True): + engine_name = self.engine_type.name.lower() + if engine_name != "ort_cuda" and not suffix: + suffix = f".{engine_name}" if opt else "" + directory_name = self.get_cached_model_name(model_name) + suffix + onnx_model_dir = os.path.join(root_dir, directory_name) + if create: + os.makedirs(onnx_model_dir, exist_ok=True) + return onnx_model_dir + + def get_onnx_path(self, model_name, onnx_dir, opt=True, suffix=""): + onnx_model_dir = self.get_model_dir(model_name, onnx_dir, opt=opt, suffix=suffix) + return os.path.join(onnx_model_dir, "model.onnx") + + def get_engine_path(self, engine_dir, model_name, profile_id): + return os.path.join(engine_dir, self.get_cached_model_name(model_name) + profile_id) + + def load_pipeline_with_lora(self): + """Load text encoders and UNet with diffusers pipeline""" + from diffusers import DiffusionPipeline # noqa: PLC0415 + + pipeline = DiffusionPipeline.from_pretrained( + self.pipeline_info.name(), + variant="fp16", + torch_dtype=torch.float16, + ) + pipeline.load_lora_weights(self.pipeline_info.lora_weights) + pipeline.fuse_lora(lora_scale=self.pipeline_info.lora_scale) + + del pipeline.vae + pipeline.vae = None + return pipeline + + def get_or_load_model(self, pipeline, model_name, model_obj, framework_model_dir): + if model_name in ["clip", "clip2", "unet", "unetxl"] and pipeline: + if model_name == "clip": + model = pipeline.text_encoder + pipeline.text_encoder = None + elif model_name == "clip2": + model = pipeline.text_encoder_2 + pipeline.text_encoder_2 = None + else: + model = pipeline.unet + pipeline.unet = None + else: + model = model_obj.load_model(framework_model_dir) + + return model.to(self.torch_device) + + def load_models(self, framework_model_dir: str): + # For TRT or ORT_TRT, we will export fp16 torch model for UNet and VAE + # For ORT_CUDA, we export fp32 model first, then optimize to fp16. + export_fp16 = self.engine_type in [EngineType.ORT_TRT, EngineType.TRT] + + if "clip" in self.stages: + self.models["clip"] = CLIP( + self.pipeline_info, + None, # not loaded yet + device=self.torch_device, + max_batch_size=self.max_batch_size, + clip_skip=0, + ) + + if "clip2" in self.stages: + self.models["clip2"] = CLIPWithProj( + self.pipeline_info, + None, # not loaded yet + device=self.torch_device, + max_batch_size=self.max_batch_size, + clip_skip=0, + ) + + if "unet" in self.stages: + self.models["unet"] = UNet( + self.pipeline_info, + None, # not loaded yet + device=self.torch_device, + fp16=export_fp16, + max_batch_size=self.max_batch_size, + unet_dim=(9 if self.pipeline_info.is_inpaint() else 4), + ) + + if "unetxl" in self.stages: + self.models["unetxl"] = UNetXL( + self.pipeline_info, + None, # not loaded yet + device=self.torch_device, + fp16=export_fp16, + max_batch_size=self.max_batch_size, + unet_dim=4, + time_dim=(5 if self.pipeline_info.is_xl_refiner() else 6), + ) + + # VAE Decoder + if "vae" in self.stages: + self.models["vae"] = VAE( + self.pipeline_info, + None, # not loaded yet + device=self.torch_device, + max_batch_size=self.max_batch_size, + fp16=export_fp16, + custom_fp16_vae=self.custom_fp16_vae, + ) + + if self.vae_torch_fallback: + self.torch_models["vae"] = self.models["vae"].load_model(framework_model_dir) + + def load_resources(self, image_height, image_width, batch_size): + if self.engine_type == EngineType.TORCH: + return + + # Allocate buffers for I/O bindings + for model_name, obj in self.models.items(): + if model_name == "vae" and self.vae_torch_fallback: + continue + slice_size = 1 if (model_name == "vae" and self.use_vae_slicing) else batch_size + self.engines[model_name].allocate_buffers( + shape_dict=obj.get_shape_dict(slice_size, image_height, image_width), device=self.torch_device + ) + + def _vae_decode(self, latents): + if self.engine_type == EngineType.TORCH: + if self.pipeline_info.is_xl() and not self.custom_fp16_vae: # need upcast + latents = latents.to(dtype=torch.float32) + images = self.engines["vae"](latents)["sample"] + else: + images = self.engines["vae"](latents)["sample"] + elif self.vae_torch_fallback: + if not self.custom_fp16_vae: + latents = latents.to(dtype=torch.float32) + self.torch_models["vae"] = self.torch_models["vae"].to(dtype=torch.float32) + images = self.torch_models["vae"](latents)["sample"] + else: + if self.pipeline_info.is_xl() and not self.custom_fp16_vae: # need upcast + images = self.run_engine("vae", {"latent": latents.to(dtype=torch.float32)})["images"] + else: + images = self.run_engine("vae", {"latent": latents})["images"] + + return images + + def vae_decode(self, latents): + if self.use_vae_slicing: + # The output tensor points to same buffer. Need clone it to avoid overwritten. + decoded_slices = [self._vae_decode(z_slice).clone() for z_slice in latents.split(1)] + return torch.cat(decoded_slices) + + return self._vae_decode(latents) + + +def get_engine_paths( + work_dir: str, pipeline_info: PipelineInfo, engine_type: EngineType, framework_model_dir: str | None = None +): + root_dir = work_dir or "." + short_name = pipeline_info.short_name() + + # When both ORT_CUDA and ORT_TRT/TRT is used, we shall make sub directory for each engine since + # ORT_CUDA need fp32 torch model, while ORT_TRT/TRT use fp16 torch model. + onnx_dir = os.path.join(root_dir, engine_type.name, short_name, "onnx") + engine_dir = os.path.join(root_dir, engine_type.name, short_name, "engine") + output_dir = os.path.join(root_dir, engine_type.name, short_name, "output") + + timing_cache = os.path.join(root_dir, engine_type.name, "timing_cache") + + # Shared among ORT_CUDA, ORT_TRT and TRT engines, and need use load_model(..., always_download_fp16=True) + # So that the shared model is always fp16. + if framework_model_dir is None: + framework_model_dir = os.path.join(root_dir, "torch_model") + + return onnx_dir, engine_dir, output_dir, framework_model_dir, timing_cache diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/engine_builder_ort_cuda.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/engine_builder_ort_cuda.py new file mode 100644 index 0000000000000000000000000000000000000000..4ee5622c671a1901ce016179b7e8350bc64c56ab --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/engine_builder_ort_cuda.py @@ -0,0 +1,387 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +# -------------------------------------------------------------------------- + +import gc +import logging +import os + +import onnx +import torch +from diffusion_models import PipelineInfo +from engine_builder import EngineBuilder, EngineType +from packaging import version + +import onnxruntime as ort +from onnxruntime.transformers.io_binding_helper import CudaSession, GpuBindingManager +from onnxruntime.transformers.onnx_model import OnnxModel + +logger = logging.getLogger(__name__) + + +class OrtCudaEngine: + def __init__( + self, + onnx_path, + device_id: int = 0, + enable_cuda_graph: bool = False, + disable_optimization: bool = False, + max_cuda_graphs: int = 1, + ): + self.onnx_path = onnx_path + self.provider = "CUDAExecutionProvider" + self.stream = torch.cuda.current_stream().cuda_stream + self.provider_options = CudaSession.get_cuda_provider_options(device_id, enable_cuda_graph, self.stream) + session_options = ort.SessionOptions() + + # When the model has been optimized by onnxruntime, we can disable optimization to save session creation time. + if disable_optimization: + session_options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_DISABLE_ALL + + logger.info("creating CUDA EP session for %s", onnx_path) + ort_session = ort.InferenceSession( + onnx_path, + session_options, + providers=[ + (self.provider, self.provider_options), + "CPUExecutionProvider", + ], + ) + logger.info("created CUDA EP session for %s", onnx_path) + + device = torch.device("cuda", device_id) + self.enable_cuda_graph = enable_cuda_graph + + # Support multiple CUDA graphs for different input shapes. + # For clip2 model that disabled cuda graph, max_cuda_graphs is updated to 0 here. + self.gpu_binding_manager = GpuBindingManager( + ort_session=ort_session, + device=device, + stream=self.stream, + max_cuda_graphs=max_cuda_graphs if enable_cuda_graph else 0, + ) + + self.current_gpu_binding = None + + def metadata(self, name: str): + data = {} + if self.current_gpu_binding is not None: + if self.current_gpu_binding.last_run_gpu_graph_id >= 0: + data[f"{name}.gpu_graph_id"] = self.current_gpu_binding.last_run_gpu_graph_id + return data + + def infer(self, feed_dict: dict[str, torch.Tensor]): + return self.current_gpu_binding.infer(feed_dict=feed_dict, disable_cuda_graph_in_run=not self.enable_cuda_graph) + + def allocate_buffers(self, shape_dict, device): + self.current_gpu_binding = self.gpu_binding_manager.get_binding( + shape_dict=shape_dict, use_cuda_graph=self.enable_cuda_graph + ) + + +class _ModelConfig: + """ + Configuration of one model (like Clip, UNet etc) on ONNX export and optimization for CUDA provider. + For example, if you want to use fp32 in layer normalization, set the following: + force_fp32_ops=["SkipLayerNormalization", "LayerNormalization"] + """ + + def __init__( + self, + onnx_opset_version: int, + use_cuda_graph: bool, + fp16: bool = True, + force_fp32_ops: list[str] | None = None, + optimize_by_ort: bool = True, + ): + self.onnx_opset_version = onnx_opset_version + self.use_cuda_graph = use_cuda_graph + self.fp16 = fp16 + self.force_fp32_ops = force_fp32_ops + self.optimize_by_ort = optimize_by_ort + + +class OrtCudaEngineBuilder(EngineBuilder): + def __init__( + self, + pipeline_info: PipelineInfo, + max_batch_size=16, + device="cuda", + use_cuda_graph=False, + ): + """ + Initializes the ONNX Runtime TensorRT ExecutionProvider Engine Builder. + + Args: + pipeline_info (PipelineInfo): + Version and Type of pipeline. + max_batch_size (int): + Maximum batch size for dynamic batch engine. + device (str): + device to run. + use_cuda_graph (bool): + Use CUDA graph to capture engine execution and then launch inference + """ + super().__init__( + EngineType.ORT_CUDA, + pipeline_info, + max_batch_size=max_batch_size, + device=device, + use_cuda_graph=use_cuda_graph, + ) + + self.model_config = {} + + def _configure( + self, + model_name: str, + onnx_opset_version: int, + use_cuda_graph: bool, + fp16: bool = True, + force_fp32_ops: list[str] | None = None, + optimize_by_ort: bool = True, + ): + self.model_config[model_name] = _ModelConfig( + onnx_opset_version, + use_cuda_graph, + fp16=fp16, + force_fp32_ops=force_fp32_ops, + optimize_by_ort=optimize_by_ort, + ) + + def configure_xl(self, onnx_opset_version: int): + self._configure( + "clip", + onnx_opset_version=onnx_opset_version, + use_cuda_graph=self.use_cuda_graph, + ) + self._configure( + "clip2", + onnx_opset_version=onnx_opset_version, # TODO: ArgMax-12 is not implemented in CUDA + use_cuda_graph=False, # TODO: fix Runtime Error with cuda graph + ) + self._configure( + "unetxl", + onnx_opset_version=onnx_opset_version, + use_cuda_graph=self.use_cuda_graph, + ) + + self._configure( + "vae", + onnx_opset_version=onnx_opset_version, + use_cuda_graph=self.use_cuda_graph, + ) + + def optimized_onnx_path(self, engine_dir, model_name): + suffix = "" if self.model_config[model_name].fp16 else ".fp32" + return self.get_onnx_path(model_name, engine_dir, opt=True, suffix=suffix) + + def import_diffusers_engine(self, diffusers_onnx_dir: str, engine_dir: str): + """Import optimized onnx models for diffusers from Olive or optimize_pipeline tools. + + Args: + diffusers_onnx_dir (str): optimized onnx directory of Olive + engine_dir (str): the directory to store imported onnx + """ + if version.parse(ort.__version__) < version.parse("1.17.0"): + print("Skip importing since onnxruntime-gpu version < 1.17.0.") + return + + for model_name, model_obj in self.models.items(): + onnx_import_path = self.optimized_onnx_path(diffusers_onnx_dir, model_name) + if not os.path.exists(onnx_import_path): + print(f"{onnx_import_path} not existed. Skip importing.") + continue + + onnx_opt_path = self.optimized_onnx_path(engine_dir, model_name) + if os.path.exists(onnx_opt_path): + print(f"{onnx_opt_path} existed. Skip importing.") + continue + + if model_name == "vae" and self.pipeline_info.is_xl(): + print(f"Skip importing VAE since it is not fully compatible with float16: {onnx_import_path}.") + continue + + model = OnnxModel(onnx.load(onnx_import_path, load_external_data=True)) + + if model_name in ["clip", "clip2"]: + hidden_states_per_layer = [] + for output in model.graph().output: + if output.name.startswith("hidden_states."): + hidden_states_per_layer.append(output.name) + if hidden_states_per_layer: + kept_hidden_states = hidden_states_per_layer[-2 - model_obj.clip_skip] + model.rename_graph_output(kept_hidden_states, "hidden_states") + + model.rename_graph_output( + "last_hidden_state" if model_name == "clip" else "text_embeds", "text_embeddings" + ) + model.prune_graph( + ["text_embeddings", "hidden_states"] if hidden_states_per_layer else ["text_embeddings"] + ) + + if model_name == "clip2": + model.change_graph_input_type(model.find_graph_input("input_ids"), onnx.TensorProto.INT32) + + model.save_model_to_file(onnx_opt_path, use_external_data_format=(model_name == "clip2")) + elif model_name in ["unet", "unetxl"]: + model.rename_graph_output("out_sample", "latent") + model.save_model_to_file(onnx_opt_path, use_external_data_format=True) + + del model + continue + + def build_engines( + self, + engine_dir: str, + framework_model_dir: str, + onnx_dir: str, + tmp_dir: str | None = None, + onnx_opset_version: int = 17, + device_id: int = 0, + save_fp32_intermediate_model: bool = False, + import_engine_dir: str | None = None, + max_cuda_graphs: int = 1, + ): + self.torch_device = torch.device("cuda", device_id) + self.load_models(framework_model_dir) + + if not os.path.isdir(engine_dir): + os.makedirs(engine_dir) + + if not os.path.isdir(onnx_dir): + os.makedirs(onnx_dir) + + # Add default configuration if missing + if self.pipeline_info.is_xl(): + self.configure_xl(onnx_opset_version) + for model_name in self.models: + if model_name not in self.model_config: + self.model_config[model_name] = _ModelConfig(onnx_opset_version, self.use_cuda_graph) + + # Import Engine + if import_engine_dir: + if self.pipeline_info.is_xl(): + self.import_diffusers_engine(import_engine_dir, engine_dir) + else: + print(f"Only support importing SDXL onnx. Ignore --engine-dir {import_engine_dir}") + + # Load lora only when we need export text encoder or UNet to ONNX. + load_lora = False + if self.pipeline_info.lora_weights: + for model_name in self.models: + if model_name not in ["clip", "clip2", "unet", "unetxl"]: + continue + onnx_path = self.get_onnx_path(model_name, onnx_dir, opt=False) + onnx_opt_path = self.optimized_onnx_path(engine_dir, model_name) + if not os.path.exists(onnx_opt_path): + if not os.path.exists(onnx_path): + load_lora = True + break + + # Export models to ONNX + self.disable_torch_spda() + pipe = self.load_pipeline_with_lora() if load_lora else None + + for model_name, model_obj in self.models.items(): + if model_name == "vae" and self.vae_torch_fallback: + continue + + onnx_path = self.get_onnx_path(model_name, onnx_dir, opt=False) + onnx_opt_path = self.optimized_onnx_path(engine_dir, model_name) + if not os.path.exists(onnx_opt_path): + if not os.path.exists(onnx_path): + print("----") + logger.info("Exporting model: %s", onnx_path) + + model = self.get_or_load_model(pipe, model_name, model_obj, framework_model_dir) + model = model.to(torch.float32) + + with torch.inference_mode(): + # For CUDA EP, export FP32 onnx since some graph fusion only supports fp32 graph pattern. + # Export model with sample of batch size 1, image size 512 x 512 + inputs = model_obj.get_sample_input(1, 512, 512) + + torch.onnx.export( + model, + inputs, + onnx_path, + export_params=True, + opset_version=self.model_config[model_name].onnx_opset_version, + do_constant_folding=True, + input_names=model_obj.get_input_names(), + output_names=model_obj.get_output_names(), + dynamic_axes=model_obj.get_dynamic_axes(), + ) + del model + torch.cuda.empty_cache() + gc.collect() + else: + logger.info("Found cached model: %s", onnx_path) + + # Generate fp32 optimized model. + # If final target is fp16 model, we save fp32 optimized model so that it is easy to tune + # fp16 conversion. That could save a lot of time in developing. + use_fp32_intermediate = save_fp32_intermediate_model and self.model_config[model_name].fp16 + onnx_fp32_path = onnx_path + if use_fp32_intermediate: + onnx_fp32_path = self.get_onnx_path(model_name, engine_dir, opt=True, suffix=".fp32") + if not os.path.exists(onnx_fp32_path): + print("------") + logger.info("Generating optimized model: %s", onnx_fp32_path) + model_obj.optimize_ort( + onnx_path, + onnx_fp32_path, + to_fp16=False, + fp32_op_list=self.model_config[model_name].force_fp32_ops, + optimize_by_ort=self.model_config[model_name].optimize_by_ort, + tmp_dir=self.get_model_dir(model_name, tmp_dir, opt=False, suffix=".fp32", create=False), + ) + else: + logger.info("Found cached optimized model: %s", onnx_fp32_path) + + # Generate the final optimized model. + if not os.path.exists(onnx_opt_path): + print("------") + logger.info("Generating optimized model: %s", onnx_opt_path) + + # When there is fp32 intermediate optimized model, this will just convert model from fp32 to fp16. + optimize_by_ort = False if use_fp32_intermediate else self.model_config[model_name].optimize_by_ort + + model_obj.optimize_ort( + onnx_fp32_path, + onnx_opt_path, + to_fp16=self.model_config[model_name].fp16, + fp32_op_list=self.model_config[model_name].force_fp32_ops, + optimize_by_ort=optimize_by_ort, + optimize_by_fusion=not use_fp32_intermediate, + tmp_dir=self.get_model_dir(model_name, tmp_dir, opt=False, suffix=".ort", create=False), + ) + else: + logger.info("Found cached optimized model: %s", onnx_opt_path) + self.enable_torch_spda() + + built_engines = {} + for model_name in self.models: + if model_name == "vae" and self.vae_torch_fallback: + continue + + onnx_opt_path = self.optimized_onnx_path(engine_dir, model_name) + use_cuda_graph = self.model_config[model_name].use_cuda_graph + + engine = OrtCudaEngine( + onnx_opt_path, + device_id=device_id, + enable_cuda_graph=use_cuda_graph, + disable_optimization=False, + max_cuda_graphs=max_cuda_graphs, + ) + + logger.info("%s options for %s: %s", engine.provider, model_name, engine.provider_options) + built_engines[model_name] = engine + + self.engines = built_engines + + def run_engine(self, model_name, feed_dict): + return self.engines[model_name].infer(feed_dict) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/engine_builder_ort_trt.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/engine_builder_ort_trt.py new file mode 100644 index 0000000000000000000000000000000000000000..0af46f70d99dbb0e0346d9b703f84d4d905f821c --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/engine_builder_ort_trt.py @@ -0,0 +1,288 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +# -------------------------------------------------------------------------- + +import gc +import logging +import os + +import torch +from cuda import cudart +from diffusion_models import PipelineInfo +from engine_builder import EngineBuilder, EngineType +from packaging import version + +import onnxruntime as ort +from onnxruntime.transformers.io_binding_helper import CudaSession + +logger = logging.getLogger(__name__) + + +class OrtTensorrtEngine(CudaSession): + def __init__( + self, + engine_path, + device_id, + onnx_path, + fp16, + input_profile, + workspace_size, + enable_cuda_graph, + timing_cache_path=None, + ): + self.engine_path = engine_path + self.ort_trt_provider_options = self.get_tensorrt_provider_options( + input_profile, + workspace_size, + fp16, + device_id, + enable_cuda_graph, + timing_cache_path=timing_cache_path, + ) + + session_options = ort.SessionOptions() + session_options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_DISABLE_ALL + logger.info("creating TRT EP session for %s", onnx_path) + ort_session = ort.InferenceSession( + onnx_path, + session_options, + providers=[ + ("TensorrtExecutionProvider", self.ort_trt_provider_options), + ], + ) + logger.info("created TRT EP session for %s", onnx_path) + + device = torch.device("cuda", device_id) + super().__init__(ort_session, device, enable_cuda_graph) + + def get_tensorrt_provider_options( + self, input_profile, workspace_size, fp16, device_id, enable_cuda_graph, timing_cache_path=None + ): + trt_ep_options = { + "device_id": device_id, + "trt_fp16_enable": fp16, + "trt_engine_cache_enable": True, + "trt_timing_cache_enable": True, + "trt_detailed_build_log": True, + "trt_engine_cache_path": self.engine_path, + } + + if version.parse(ort.__version__) > version.parse("1.16.2") and timing_cache_path is not None: + trt_ep_options["trt_timing_cache_path"] = timing_cache_path + + if enable_cuda_graph: + trt_ep_options["trt_cuda_graph_enable"] = True + + if workspace_size > 0: + trt_ep_options["trt_max_workspace_size"] = workspace_size + + if input_profile: + min_shapes = [] + max_shapes = [] + opt_shapes = [] + for name, profile in input_profile.items(): + assert isinstance(profile, list) and len(profile) == 3 + min_shape = profile[0] + opt_shape = profile[1] + max_shape = profile[2] + assert len(min_shape) == len(opt_shape) and len(opt_shape) == len(max_shape) + + min_shapes.append(f"{name}:" + "x".join([str(x) for x in min_shape])) + opt_shapes.append(f"{name}:" + "x".join([str(x) for x in opt_shape])) + max_shapes.append(f"{name}:" + "x".join([str(x) for x in max_shape])) + + trt_ep_options["trt_profile_min_shapes"] = ",".join(min_shapes) + trt_ep_options["trt_profile_max_shapes"] = ",".join(max_shapes) + trt_ep_options["trt_profile_opt_shapes"] = ",".join(opt_shapes) + + logger.info("trt_ep_options=%s", trt_ep_options) + + return trt_ep_options + + def allocate_buffers(self, shape_dict, device): + super().allocate_buffers(shape_dict) + + +class OrtTensorrtEngineBuilder(EngineBuilder): + def __init__( + self, + pipeline_info: PipelineInfo, + max_batch_size=16, + device="cuda", + use_cuda_graph=False, + ): + """ + Initializes the ONNX Runtime TensorRT ExecutionProvider Engine Builder. + + Args: + pipeline_info (PipelineInfo): + Version and Type of pipeline. + max_batch_size (int): + Maximum batch size for dynamic batch engine. + device (str): + device to run. + use_cuda_graph (bool): + Use CUDA graph to capture engine execution and then launch inference + """ + super().__init__( + EngineType.ORT_TRT, + pipeline_info, + max_batch_size=max_batch_size, + device=device, + use_cuda_graph=use_cuda_graph, + ) + + def has_engine_file(self, engine_path): + if os.path.isdir(engine_path): + children = os.scandir(engine_path) + for entry in children: + if entry.is_file() and entry.name.endswith(".engine"): + return True + return False + + def get_work_space_size(self, model_name, max_workspace_size): + gibibyte = 2**30 + workspace_size = 4 * gibibyte if model_name == "clip" else max_workspace_size + if workspace_size == 0: + _, free_mem, _ = cudart.cudaMemGetInfo() + # The following logic are adopted from TensorRT demo diffusion. + if free_mem > 6 * gibibyte: + workspace_size = free_mem - 4 * gibibyte + return workspace_size + + def build_engines( + self, + engine_dir, + framework_model_dir, + onnx_dir, + onnx_opset, + opt_image_height, + opt_image_width, + opt_batch_size=1, + static_batch=False, + static_image_shape=True, + max_workspace_size=0, + device_id=0, + timing_cache=None, + ): + self.torch_device = torch.device("cuda", device_id) + self.load_models(framework_model_dir) + + if not os.path.isdir(engine_dir): + os.makedirs(engine_dir) + + if not os.path.isdir(onnx_dir): + os.makedirs(onnx_dir) + + # Load lora only when we need export text encoder or UNet to ONNX. + load_lora = False + if self.pipeline_info.lora_weights: + for model_name, model_obj in self.models.items(): + if model_name not in ["clip", "clip2", "unet", "unetxl"]: + continue + profile_id = model_obj.get_profile_id( + opt_batch_size, opt_image_height, opt_image_width, static_batch, static_image_shape + ) + engine_path = self.get_engine_path(engine_dir, model_name, profile_id) + if not self.has_engine_file(engine_path): + onnx_path = self.get_onnx_path(model_name, onnx_dir, opt=False) + onnx_opt_path = self.get_onnx_path(model_name, onnx_dir, opt=True) + if not os.path.exists(onnx_opt_path): + if not os.path.exists(onnx_path): + load_lora = True + break + + # Export models to ONNX + self.disable_torch_spda() + pipe = self.load_pipeline_with_lora() if load_lora else None + + for model_name, model_obj in self.models.items(): + if model_name == "vae" and self.vae_torch_fallback: + continue + + profile_id = model_obj.get_profile_id( + opt_batch_size, opt_image_height, opt_image_width, static_batch, static_image_shape + ) + engine_path = self.get_engine_path(engine_dir, model_name, profile_id) + if not self.has_engine_file(engine_path): + onnx_path = self.get_onnx_path(model_name, onnx_dir, opt=False) + onnx_opt_path = self.get_onnx_path(model_name, onnx_dir, opt=True) + if not os.path.exists(onnx_opt_path): + if not os.path.exists(onnx_path): + logger.info(f"Exporting model: {onnx_path}") + model = self.get_or_load_model(pipe, model_name, model_obj, framework_model_dir) + + with torch.inference_mode(), torch.autocast("cuda"): + inputs = model_obj.get_sample_input(opt_batch_size, opt_image_height, opt_image_width) + torch.onnx.export( + model, + inputs, + onnx_path, + export_params=True, + opset_version=onnx_opset, + do_constant_folding=True, + input_names=model_obj.get_input_names(), + output_names=model_obj.get_output_names(), + dynamic_axes=model_obj.get_dynamic_axes(), + ) + del model + torch.cuda.empty_cache() + gc.collect() + else: + logger.info("Found cached model: %s", onnx_path) + + # Optimize onnx + if not os.path.exists(onnx_opt_path): + logger.info("Generating optimizing model: %s", onnx_opt_path) + model_obj.optimize_trt(onnx_path, onnx_opt_path) + else: + logger.info("Found cached optimized model: %s", onnx_opt_path) + self.enable_torch_spda() + + built_engines = {} + for model_name, model_obj in self.models.items(): + if model_name == "vae" and self.vae_torch_fallback: + continue + + profile_id = model_obj.get_profile_id( + opt_batch_size, opt_image_height, opt_image_width, static_batch, static_image_shape + ) + + engine_path = self.get_engine_path(engine_dir, model_name, profile_id) + onnx_opt_path = self.get_onnx_path(model_name, onnx_dir, opt=True) + if not self.has_engine_file(engine_path): + logger.info( + "Building TensorRT engine for %s from %s to %s. It can take a while to complete...", + model_name, + onnx_opt_path, + engine_path, + ) + else: + logger.info("Reuse cached TensorRT engine in directory %s", engine_path) + + input_profile = model_obj.get_input_profile( + opt_batch_size, + opt_image_height, + opt_image_width, + static_batch=static_batch, + static_image_shape=static_image_shape, + ) + + engine = OrtTensorrtEngine( + engine_path, + device_id, + onnx_opt_path, + fp16=True, + input_profile=input_profile, + workspace_size=self.get_work_space_size(model_name, max_workspace_size), + enable_cuda_graph=self.use_cuda_graph, + timing_cache_path=timing_cache, + ) + + built_engines[model_name] = engine + + self.engines = built_engines + + def run_engine(self, model_name, feed_dict): + return self.engines[model_name].infer(feed_dict) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/engine_builder_tensorrt.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/engine_builder_tensorrt.py new file mode 100644 index 0000000000000000000000000000000000000000..9ba92f4569b9df1847f3859c93eca19357a74a49 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/engine_builder_tensorrt.py @@ -0,0 +1,395 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +# -------------------------------------------------------------------------- +# Modified from TensorRT demo diffusion, which has the following license: +# +# SPDX-FileCopyrightText: Copyright (c) 1993-2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# -------------------------------------------------------------------------- + +import gc +import os +import pathlib +from collections import OrderedDict + +import numpy as np +import tensorrt as trt +import torch +from cuda import cudart +from diffusion_models import PipelineInfo +from engine_builder import EngineBuilder, EngineType +from polygraphy.backend.common import bytes_from_path +from polygraphy.backend.trt import ( + CreateConfig, + ModifyNetworkOutputs, + Profile, + engine_from_bytes, + engine_from_network, + network_from_onnx_path, + save_engine, +) + +# Map of numpy dtype -> torch dtype +numpy_to_torch_dtype_dict = { + np.int32: torch.int32, + np.int64: torch.int64, + np.float16: torch.float16, + np.float32: torch.float32, +} + + +def _cuda_assert(cuda_ret): + err = cuda_ret[0] + if err != cudart.cudaError_t.cudaSuccess: + raise RuntimeError( + f"CUDA ERROR: {err}, error code reference: https://nvidia.github.io/cuda-python/module/cudart.html#cuda.cudart.cudaError_t" + ) + if len(cuda_ret) > 1: + return cuda_ret[1] + return None + + +class TensorrtEngine: + def __init__( + self, + engine_path, + ): + self.engine_path = engine_path + self.engine = None + self.context = None + self.buffers = OrderedDict() + self.tensors = OrderedDict() + self.cuda_graph_instance = None + + def __del__(self): + del self.engine + del self.context + del self.buffers + del self.tensors + + def build( + self, + onnx_path, + fp16, + input_profile=None, + enable_all_tactics=False, + timing_cache=None, + update_output_names=None, + ): + print(f"Building TensorRT engine for {onnx_path}: {self.engine_path}") + p = Profile() + if input_profile: + for name, dims in input_profile.items(): + assert len(dims) == 3 + p.add(name, min=dims[0], opt=dims[1], max=dims[2]) + + config_kwargs = {} + if not enable_all_tactics: + config_kwargs["tactic_sources"] = [] + + network = network_from_onnx_path(onnx_path, flags=[trt.OnnxParserFlag.NATIVE_INSTANCENORM]) + if update_output_names: + print(f"Updating network outputs to {update_output_names}") + network = ModifyNetworkOutputs(network, update_output_names) + engine = engine_from_network( + network, + config=CreateConfig( + fp16=fp16, refittable=False, profiles=[p], load_timing_cache=timing_cache, **config_kwargs + ), + save_timing_cache=timing_cache, + ) + save_engine(engine, path=self.engine_path) + + def load(self): + print(f"Loading TensorRT engine: {self.engine_path}") + self.engine = engine_from_bytes(bytes_from_path(self.engine_path)) + + def activate(self, reuse_device_memory=None): + if reuse_device_memory: + self.context = self.engine.create_execution_context_without_device_memory() + self.context.device_memory = reuse_device_memory + else: + self.context = self.engine.create_execution_context() + + def allocate_buffers(self, shape_dict=None, device="cuda"): + for idx in range(self.engine.num_io_tensors): + binding = self.engine[idx] + if shape_dict and binding in shape_dict: + shape = shape_dict[binding] + else: + shape = self.engine.get_binding_shape(binding) + dtype = trt.nptype(self.engine.get_binding_dtype(binding)) + if self.engine.binding_is_input(binding): + self.context.set_binding_shape(idx, shape) + tensor = torch.empty(tuple(shape), dtype=numpy_to_torch_dtype_dict[dtype]).to(device=device) + self.tensors[binding] = tensor + + def infer(self, feed_dict, stream, use_cuda_graph=False): + for name, buf in feed_dict.items(): + self.tensors[name].copy_(buf) + + for name, tensor in self.tensors.items(): + self.context.set_tensor_address(name, tensor.data_ptr()) + + if use_cuda_graph: + if self.cuda_graph_instance is not None: + _cuda_assert(cudart.cudaGraphLaunch(self.cuda_graph_instance, stream)) + _cuda_assert(cudart.cudaStreamSynchronize(stream)) + else: + # do inference before CUDA graph capture + noerror = self.context.execute_async_v3(stream) + if not noerror: + raise ValueError("ERROR: inference failed.") + # capture cuda graph + _cuda_assert( + cudart.cudaStreamBeginCapture(stream, cudart.cudaStreamCaptureMode.cudaStreamCaptureModeGlobal) + ) + self.context.execute_async_v3(stream) + self.graph = _cuda_assert(cudart.cudaStreamEndCapture(stream)) + + from cuda import nvrtc # noqa: PLC0415 + + result, major, minor = nvrtc.nvrtcVersion() + assert result == nvrtc.nvrtcResult(0) + if major < 12: + self.cuda_graph_instance = _cuda_assert( + cudart.cudaGraphInstantiate(self.graph, b"", 0) + ) # cuda < 12 + else: + self.cuda_graph_instance = _cuda_assert(cudart.cudaGraphInstantiate(self.graph, 0)) # cuda >= 12 + else: + noerror = self.context.execute_async_v3(stream) + if not noerror: + raise ValueError("ERROR: inference failed.") + + return self.tensors + + +class TensorrtEngineBuilder(EngineBuilder): + """ + Helper class to hide the detail of TensorRT Engine from pipeline. + """ + + def __init__( + self, + pipeline_info: PipelineInfo, + max_batch_size=16, + device="cuda", + use_cuda_graph=False, + ): + """ + Initializes the ONNX Runtime TensorRT ExecutionProvider Engine Builder. + + Args: + pipeline_info (PipelineInfo): + Version and Type of pipeline. + max_batch_size (int): + Maximum batch size for dynamic batch engine. + device (str): + device to run. + use_cuda_graph (bool): + Use CUDA graph to capture engine execution and then launch inference + """ + super().__init__( + EngineType.TRT, + pipeline_info, + max_batch_size=max_batch_size, + device=device, + use_cuda_graph=use_cuda_graph, + ) + + self.stream = None + self.shared_device_memory = None + + def load_resources(self, image_height, image_width, batch_size): + super().load_resources(image_height, image_width, batch_size) + + self.stream = _cuda_assert(cudart.cudaStreamCreate()) + + def teardown(self): + super().teardown() + + if self.shared_device_memory: + cudart.cudaFree(self.shared_device_memory) + + cudart.cudaStreamDestroy(self.stream) + del self.stream + + def load_engines( + self, + engine_dir, + framework_model_dir, + onnx_dir, + onnx_opset, + opt_batch_size, + opt_image_height, + opt_image_width, + static_batch=False, + static_shape=True, + enable_all_tactics=False, + timing_cache=None, + ): + """ + Build and load engines for TensorRT accelerated inference. + Export ONNX models first, if applicable. + + Args: + engine_dir (str): + Directory to write the TensorRT engines. + framework_model_dir (str): + Directory to write the framework model ckpt. + onnx_dir (str): + Directory to write the ONNX models. + onnx_opset (int): + ONNX opset version to export the models. + opt_batch_size (int): + Batch size to optimize for during engine building. + opt_image_height (int): + Image height to optimize for during engine building. Must be a multiple of 8. + opt_image_width (int): + Image width to optimize for during engine building. Must be a multiple of 8. + static_batch (bool): + Build engine only for specified opt_batch_size. + static_shape (bool): + Build engine only for specified opt_image_height & opt_image_width. Default = True. + enable_all_tactics (bool): + Enable all tactic sources during TensorRT engine builds. + timing_cache (str): + Path to the timing cache to accelerate build or None + """ + # Create directory + for directory in [engine_dir, onnx_dir]: + if not os.path.exists(directory): + print(f"[I] Create directory: {directory}") + pathlib.Path(directory).mkdir(parents=True) + + self.load_models(framework_model_dir) + + # Load lora only when we need export text encoder or UNet to ONNX. + load_lora = False + if self.pipeline_info.lora_weights: + for model_name, model_obj in self.models.items(): + if model_name not in ["clip", "clip2", "unet", "unetxl"]: + continue + profile_id = model_obj.get_profile_id( + opt_batch_size, opt_image_height, opt_image_width, static_batch, static_shape + ) + engine_path = self.get_engine_path(engine_dir, model_name, profile_id) + if not os.path.exists(engine_path): + onnx_path = self.get_onnx_path(model_name, onnx_dir, opt=False) + onnx_opt_path = self.get_onnx_path(model_name, onnx_dir, opt=True) + if not os.path.exists(onnx_opt_path): + if not os.path.exists(onnx_path): + load_lora = True + break + + # Export models to ONNX + self.disable_torch_spda() + pipe = self.load_pipeline_with_lora() if load_lora else None + + for model_name, model_obj in self.models.items(): + if model_name == "vae" and self.vae_torch_fallback: + continue + profile_id = model_obj.get_profile_id( + opt_batch_size, opt_image_height, opt_image_width, static_batch, static_shape + ) + engine_path = self.get_engine_path(engine_dir, model_name, profile_id) + if not os.path.exists(engine_path): + onnx_path = self.get_onnx_path(model_name, onnx_dir, opt=False) + onnx_opt_path = self.get_onnx_path(model_name, onnx_dir, opt=True) + if not os.path.exists(onnx_opt_path): + if not os.path.exists(onnx_path): + print(f"Exporting model: {onnx_path}") + model = self.get_or_load_model(pipe, model_name, model_obj, framework_model_dir) + + with torch.inference_mode(), torch.autocast("cuda"): + inputs = model_obj.get_sample_input(1, opt_image_height, opt_image_width) + torch.onnx.export( + model, + inputs, + onnx_path, + export_params=True, + opset_version=onnx_opset, + do_constant_folding=True, + input_names=model_obj.get_input_names(), + output_names=model_obj.get_output_names(), + dynamic_axes=model_obj.get_dynamic_axes(), + ) + del model + torch.cuda.empty_cache() + gc.collect() + else: + print(f"Found cached model: {onnx_path}") + + # Optimize onnx + if not os.path.exists(onnx_opt_path): + print(f"Generating optimizing model: {onnx_opt_path}") + model_obj.optimize_trt(onnx_path, onnx_opt_path) + else: + print(f"Found cached optimized model: {onnx_opt_path} ") + self.enable_torch_spda() + + # Build TensorRT engines + for model_name, model_obj in self.models.items(): + if model_name == "vae" and self.vae_torch_fallback: + continue + profile_id = model_obj.get_profile_id( + opt_batch_size, opt_image_height, opt_image_width, static_batch, static_shape + ) + engine_path = self.get_engine_path(engine_dir, model_name, profile_id) + engine = TensorrtEngine(engine_path) + onnx_opt_path = self.get_onnx_path(model_name, onnx_dir, opt=True) + + if not os.path.exists(engine.engine_path): + engine.build( + onnx_opt_path, + fp16=True, + input_profile=model_obj.get_input_profile( + opt_batch_size, + opt_image_height, + opt_image_width, + static_batch, + static_shape, + ), + enable_all_tactics=enable_all_tactics, + timing_cache=timing_cache, + update_output_names=None, + ) + self.engines[model_name] = engine + + # Load TensorRT engines + for model_name in self.models: + if model_name == "vae" and self.vae_torch_fallback: + continue + self.engines[model_name].load() + + def max_device_memory(self): + max_device_memory = 0 + for engine in self.engines.values(): + max_device_memory = max(max_device_memory, engine.engine.device_memory_size) + return max_device_memory + + def activate_engines(self, shared_device_memory=None): + if shared_device_memory is None: + max_device_memory = self.max_device_memory() + _, shared_device_memory = cudart.cudaMalloc(max_device_memory) + self.shared_device_memory = shared_device_memory + # Load and activate TensorRT engines + for engine in self.engines.values(): + engine.activate(reuse_device_memory=self.shared_device_memory) + + def run_engine(self, model_name, feed_dict): + return self.engines[model_name].infer(feed_dict, self.stream, use_cuda_graph=self.use_cuda_graph) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/engine_builder_torch.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/engine_builder_torch.py new file mode 100644 index 0000000000000000000000000000000000000000..9cddc783cc006757effe938dffef971466db630d --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/engine_builder_torch.py @@ -0,0 +1,108 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +# -------------------------------------------------------------------------- +import logging + +from diffusion_models import PipelineInfo +from engine_builder import EngineBuilder, EngineType + +logger = logging.getLogger(__name__) + + +class TorchEngineBuilder(EngineBuilder): + def __init__( + self, + pipeline_info: PipelineInfo, + max_batch_size=16, + device="cuda", + use_cuda_graph=False, + ): + """ + Initializes the ONNX Runtime TensorRT ExecutionProvider Engine Builder. + + Args: + pipeline_info (PipelineInfo): + Version and Type of pipeline. + max_batch_size (int): + Maximum batch size for dynamic batch engine. + device (str): + device to run. + use_cuda_graph (bool): + Use CUDA graph to capture engine execution and then launch inference + """ + super().__init__( + EngineType.TORCH, + pipeline_info, + max_batch_size=max_batch_size, + device=device, + use_cuda_graph=use_cuda_graph, + ) + + self.compile_config = {} + if use_cuda_graph: + self.compile_config = { + "clip": {"mode": "reduce-overhead", "dynamic": False}, + "clip2": {"mode": "reduce-overhead", "dynamic": False}, + "unet": {"mode": "reduce-overhead", "fullgraph": True, "dynamic": False}, + "unetxl": {"mode": "reduce-overhead", "fullgraph": True, "dynamic": False}, + "vae": {"mode": "reduce-overhead", "fullgraph": False, "dynamic": False}, + } + + def build_engines( + self, + framework_model_dir: str, + ): + import torch # noqa: PLC0415 + + self.torch_device = torch.device("cuda", torch.cuda.current_device()) + self.load_models(framework_model_dir) + + pipe = self.load_pipeline_with_lora() if self.pipeline_info.lora_weights else None + + built_engines = {} + for model_name, model_obj in self.models.items(): + model = self.get_or_load_model(pipe, model_name, model_obj, framework_model_dir) + if self.pipeline_info.is_xl() and not self.custom_fp16_vae: + model = model.to(device=self.torch_device, dtype=torch.float32) + else: + model = model.to(device=self.torch_device, dtype=torch.float16) + + if model_name in self.compile_config: + compile_config = self.compile_config[model_name] + if model_name in ["unet", "unetxl"]: + model.to(memory_format=torch.channels_last) + engine = torch.compile(model, **compile_config) + built_engines[model_name] = engine + else: # eager mode + built_engines[model_name] = model + + self.engines = built_engines + + def run_engine(self, model_name, feed_dict): + if model_name in ["unet", "unetxl"]: + if "controlnet_images" in feed_dict: + return {"latent": self.engines[model_name](**feed_dict)} + + if model_name == "unetxl": + added_cond_kwargs = {k: feed_dict[k] for k in feed_dict if k in ["text_embeds", "time_ids"]} + return { + "latent": self.engines[model_name]( + feed_dict["sample"], + feed_dict["timestep"], + feed_dict["encoder_hidden_states"], + added_cond_kwargs=added_cond_kwargs, + return_dict=False, + )[0] + } + + return { + "latent": self.engines[model_name]( + feed_dict["sample"], feed_dict["timestep"], feed_dict["encoder_hidden_states"], return_dict=False + )[0] + } + + if model_name in ["vae_encoder"]: + return {"latent": self.engines[model_name](feed_dict["images"])} + + raise RuntimeError(f"Shall not reach here: {model_name}") diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/optimize_pipeline.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/optimize_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..83e4dac2d09aa9553eaedefdae3085f56d43024d --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/optimize_pipeline.py @@ -0,0 +1,590 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +# -------------------------------------------------------------------------- +# +# This script converts stable diffusion onnx models from float to half (mixed) precision for GPU inference. +# +# Before running this script, follow README.md to setup python environment and convert stable diffusion checkpoint +# to float32 onnx models. +# +# For example, the float32 ONNX pipeline is saved to ./sd-v1-5 directory, you can optimize and convert it to float16 +# like the following: +# python optimize_pipeline.py -i ./sd-v1-5 -o ./sd-v1-5-fp16 --float16 +# +# Note that the optimizations are carried out for CUDA Execution Provider at first, other EPs may not have the support +# for the fused operators. The users could disable the operator fusion manually to workaround. + +import argparse +import logging +import os +import shutil +import tempfile +import warnings +from pathlib import Path + +import onnx +from fusion_options import FusionOptions +from onnx_model_clip import ClipOnnxModel +from onnx_model_mmdit import MmditOnnxModel +from onnx_model_t5 import T5OnnxModel +from onnx_model_unet import UnetOnnxModel +from onnx_model_vae import VaeOnnxModel +from optimizer import optimize_by_onnxruntime, optimize_model +from packaging import version + +import onnxruntime + +logger = logging.getLogger(__name__) + + +def has_external_data(onnx_model_path): + original_model = onnx.load_model(str(onnx_model_path), load_external_data=False) + for initializer in original_model.graph.initializer: + if initializer.HasField("data_location") and initializer.data_location == onnx.TensorProto.EXTERNAL: + return True + return False + + +def is_sd_3(source_dir: Path): + return (source_dir / "text_encoder_3").exists() + + +def is_sdxl(source_dir: Path): + return ( + (source_dir / "text_encoder_2").exists() + and not (source_dir / "text_encoder_3").exists() + and not (source_dir / "transformer").exists() + ) + + +def is_flux(source_dir: Path): + return ( + (source_dir / "text_encoder_2").exists() + and not (source_dir / "text_encoder_3").exists() + and (source_dir / "transformer").exists() + ) + + +def _classify_pipeline_type(source_dir: Path): + # May also check _class_name in model_index.json like `StableDiffusion3Pipeline` or `FluxPipeline` etc to classify. + if is_sd_3(source_dir): + return "sd3" + + if is_flux(source_dir): + return "flux" + + if is_sdxl(source_dir): + return "sdxl" + + # sd 1.x and 2.x + return "sd" + + +def _get_model_list(pipeline_type: str): + if pipeline_type == "sd3": + return ["text_encoder", "text_encoder_2", "text_encoder_3", "transformer", "vae_encoder", "vae_decoder"] + + if pipeline_type == "flux": + return ["text_encoder", "text_encoder_2", "transformer", "vae_encoder", "vae_decoder"] + + if pipeline_type == "sdxl": + return ["text_encoder", "text_encoder_2", "unet", "vae_encoder", "vae_decoder"] + + assert pipeline_type == "sd" + return ["text_encoder", "unet", "vae_encoder", "vae_decoder"] + + +def _optimize_sd_pipeline( + source_dir: Path, + target_dir: Path, + pipeline_type: str, + model_list: list[str], + use_external_data_format: bool | None, + float16: bool, + bfloat16: bool, + force_fp32_ops: list[str], + enable_runtime_optimization: bool, + args, +): + """Optimize onnx models used in stable diffusion onnx pipeline and optionally convert to float16. + + Args: + source_dir (Path): Root of input directory of stable diffusion onnx pipeline with float32 models. + target_dir (Path): Root of output directory of stable diffusion onnx pipeline with optimized models. + model_list (List[str]): list of directory names with onnx model. + use_external_data_format (Optional[bool]): use external data format. + float16 (bool): use half precision + bfloat16 (bool): use bfloat16 as fallback if float16 is also provided. + force_fp32_ops(List[str]): operators that are forced to run in float32. + enable_runtime_optimization(bool): run graph optimization using Onnx Runtime. + + Raises: + RuntimeError: input onnx model does not exist + RuntimeError: output onnx model path existed + """ + is_flux_pipeline = pipeline_type == "flux" + model_type_mapping = { + "transformer": "mmdit", + "unet": "unet", + "vae_encoder": "vae", + "vae_decoder": "vae", + "text_encoder": "clip", + "text_encoder_2": "t5" if is_flux_pipeline else "clip", + "text_encoder_3": "t5", # t5-v1_1-xxl is used in SD 3.x text_encoder_3 and Flux text_encoder_2. + "safety_checker": "unet", + } + + model_type_class_mapping = { + "unet": UnetOnnxModel, + "vae": VaeOnnxModel, + "clip": ClipOnnxModel, + "t5": T5OnnxModel, + "mmdit": MmditOnnxModel, + } + + force_fp32_operators = { + "unet": [], + "vae_encoder": [], + "vae_decoder": [], + "text_encoder": [], + "text_encoder_2": [], + "safety_checker": [], + "text_encoder_3": [], + "transformer": [], + } + + # The node block list is generated by running the fp32 model and get statistics of node inputs and outputs. + # Nodes with any input or output of float or double data type, but value ouf of range of float16 are candidates. + # python optimize_pipeline.py -i ./flux1_schnell_onnx/fp32 -o ./flux1_schnell_onnx/fp32_opt + # export ORT_DEBUG_NODE_IO_DUMP_STATISTICS_DATA=1 + # export ORT_DEBUG_NODE_IO_DUMP_INPUT_DATA=1 + # export ORT_DEBUG_NODE_IO_DUMP_OUTPUT_DATA=1 + # python benchmark.py --height 1024 --width 1024 --steps 4 -b 1 -v Flux.1S -p flux1_schnell_onnx/fp32_opt -e optimum >stdout.txt 2>stderr.txt + # Warning: The node name might change in different export settings. See benchmark_flux.sh for the settings. + flux_node_block_list = { + "text_encoder_2": [ + "/encoder/block.10/layer.1/DenseReluDense/wo/MatMul", + "SkipLayerNorm_20", + "SkipLayerNorm_21", + "SkipLayerNorm_22", + "SkipLayerNorm_23", + "SkipLayerNorm_24", + "SkipLayerNorm_25", + "SkipLayerNorm_26", + "SkipLayerNorm_27", + "SkipLayerNorm_28", + "SkipLayerNorm_29", + "SkipLayerNorm_30", + "SkipLayerNorm_31", + "SkipLayerNorm_32", + "SkipLayerNorm_33", + "SkipLayerNorm_34", + "SkipLayerNorm_35", + "SkipLayerNorm_36", + "SkipLayerNorm_37", + "SkipLayerNorm_38", + "SkipLayerNorm_39", + "SkipLayerNorm_40", + "SkipLayerNorm_41", + "SkipLayerNorm_42", + "SkipLayerNorm_43", + "SkipLayerNorm_44", + "SkipLayerNorm_45", + "/encoder/block.23/layer.1/DenseReluDense/wo/MatMul", + "SkipLayerNorm_46", + ], + "vae_decoder": [ + "/decoder/mid_block/attentions.0/MatMul", + "/decoder/mid_block/attentions.0/Softmax", + ], + "transformer": [ + "/transformer_blocks.18/Mul_5", + "/transformer_blocks.18/Add_7", + "/Concat_1", + "LayerNorm_76", + "/single_transformer_blocks.0/Add", + "LayerNorm_77", + "/single_transformer_blocks.1/Add", + "LayerNorm_78", + "/single_transformer_blocks.2/Add", + "LayerNorm_79", + "/single_transformer_blocks.3/Add", + "LayerNorm_80", + "/single_transformer_blocks.4/Add", + "LayerNorm_81", + "/single_transformer_blocks.5/Add", + "LayerNorm_82", + "/single_transformer_blocks.6/Add", + "LayerNorm_83", + "/single_transformer_blocks.7/Add", + "LayerNorm_84", + "/single_transformer_blocks.8/Add", + "LayerNorm_85", + "/single_transformer_blocks.9/Add", + "LayerNorm_86", + "/single_transformer_blocks.10/Add", + "LayerNorm_87", + "/single_transformer_blocks.11/Add", + "LayerNorm_88", + "/single_transformer_blocks.12/Add", + "LayerNorm_89", + "/single_transformer_blocks.13/Add", + "LayerNorm_90", + "/single_transformer_blocks.14/Add", + "LayerNorm_91", + "/single_transformer_blocks.15/Add", + "LayerNorm_92", + "/single_transformer_blocks.16/Add", + "LayerNorm_93", + "/single_transformer_blocks.17/Add", + "LayerNorm_94", + "/single_transformer_blocks.18/Add", + "LayerNorm_95", + "/single_transformer_blocks.19/Add", + "LayerNorm_96", + "/single_transformer_blocks.20/Add", + "LayerNorm_97", + "/single_transformer_blocks.21/Add", + "LayerNorm_98", + "/single_transformer_blocks.22/Add", + "LayerNorm_99", + "/single_transformer_blocks.23/Add", + "LayerNorm_100", + "/single_transformer_blocks.24/Add", + "LayerNorm_101", + "/single_transformer_blocks.25/Add", + "LayerNorm_102", + "/single_transformer_blocks.26/Add", + "LayerNorm_103", + "/single_transformer_blocks.27/Add", + "LayerNorm_104", + "/single_transformer_blocks.28/Add", + "LayerNorm_105", + "/single_transformer_blocks.29/Add", + "LayerNorm_106", + "/single_transformer_blocks.30/Add", + "LayerNorm_107", + "/single_transformer_blocks.31/Add", + "LayerNorm_108", + "/single_transformer_blocks.32/Add", + "LayerNorm_109", + "/single_transformer_blocks.33/Add", + "LayerNorm_110", + "/single_transformer_blocks.34/Add", + "LayerNorm_111", + "/single_transformer_blocks.35/Add", + "LayerNorm_112", + "/single_transformer_blocks.36/Add", + "LayerNorm_113", + "/single_transformer_blocks.37/Add", + "/Shape", + "/Slice", + ], + } + + sd3_node_block_list = {"text_encoder_3": flux_node_block_list["text_encoder_2"]} + + if force_fp32_ops: + for fp32_operator in force_fp32_ops: + parts = fp32_operator.split(":") + if len(parts) == 2 and parts[0] in force_fp32_operators and (parts[1] and parts[1][0].isupper()): + force_fp32_operators[parts[0]].append(parts[1]) + else: + raise ValueError( + f"--force_fp32_ops shall be in the format of module:operator like unet:Attention, got {fp32_operator}" + ) + + op_counters = {} + for name, model_type in model_type_mapping.items(): + onnx_model_path = source_dir / name / "model.onnx" + if not os.path.exists(onnx_model_path): + if name != "safety_checker" and name in model_list: + logger.warning("input onnx model does not exist: %s", onnx_model_path) + # some model are optional so we do not raise error here. + continue + + # Prepare output directory + optimized_model_path = target_dir / name / "model.onnx" + if os.path.exists(optimized_model_path): + if not args.overwrite: + logger.warning("Skipped optimization since the target file existed: %s", optimized_model_path) + continue + output_dir = optimized_model_path.parent + output_dir.mkdir(parents=True, exist_ok=True) + + if use_external_data_format is None: + use_external_data_format = has_external_data(onnx_model_path) + + # Graph fusion before fp16 conversion, otherwise they cannot be fused later. + logger.info("Optimize %s ...", onnx_model_path) + + args.model_type = model_type + fusion_options = FusionOptions.parse(args) + + if model_type in ["unet"]: + # Some optimizations are not available in v1.14 or older version: packed QKV and BiasAdd + has_all_optimizations = version.parse(onnxruntime.__version__) >= version.parse("1.15.0") + fusion_options.enable_packed_kv = float16 and fusion_options.enable_packed_kv + fusion_options.enable_packed_qkv = float16 and has_all_optimizations and fusion_options.enable_packed_qkv + fusion_options.enable_bias_add = has_all_optimizations and fusion_options.enable_bias_add + + m = optimize_model( + str(onnx_model_path), + model_type=model_type, + num_heads=0, # will be deduced from graph + hidden_size=0, # will be deduced from graph + opt_level=0, + optimization_options=fusion_options, + use_gpu=True, + provider=args.provider, + ) + + if float16: + model_node_block_list = ( + flux_node_block_list if is_flux_pipeline else sd3_node_block_list if pipeline_type == "sd3" else {} + ) + if name in model_node_block_list: + # Opset 12 does not support bfloat16. + # By default, optimum exports T5 model with opset 12. So we need to check the opset version. + use_bfloat16 = bfloat16 + if use_bfloat16: + for opset in m.model.opset_import: + if opset.domain in ["", "ai.onnx"] and opset.version < 13: + logger.warning( + "onnx model requires opset 13 or higher to use bfloat16. Fall back to float32." + ) + use_bfloat16 = False + + m.convert_float_to_float16( + keep_io_types=False, + node_block_list=model_node_block_list[name], + use_bfloat16_as_blocked_nodes_dtype=use_bfloat16, + ) + # For SD-XL, use FP16 in VAE decoder will cause NaN and black image so we keep it in FP32. + elif pipeline_type in ["sdxl"] and name in ["vae_decoder"]: + logger.info("Skip converting %s to float16 to avoid NaN", name) + else: + logger.info("Convert %s to float16 ...", name) + m.convert_float_to_float16( + keep_io_types=False, + op_block_list=force_fp32_operators[name], + ) + + if enable_runtime_optimization: + # Use this step to see the final graph that executed by Onnx Runtime. + with tempfile.TemporaryDirectory() as tmp_dir: + # Save to a temporary file so that we can load it with Onnx Runtime. + logger.info("Saving a temporary model to run OnnxRuntime graph optimizations...") + tmp_model_path = Path(tmp_dir) / "model.onnx" + m.save_model_to_file(str(tmp_model_path), use_external_data_format=use_external_data_format) + ort_optimized_model_path = Path(tmp_dir) / "optimized.onnx" + optimize_by_onnxruntime( + str(tmp_model_path), + use_gpu=True, + provider=args.provider, + optimized_model_path=str(ort_optimized_model_path), + save_as_external_data=use_external_data_format, + ) + model = onnx.load(str(ort_optimized_model_path), load_external_data=True) + m = model_type_class_mapping[model_type](model) + + m.get_operator_statistics() + op_counters[name] = m.get_fused_operator_statistics() + m.save_model_to_file(str(optimized_model_path), use_external_data_format=use_external_data_format) + logger.info("%s is optimized", name) + logger.info("*" * 20) + + return op_counters + + +def _copy_extra_directory(source_dir: Path, target_dir: Path, model_list: list[str]): + """Copy extra directory that does not have onnx model + + Args: + source_dir (Path): source directory + target_dir (Path): target directory + model_list (List[str]): list of directory names with onnx model. + + Raises: + RuntimeError: source path does not exist + """ + extra_dirs = ["scheduler", "tokenizer", "tokenizer_2", "tokenizer_3", "feature_extractor"] + + for name in extra_dirs: + source_path = source_dir / name + if not os.path.exists(source_path): + continue + + target_path = target_dir / name + if target_path.exists(): + shutil.rmtree(target_path) + shutil.copytree(source_path, target_path) + logger.info("%s => %s", source_path, target_path) + + extra_files = ["model_index.json"] + for name in extra_files: + source_path = source_dir / name + if not os.path.exists(source_path): + raise RuntimeError(f"source path does not exist: {source_path}") + + target_path = target_dir / name + shutil.copyfile(source_path, target_path) + logger.info("%s => %s", source_path, target_path) + + # Some directory are optional + for onnx_model_dir in model_list: + source_path = source_dir / onnx_model_dir / "config.json" + target_path = target_dir / onnx_model_dir / "config.json" + if source_path.exists(): + target_path.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(source_path, target_path) + logger.info("%s => %s", source_path, target_path) + + +def optimize_stable_diffusion_pipeline( + input_dir: str, + output_dir: str, + overwrite: bool, + use_external_data_format: bool | None, + float16: bool, + enable_runtime_optimization: bool, + args, +): + if os.path.exists(output_dir): + if overwrite: + shutil.rmtree(output_dir, ignore_errors=True) + + source_dir = Path(input_dir) + target_dir = Path(output_dir) + target_dir.mkdir(parents=True, exist_ok=True) + + pipeline_type = _classify_pipeline_type(source_dir) + model_list = _get_model_list(pipeline_type) + + _copy_extra_directory(source_dir, target_dir, model_list) + + return _optimize_sd_pipeline( + source_dir, + target_dir, + pipeline_type, + model_list, + use_external_data_format, + float16, + args.bfloat16, + args.force_fp32_ops, + enable_runtime_optimization, + args, + ) + + +def parse_arguments(argv: list[str] | None = None): + """Parse arguments + + Returns: + Namespace: arguments + """ + parser = argparse.ArgumentParser() + + parser.add_argument( + "-i", + "--input", + required=True, + type=str, + help="Root of input directory of stable diffusion onnx pipeline with float32 models.", + ) + + parser.add_argument( + "-o", + "--output", + required=True, + type=str, + help="Root of output directory of stable diffusion onnx pipeline with optimized models.", + ) + + parser.add_argument( + "--float16", + required=False, + action="store_true", + help="Output models of float16, except some nodes falls back to float32 or bfloat16 to avoid overflow.", + ) + parser.set_defaults(float16=False) + + parser.add_argument( + "--bfloat16", + required=False, + action="store_true", + help="Allow bfloat16 as fallback if --float16 is also provided.", + ) + parser.set_defaults(bfloat16=False) + + parser.add_argument( + "--force_fp32_ops", + required=False, + nargs="+", + type=str, + help="Force given operators (like unet:Attention) to run in float32. It is case sensitive!", + ) + + parser.add_argument( + "--inspect", + required=False, + action="store_true", + help="Save the optimized graph from Onnx Runtime. " + "This option has no impact on inference performance except it might reduce session creation time.", + ) + parser.set_defaults(inspect=False) + + parser.add_argument( + "--overwrite", + required=False, + action="store_true", + help="Overwrite exists files.", + ) + parser.set_defaults(overwrite=False) + + parser.add_argument( + "-e", + "--use_external_data_format", + required=False, + action="store_true", + help="Onnx model larger than 2GB need to use external data format. " + "If specified, save each onnx model to two files: one for onnx graph, another for weights. " + "If not specified, use same format as original model by default. ", + ) + parser.set_defaults(use_external_data_format=None) + + parser.add_argument( + "--provider", + required=False, + type=str, + default=None, + help="Execution provider to use.", + ) + + FusionOptions.add_arguments(parser) + + args = parser.parse_args(argv) + return args + + +def main(argv: list[str] | None = None): + warnings.warn( + "This example is deprecated. Use the Olive recipe instead: " + "https://github.com/microsoft/olive-recipes/tree/main", + DeprecationWarning, + stacklevel=2, + ) + args = parse_arguments(argv) + + logger.info("Arguments: %s", str(args)) + + # Return op counters for testing purpose. + return optimize_stable_diffusion_pipeline( + args.input, args.output, args.overwrite, args.use_external_data_format, args.float16, args.inspect, args + ) + + +if __name__ == "__main__": + logging.basicConfig(format="%(funcName)20s: %(message)s", level=logging.INFO) + main() diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/ort_optimizer.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/ort_optimizer.py new file mode 100644 index 0000000000000000000000000000000000000000..8ea1a0969fd9d274b678e413327866be9800025f --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/ort_optimizer.py @@ -0,0 +1,136 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +# -------------------------------------------------------------------------- + +""" +ONNX Model Optimizer for Stable Diffusion +""" + +import gc +import logging +import os +import shutil +import tempfile +from pathlib import Path + +import onnx +from packaging import version + +from onnxruntime.transformers.fusion_options import FusionOptions +from onnxruntime.transformers.onnx_model_clip import ClipOnnxModel +from onnxruntime.transformers.onnx_model_unet import UnetOnnxModel +from onnxruntime.transformers.onnx_model_vae import VaeOnnxModel +from onnxruntime.transformers.optimizer import optimize_by_onnxruntime, optimize_model + +logger = logging.getLogger(__name__) + + +class OrtStableDiffusionOptimizer: + def __init__(self, model_type: str): + assert model_type in ["vae", "unet", "clip"] + self.model_type = model_type + self.model_type_class_mapping = { + "unet": UnetOnnxModel, + "vae": VaeOnnxModel, + "clip": ClipOnnxModel, + } + + def _optimize_by_ort(self, onnx_model, use_external_data_format, tmp_dir): + # Save to a temporary file so that we can load it with Onnx Runtime. + logger.info("Saving a temporary model to run OnnxRuntime graph optimizations...") + tmp_model_path = Path(tmp_dir) / "model.onnx" + onnx_model.save_model_to_file(str(tmp_model_path), use_external_data_format=use_external_data_format) + + del onnx_model + gc.collect() + + ort_optimized_model_path = Path(tmp_dir) / "optimized.onnx" + optimize_by_onnxruntime( + str(tmp_model_path), + use_gpu=True, + optimized_model_path=str(ort_optimized_model_path), + save_as_external_data=use_external_data_format, + external_data_filename="optimized.onnx_data", + ) + model = onnx.load(str(ort_optimized_model_path), load_external_data=True) + return self.model_type_class_mapping[self.model_type](model) + + def optimize_by_ort(self, onnx_model, use_external_data_format=False, tmp_dir=None): + # Use this step to see the final graph that executed by Onnx Runtime. + if tmp_dir is None: + with tempfile.TemporaryDirectory() as temp_dir: + return self._optimize_by_ort(onnx_model, use_external_data_format, temp_dir) + else: + os.makedirs(tmp_dir, exist_ok=True) + model = self._optimize_by_ort(onnx_model, use_external_data_format, tmp_dir) + shutil.rmtree(tmp_dir) + return model + + def optimize( + self, + input_fp32_onnx_path, + optimized_onnx_path, + float16=True, + keep_io_types=False, + fp32_op_list=None, + keep_outputs=None, + optimize_by_ort=True, + optimize_by_fusion=True, + final_target_float16=True, + tmp_dir=None, + ): + """Optimize onnx model using ONNX Runtime transformers optimizer""" + logger.info(f"Optimize {input_fp32_onnx_path}...") + + if optimize_by_fusion: + fusion_options = FusionOptions(self.model_type) + + # It is allowed float16=False and final_target_float16=True, for using fp32 as intermediate optimization step. + # For rare fp32 use case, we can disable packed kv/qkv since there is no fp32 TRT fused attention kernel. + if self.model_type in ["unet"] and not final_target_float16: + fusion_options.enable_packed_kv = False + fusion_options.enable_packed_qkv = False + + m = optimize_model( + input_fp32_onnx_path, + model_type=self.model_type, + num_heads=0, # will be deduced from graph + hidden_size=0, # will be deduced from graph + opt_level=0, + optimization_options=fusion_options, + use_gpu=True, + ) + else: + model = onnx.load_model(input_fp32_onnx_path, load_external_data=True) + m = self.model_type_class_mapping[self.model_type](model) + + if keep_outputs: + m.prune_graph(outputs=keep_outputs) + + model_size = m.model.ByteSize() + + # model size might be negative (overflow?) in Windows. + use_external_data_format = model_size <= 0 or model_size >= onnx.checker.MAXIMUM_PROTOBUF + + # Note that ORT < 1.16 could not save model larger than 2GB. + # This step is is optional since it has no impact on inference latency. + # The optimized model is not portable. It could only run in the same execution provider (CUDA EP in this case). + # When the model has been optimized by onnxruntime, we can disable optimization in SessionOption + # to save session creation time. Another benefit is to inspect the final graph for developing purpose. + from onnxruntime import __version__ as ort_version # noqa: PLC0415 + + if optimize_by_ort and (version.parse(ort_version) >= version.parse("1.16.0") or not use_external_data_format): + m = self.optimize_by_ort(m, use_external_data_format=use_external_data_format, tmp_dir=tmp_dir) + + if float16: + logger.info("Convert to float16 ...") + m.convert_float_to_float16( + keep_io_types=keep_io_types, + op_block_list=fp32_op_list, + ) + + m.get_operator_statistics() + m.get_fused_operator_statistics() + m.save_model_to_file(optimized_onnx_path, use_external_data_format=use_external_data_format) + logger.info("%s is optimized: %s", self.model_type, optimized_onnx_path) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/pipeline_stable_diffusion.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/pipeline_stable_diffusion.py new file mode 100644 index 0000000000000000000000000000000000000000..5ad7ac91a9df978a537ccad546b891e63aa83e6a --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/pipeline_stable_diffusion.py @@ -0,0 +1,831 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +# -------------------------------------------------------------------------- +# Modified from TensorRT demo diffusion, which has the following license: +# +# SPDX-FileCopyrightText: Copyright (c) 1993-2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# -------------------------------------------------------------------------- + +import os +import pathlib +import random +import time +from typing import Any + +import numpy as np +import nvtx +import torch +from cuda import cudart +from diffusion_models import PipelineInfo, get_tokenizer +from diffusion_schedulers import DDIMScheduler, EulerAncestralDiscreteScheduler, LCMScheduler, UniPCMultistepScheduler +from engine_builder import EngineType +from engine_builder_ort_cuda import OrtCudaEngineBuilder +from engine_builder_ort_trt import OrtTensorrtEngineBuilder +from engine_builder_tensorrt import TensorrtEngineBuilder +from engine_builder_torch import TorchEngineBuilder +from PIL import Image + + +class StableDiffusionPipeline: + """ + Stable Diffusion pipeline using TensorRT. + """ + + def __init__( + self, + pipeline_info: PipelineInfo, + max_batch_size=16, + scheduler="DDIM", + device="cuda", + output_dir=".", + verbose=False, + nvtx_profile=False, + use_cuda_graph=False, + framework_model_dir="pytorch_model", + engine_type: EngineType = EngineType.ORT_CUDA, + ): + """ + Initializes the Diffusion pipeline. + + Args: + pipeline_info (PipelineInfo): + Version and Type of pipeline. + max_batch_size (int): + Maximum batch size for dynamic batch engine. + scheduler (str): + The scheduler to guide the denoising process. Must be one of [DDIM, EulerA, UniPC, LCM]. + device (str): + PyTorch device to run inference. Default: 'cuda' + output_dir (str): + Output directory for log files and image artifacts + verbose (bool): + Enable verbose logging. + nvtx_profile (bool): + Insert NVTX profiling markers. + use_cuda_graph (bool): + Use CUDA graph to capture engine execution and then launch inference + framework_model_dir (str): + cache directory for framework checkpoints + engine_type (EngineType) + backend engine type like ORT_TRT or TRT + """ + + self.pipeline_info = pipeline_info + self.version = pipeline_info.version + + self.vae_scaling_factor = pipeline_info.vae_scaling_factor() + + self.max_batch_size = max_batch_size + + self.framework_model_dir = framework_model_dir + self.output_dir = output_dir + for directory in [self.framework_model_dir, self.output_dir]: + if not os.path.exists(directory): + print(f"[I] Create directory: {directory}") + pathlib.Path(directory).mkdir(parents=True) + + self.device = device + self.torch_device = torch.device(device, torch.cuda.current_device()) + self.verbose = verbose + self.nvtx_profile = nvtx_profile + + self.use_cuda_graph = use_cuda_graph + + self.tokenizer = None + self.tokenizer2 = None + + self.generator = torch.Generator(device="cuda") + self.actual_steps = None + + self.current_scheduler = None + self.set_scheduler(scheduler) + + # backend engine + self.engine_type = engine_type + if engine_type == EngineType.TRT: + self.backend = TensorrtEngineBuilder(pipeline_info, max_batch_size, device, use_cuda_graph) + elif engine_type == EngineType.ORT_TRT: + self.backend = OrtTensorrtEngineBuilder(pipeline_info, max_batch_size, device, use_cuda_graph) + elif engine_type == EngineType.ORT_CUDA: + self.backend = OrtCudaEngineBuilder(pipeline_info, max_batch_size, device, use_cuda_graph) + elif engine_type == EngineType.TORCH: + self.backend = TorchEngineBuilder(pipeline_info, max_batch_size, device, use_cuda_graph) + else: + raise RuntimeError(f"Backend engine type {engine_type.name} is not supported") + + # Load text tokenizer + if not self.pipeline_info.is_xl_refiner(): + self.tokenizer = get_tokenizer(self.pipeline_info, self.framework_model_dir, subfolder="tokenizer") + + if self.pipeline_info.is_xl(): + self.tokenizer2 = get_tokenizer(self.pipeline_info, self.framework_model_dir, subfolder="tokenizer_2") + + self.control_image_processor = None + if self.pipeline_info.is_xl() and self.pipeline_info.controlnet: + from diffusers.image_processor import VaeImageProcessor # noqa: PLC0415 + + self.control_image_processor = VaeImageProcessor( + vae_scale_factor=8, do_convert_rgb=True, do_normalize=False + ) + + # Create CUDA events + self.events = {} + for stage in ["clip", "denoise", "vae", "vae_encoder", "pil"]: + for marker in ["start", "stop"]: + self.events[stage + "-" + marker] = cudart.cudaEventCreate()[1] + self.markers = {} + + def is_backend_tensorrt(self): + return self.engine_type == EngineType.TRT + + def set_scheduler(self, scheduler: str): + if scheduler == self.current_scheduler: + return + + # Scheduler options + sched_opts = {"num_train_timesteps": 1000, "beta_start": 0.00085, "beta_end": 0.012} + if self.version in ("2.0", "2.1"): + sched_opts["prediction_type"] = "v_prediction" + else: + sched_opts["prediction_type"] = "epsilon" + + if scheduler == "DDIM": + self.scheduler = DDIMScheduler(device=self.device, **sched_opts) + elif scheduler == "EulerA": + self.scheduler = EulerAncestralDiscreteScheduler(device=self.device, **sched_opts) + elif scheduler == "UniPC": + self.scheduler = UniPCMultistepScheduler(device=self.device, **sched_opts) + elif scheduler == "LCM": + self.scheduler = LCMScheduler(device=self.device, **sched_opts) + else: + raise ValueError("Scheduler should be either DDIM, EulerA, UniPC or LCM") + + self.current_scheduler = scheduler + self.denoising_steps = None + + def set_denoising_steps(self, denoising_steps: int): + if not (self.denoising_steps == denoising_steps and isinstance(self.scheduler, DDIMScheduler)): + self.scheduler.set_timesteps(denoising_steps) + self.scheduler.configure() + self.denoising_steps = denoising_steps + + def load_resources(self, image_height, image_width, batch_size): + # If engine is built with static input shape, call this only once after engine build. + # Otherwise, it need be called before every inference run. + self.backend.load_resources(image_height, image_width, batch_size) + + def set_random_seed(self, seed): + if isinstance(seed, int): + self.generator.manual_seed(seed) + else: + self.generator.seed() + + def get_current_seed(self): + return self.generator.initial_seed() + + def teardown(self): + for e in self.events.values(): + cudart.cudaEventDestroy(e) + + if self.backend: + self.backend.teardown() + + def run_engine(self, model_name, feed_dict): + return self.backend.run_engine(model_name, feed_dict) + + def initialize_latents(self, batch_size, unet_channels, latent_height, latent_width): + latents_dtype = torch.float16 + latents_shape = (batch_size, unet_channels, latent_height, latent_width) + latents = torch.randn(latents_shape, device=self.device, dtype=latents_dtype, generator=self.generator) + # Scale the initial noise by the standard deviation required by the scheduler + latents = latents * self.scheduler.init_noise_sigma + return latents + + def initialize_timesteps(self, timesteps, strength): + """Initialize timesteps for refiner.""" + self.scheduler.set_timesteps(timesteps) + offset = self.scheduler.steps_offset if hasattr(self.scheduler, "steps_offset") else 0 + init_timestep = int(timesteps * strength) + offset + init_timestep = min(init_timestep, timesteps) + t_start = max(timesteps - init_timestep + offset, 0) + timesteps = self.scheduler.timesteps[t_start:].to(self.device) + return timesteps, t_start + + def initialize_refiner(self, batch_size, image, strength): + """Add noise to a reference image.""" + # Initialize timesteps + timesteps, t_start = self.initialize_timesteps(self.denoising_steps, strength) + + latent_timestep = timesteps[:1].repeat(batch_size) + + # Pre-process input image + image = self.preprocess_images(batch_size, (image,))[0] + + # VAE encode init image + if image.shape[1] == 4: + init_latents = image + else: + init_latents = self.encode_image(image) + + # Add noise to latents using timesteps + noise = torch.randn(init_latents.shape, device=self.device, dtype=torch.float16, generator=self.generator) + + latents = self.scheduler.add_noise(init_latents, noise, t_start, latent_timestep) + + return timesteps, t_start, latents + + def _get_add_time_ids( + self, + original_size, + crops_coords_top_left, + target_size, + aesthetic_score, + negative_aesthetic_score, + dtype, + requires_aesthetics_score, + ): + if requires_aesthetics_score: + add_time_ids = list(original_size + crops_coords_top_left + (aesthetic_score,)) + add_neg_time_ids = list(original_size + crops_coords_top_left + (negative_aesthetic_score,)) + else: + add_time_ids = list(original_size + crops_coords_top_left + target_size) + add_neg_time_ids = list(original_size + crops_coords_top_left + target_size) + + add_time_ids = torch.tensor([add_time_ids], dtype=dtype) + add_neg_time_ids = torch.tensor([add_neg_time_ids], dtype=dtype) + + return add_time_ids, add_neg_time_ids + + def start_profile(self, name, color="blue"): + if self.nvtx_profile: + self.markers[name] = nvtx.start_range(message=name, color=color) + event_name = name + "-start" + if event_name in self.events: + cudart.cudaEventRecord(self.events[event_name], 0) + + def stop_profile(self, name): + event_name = name + "-stop" + if event_name in self.events: + cudart.cudaEventRecord(self.events[event_name], 0) + if self.nvtx_profile: + nvtx.end_range(self.markers[name]) + + def preprocess_images(self, batch_size, images=()): + self.start_profile("preprocess", color="pink") + init_images = [] + for i in images: + image = i.to(self.device) + if image.shape[0] != batch_size: + image = image.repeat(batch_size, 1, 1, 1) + init_images.append(image) + self.stop_profile("preprocess") + return tuple(init_images) + + def preprocess_controlnet_images( + self, batch_size, images=None, do_classifier_free_guidance=True, height=1024, width=1024 + ): + """ + Process a list of PIL.Image.Image as control images, and return a torch tensor. + """ + if images is None: + return None + self.start_profile("preprocess", color="pink") + + if not self.pipeline_info.is_xl(): + images = [ + torch.from_numpy( + (np.array(image.convert("RGB")).astype(np.float32) / 255.0)[..., None].transpose(3, 2, 0, 1) + ) + .to(device=self.device, dtype=torch.float16) + .repeat_interleave(batch_size, dim=0) + for image in images + ] + else: + images = [ + self.control_image_processor.preprocess(image, height=height, width=width) + .to(device=self.device, dtype=torch.float16) + .repeat_interleave(batch_size, dim=0) + for image in images + ] + + if do_classifier_free_guidance: + images = [torch.cat([i] * 2) for i in images] + images = torch.cat([image[None, ...] for image in images], dim=0) + + self.stop_profile("preprocess") + return images + + def encode_prompt( + self, + prompt, + negative_prompt, + encoder="clip", + tokenizer=None, + pooled_outputs=False, + output_hidden_states=False, + force_zeros_for_empty_prompt=False, + do_classifier_free_guidance=True, + dtype=torch.float16, + ): + if tokenizer is None: + tokenizer = self.tokenizer + + self.start_profile("clip", color="green") + + def tokenize(prompt, output_hidden_states): + text_input_ids = ( + tokenizer( + prompt, + padding="max_length", + max_length=tokenizer.model_max_length, + truncation=True, + return_tensors="pt", + ) + .input_ids.type(torch.int32) + .to(self.device) + ) + + hidden_states = None + if self.engine_type == EngineType.TORCH: + outputs = self.backend.engines[encoder](text_input_ids) + text_embeddings = outputs[0] + if output_hidden_states: + hidden_states = outputs["last_hidden_state"] + else: + outputs = self.run_engine(encoder, {"input_ids": text_input_ids}) + text_embeddings = outputs["text_embeddings"] + if output_hidden_states: + hidden_states = outputs["hidden_states"] + return text_embeddings, hidden_states + + # Tokenize prompt + text_embeddings, hidden_states = tokenize(prompt, output_hidden_states) + + # NOTE: output tensor for CLIP must be cloned because it will be overwritten when called again for negative prompt + text_embeddings = text_embeddings.clone() + if hidden_states is not None: + hidden_states = hidden_states.clone() + + # Note: negative prompt embedding is not needed for SD XL when guidance <= 1 + if do_classifier_free_guidance: + # For SD XL base, handle force_zeros_for_empty_prompt + is_empty_negative_prompt = all(not i for i in negative_prompt) + if force_zeros_for_empty_prompt and is_empty_negative_prompt: + uncond_embeddings = torch.zeros_like(text_embeddings) + if output_hidden_states: + uncond_hidden_states = torch.zeros_like(hidden_states) + else: + # Tokenize negative prompt + uncond_embeddings, uncond_hidden_states = tokenize(negative_prompt, output_hidden_states) + + # Concatenate the unconditional and text embeddings into a single batch to avoid doing two forward passes for classifier free guidance + text_embeddings = torch.cat([uncond_embeddings, text_embeddings]) + + if output_hidden_states: + hidden_states = torch.cat([uncond_hidden_states, hidden_states]) + + self.stop_profile("clip") + + if pooled_outputs: + # For text encoder in sdxl base + return hidden_states.to(dtype=dtype), text_embeddings.to(dtype=dtype) + + if output_hidden_states: + # For text encoder 2 in sdxl base or refiner + return hidden_states.to(dtype=dtype) + + # For text encoder in sd 1.5 + return text_embeddings.to(dtype=dtype) + + def denoise_latent( + self, + latents, + text_embeddings, + denoiser="unet", + timesteps=None, + step_offset=0, + guidance=7.5, + add_kwargs=None, + ): + do_classifier_free_guidance = guidance > 1.0 + + self.start_profile("denoise", color="blue") + + if not isinstance(timesteps, torch.Tensor): + timesteps = self.scheduler.timesteps + + for step_index, timestep in enumerate(timesteps): + # Expand the latents if we are doing classifier free guidance + latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents + + latent_model_input = self.scheduler.scale_model_input( + latent_model_input, step_offset + step_index, timestep + ) + + # Predict the noise residual + if self.nvtx_profile: + nvtx_unet = nvtx.start_range(message="unet", color="blue") + + params = { + "sample": latent_model_input, + "timestep": timestep.to(latents.dtype), + "encoder_hidden_states": text_embeddings, + } + + if add_kwargs: + params.update(add_kwargs) + + noise_pred = self.run_engine(denoiser, params)["latent"] + + if self.nvtx_profile: + nvtx.end_range(nvtx_unet) + + # perform guidance + if do_classifier_free_guidance: + noise_pred_uncond, noise_pred_text = noise_pred.chunk(2) + noise_pred = noise_pred_uncond + guidance * (noise_pred_text - noise_pred_uncond) + + if type(self.scheduler) is UniPCMultistepScheduler: + latents = self.scheduler.step(noise_pred, timestep, latents, return_dict=False)[0] + elif type(self.scheduler) is LCMScheduler: + latents = self.scheduler.step(noise_pred, timestep, latents, generator=self.generator)[0] + else: + latents = self.scheduler.step(noise_pred, latents, step_offset + step_index, timestep) + + # The actual number of steps. It might be different from denoising_steps. + self.actual_steps = len(timesteps) + + self.stop_profile("denoise") + return latents + + def encode_image(self, image): + self.start_profile("vae_encoder", color="red") + init_latents = self.run_engine("vae_encoder", {"images": image})["latent"] + init_latents = self.vae_scaling_factor * init_latents + self.stop_profile("vae_encoder") + return init_latents + + def decode_latent(self, latents): + self.start_profile("vae", color="red") + images = self.backend.vae_decode(latents) + self.stop_profile("vae") + return images + + def print_summary(self, tic, toc, batch_size, vae_enc=False, pil=False) -> dict[str, Any]: + throughput = batch_size / (toc - tic) + latency_clip = cudart.cudaEventElapsedTime(self.events["clip-start"], self.events["clip-stop"])[1] + latency_unet = cudart.cudaEventElapsedTime(self.events["denoise-start"], self.events["denoise-stop"])[1] + latency_vae = cudart.cudaEventElapsedTime(self.events["vae-start"], self.events["vae-stop"])[1] + latency_vae_encoder = ( + cudart.cudaEventElapsedTime(self.events["vae_encoder-start"], self.events["vae_encoder-stop"])[1] + if vae_enc + else None + ) + latency_pil = cudart.cudaEventElapsedTime(self.events["pil-start"], self.events["pil-stop"])[1] if pil else None + + latency = (toc - tic) * 1000.0 + + print("|----------------|--------------|") + print("| {:^14} | {:^12} |".format("Module", "Latency")) + print("|----------------|--------------|") + if vae_enc: + print("| {:^14} | {:>9.2f} ms |".format("VAE-Enc", latency_vae_encoder)) + print("| {:^14} | {:>9.2f} ms |".format("CLIP", latency_clip)) + print( + "| {:^14} | {:>9.2f} ms |".format( + "UNet" + ("+CNet" if self.pipeline_info.controlnet else "") + " x " + str(self.actual_steps), + latency_unet, + ) + ) + print("| {:^14} | {:>9.2f} ms |".format("VAE-Dec", latency_vae)) + pipeline = "Refiner" if self.pipeline_info.is_xl_refiner() else "Pipeline" + if pil: + print("| {:^14} | {:>9.2f} ms |".format("PIL", latency_pil)) + print("|----------------|--------------|") + print(f"| {pipeline:^14} | {latency:>9.2f} ms |") + print("|----------------|--------------|") + print(f"Throughput: {throughput:.2f} image/s") + + perf_data = { + "latency_clip": latency_clip, + "latency_unet": latency_unet, + "latency_vae": latency_vae, + "latency_pil": latency_pil, + "latency": latency, + "throughput": throughput, + } + if vae_enc: + perf_data["latency_vae_encoder"] = latency_vae_encoder + return perf_data + + @staticmethod + def pt_to_pil(images): + images = ( + ((images + 1) * 255 / 2).clamp(0, 255).detach().permute(0, 2, 3, 1).round().type(torch.uint8).cpu().numpy() + ) + return [Image.fromarray(images[i]) for i in range(images.shape[0])] + + @staticmethod + def pt_to_numpy(images: torch.FloatTensor): + """ + Convert a PyTorch tensor to a NumPy image. + """ + return ((images + 1) / 2).clamp(0, 1).detach().permute(0, 2, 3, 1).float().cpu().numpy() + + def metadata(self) -> dict[str, Any]: + data = { + "actual_steps": self.actual_steps, + "seed": self.get_current_seed(), + "name": self.pipeline_info.name(), + "custom_vae": self.pipeline_info.custom_fp16_vae(), + "custom_unet": self.pipeline_info.custom_unet(), + } + + if self.engine_type == EngineType.ORT_CUDA: + for engine_name, engine in self.backend.engines.items(): + data.update(engine.metadata(engine_name)) + + return data + + def save_images(self, images: list, prompt: list[str], negative_prompt: list[str], metadata: dict[str, Any]): + session_id = str(random.randint(1000, 9999)) + for i, image in enumerate(images): + seed = str(self.get_current_seed()) + prefix = "".join(x for x in prompt[i] if x.isalnum() or x in ", -").replace(" ", "_")[:20] + parts = [prefix, session_id, str(i + 1), str(seed), self.current_scheduler, str(self.actual_steps)] + image_path = os.path.join(self.output_dir, "-".join(parts) + ".png") + print(f"Saving image {i + 1} / {len(images)} to: {image_path}") + + from PIL import PngImagePlugin # noqa: PLC0415 + + info = PngImagePlugin.PngInfo() + for k, v in metadata.items(): + info.add_text(k, str(v)) + info.add_text("prompt", prompt[i]) + info.add_text("negative_prompt", negative_prompt[i]) + + image.save(image_path, "PNG", pnginfo=info) + + def _infer( + self, + prompt, + negative_prompt, + image_height, + image_width, + denoising_steps=30, + guidance=5.0, + seed=None, + image=None, + strength=0.3, + controlnet_images=None, + controlnet_scales=None, + show_latency=False, + output_type="pil", + ): + if show_latency: + torch.cuda.synchronize() + start_time = time.perf_counter() + + assert len(prompt) == len(negative_prompt) + batch_size = len(prompt) + + self.set_denoising_steps(denoising_steps) + self.set_random_seed(seed) + + timesteps = None + step_offset = 0 + with torch.inference_mode(), torch.autocast("cuda"): + if image is not None: + timesteps, step_offset, latents = self.initialize_refiner( + batch_size=batch_size, + image=image, + strength=strength, + ) + else: + # Pre-initialize latents + latents = self.initialize_latents( + batch_size=batch_size, + unet_channels=4, + latent_height=(image_height // 8), + latent_width=(image_width // 8), + ) + + do_classifier_free_guidance = guidance > 1.0 + if not self.pipeline_info.is_xl(): + denoiser = "unet" + text_embeddings = self.encode_prompt( + prompt, + negative_prompt, + do_classifier_free_guidance=do_classifier_free_guidance, + dtype=latents.dtype, + ) + add_kwargs = {} + else: + denoiser = "unetxl" + + # Time embeddings + original_size = (image_height, image_width) + crops_coords_top_left = (0, 0) + target_size = (image_height, image_width) + aesthetic_score = 6.0 + negative_aesthetic_score = 2.5 + add_time_ids, add_negative_time_ids = self._get_add_time_ids( + original_size, + crops_coords_top_left, + target_size, + aesthetic_score, + negative_aesthetic_score, + dtype=latents.dtype, + requires_aesthetics_score=self.pipeline_info.is_xl_refiner(), + ) + if do_classifier_free_guidance: + add_time_ids = torch.cat([add_negative_time_ids, add_time_ids], dim=0) + add_time_ids = add_time_ids.to(device=self.device).repeat(batch_size, 1) + + if self.pipeline_info.is_xl_refiner(): + # CLIP text encoder 2 + text_embeddings, pooled_embeddings2 = self.encode_prompt( + prompt, + negative_prompt, + encoder="clip2", + tokenizer=self.tokenizer2, + pooled_outputs=True, + output_hidden_states=True, + dtype=latents.dtype, + ) + add_kwargs = {"text_embeds": pooled_embeddings2, "time_ids": add_time_ids} + else: # XL Base + # CLIP text encoder + text_embeddings = self.encode_prompt( + prompt, + negative_prompt, + encoder="clip", + tokenizer=self.tokenizer, + output_hidden_states=True, + force_zeros_for_empty_prompt=True, + do_classifier_free_guidance=do_classifier_free_guidance, + dtype=latents.dtype, + ) + # CLIP text encoder 2 + text_embeddings2, pooled_embeddings2 = self.encode_prompt( + prompt, + negative_prompt, + encoder="clip2", + tokenizer=self.tokenizer2, + pooled_outputs=True, + output_hidden_states=True, + force_zeros_for_empty_prompt=True, + do_classifier_free_guidance=do_classifier_free_guidance, + dtype=latents.dtype, + ) + + # Merged text embeddings + text_embeddings = torch.cat([text_embeddings, text_embeddings2], dim=-1) + + add_kwargs = {"text_embeds": pooled_embeddings2, "time_ids": add_time_ids} + + if self.pipeline_info.controlnet: + controlnet_images = self.preprocess_controlnet_images( + latents.shape[0], + controlnet_images, + do_classifier_free_guidance=do_classifier_free_guidance, + height=image_height, + width=image_width, + ) + add_kwargs.update( + { + "controlnet_images": controlnet_images, + "controlnet_scales": controlnet_scales.to(controlnet_images.dtype).to(controlnet_images.device), + } + ) + + # UNet denoiser + latents = self.denoise_latent( + latents, + text_embeddings, + timesteps=timesteps, + step_offset=step_offset, + denoiser=denoiser, + guidance=guidance, + add_kwargs=add_kwargs, + ) + + with torch.inference_mode(): + # VAE decode latent + if output_type == "latent": + images = latents + else: + images = self.decode_latent(latents / self.vae_scaling_factor) + if output_type == "pil": + self.start_profile("pil", color="green") + images = self.pt_to_pil(images) + self.stop_profile("pil") + + perf_data = None + if show_latency: + torch.cuda.synchronize() + end_time = time.perf_counter() + perf_data = self.print_summary( + start_time, end_time, batch_size, vae_enc=self.pipeline_info.is_xl_refiner(), pil=(output_type == "pil") + ) + + return images, perf_data + + def run( + self, + prompt: list[str], + negative_prompt: list[str], + image_height: int, + image_width: int, + denoising_steps: int = 30, + guidance: float = 5.0, + seed: int | None = None, + image: torch.Tensor | None = None, + strength: float = 0.3, + controlnet_images: torch.Tensor | None = None, + controlnet_scales: torch.Tensor | None = None, + show_latency: bool = False, + output_type: str = "pil", + deterministic: bool = False, + ): + """ + Run the diffusion pipeline. + + Args: + prompt (List[str]): + The text prompt to guide image generation. + negative_prompt (List[str]): + The prompt not to guide the image generation. + image_height (int): + Height (in pixels) of the image to be generated. Must be a multiple of 8. + image_width (int): + Width (in pixels) of the image to be generated. Must be a multiple of 8. + denoising_steps (int): + Number of denoising steps. More steps usually lead to higher quality image at the expense of slower inference. + guidance (float): + Higher guidance scale encourages to generate images that are closely linked to the text prompt. + seed (int): + Seed for the random generator + image (tuple[torch.Tensor]): + Reference image. + strength (float): + Indicates extent to transform the reference image, which is used as a starting point, + and more noise is added the higher the strength. + show_latency (bool): + Whether return latency data. + output_type (str): + It can be "latent", "pt" or "pil". + """ + if deterministic: + torch.use_deterministic_algorithms(True) + + if self.is_backend_tensorrt(): + import tensorrt as trt # noqa: PLC0415 + from trt_utilities import TRT_LOGGER # noqa: PLC0415 + + with trt.Runtime(TRT_LOGGER): + return self._infer( + prompt, + negative_prompt, + image_height, + image_width, + denoising_steps=denoising_steps, + guidance=guidance, + seed=seed, + image=image, + strength=strength, + controlnet_images=controlnet_images, + controlnet_scales=controlnet_scales, + show_latency=show_latency, + output_type=output_type, + ) + else: + return self._infer( + prompt, + negative_prompt, + image_height, + image_width, + denoising_steps=denoising_steps, + guidance=guidance, + seed=seed, + image=image, + strength=strength, + controlnet_images=controlnet_images, + controlnet_scales=controlnet_scales, + show_latency=show_latency, + output_type=output_type, + ) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/trt_utilities.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/trt_utilities.py new file mode 100644 index 0000000000000000000000000000000000000000..c75d53bb61f6ff8fd615ab303307effad4a8d059 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/stable_diffusion/trt_utilities.py @@ -0,0 +1,12 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +# -------------------------------------------------------------------------- +import tensorrt as trt + +TRT_LOGGER = trt.Logger(trt.Logger.ERROR) + + +def init_trt_plugins(): + # Register TensorRT plugins + trt.init_libnvinfer_plugins(TRT_LOGGER, "") diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/t5/__init__.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/t5/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5ef71ce9e355e17ea1c2ca9fb648951d917734b5 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/t5/__init__.py @@ -0,0 +1,12 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +# -------------------------------------------------------------------------- +import os.path +import sys + +sys.path.append(os.path.dirname(__file__)) + +transformers_dir = os.path.normpath(os.path.join(os.path.dirname(__file__), "..", "..")) +if transformers_dir not in sys.path: + sys.path.append(transformers_dir) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/t5/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/t5/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e8f1740c069b580a4e444e3402a7a8e185e7d898 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/t5/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/t5/__pycache__/convert_to_onnx.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/t5/__pycache__/convert_to_onnx.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5c1d304adec8c50bce5222659a84c56b73e023e0 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/t5/__pycache__/convert_to_onnx.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/t5/__pycache__/t5_decoder.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/t5/__pycache__/t5_decoder.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2fc792c9f6cb8e7652a72935dcbcd05fe433007b Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/t5/__pycache__/t5_decoder.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/t5/__pycache__/t5_encoder.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/t5/__pycache__/t5_encoder.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c0a52531045d39078537c85ddf77e7cf4c97b119 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/t5/__pycache__/t5_encoder.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/t5/__pycache__/t5_encoder_decoder_init.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/t5/__pycache__/t5_encoder_decoder_init.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..316eccf92c1b5ff669b49834115157cbe4c985c4 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/t5/__pycache__/t5_encoder_decoder_init.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/t5/__pycache__/t5_helper.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/t5/__pycache__/t5_helper.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..301af81d39d7cf7ea25cc625f11a54e6efa07ed0 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/t5/__pycache__/t5_helper.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/t5/convert_to_onnx.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/t5/convert_to_onnx.py new file mode 100644 index 0000000000000000000000000000000000000000..4d891628211248f79a58de18f3aab8bc08606e6b --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/t5/convert_to_onnx.py @@ -0,0 +1,318 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +import argparse +import copy +import logging +import os + +import torch +from benchmark_helper import ( + Precision, + create_onnxruntime_session, + prepare_environment, + setup_logger, +) +from onnx.shape_inference import infer_shapes_path +from t5_helper import PRETRAINED_MT5_MODELS, PRETRAINED_T5_MODELS, T5Helper +from transformers import MT5Config, T5Config + +logger = logging.getLogger("") + + +def parse_arguments(): + parser = argparse.ArgumentParser() + + pretrained_models = PRETRAINED_T5_MODELS + PRETRAINED_MT5_MODELS + parser.add_argument( + "-m", + "--model_name_or_path", + required=False, + default=PRETRAINED_T5_MODELS[0], + type=str, + help="Model path, or pretrained model name in the list: " + ", ".join(pretrained_models), + ) + + parser.add_argument( + "--model_type", + required=False, + type=str, + default="t5", + choices=["t5", "mt5"], + help="Model type: either t5 (default) or mt5", + ) + + parser.add_argument( + "--cache_dir", + required=False, + type=str, + default=os.path.join(".", "cache_models"), + help="Directory to cache pre-trained models", + ) + + parser.add_argument( + "--output", + required=False, + type=str, + default=os.path.join(".", "onnx_models"), + help="Output directory", + ) + + parser.add_argument( + "-o", + "--optimize_onnx", + required=False, + action="store_true", + help="Use optimizer.py to optimize onnx model", + ) + parser.set_defaults(optimize_onnx=False) + + parser.add_argument("--use_gpu", required=False, action="store_true", help="use GPU for inference") + parser.set_defaults(use_gpu=False) + + parser.add_argument( + "-p", + "--precision", + required=False, + type=str, + default=Precision.FLOAT32.value, + choices=[Precision.FLOAT32.value, Precision.FLOAT16.value], + help="Precision of model to run. fp32 for full precision, fp16 for half precision", + ) + + parser.add_argument("--verbose", required=False, action="store_true") + parser.set_defaults(verbose=False) + + parser.add_argument("-e", "--use_external_data_format", required=False, action="store_true") + parser.set_defaults(use_external_data_format=False) + + parser.add_argument( + "-s", + "--use_decoder_start_token", + required=False, + action="store_true", + help="Use config.decoder_start_token_id. Otherwise, add an extra graph input for decoder_input_ids.", + ) + parser.set_defaults(use_decoder_start_token=False) + + parser.add_argument( + "-w", + "--overwrite", + required=False, + action="store_true", + help="overwrite existing ONNX model", + ) + parser.set_defaults(overwrite=False) + + parser.add_argument( + "--disable_auto_mixed_precision", + required=False, + action="store_true", + help="do not use auto mixed precision conversion", + ) + parser.set_defaults(disable_auto_mixed_precision=False) + + parser.add_argument( + "--force_fp16_io", + required=False, + action="store_true", + help="Force to convert all float inputs and outputs to fp16 when precision is fp16.", + ) + parser.set_defaults(force_fp16_io=False) + + parser.add_argument( + "--use_int64_inputs", + required=False, + action="store_true", + help="Use int64 instead of int32 for input_ids, position_ids and attention_mask.", + ) + parser.set_defaults(use_int64_inputs=False) + + parser.add_argument( + "--state_dict_path", + type=str, + default="", + help="filepath to load pre-trained model with custom state dictionary (e.g. pytorch_model.bin)", + ) + + parser.add_argument( + "--encoder_decoder_init", + required=False, + action="store_true", + help="Combine encoder and decoder kv cache initialization into one model. It is legacy format that will be deprecated.", + ) + parser.set_defaults(encoder_decoder_init=False) + + args = parser.parse_args() + + return args + + +def export_onnx_models( + model_name_or_path: str, + cache_dir: str, + output_dir: str, + use_gpu: bool = False, + use_external_data_format: bool = False, + optimize_onnx: bool = False, + precision: str = Precision.FLOAT32.value, + verbose: bool = False, + use_decoder_start_token: bool = False, + overwrite: bool = False, + disable_auto_mixed_precision: bool = False, + use_int32_inputs: bool = True, + model_type: str = "t5", + state_dict_path: str = "", + encoder_decoder_init: bool = False, + force_fp16_io: bool = False, + shape_infer_before_optimization: bool = False, +): + assert precision in [Precision.FLOAT32.value, Precision.FLOAT16.value], ( + f"Invalid precision: {precision}. Use 'fp32' or 'fp16'." + ) + device = torch.device("cuda:0" if use_gpu else "cpu") + + models = T5Helper.load_model( + model_name_or_path, + cache_dir, + device, + model_type, + state_dict_path, + encoder_decoder_init=encoder_decoder_init, + ) + config: T5Config | MT5Config = models["decoder"].config + + if (not use_external_data_format) and (config.num_layers > 24): + logger.info("Try use_external_data_format when model size > 2GB") + + output_paths = [] + for name, model in models.items(): + model.to(device) + filename_suffix = "_" + name + + onnx_path = T5Helper.get_onnx_path( + output_dir, + model_name_or_path, + suffix=filename_suffix, + new_folder=False, + ) + + if overwrite or not os.path.exists(onnx_path): + logger.info(f"Exporting ONNX model to {onnx_path}") + # We have to clone model before exporting onnx, otherwise verify_onnx will report large difference. + cloned_model = copy.deepcopy(model).to(device) + T5Helper.export_onnx( + cloned_model, + device, + onnx_path, + verbose, + use_external_data_format, + use_decoder_input_ids=not use_decoder_start_token, + use_int32_inputs=use_int32_inputs, + ) + else: + logger.info(f"Skip exporting: existed ONNX model {onnx_path}") + + # Optimize ONNX graph. + # The precision shall be compared with string value. It is because the Precision enum loaded from local file + # (like by transformers test in CI pipeline) are not same as Precision enum from package. + if optimize_onnx or precision != Precision.FLOAT32.value: + onnx_shape_path = None + if shape_infer_before_optimization: + onnx_shape_path = T5Helper.get_onnx_path( + output_dir, + model_name_or_path, + suffix=filename_suffix + "_shape", + new_folder=False, + ) + infer_shapes_path(onnx_path, onnx_shape_path) + + output_path = T5Helper.get_onnx_path( + output_dir, + model_name_or_path, + suffix=filename_suffix + "_" + str(precision), + new_folder=False, + ) + + if overwrite or not os.path.exists(output_path): + logger.info(f"Optimizing model to {output_path}") + T5Helper.optimize_onnx( + onnx_shape_path or onnx_path, + output_path, + precision == Precision.FLOAT16.value, + config.num_heads, + config.hidden_size, + use_external_data_format, + auto_mixed_precision=not disable_auto_mixed_precision, + use_gpu=use_gpu, + force_fp16_io=force_fp16_io, + ) + else: + logger.info(f"Skip optimizing: existed ONNX model {output_path}") + else: + output_path = onnx_path + + ort_session = create_onnxruntime_session( + output_path, + use_gpu=use_gpu, + verbose=verbose, + ) + if ort_session is None: + break + + with torch.no_grad(): + max_diff = T5Helper.verify_onnx(model, ort_session, device, use_int32_inputs) + logger.info(f"PyTorch and OnnxRuntime results max difference = {max_diff}") + + # The threshold cannot apply to fp16 model, which need a larger threshold. + if precision == Precision.FLOAT32.value and max_diff > 1e-4: + logger.warning("PyTorch and OnnxRuntime results are NOT close") + + output_paths.append(output_path) + + return output_paths + + +def main(): + args = parse_arguments() + + setup_logger(args.verbose) + + logger.info(f"Arguments:{args}") + + cache_dir = args.cache_dir + output_dir = args.output if not args.output.endswith(".onnx") else os.path.dirname(args.output) + prepare_environment(cache_dir, output_dir, args.use_gpu) + + if args.precision != Precision.FLOAT32.value: + assert args.optimize_onnx, "fp16/int8 requires --optimize_onnx" + + if args.precision == Precision.FLOAT16.value: + assert args.use_gpu, "fp16 requires --use_gpu" + + output_paths = export_onnx_models( + args.model_name_or_path, + cache_dir, + output_dir, + args.use_gpu, + args.use_external_data_format, + args.optimize_onnx, + args.precision, + args.verbose, + args.use_decoder_start_token, + args.overwrite, + args.disable_auto_mixed_precision, + not args.use_int64_inputs, + args.model_type, + encoder_decoder_init=args.encoder_decoder_init, + force_fp16_io=args.force_fp16_io, + ) + + logger.info(f"Done! Outputs: {output_paths}") + + +if __name__ == "__main__": + main() diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/t5/t5_decoder.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/t5/t5_decoder.py new file mode 100644 index 0000000000000000000000000000000000000000..1300bee0dd91f3e1d4a9ecba37c994800b9c6b0d --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/t5/t5_decoder.py @@ -0,0 +1,437 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +import logging +import os +import tempfile +from pathlib import Path + +import numpy +import onnx +import torch +from io_binding_helper import TypeHelper +from onnx_model import OnnxModel +from past_helper import PastKeyValuesHelper +from t5_encoder import T5EncoderInputs +from torch_onnx_export_helper import torch_onnx_export +from transformers import MT5Config, T5Config + +from onnxruntime import InferenceSession + +logger = logging.getLogger(__name__) + + +class T5DecoderInit(torch.nn.Module): + """A T5 decoder with LM head to create initial past key values. + This model is only called once during starting decoding. + """ + + def __init__( + self, + decoder: torch.nn.Module, + lm_head: torch.nn.Module, + config: T5Config | MT5Config, + decoder_start_token_id: int | None = None, + ): + super().__init__() + self.decoder = decoder + self.lm_head = lm_head + self.config = config + self.decoder_start_token_id = ( + decoder_start_token_id if decoder_start_token_id is not None else self.config.decoder_start_token_id + ) + self.tie_word_embeddings = ( + self.config.tie_word_embeddings if hasattr(self.config, "tie_word_embeddings") else True + ) + + def forward( + self, + decoder_input_ids: torch.Tensor, + encoder_attention_mask: torch.Tensor, + encoder_hidden_states: torch.FloatTensor, + ): + if decoder_input_ids is None: + batch_size = encoder_attention_mask.shape[0] + decoder_input_ids = ( + torch.ones( + (batch_size, 1), + dtype=torch.long, + device=encoder_attention_mask.device, + ) + * self.decoder_start_token_id + ) + + decoder_outputs = self.decoder( + input_ids=decoder_input_ids, + encoder_hidden_states=encoder_hidden_states, + encoder_attention_mask=encoder_attention_mask, + use_cache=True, + return_dict=True, + ) + + sequence_output = decoder_outputs.last_hidden_state + present_key_values = decoder_outputs.past_key_values + + if self.tie_word_embeddings: + sequence_output = sequence_output * (self.config.d_model**-0.5) + + lm_logits = self.lm_head(sequence_output) + past_self, past_cross = PastKeyValuesHelper.group_by_self_or_cross(present_key_values) + return lm_logits, past_self, past_cross + + +class T5Decoder(torch.nn.Module): + """A T5 decoder with LM head and past key values""" + + def __init__(self, decoder, lm_head, config): + super().__init__() + self.decoder = decoder + self.lm_head = lm_head + self.config = config + self.tie_word_embeddings = ( + self.config.tie_word_embeddings if hasattr(self.config, "tie_word_embeddings") else True + ) + + def forward(self, decoder_input_ids, encoder_attention_mask, *past): + num_decoder_layers = self.config.num_decoder_layers + past_key_values = PastKeyValuesHelper.group_by_layer(past, num_decoder_layers) + + # This is a hack since only the third dimension of encoder_hidden_states is used here + dummy_encoder_hidden_states = encoder_attention_mask.unsqueeze(2) + decoder_outputs = self.decoder( + input_ids=decoder_input_ids, + past_key_values=past_key_values, + encoder_hidden_states=dummy_encoder_hidden_states, + encoder_attention_mask=encoder_attention_mask, + use_cache=True, + return_dict=True, + ) + + sequence_output = decoder_outputs.last_hidden_state + present_key_values = decoder_outputs.past_key_values + + if self.tie_word_embeddings: + sequence_output = sequence_output * (self.config.d_model**-0.5) + + lm_logits = self.lm_head(sequence_output) + present_self, _ = PastKeyValuesHelper.group_by_self_or_cross(present_key_values) + + # Do not return present_cross since they are identical to corresponding past_cross input + return lm_logits, present_self + + +class T5DecoderInputs: + def __init__( + self, + decoder_input_ids, + encoder_attention_mask, + past_key_values=None, + ): + self.decoder_input_ids: torch.LongTensor = decoder_input_ids + self.encoder_attention_mask: torch.LongTensor = encoder_attention_mask + self.past_key_values: list[torch.FloatTensor] | list[torch.HalfTensor] | None = past_key_values + + @staticmethod + def create_dummy( + config: T5Config | MT5Config, + batch_size: int, + encode_sequence_length: int, + past_decode_sequence_length: int, + device: torch.device, + float16: bool = False, + use_int32_inputs: bool = False, + ): # -> T5DecoderInputs: + """Create dummy inputs for T5Decoder. + + Args: + decoder: decoder + batch_size (int): batch size + encode_sequence_length (int): sequence length of input_ids for encoder + past_decode_sequence_length (int): past sequence length of input_ids for decoder + device (torch.device): device of output tensors + float16 (bool): whether the model uses float32 or float16 in input + use_int32_inputs(bool): whether use int32 instead of int64 for some inputs + + Returns: + T5DecoderInputs: dummy inputs for decoder + """ + num_attention_heads: int = config.num_heads + num_layers: int = config.num_decoder_layers + vocab_size: int = config.vocab_size + + # Do not use head_size = hidden_size / num_attention_heads here. + # For example, mt5-small, d_model=512 and num_heads=6 + head_size: int = config.d_kv + + sequence_length: int = 1 # fixed for decoding + decoder_input_ids = torch.randint( + low=0, + high=vocab_size - 1, + size=(batch_size, sequence_length), + dtype=(torch.int32 if use_int32_inputs else torch.int64), + device=device, + ) + + encoder_inputs = T5EncoderInputs.create_dummy( + batch_size, + encode_sequence_length, + vocab_size, + device, + use_int32_inputs=use_int32_inputs, + ) + + float_type = torch.float16 if float16 else torch.float32 + + if past_decode_sequence_length > 0: + self_attention_past_shape = [ + batch_size, + num_attention_heads, + past_decode_sequence_length, + head_size, + ] + cross_attention_past_shape = [ + batch_size, + num_attention_heads, + encode_sequence_length, + head_size, + ] + + past = [] + for _ in range(2 * num_layers): + past.append(torch.rand(self_attention_past_shape, dtype=float_type, device=device)) + + for _ in range(2 * num_layers): + past.append(torch.rand(cross_attention_past_shape, dtype=float_type, device=device)) + else: + past = None + + return T5DecoderInputs(decoder_input_ids, encoder_inputs.attention_mask, past) + + def to_list(self) -> list: + input_list = [ + self.decoder_input_ids, + self.encoder_attention_mask, + ] + if self.past_key_values: + input_list.extend(self.past_key_values) + return input_list + + def to_fp32(self): + past = [p.to(dtype=torch.float32) for p in self.past_key_values] if self.past_key_values else None + return T5DecoderInputs( + self.decoder_input_ids.clone(), + self.encoder_attention_mask.clone(), + past, + ) + + +class T5DecoderHelper: + @staticmethod + def export_onnx( + decoder: T5Decoder | T5DecoderInit, + device: torch.device, + onnx_model_path: str, + verbose: bool = True, + use_external_data_format: bool = False, + use_int32_inputs: bool = False, + ): + """Export decoder to ONNX + + Args: + decoder (Union[T5Decoder, T5DecoderNoPastState]): decoder object + device (torch.device): device of decoder object + onnx_model_path (str): onnx path + verbose (bool, optional): print verbose information. Defaults to True. + use_external_data_format (bool, optional): use external data format or not. Defaults to False. + use_int32_inputs (bool, optional): use int32 inputs + """ + assert isinstance(decoder, (T5Decoder, T5DecoderInit)) + + inputs = T5DecoderInputs.create_dummy( + decoder.config, + batch_size=2, + encode_sequence_length=3, + past_decode_sequence_length=5 if isinstance(decoder, T5Decoder) else 0, + device=device, + use_int32_inputs=use_int32_inputs, + ) + input_list = inputs.to_list() + + num_decoder_layers = decoder.config.num_decoder_layers + + past_names = PastKeyValuesHelper.get_past_names(num_decoder_layers, present=False) + present_names = PastKeyValuesHelper.get_past_names(num_decoder_layers, present=True) + present_self_names = present_names[: 2 * num_decoder_layers] + + input_past_names = past_names if isinstance(decoder, T5Decoder) else [] + output_present_names = present_self_names if isinstance(decoder, T5Decoder) else present_names + output_names = ["logits", *output_present_names] + + # Shape of input tensors (sequence_length==1): + # input_ids: (batch_size, sequence_length) + # encoder_attention_mask: (batch_size, encode_sequence_length) + # past_self_*: (batch_size, num_heads, past_decode_sequence_length, head_size) + # past_cross_*: (batch_size, num_heads, encode_sequence_length, head_size) + + # Shape of output tensors: + # logits: (batch_size, sequence_length, vocab_size) + # past_self_*: (batch_size, num_heads, past_decode_sequence_length + sequence_length, head_size) + # past_cross_*: (batch_size, num_heads, encode_sequence_length, head_size) + + input_names = ["input_ids"] + input_names.append("encoder_attention_mask") + input_names.extend(input_past_names) + + dynamic_axes = { + "input_ids": { + 0: "batch_size", + # 1: 'sequence_length' + }, + "encoder_attention_mask": {0: "batch_size", 1: "encode_sequence_length"}, + "encoder_hidden_states": {0: "batch_size", 1: "encode_sequence_length"}, + "logits": { + 0: "batch_size", + # 1: 'sequence_length' + }, + } + + for name in input_past_names: + dynamic_axes[name] = { + 0: "batch_size", + 2: "past_decode_sequence_length" if "self" in name else "encode_sequence_length", + } + + for name in output_present_names: + if "cross" in name: + dynamic_axes[name] = {0: "batch_size", 2: "encode_sequence_length"} + else: # self attention past state + if isinstance(decoder, T5Decoder): + dynamic_axes[name] = { + 0: "batch_size", + 2: "past_decode_sequence_length + 1", + } + else: + dynamic_axes[name] = { + 0: "batch_size", + # 2: 'sequence_length' + } + + Path(onnx_model_path).parent.mkdir(parents=True, exist_ok=True) + + with tempfile.TemporaryDirectory() as tmp_dir_name: + temp_onnx_model_path = os.path.join(tmp_dir_name, "decoder.onnx") + Path(temp_onnx_model_path).parent.mkdir(parents=True, exist_ok=True) + torch_onnx_export( + decoder, + args=tuple(input_list), + f=temp_onnx_model_path if use_external_data_format else onnx_model_path, + export_params=True, + input_names=input_names, + output_names=output_names, + dynamic_axes=dynamic_axes, + opset_version=12, + do_constant_folding=True, + use_external_data_format=use_external_data_format, + verbose=verbose, + ) + + if use_external_data_format: + model = onnx.load_model(temp_onnx_model_path, load_external_data=True) + OnnxModel.save( + model, + onnx_model_path, + save_as_external_data=True, + all_tensors_to_one_file=True, + ) + + @staticmethod + def onnxruntime_inference(ort_session, inputs: T5DecoderInputs): + """Run inference of ONNX model.""" + logger.debug("start onnxruntime_inference") + + ort_inputs = { + "input_ids": numpy.ascontiguousarray(inputs.decoder_input_ids.cpu().numpy()), + "encoder_attention_mask": numpy.ascontiguousarray(inputs.encoder_attention_mask.cpu().numpy()), + } + + if inputs.past_key_values: + assert len(inputs.past_key_values) % 4 == 0 + num_layers = int(len(inputs.past_key_values) / 4) + past_names = PastKeyValuesHelper.get_past_names(num_layers) + for i, past_tensor in enumerate(inputs.past_key_values): + ort_inputs[past_names[i]] = numpy.ascontiguousarray(past_tensor.cpu().numpy()) + + ort_outputs = ort_session.run(None, ort_inputs) + return ort_outputs + + @staticmethod + def verify_onnx( + model: T5Decoder | T5DecoderInit, + ort_session: InferenceSession, + device: torch.device, + use_int32_inputs: bool, + max_cases: int = 4, + ): + """Compare the result from PyTorch and OnnxRuntime to verify the ONNX model is good.""" + float16: bool = TypeHelper.get_input_type(ort_session, "past_key_self_0") == "tensor(float16)" + + test_cases = [(4, 11, 3), (1, 2, 5), (3, 1, 1), (8, 5, 2)] + test_cases_max_diff = [] + for ( + batch_size, + encode_sequence_length, + past_decode_sequence_length, + ) in test_cases[:max_cases]: + if isinstance(model, T5DecoderInit): + past_decode_sequence_length = 0 # noqa: PLW2901 + + inputs = T5DecoderInputs.create_dummy( + model.config, + batch_size, + encode_sequence_length, + past_decode_sequence_length, + device=device, + float16=float16, + use_int32_inputs=use_int32_inputs, + ) + + # We use fp32 PyTroch model as baseline even when ONNX model is fp16 + input_list = inputs.to_fp32().to_list() + + # Run inference of PyTorch model + with torch.no_grad(): + torch_outputs = model(*input_list) + + ort_outputs = T5DecoderHelper.onnxruntime_inference(ort_session, inputs) + num_decoder_layers = model.config.num_decoder_layers + + max_diff = numpy.amax(numpy.abs(torch_outputs[0].cpu().numpy() - ort_outputs[0])) + max_diff_all = max_diff + logger.debug(f"logits max_diff={max_diff}") + + for i in range(2 * num_decoder_layers): + max_diff = numpy.amax(numpy.abs(torch_outputs[1][i].cpu().numpy() - ort_outputs[1 + i])) + logger.debug(f"self attention past state {i} max_diff={max_diff}") + max_diff_all = max(max_diff_all, max_diff) + + if isinstance(model, T5DecoderInit): + for i in range(2 * num_decoder_layers): + max_diff = numpy.amax( + numpy.abs(torch_outputs[2][i].cpu().numpy() - ort_outputs[1 + 2 * num_decoder_layers + i]) + ) + logger.debug(f"cross attention past state {i} max_diff={max_diff}") + max_diff_all = max(max_diff_all, max_diff) + + test_cases_max_diff.append(max_diff_all) + logger.info( + "batch_size=%s, encode_sequence_length=%s, past_decode_sequence_length=%s, max_diff=%s", + batch_size, + encode_sequence_length, + past_decode_sequence_length, + max_diff_all, + ) + + return max_diff_all diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/t5/t5_encoder.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/t5/t5_encoder.py new file mode 100644 index 0000000000000000000000000000000000000000..ee287941ddf1a95a42093eb94b9eda7436f00e2e --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/t5/t5_encoder.py @@ -0,0 +1,70 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +# ------------------------------------------------------------------------- + +import logging +import random + +import torch +from transformers import MT5Config, T5Config + +logger = logging.getLogger(__name__) + + +class T5Encoder(torch.nn.Module): + """T5 encoder outputs only the last hidden state""" + + def __init__(self, encoder, config: T5Config | MT5Config): + super().__init__() + self.encoder = encoder + self.config = config + + def forward(self, input_ids, attention_mask): + return self.encoder(input_ids, attention_mask)[0] + + +class T5EncoderInputs: + def __init__(self, input_ids, attention_mask): + self.input_ids: torch.LongTensor = input_ids + self.attention_mask: torch.LongTensor = attention_mask + + @staticmethod + def create_dummy( + batch_size: int, + sequence_length: int, + vocab_size: int, + device: torch.device, + use_int32_inputs: bool = False, + ): # -> T5EncoderInputs + """Create dummy inputs for T5 encoder. + + Args: + batch_size (int): batch size + sequence_length (int): sequence length + vocab_size (int): vocabulary size + device (torch.device): device of output tensors + + Returns: + T5EncoderInputs: dummy inputs for encoder + """ + dtype = torch.int32 if use_int32_inputs else torch.int64 + + input_ids = torch.randint( + low=0, + high=vocab_size - 1, + size=(batch_size, sequence_length), + dtype=dtype, + device=device, + ) + + attention_mask = torch.ones([batch_size, sequence_length], dtype=dtype, device=device) + if sequence_length >= 2: + for i in range(batch_size): + padding_position = random.randint(0, sequence_length - 1) + attention_mask[i, :padding_position] = 0 + return T5EncoderInputs(input_ids, attention_mask) + + def to_list(self) -> list: + input_list = [v for v in [self.input_ids, self.attention_mask] if v is not None] + return input_list diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/t5/t5_encoder_decoder_init.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/t5/t5_encoder_decoder_init.py new file mode 100644 index 0000000000000000000000000000000000000000..ba725862b6cb353e2dfc3d2683bfa95ca2fd530b --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/t5/t5_encoder_decoder_init.py @@ -0,0 +1,361 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +# ------------------------------------------------------------------------- + +import logging +import os +import tempfile +from pathlib import Path + +import numpy +import onnx +import torch +from onnx_model import OnnxModel +from past_helper import PastKeyValuesHelper +from t5_decoder import T5DecoderInit +from t5_encoder import T5Encoder, T5EncoderInputs +from torch_onnx_export_helper import torch_onnx_export +from transformers import MT5Config, T5Config + +from onnxruntime import InferenceSession + +logger = logging.getLogger(__name__) + + +class T5EncoderDecoderInit(torch.nn.Module): + """A combination of T5Encoder and T5DecoderInit.""" + + def __init__( + self, + encoder: torch.nn.Module, + decoder: torch.nn.Module, + lm_head: torch.nn.Linear, + config: T5Config | MT5Config, + decoder_start_token_id: int | None = None, + output_cross_only: bool = False, + ): + super().__init__() + self.config: T5Config | MT5Config = config + self.t5_encoder = T5Encoder(encoder, config) + self.t5_decoder_init = T5DecoderInit(decoder, lm_head, config, decoder_start_token_id) + self.output_cross_only = output_cross_only + + def forward( + self, + encoder_input_ids: torch.Tensor, + encoder_attention_mask: torch.Tensor, + decoder_input_ids: torch.Tensor | None = None, + ): + encoder_hidden_states: torch.FloatTensor = self.t5_encoder(encoder_input_ids, encoder_attention_mask) + + lm_logits, past_self, past_cross = self.t5_decoder_init( + decoder_input_ids, encoder_attention_mask, encoder_hidden_states + ) + + if self.output_cross_only: + return past_cross + else: + return lm_logits, encoder_hidden_states, past_self, past_cross + + +class T5EncoderDecoderInitInputs: + def __init__(self, encoder_input_ids, encoder_attention_mask, decoder_input_ids=None): + self.encoder_input_ids: torch.LongTensor = encoder_input_ids + self.encoder_attention_mask: torch.LongTensor = encoder_attention_mask + self.decoder_input_ids: torch.LongTensor | None = decoder_input_ids + + @staticmethod + def create_dummy( + config: T5Config | MT5Config, + batch_size: int, + encode_sequence_length: int, + use_decoder_input_ids: int, + device: torch.device, + use_int32_inputs: bool = False, + ): # -> T5EncoderDecoderInitInputs: + encoder_inputs: T5EncoderInputs = T5EncoderInputs.create_dummy( + batch_size, + encode_sequence_length, + config.vocab_size, + device, + use_int32_inputs=use_int32_inputs, + ) + decoder_input_ids = None + if use_decoder_input_ids: + dtype = torch.int32 if use_int32_inputs else torch.int64 + decoder_input_ids = torch.ones((batch_size, 1), dtype=dtype, device=device) * config.decoder_start_token_id + + return T5EncoderDecoderInitInputs(encoder_inputs.input_ids, encoder_inputs.attention_mask, decoder_input_ids) + + def to_list(self) -> list: + input_list = [self.encoder_input_ids, self.encoder_attention_mask] + if self.decoder_input_ids is not None: + input_list.append(self.decoder_input_ids) + return input_list + + +class T5EncoderDecoderInitHelper: + @staticmethod + def export_onnx( + model: T5EncoderDecoderInit, + device: torch.device, + onnx_model_path: str, + use_decoder_input_ids: bool = True, + verbose: bool = True, + use_external_data_format: bool = False, + use_int32_inputs: bool = False, + ): + """Export decoder to ONNX + + Args: + model (T5EncoderDecoderInit): the model to export + device (torch.device): device of decoder object + onnx_model_path (str): onnx path + verbose (bool, optional): print verbose information. Defaults to True. + use_external_data_format (bool, optional): use external data format or not. Defaults to False. + use_int32_inputs (bool, optional): use int32 instead of int64 for integer inputs. Defaults to False. + """ + assert isinstance(model, T5EncoderDecoderInit) + + # Do not exclude decoder in torch onnx export so that cross can show up. + output_cross_only = model.output_cross_only + model.output_cross_only = False + + inputs = T5EncoderDecoderInitInputs.create_dummy( + model.config, + batch_size=2, + encode_sequence_length=3, + use_decoder_input_ids=use_decoder_input_ids, + device=device, + use_int32_inputs=use_int32_inputs, + ) + input_list = inputs.to_list() + + present_names = PastKeyValuesHelper.get_past_names(model.config.num_decoder_layers, present=True) + + output_names = ["logits", "encoder_hidden_states", *present_names] + + # Shape of input tensors (sequence_length==1): + # input_ids: (batch_size, sequence_length) + # encoder_attention_mask: (batch_size, encode_sequence_length) + # encoder_hidden_states: (batch_size, encode_sequence_length, hidden_size) + # past_self_*: (batch_size, num_heads, past_decode_sequence_length, head_size) + # past_cross_*: (batch_size, num_heads, encode_sequence_length, head_size) + + # Shape of output tensors: + # logits: (batch_size, sequence_length, vocab_size) + # past_self_*: (batch_size, num_heads, past_decode_sequence_length + sequence_length, head_size) + # past_cross_*: (batch_size, num_heads, encode_sequence_length, head_size) + + input_names = ["encoder_input_ids", "encoder_attention_mask"] + + # ONNX exporter might mark dimension like 'present_value_self_1_dim_2' in shape inference. + # We use a workaround here: first use dim_param "1" for sequence_length, and later change to dim_value. + sequence_length = "1" + num_heads = str(model.config.num_heads) + hidden_size = str(model.config.d_model) + head_size = str(model.config.d_kv) + + dynamic_axes = { + "encoder_input_ids": {0: "batch_size", 1: "encode_sequence_length"}, + "encoder_attention_mask": {0: "batch_size", 1: "encode_sequence_length"}, + "encoder_hidden_states": { + 0: "batch_size", + 1: "encode_sequence_length", + 2: hidden_size, + }, + "logits": { + 0: "batch_size", + 1: sequence_length, + }, + } + + if use_decoder_input_ids: + input_names.append("decoder_input_ids") + dynamic_axes["decoder_input_ids"] = { + 0: "batch_size", + 1: sequence_length, + } + + for name in present_names: + if "cross" in name: + dynamic_axes[name] = { + 0: "batch_size", + 1: num_heads, + 2: "encode_sequence_length", + 3: head_size, + } + + else: # self attention past state + dynamic_axes[name] = { + 0: "batch_size", + 1: num_heads, + 2: sequence_length, + 3: head_size, + } + + with tempfile.TemporaryDirectory() as tmp_dir_name: + temp_onnx_model_path = os.path.join(tmp_dir_name, "encoder_decoder_init.onnx") + Path(temp_onnx_model_path).parent.mkdir(parents=True, exist_ok=True) + torch_onnx_export( + model, + args=tuple(input_list), + f=temp_onnx_model_path, + export_params=True, + input_names=input_names, + output_names=output_names, + dynamic_axes=dynamic_axes, + opset_version=12, + do_constant_folding=True, + use_external_data_format=use_external_data_format, + verbose=verbose, + ) + + # Restore output_cross_only setting. + model.output_cross_only = output_cross_only + + # Workaround as mentioned earlier: change numeric dim_param to dim_value + exported_model: onnx.ModelProto = onnx.load(temp_onnx_model_path) + for tensor in exported_model.graph.output: + for dim_proto in tensor.type.tensor_type.shape.dim: + if dim_proto.HasField("dim_param") and dim_proto.dim_param in [ + sequence_length, + num_heads, + hidden_size, + head_size, + ]: + dim_value = int(dim_proto.dim_param) + dim_proto.Clear() + dim_proto.dim_value = dim_value + + if output_cross_only: + # Rewrite onnx graph to only keep present_[key|value]_cross_* outputs. + onnx_model = OnnxModel(exported_model) + output_name_to_node = onnx_model.output_name_to_node() + + for output in exported_model.graph.output: + if "cross" in output.name: + assert output.name in output_name_to_node + + transpose_node = output_name_to_node[output.name] + assert transpose_node and transpose_node.op_type == "Transpose" + + permutation = OnnxModel.get_node_attribute(transpose_node, "perm") + assert isinstance(permutation, list) + assert permutation == [0, 2, 1, 3] + + matched_nodes = onnx_model.match_parent_path( + transpose_node, + ["Reshape", "MatMul"], + [0, 0], + output_name_to_node, + ) + assert matched_nodes is not None + + reshape_node, matmul_node = matched_nodes + assert "encoder_hidden_states" in matmul_node.input + + if not onnx_model.get_initializer("cross_reshape_shape"): + shape_tensor = onnx.helper.make_tensor( + name="cross_reshape_shape", + data_type=onnx.TensorProto.INT64, + dims=[4], + vals=[0, 0, int(num_heads), int(head_size)], + raw=False, + ) + onnx_model.add_initializer(shape_tensor) + + reshape_node.input[1] = "cross_reshape_shape" + + cross_outputs = [output.name for output in exported_model.graph.output if "cross" in output.name] + onnx_model.prune_graph(cross_outputs, allow_remove_graph_inputs=True) + + OnnxModel.save( + exported_model, + onnx_model_path, + save_as_external_data=use_external_data_format, + all_tensors_to_one_file=True, + ) + + @staticmethod + def onnxruntime_inference(ort_session, inputs: T5EncoderDecoderInitInputs): + """Run inference of ONNX model.""" + logger.debug("start onnxruntime_inference") + + ort_inputs = { + "encoder_input_ids": numpy.ascontiguousarray(inputs.encoder_input_ids.cpu().numpy()), + "encoder_attention_mask": numpy.ascontiguousarray(inputs.encoder_attention_mask.cpu().numpy()), + } + if inputs.decoder_input_ids is not None: + ort_inputs["decoder_input_ids"] = numpy.ascontiguousarray(inputs.decoder_input_ids.cpu().numpy()) + + ort_outputs = ort_session.run(None, ort_inputs) + return ort_outputs + + @staticmethod + def verify_onnx( + model: T5EncoderDecoderInit, + ort_session: InferenceSession, + device: torch.device, + use_int32_inputs: bool, + max_cases: int = 4, + ): + """Compare the result from PyTorch and OnnxRuntime to verify the ONNX model is good.""" + ort_inputs = ort_session.get_inputs() + use_decoder_input_ids = len(ort_inputs) == 3 + + test_cases = [(4, 11), (1, 2), (3, 1), (8, 5)] + test_cases_max_diff = [] + for batch_size, encode_sequence_length in test_cases[:max_cases]: + inputs = T5EncoderDecoderInitInputs.create_dummy( + model.config, + batch_size, + encode_sequence_length, + use_decoder_input_ids=use_decoder_input_ids, + device=device, + use_int32_inputs=use_int32_inputs, + ) + + ort_outputs = T5EncoderDecoderInitHelper.onnxruntime_inference(ort_session, inputs) + + # Run inference of PyTorch model + input_list = inputs.to_list() + torch_outputs = model(*input_list) + + num_decoder_layers = model.config.num_decoder_layers + + if not model.output_cross_only: + assert torch_outputs[0].cpu().numpy().shape == ort_outputs[0].shape + max_diff = numpy.amax(numpy.abs(torch_outputs[0].cpu().numpy() - ort_outputs[0])) + logger.debug(f"logits max_diff={max_diff}") + max_diff_all = max_diff + + assert torch_outputs[1].cpu().numpy().shape == ort_outputs[1].shape + max_diff = numpy.amax(numpy.abs(torch_outputs[1].cpu().numpy() - ort_outputs[1])) + logger.debug(f"encoder_hidden_states max_diff={max_diff}") + max_diff_all = max(max_diff_all, max_diff) + + for i in range(2 * num_decoder_layers): + max_diff = numpy.amax(numpy.abs(torch_outputs[2][i].cpu().numpy() - ort_outputs[2 + i])) + logger.debug(f"self attention past state {i} max_diff={max_diff}") + + for i in range(2 * num_decoder_layers): + max_diff = numpy.amax( + numpy.abs(torch_outputs[3][i].cpu().numpy() - ort_outputs[2 + 2 * num_decoder_layers + i]) + ) + logger.debug(f"cross attention past state {i} max_diff={max_diff}") + max_diff_all = max(max_diff_all, max_diff) + else: + max_diff_all = -float("inf") + for i in range(2 * num_decoder_layers): + max_diff = numpy.amax(numpy.abs(torch_outputs[i].cpu().numpy() - ort_outputs[i])) + logger.debug(f"cross attention past state {i} max_diff={max_diff}") + max_diff_all = max(max_diff_all, max_diff) + + test_cases_max_diff.append(max_diff_all) + logger.info( + f"batch_size={batch_size} encode_sequence_length={encode_sequence_length}, max_diff={max_diff_all}" + ) + + return max(test_cases_max_diff) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/t5/t5_helper.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/t5/t5_helper.py new file mode 100644 index 0000000000000000000000000000000000000000..0617ec19c2480d4877e3d5cfcc6e6acc33164a22 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/t5/t5_helper.py @@ -0,0 +1,315 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +# ------------------------------------------------------------------------- + +import logging +import os +from pathlib import Path + +import torch +from float16 import float_to_float16_max_diff +from onnx_model import OnnxModel +from optimizer import optimize_model +from t5_decoder import T5Decoder, T5DecoderHelper +from t5_encoder_decoder_init import T5EncoderDecoderInit, T5EncoderDecoderInitHelper +from transformers import MT5ForConditionalGeneration, T5ForConditionalGeneration + +from onnxruntime import InferenceSession + +logger = logging.getLogger(__name__) + + +def _torch_load_weights_only(path: str, **kwargs): + try: + return torch.load(path, weights_only=True, **kwargs) + except TypeError: + logger.warning( + "Current PyTorch version does not support torch.load(..., weights_only=True); " + "falling back to default torch.load behavior for %s.", + path, + ) + return torch.load(path, **kwargs) + + +PRETRAINED_T5_MODELS = ["t5-small", "t5-base", "t5-large", "t5-3b", "t5-11b"] +PRETRAINED_MT5_MODELS = [ + "google/mt5-small", + "google/mt5-base", + "google/mt5-large", + "google/mt5-xl", + "google/mt5-xxl", +] + + +class T5Helper: + @staticmethod + def get_onnx_path( + output_dir: str, + model_name_or_path: str, + suffix: str = "", + new_folder: bool = False, + ) -> str: + """Build onnx path + + Args: + output_dir (str): output directory + model_name_or_path (str): pretrained model name, or path to the model checkpoint + suffix (str, optional): suffix like "_encoder" or "_decoder_fp16" will be appended to file name. Defaults to None. + new_folder (bool, optional): create a new directory for the model. Defaults to False. + + Returns: + str: path of onnx model + """ + model_name = model_name_or_path + if os.path.isdir(model_name_or_path): + model_name = Path(model_name_or_path).parts[-1] + else: + model_name.split("/")[-1] + + model_name += suffix + + directory = os.path.join(output_dir, model_name) if new_folder else output_dir + return os.path.join(directory, model_name + ".onnx") + + @staticmethod + def load_model( + model_name_or_path: str, + cache_dir: str, + device: torch.device, + model_type: str = "t5", + state_dict_path: str = "", + encoder_decoder_init: bool = False, + ) -> dict[str, T5EncoderDecoderInit | T5Decoder]: + """Load model given a pretrained name or path, then build models for ONNX conversion. + + Args: + model_name_or_path (str): pretrained model name or path + cache_dir (str): cache directory + device (torch.device): device to run the model + model_type (str, optional): model type "t5" or "mt5" + state_dict_path(str, optional): state dictionary path + encoder_decoder_init (bool, optional): combine encoder and decoder kv cache initialization into one model. + Returns: + Dict[str, torch.nn.Module]: mapping from name to modules for ONNX conversion. + """ + if model_type == "t5": + model = T5ForConditionalGeneration.from_pretrained(model_name_or_path, cache_dir=cache_dir) + elif model_type == "mt5": + model = MT5ForConditionalGeneration.from_pretrained(model_name_or_path, cache_dir=cache_dir) + else: + raise ValueError("only support mode_type=t5 or mt5") + + if state_dict_path: + model.load_state_dict(_torch_load_weights_only(state_dict_path)) + + decoder = T5Decoder(model.decoder, model.lm_head, model.config) + decoder.eval().to(device) + + encoder = T5EncoderDecoderInit( + model.encoder, + model.decoder, + model.lm_head, + model.config, + decoder_start_token_id=None, + output_cross_only=not encoder_decoder_init, + ) + + encoder_name = "encoder_decoder_init" if encoder_decoder_init else "encoder" + return {encoder_name: encoder, "decoder": decoder} + + @staticmethod + def export_onnx( + model: T5Decoder | T5EncoderDecoderInit, + device: torch.device, + onnx_model_path: str, + verbose: bool = True, + use_external_data_format: bool = False, + use_decoder_input_ids: bool = True, + use_int32_inputs: bool = False, + ): + if isinstance(model, T5EncoderDecoderInit): + T5EncoderDecoderInitHelper.export_onnx( + model, + device, + onnx_model_path, + use_decoder_input_ids, + verbose, + use_external_data_format, + use_int32_inputs, + ) + else: + T5DecoderHelper.export_onnx( + model, + device, + onnx_model_path, + verbose, + use_external_data_format, + use_int32_inputs, + ) + + @staticmethod + def auto_mixed_precision( + onnx_model: OnnxModel, + op_block_list: list[str] | None = None, + force_fp16_logits: bool = False, + use_symbolic_shape_infer: bool = True, + ): + """Convert model to mixed precision. + It detects whether original model has fp16 precision weights, and set parameters for float16 conversion automatically. + Args: + onnx_model (OnnxModel): optimized ONNX model + op_block_list (List[str], optional): operators need to run in fp32. + force_fp16_logits (bool, optional): force logits and last MatMul node to be in float16. Defaults to False. + use_symbolic_shape_infer (bool, optional): use symbolic shape inference to convert float to float16. Defaults to True. + Returns: + parameters(dict): a dictionary of parameters used in float16 conversion + """ + if op_block_list is None: + op_block_list = [ + "SimplifiedLayerNormalization", + "SkipSimplifiedLayerNormalization", + "Relu", + "Add", + ] + + op_full_set = {node.op_type for node in onnx_model.nodes()} + fp32_op_set = set(op_block_list) + fp16_op_set = op_full_set.difference(fp32_op_set) + logger.info(f"fp32 op: {fp32_op_set} fp16 op: {fp16_op_set}") + + # logits is the first output + logits_output_name = onnx_model.graph().output[0].name + + # We use the weight in last MatMul node to detect whether the model is stored with float16 weights from training. + is_weight_fp16_precision = False + output_name_to_node = onnx_model.output_name_to_node() + assert logits_output_name in output_name_to_node + node = output_name_to_node[logits_output_name] + last_matmul_node = None + if node.op_type == "MatMul": + last_matmul_node = node + logger.info(f"Found last MatMul node for logits: {node.name}") + initializer = None + for input in node.input: + initializer = onnx_model.get_initializer(input) + if initializer is not None: + break + + # when the max difference of value after converting float to float16 is lower than a threshold (1e-6), + # we can deduce that the weights are stored in float16 precision. + max_diff = float_to_float16_max_diff(initializer) + logger.debug(f"max diff of converting weights in last MatMul node {node.name}: {max_diff}") + is_weight_fp16_precision = max_diff < 1e-6 + else: + logger.warning(f"Failed to find MatMul node for logits. Found {node.op_type} of node {node.name}") + + keep_io_types = [] + node_block_list = [] + if (not is_weight_fp16_precision) and (last_matmul_node is not None) and not force_fp16_logits: + # When original weight is float32 precision, keep logits and last MatMul in float32 could get better precision. + keep_io_types = [logits_output_name] + node_block_list = [last_matmul_node.name] + + if "Add" not in op_block_list: + input_name_to_nodes = onnx_model.input_name_to_nodes() + fp32_add = 0 + changed = True + add_nodes = onnx_model.get_nodes_by_op_type("Add") + while changed: + changed = False + for node in add_nodes: + if node.name not in node_block_list: + parents = onnx_model.get_parents(node, output_name_to_node) + children = onnx_model.get_children(node, input_name_to_nodes) + blocked_children = [ + child for child in children if child.op_type in op_block_list or child in node_block_list + ] + blocked_parents = [ + parent for parent in parents if parent.op_type in op_block_list or parent in node_block_list + ] + # If any child or parent is in fp32, we place the Add node to fp32. + if (len(blocked_children) + len(blocked_parents)) > 0: + node_block_list.append(node.name) + fp32_add += 1 + changed = True + fp16_add = len(add_nodes) - fp32_add + logger.info(f"node counter of Add operator: fp32={fp32_add} fp16={fp16_add}") + + logger.info(f"node_block_list: {node_block_list}") + + parameters = { + "keep_io_types": keep_io_types, + "op_block_list": op_block_list, + "node_block_list": node_block_list, + "force_fp16_initializers": is_weight_fp16_precision, + } + + logger.info(f"auto_mixed_precision parameters: {parameters}") + if use_symbolic_shape_infer: + onnx_model.convert_float_to_float16(use_symbolic_shape_infer=True, **parameters) + else: + # Workaround when symbolic shape inference fails. + # Need enable shape_infer_before_optimization in convert_to_onnx.py as well. + from float16 import convert_float_to_float16 # noqa: PLC0415 + + convert_float_to_float16( + onnx_model.model, + disable_shape_infer=True, + **parameters, + ) + + return parameters + + @staticmethod + def optimize_onnx( + onnx_model_path: str, + optimized_model_path: str, + is_float16: bool, + num_attention_heads: int, + hidden_size: int, + use_external_data_format: bool = False, + auto_mixed_precision: bool = True, + use_gpu: bool = False, + force_fp16_io: bool = False, + ): + """Optimize ONNX model with an option to convert it to use mixed precision.""" + + from fusion_options import FusionOptions # noqa: PLC0415 + + optimization_options = None + if is_float16: + optimization_options = FusionOptions("t5") + # SkipLayerNormalization is faster but might bring accuracy drop since it uses fp16 accumulation. + optimization_options.enable_skip_layer_norm = not auto_mixed_precision + + m = optimize_model( + onnx_model_path, + model_type="t5", + num_heads=num_attention_heads, + hidden_size=hidden_size, + opt_level=0, + optimization_options=optimization_options, + use_gpu=use_gpu, + ) + + if is_float16: + if auto_mixed_precision: + T5Helper.auto_mixed_precision(m, force_fp16_logits=force_fp16_io) + else: + m.convert_model_float32_to_float16(cast_input_output=force_fp16_io) + + m.save_model_to_file(optimized_model_path, use_external_data_format, all_tensors_to_one_file=True) + + @staticmethod + def verify_onnx( + model: T5Decoder | T5EncoderDecoderInit, + ort_session: InferenceSession, + device: torch.device, + use_int32_inputs: bool, + ): + """Compare the result from PyTorch and OnnxRuntime to verify the ONNX model is good.""" + if isinstance(model, T5EncoderDecoderInit): + return T5EncoderDecoderInitHelper.verify_onnx(model, ort_session, device, use_int32_inputs) + + return T5DecoderHelper.verify_onnx(model, ort_session, device, use_int32_inputs) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/whisper/__init__.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/whisper/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8f9a57c902589567201d260a9248c59309a74576 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/whisper/__init__.py @@ -0,0 +1,12 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +# -------------------------------------------------------------------------- +import os +import sys + +sys.path.append(os.path.dirname(__file__)) + +transformers_dir = os.path.normpath(os.path.join(os.path.dirname(__file__), "..", "..")) +if transformers_dir not in sys.path: + sys.path.append(transformers_dir) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/whisper/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/whisper/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..44990defd7cd41462b8d0a9ec835272565ca7a1d Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/whisper/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/whisper/__pycache__/benchmark.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/whisper/__pycache__/benchmark.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..92f5d79b6ce7ebcec55bc06d490a89dfc7a39fd7 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/whisper/__pycache__/benchmark.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/whisper/__pycache__/benchmark_all.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/whisper/__pycache__/benchmark_all.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c5aed83238073425affda2ec642f77e7eca352f9 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/whisper/__pycache__/benchmark_all.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/whisper/__pycache__/convert_to_onnx.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/whisper/__pycache__/convert_to_onnx.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4b48b3d7d2a1598f692f699f6d2888324e888e35 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/whisper/__pycache__/convert_to_onnx.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/whisper/__pycache__/whisper_chain.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/whisper/__pycache__/whisper_chain.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b91230ffef292a5ae3c70fa434895111e76c5cea Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/whisper/__pycache__/whisper_chain.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/whisper/__pycache__/whisper_decoder.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/whisper/__pycache__/whisper_decoder.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3eb9822c5788abfd2d941ec3d5d759719b4a9fbb Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/whisper/__pycache__/whisper_decoder.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/whisper/__pycache__/whisper_encoder.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/whisper/__pycache__/whisper_encoder.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e3a44e89b3648c8f54c9cd3dd31762e0a42144ae Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/whisper/__pycache__/whisper_encoder.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/whisper/__pycache__/whisper_encoder_decoder_init.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/whisper/__pycache__/whisper_encoder_decoder_init.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1dd7ff959087218f20f28cabd95a8ea8a36d1f79 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/whisper/__pycache__/whisper_encoder_decoder_init.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/whisper/__pycache__/whisper_helper.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/whisper/__pycache__/whisper_helper.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..773a4534e8c3bba67e1daa2b35a34cca4f3e9d7b Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/whisper/__pycache__/whisper_helper.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/whisper/__pycache__/whisper_inputs.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/whisper/__pycache__/whisper_inputs.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c3dbee88fd93ae834bf9b4d969fdc572d26dc68b Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/whisper/__pycache__/whisper_inputs.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/whisper/__pycache__/whisper_jump_times.cpython-313.pyc b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/whisper/__pycache__/whisper_jump_times.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b5f24fa051ea2dc5c920dff95301b155a1300d19 Binary files /dev/null and b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/whisper/__pycache__/whisper_jump_times.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/whisper/benchmark.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/whisper/benchmark.py new file mode 100644 index 0000000000000000000000000000000000000000..b6b5b3f3bcc90165d3eb1a8ce268504e0731bbec --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/whisper/benchmark.py @@ -0,0 +1,585 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +import argparse +import ast +import datetime +import gc +import logging +import os +import sys +import time + +import numpy as np +import psutil +import torch +import whisper +from benchmark_helper import measure_memory, setup_logger +from onnxruntime_extensions import get_library_path +from optimum.onnxruntime import ORTModelForSpeechSeq2Seq +from torch.profiler import ProfilerActivity, profile, record_function +from tqdm import trange +from transformers import AutoModelForSpeechSeq2Seq, WhisperConfig, WhisperProcessor + +import onnxruntime as ort + +logger = logging.getLogger(__name__) + + +def get_inputs(args: argparse.Namespace): + if args.benchmark_type not in {"hf-pt-eager", "hf-pt-compile", "hf-ort", "ort"}: + raise Exception("Unable to auto-detect inputs for provided model") + + def load_via_ffmpeg(): + audio = whisper.load_audio(args.audio_path) + audio = whisper.pad_or_trim(audio) + return audio + + def load_via_numpy(): + with open(args.audio_path, "rb") as f: + audio = np.asarray(list(f.read()), dtype=np.uint8) + audio = np.array([audio]) + return audio + + inputs = { + "max_length": args.max_length, + "min_length": args.min_length, + "num_beams": args.num_beams, + "num_return_sequences": args.num_return_sequences, + "length_penalty": args.length_penalty, + "repetition_penalty": args.repetition_penalty, + } + if args.benchmark_type == "ort": + # convert_to_onnx export or ONNX E2E solution created by Olive + for k, v in inputs.items(): + inputs[k] = np.array([v], dtype=np.float32 if "penalty" in k else np.int32) + if args.has_decoder_input_ids: + inputs["decoder_input_ids"] = np.array([args.decoder_input_ids], dtype=np.int32) + if args.has_logits_processor: + inputs["logits_processor"] = np.array([args.logits_processor], dtype=np.int32) + if args.has_temperature: + inputs["temperature"] = np.array([args.temperature], dtype=np.float32) + + # Measure time taken to load audio file + logger.info(f"Load audio: {args.audio_path}") + load_audio_fn = lambda onnx_e2e: load_via_numpy() if onnx_e2e else load_via_ffmpeg() # noqa: E731 + time_fn(args, load_audio_fn, args.has_audio_stream) + audio_data = load_audio_fn(args.has_audio_stream) + + if args.has_audio_stream: + # ONNX E2E solution created by Olive + inputs["audio_stream"] = audio_data + return inputs + + # Measure time taken to get input features + logger.info("Feature extraction: ") + return_type = "np" if args.benchmark_type == "ort" else "pt" + processor_fn = lambda audio: args.processor.feature_extractor( # noqa: E731 + [audio], return_tensors=return_type, sampling_rate=args.sampling_rate + ).input_features + time_fn(args, processor_fn, audio_data) + input_features = processor_fn(audio_data) + + if args.benchmark_type == "ort": + # convert_to_onnx export + inputs["input_features"] = input_features + return inputs + + inputs["inputs"] = input_features.to( + dtype=torch.float16 if args.use_fp16 else torch.float32, device=args.target_device + ) + inputs["no_repeat_ngram_size"] = args.no_repeat_ngram_size + inputs["early_stopping"] = True + inputs["use_cache"] = True + + if args.decoder_input_ids: + inputs["forced_decoder_ids"] = args.decoder_input_ids + + return inputs + + +def get_model(args: argparse.Namespace): + model, sess_options = None, None + start_time, end_time = None, None + + # There are multiple sources that the model could come from: + # 1) Benchmark Whisper from Hugging Face + # 2) Benchmark Whisper ONNX model from Optimum export (without pre/post processing) + # 3) Benchmark Whisper ONNX E2E model from Olive (with pre/post processing) + + if args.benchmark_type in {"hf-pt-eager", "hf-pt-compile"}: + source = args.hf_pt_model_path if args.hf_pt_model_path else args.model_name + start_time = time.time() + model = AutoModelForSpeechSeq2Seq.from_pretrained( + source, + torch_dtype=torch.float16 if args.use_fp16 else torch.float32, + use_cache=True, + ).to(args.target_device) + end_time = time.time() + + if args.benchmark_type == "hf-pt-compile": + model = torch.compile(model) + + elif args.benchmark_type in {"hf-ort", "ort"}: + sess_options = ort.SessionOptions() + sess_options.enable_profiling = args.profile + sess_options.register_custom_ops_library(get_library_path()) + if args.verbose: + sess_options.log_verbosity_level = 1 + sess_options.log_severity_level = 1 + + else: + raise Exception(f"Cannot recognize {args.benchmark_type}") + + if args.benchmark_type == "hf-ort": + # Optimum export + provider = args.execution_provider[0] if type(args.execution_provider) is tuple else args.execution_provider + provider_options = args.execution_provider[1] if type(args.execution_provider) is tuple else None + + start_time = time.time() + model = ORTModelForSpeechSeq2Seq.from_pretrained( + args.hf_ort_dir_path, + provider=provider, + provider_options=provider_options, + session_options=sess_options, + use_io_binding=True, # Avoid memory copy overhead + ) + end_time = time.time() + + if args.benchmark_type == "ort": + # convert_to_onnx.py export + logger.info(f"Loading model from {args.ort_model_path}") + start_time = time.time() + model = ort.InferenceSession( + args.ort_model_path, + sess_options, + providers=[args.execution_provider], + ) + end_time = time.time() + + logger.info(f"Loaded model in {end_time - start_time} s") + + return model + + +def time_fn(args, fn, inputs): + warmup_inputs = inputs[0] if type(inputs) is tuple else inputs + benchmark_inputs = inputs[1] if type(inputs) is tuple else inputs + torch_device = torch.device(args.target_device) + + # Warm up + warmup_range = ( + range(args.warmup_runs) + if args.benchmark_type == "ort" + else trange(args.warmup_runs, file=sys.stdout, desc="Warm up") + ) + + if args.verbose: + outputs = fn(warmup_inputs) + logger.info(outputs) + + for _ in warmup_range: + fn(warmup_inputs) + + # Benchmark + if args.device != "cpu": + torch.cuda.synchronize(torch_device) + start_time = time.time() + + bench_range = ( + range(args.num_runs) + if args.benchmark_type == "ort" + else trange(args.num_runs, file=sys.stdout, desc="Benchmark") + ) + for _ in bench_range: + fn(benchmark_inputs) + + if args.device != "cpu": + torch.cuda.synchronize(torch_device) + end_time = time.time() + + # Newline print after trange in order to print metrics on new lines without progress bar on same line + if args.benchmark_type != "ort": + logger.info("") + + batch_size = 1 + latency = (end_time - start_time) / args.num_runs + throughput = batch_size / latency + + logger.info(f"Latency: {latency} s") + logger.info(f"Throughput: {throughput} qps") + return + + +def profile_fn(args, fn, inputs, inputs_type): + # Filename prefix format: + # "--___" + prefix = f"{args.benchmark_type.lower()}-{args.precision}-{args.device}_{fn.__name__.replace('_', '-')}_{inputs_type}_{datetime.datetime.now():%Y-%m-%d_%H:%M:%S}" + filename = None + + if args.benchmark_type in {"hf-pt-eager", "hf-pt-compile"}: + # Profile PyTorch kernels + with profile( # noqa: SIM117 + activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA], record_shapes=True, profile_memory=True + ) as prof: + with record_function("model_inference"): + fn(inputs) + prof_data = prof.key_averages(group_by_stack_n=5).table(sort_by=args.pt_filter_by, row_limit=args.pt_num_rows) + + filename = os.path.join(args.log_folder, f"{prefix}.log") + with open(filename, "w") as f: + f.write(prof_data) + + else: + # Profile ORT kernels + fn(inputs) + + # Set new log name for ORT profile log generated + filename = f"{prefix}.json" + + return filename + + +def measure_fn(args, fn, inputs): + # Measure CPU usage + pid = os.getpid() + process = psutil.Process(pid) + process.cpu_percent(interval=0.1) + + fn(inputs) + logger.info(f"CPU usage: {process.cpu_percent(interval=None)}%") + + # Measure memory usage + gc.collect() + torch.cuda.empty_cache() + measure_memory(is_gpu=(args.device != "cpu"), func=lambda: fn(inputs), monitor_type=args.monitor_type) + + # Flush output so memory usage is printed + sys.stdout.flush() + + +def run_hf_inference(args, inputs, model): + # Inference steps to measure + def get_pred_ids(inputs): + # Inference pass with predicted token ids generation + predicted_ids = model.generate(**inputs) + return predicted_ids + + def gen_and_dec(inputs): + # Inference pass with generation and decoding + predicted_ids = get_pred_ids(inputs) + transcription = [] + for _ in range(args.num_return_sequences): + transcription.append(args.processor.batch_decode(predicted_ids, skip_special_tokens=True)[0]) + return predicted_ids, transcription + + # Examples of other inference steps that can be measured: + # To use, uncomment the function and assign it to `generate_fn` + + # def get_logits(inputs): + # # Inference pass without decoding + # outputs = model(**inputs) + # return outputs + + generate_fn = gen_and_dec + + if args.benchmark_type == "hf-pt-compile": + # Run forward pass once with each set of inputs to process through Dynamo + generate_fn(inputs) + + if args.profile: + new_logname = profile_fn(args, generate_fn, inputs, "gen-and-dec") + if args.benchmark_type == "hf-ort": + # Rename log files per model component and turn profiling off to stop appending to log + new_prefix = new_logname[: -len(".json")] + + old_logname = model.encoder.session.end_profiling() + new_logname = new_prefix + "-encoder.json" + if os.path.isfile(old_logname): + logger.warning(f"Renaming {old_logname} to {new_logname}") + os.rename(old_logname, os.path.join(args.log_folder, new_logname)) + + old_logname = model.decoder.session.end_profiling() + new_logname = new_prefix + "-decoder.json" + if os.path.isfile(old_logname): + logger.warning(f"Renaming {old_logname} to {new_logname}") + os.rename(old_logname, os.path.join(args.log_folder, new_logname)) + + old_logname = model.decoder_with_past.session.end_profiling() + new_logname = new_prefix + "-decoder-with-past.json" + if os.path.isfile(old_logname): + logger.warning(f"Renaming {old_logname} to {new_logname}") + os.rename(old_logname, os.path.join(args.log_folder, new_logname)) + + return + + # PyTorch evaluations + logger.info("\nEvaluating PyTorch...") + time_fn(args, generate_fn, inputs) + predicted_ids, transcription = generate_fn(inputs) + logger.info(f"Generated token length: {len(predicted_ids[0])} tokens") + logger.info(f"Transcription: {transcription[0]}") + measure_fn(args, generate_fn, inputs) + + +def run_ort_inference(args, inputs, model): + def prepare_ort_inputs(inputs, warmup=False): + # Check that all model inputs will be provided + model_inputs = {model_input.name for model_input in model.get_inputs()} + user_inputs = set(inputs.keys()) + missing_inputs = model_inputs - user_inputs + if len(missing_inputs): + logger.error(f"The following model inputs are missing: {missing_inputs}") + raise Exception("There are missing inputs to the model. Please add them and try again.") + + # Remove unnecessary inputs from model inputs + unnecessary_inputs = user_inputs - model_inputs + if len(unnecessary_inputs): + for unnecessary_input in unnecessary_inputs: + logger.info(f"Removing unnecessary input '{unnecessary_input}' from user provided inputs") + del inputs[unnecessary_input] + + # Add IO bindings for non-CPU execution providers + if args.device != "cpu": + io_binding = model.io_binding() + for k, v in inputs.items(): + io_binding.bind_cpu_input(k, v) + for output in model.get_outputs(): + io_binding.bind_output(output.name, device_type=args.device, device_id=args.device_id) + return io_binding + + return inputs + + def with_io_binding(io_binding): + # Inference pass with IO binding + model.run_with_iobinding(io_binding) + return io_binding + + def without_io_binding(inputs): + # Inference pass without IO binding + outputs = model.run(None, inputs) + return outputs + + def handle_output(output): + if args.eos_token_id in output: + first_end = np.where(output == args.eos_token_id)[0][0] + return output[: first_end + 1] + + return output + + generate_fn = with_io_binding if args.device != "cpu" else without_io_binding + ort_inputs = prepare_ort_inputs(inputs) + + if args.profile: + new_logname = profile_fn(args, generate_fn, ort_inputs, "e2e") + + # Turn profiling off to stop appending to log file + old_logname = model.end_profiling() + logger.warning(f"Renaming {old_logname} to {new_logname}") + os.rename(old_logname, os.path.join(args.log_folder, new_logname)) + + return + + # ORT evaluation + logger.info("\nEvaluating ONNX Runtime...") + ort_evaluate_inputs = ort_inputs + + time_fn(args, generate_fn, ort_evaluate_inputs) + ort_outputs = generate_fn(ort_inputs) + if args.device != "cpu": + ort_outputs = ort_outputs.copy_outputs_to_cpu() + ort_outputs = ort_outputs[0] + + if args.has_audio_stream: + # ONNX E2E model from Olive produces transcribed output + logger.info(f"Transcription: {ort_outputs[0][0]}") + else: + # convert_to_onnx model produces generated ids + actual_output = handle_output(ort_outputs[0][0]) + logger.info(f"Generated token length: {len(actual_output)} tokens") + transcription = args.processor.batch_decode(ort_outputs[0], skip_special_tokens=True)[0] + # print to stdout as the output for comparison + print(f"{transcription}") + + measure_fn(args, generate_fn, ort_inputs) + + +def run_inference(args, inputs, model): + if args.benchmark_type in {"hf-pt-eager", "hf-pt-compile", "hf-ort"}: + run_hf_inference(args, inputs, model) + elif args.benchmark_type == "ort": + run_ort_inference(args, inputs, model) + else: + raise Exception(f"Cannot recognize {args.benchmark_type}") + + +def parse_args(): + parser = argparse.ArgumentParser() + + parser.add_argument( + "-bt", + "--benchmark-type", + type=str, + required=True, + choices=["hf-pt-eager", "hf-pt-compile", "hf-ort", "ort"], + ) + + parser.add_argument( + "-m", + "--model-name", + type=str, + required=True, + help="Hugging Face name of model (e.g. 'openai/whisper-large-v2')", + ) + parser.add_argument( + "-p", + "--precision", + type=str, + required=True, + default="fp32", + choices=["int4", "int8", "fp16", "fp32"], + help="Precision for model. For ONNX models, the model's precision should be set before running this script.", + ) + + parser.add_argument( + "--hf-pt-model-path", + type=str, + default="", + help="Path to directory containing all PyTorch files (e.g. tokenizer, PyTorch model)", + ) + parser.add_argument( + "--hf-ort-dir-path", + type=str, + default="", + help="Path to directory containing all ONNX files (e.g. tokenizer, encoder, decoder, decoder_with_past)", + ) + parser.add_argument( + "--ort-model-path", + type=str, + default="", + help="Path to ONNX model", + ) + + # Args for running and evaluating the model + parser.add_argument("-a", "--audio-path", type=str, required=True, help="Path to audio file for E2E evaluation") + parser.add_argument( + "-d", + "--device", + type=str, + default="cuda" if torch.cuda.is_available() else "cpu", + choices=["cpu", "cuda"], + ) + parser.add_argument("-id", "--device-id", type=int, default=0) + parser.add_argument("-w", "--warmup-runs", type=int, default=5) + parser.add_argument("-n", "--num-runs", type=int, default=10) + parser.add_argument("--seed", type=int, default=2) + + # Optional args: + parser.add_argument("--sampling-rate", type=int, default=16000, help="Sampling rate for audio (in Hz)") + + # Args for decoding logic + # Required args: + parser.add_argument("--max-length", type=int, default=448) + parser.add_argument("--min-length", type=int, default=0) + parser.add_argument("--num-beams", type=int, default=1) + parser.add_argument("--num-return-sequences", type=int, default=1) + parser.add_argument("--length-penalty", type=float, default=1.0) + parser.add_argument("--repetition-penalty", type=float, default=1.0) + parser.add_argument("--no-repeat-ngram-size", type=int, default=3) + + # Optional args for E2E solution: + parser.add_argument( + "--decoder-input-ids", + type=str, + default="[]", + help="The forced decoder ids for generation. Format is [start token, timestamp token, language token, task token]. Default is [start token]. See `decoder_input_ids` in https://github.com/microsoft/Olive/tree/main/examples/whisper for details.", + ) + parser.add_argument( + "--logits-processor", + type=int, + default=1, + help="Whether to use timestamps logits processor or not (0 for false, 1 for true).", + ) + parser.add_argument( + "--temperature", + type=float, + default=1.0, + help="Temperature value for generation.", + ) + + # Args for accessing detailed info + parser.add_argument("--profile", default=False, action="store_true") + parser.add_argument( + "--pt-filter-by", type=str, default="self_cpu_time_total", help="What to filter PyTorch profiler by" + ) + parser.add_argument("--pt-num-rows", type=int, default=1000, help="Number of rows for PyTorch profiler to display") + parser.add_argument("--verbose", default=False, action="store_true") + parser.add_argument("--log-folder", type=str, default=os.path.join("."), help="Folder to cache log files") + + args = parser.parse_args() + + # Set seed properties + np.random.seed(args.seed) + torch.manual_seed(args.seed) + + args.monitor_type = args.device + # Set runtime properties + if "ort" in args.benchmark_type: + args.execution_provider = f"{args.device.upper()}ExecutionProvider" + if args.execution_provider == "CUDAExecutionProvider": + args.execution_provider = (args.execution_provider, {"device_id": args.device_id}) + + # Check that model paths have been specified for any benchmarking with ORT + if args.benchmark_type == "hf-ort": + assert args.hf_ort_dir_path, "Please specify a path to `--hf-ort-dir-path`" + if args.benchmark_type == "ort": + assert args.ort_model_path, "Please specify a path to `--ort-model-path`" + + # Convert decoder_input_ids string to list of ids + # (e.g. "[1, 50257]" for Hugging Face or "[50257]" for ORT) + args.decoder_input_ids = ast.literal_eval(args.decoder_input_ids) + + return args + + +def main(): + args = parse_args() + setup_logger(args.verbose) + logger.info(args.__dict__) + torch.backends.cudnn.benchmark = True + + config = WhisperConfig.from_pretrained(args.model_name) + processor = WhisperProcessor.from_pretrained(args.model_name) + target_device = f"cuda:{args.device_id}" if args.device != "cpu" else args.device + use_fp16 = args.precision == "fp16" or (args.precision in {"int8", "int4"} and args.device != "cpu") + + setattr(args, "processor", processor) # noqa: B010 + setattr(args, "target_device", target_device) # noqa: B010 + setattr(args, "use_fp16", use_fp16) # noqa: B010 + setattr(args, "has_audio_stream", False) # noqa: B010 + setattr(args, "eos_token_id", config.eos_token_id) # noqa: B010 + + logger.info(f"Forced decoder prompt ids: {args.decoder_input_ids}") + + # Measure cost to transcribe audio + model = get_model(args) + if args.benchmark_type == "ort": + # Check for optional inputs that could have been added during export + ort_model_inputs = {model_input.name for model_input in model.get_inputs()} + args.has_audio_stream = "audio_stream" in ort_model_inputs + setattr(args, "has_decoder_input_ids", "decoder_input_ids" in ort_model_inputs) # noqa: B010 + setattr(args, "has_logits_processor", "logits_processor" in ort_model_inputs) # noqa: B010 + setattr(args, "has_temperature", "temperature" in ort_model_inputs) # noqa: B010 + + if args.decoder_input_ids == []: + args.decoder_input_ids = [config.decoder_start_token_id] + + inputs = get_inputs(args) + run_inference(args, inputs, model) + + +if __name__ == "__main__": + main() diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/whisper/benchmark_all.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/whisper/benchmark_all.py new file mode 100644 index 0000000000000000000000000000000000000000..57b763f7f7883f97bd92518ce4687dead856d952 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/whisper/benchmark_all.py @@ -0,0 +1,526 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +import argparse +import datetime +import json +import logging +import os +import subprocess + +import librosa +import torch +from benchmark_helper import setup_logger +from metrics import BenchmarkRecord +from transformers import WhisperConfig, WhisperProcessor + +logger = logging.getLogger(__name__) + + +def get_args(): + parser = argparse.ArgumentParser() + + parser.add_argument( + "-a", + "--audio-path", + type=str, + required=True, + help="Path to folder of audio files for E2E evaluation", + ) + + parser.add_argument( + "-l", + "--language", + default=None, + help="Language of audio file", + ) + + parser.add_argument( + "-t", + "--task", + default=None, + choices=["transcribe", "translate"], + help="Task to complete", + ) + + parser.add_argument( + "-w", + "--warmup-runs", + type=int, + default=5, + ) + + parser.add_argument( + "-n", + "--num-runs", + type=int, + default=10, + ) + + parser.add_argument( + "--hf-pt-eager", + default=False, + action="store_true", + help="Benchmark in PyTorch without `torch.compile`", + ) + + parser.add_argument( + "--hf-pt-compile", + default=False, + action="store_true", + help="Benchmark in PyTorch with `torch.compile`", + ) + + parser.add_argument( + "--hf-ort-dir-path", + type=str, + help="Path to folder containing ONNX models for Optimum + ORT benchmarking", + ) + + parser.add_argument( + "--ort-model-path", + type=str, + help="Path to ONNX model for ORT benchmarking", + ) + + parser.add_argument( + "--model-name", + type=str, + required=True, + help="Model name in Hugging Face (e.g. openai/whisper-large-v2)", + ) + + parser.add_argument( + "--precision", + type=str, + required=True, + choices=["int4", "int8", "fp16", "fp32"], + help="Precision to run model", + ) + + parser.add_argument( + "--device", + type=str, + required=True, + choices=["cpu", "cuda"], + help="Device to benchmark models", + ) + + parser.add_argument( + "--device-id", + type=int, + default=0, + help="GPU device ID", + ) + + parser.add_argument( + "--verbose", + default=False, + action="store_true", + help="Print detailed logs", + ) + + parser.add_argument( + "--timeout", + type=int, + default=5, + help="Number of mins to attempt the benchmark before moving on", + ) + + parser.add_argument( + "--log-folder", + type=str, + default=None, + help="Path to folder to save logs and results", + ) + + parser.add_argument("--tune", default=False, action="store_true") + + args = parser.parse_args() + + setattr(args, "model_size", args.model_name.split("/")[-1].replace(".", "-")) # noqa: B010 + log_folder_name = f"./{args.model_size}-{args.precision}" + if not args.log_folder: + args.log_folder = log_folder_name + os.makedirs(args.log_folder, exist_ok=True) + + # Convert timeout value to secs + args.timeout *= 60 + + return args + + +def process_log_file(device_id, log_file, base_results): + entries = [] + + # Detect steps in speech pipeline + step = None + load_audio_pattern = "Load audio: " + feat_ext_pattern = "Feature extraction: " + pytorch_pattern = "Evaluating PyTorch..." + onnxruntime_pattern = "Evaluating ONNX Runtime..." + + load_audio_latency_s, load_audio_throughput_s = None, None + feat_ext_latency_s, feat_ext_throughput_s = None, None + token_length, latency_s, per_token_latency_s, per_token_latency_ms = None, None, None, None + throughput, memory = None, None + + # Detect metrics + latency_pattern = "Latency: " + throughput_pattern = "Throughput: " + token_length_pattern = "Generated token length: " + memory_pattern = "peak=" + + with open(log_file) as f: + for input_line in f: + line = input_line.replace("\n", "") + + # Get step in speech recognition pipeline + if load_audio_pattern in line: + step = "load-audio" + elif feat_ext_pattern in line: + step = "feature-extraction" + elif pytorch_pattern in line or onnxruntime_pattern in line: + step = "process" + + # Check metrics + if latency_pattern in line: + latency_s = float(line[len(latency_pattern) : line.rfind(" ")]) + elif throughput_pattern in line: + throughput = float(line[len(throughput_pattern) : line.rfind(" ")]) + if step == "load-audio": + load_audio_latency_s, load_audio_throughput_s = latency_s, throughput + step = None + if step == "feature-extraction": + feat_ext_latency_s, feat_ext_throughput_s = latency_s, throughput + step = None + elif token_length_pattern in line: + token_length = int(line[len(token_length_pattern) : line.rfind(" ")]) + per_token_latency_s = latency_s / token_length + per_token_latency_ms = per_token_latency_s * 1000 + elif memory_pattern in line: + if "CPU" in line: + # Example format for log entry: + # CPU memory usage: before=1000.0 MB, peak=2000.0 MB + memory = float(line[line.rfind("=") + 1 : line.rfind(" MB")]) / 1000 + else: + # Example format for log entry: + # GPU memory usage: before=[{'device_id': 0, 'name': 'Tesla V100-PCIE-16GB', 'max_used_MB': 1638.875}, {'device_id': 1, 'name': 'Tesla V100-PCIE-16GB', 'max_used_MB': 236.875}, peak=[{'device_id': 0, 'name': 'Tesla V100-PCIE-16GB', 'max_used_MB': 1780.875}, {'device_id': 1, 'name': 'Tesla V100-PCIE-16GB', 'max_used_MB': 236.875}] + peak = line[line.find(memory_pattern) + len(memory_pattern) :].replace("'", '"') + usage = json.loads(peak)[device_id]["max_used_MB"] + memory = float(usage) / 1000 + + # Calculate real-time factor (RTF): + # RTF = total latency / audio duration + total_latency = ( + (load_audio_latency_s if load_audio_latency_s else 0) + + (feat_ext_latency_s if feat_ext_latency_s else 0) + + (latency_s if latency_s else 0) + ) + audio_duration = base_results[-1] + rtf = (total_latency / audio_duration) if audio_duration else -1 + logger.info(f"Total latency: {total_latency} s") + logger.info(f"Audio duration: {audio_duration} s") + logger.info(f"Real-time factor: {rtf}") + + # Append log entry to list of entries + entry = base_results + [ # noqa: RUF005 + token_length, + load_audio_latency_s, + load_audio_throughput_s, + feat_ext_latency_s if feat_ext_latency_s else -1, + feat_ext_throughput_s if feat_ext_throughput_s else -1, + latency_s, + per_token_latency_ms, + throughput, + memory, + rtf, + ] + entries.append(entry) + + return entries + + +def save_results(results, filename): + import pandas as pd # noqa: PLC0415 + + df = pd.DataFrame( + results, + columns=[ + "Warmup Runs", + "Measured Runs", + "Model Name", + "Engine", + "Precision", + "Device", + "Audio File", + "Duration (s)", + "Token Length", + "Load Audio Latency (s)", + "Load Audio Throughput (qps)", + "Feature Extractor Latency (s)", + "Feature Extractor Throughput (qps)", + "Latency (s)", + "Per Token Latency (ms/token)", + "Throughput (qps)", + "Memory (GB)", + "Real Time Factor (RTF)", + ], + ) + + # Set column types + df["Warmup Runs"] = df["Warmup Runs"].astype("int") + df["Measured Runs"] = df["Measured Runs"].astype("int") + df["Duration (s)"] = df["Duration (s)"].astype("float") + df["Token Length"] = df["Token Length"].astype("int") + df["Load Audio Latency (s)"] = df["Load Audio Latency (s)"].astype("float") + df["Load Audio Throughput (qps)"] = df["Load Audio Throughput (qps)"].astype("float") + df["Feature Extractor Latency (s)"] = df["Feature Extractor Latency (s)"].astype("float") + df["Feature Extractor Throughput (qps)"] = df["Feature Extractor Throughput (qps)"].astype("float") + df["Latency (s)"] = df["Latency (s)"].astype("float") + df["Per Token Latency (ms/token)"] = df["Per Token Latency (ms/token)"].astype("float") + df["Throughput (qps)"] = df["Throughput (qps)"].astype("float") + df["Memory (GB)"] = df["Memory (GB)"].astype("float") + df["Real Time Factor (RTF)"] = df["Real Time Factor (RTF)"].astype("float") + + # get package name and version + import pkg_resources # noqa: PLC0415 + + installed_packages = pkg_resources.working_set + installed_packages_list = sorted( + [f"{i.key}=={i.version}" for i in installed_packages if i.key in ["onnxruntime", "onnxruntime-gpu"]] + ) + ort_pkg_name = "" + ort_pkg_version = "" + if installed_packages_list: + ort_pkg_name = installed_packages_list[0].split("==")[0] + ort_pkg_version = installed_packages_list[0].split("==")[1] + + # Save results to csv with standard format + records = [] + for _, row in df.iterrows(): + if row["Engine"] == "onnxruntime": + record = BenchmarkRecord( + row["Model Name"], row["Precision"], row["Engine"], row["Device"], ort_pkg_name, ort_pkg_version + ) + else: + record = BenchmarkRecord( + row["Model Name"], row["Precision"], row["Engine"], row["Device"], torch.__name__, torch.__version__ + ) + record.config.customized["audio_file"] = row["Audio File"] + record.config.warmup_runs = row["Warmup Runs"] + record.config.measured_runs = row["Measured Runs"] + + record.metrics.customized["duration"] = row["Duration (s)"] + record.metrics.customized["token_length"] = row["Token Length"] + record.metrics.customized["load_audio_latency"] = row["Load Audio Latency (s)"] + record.metrics.customized["load_audio_throughput"] = row["Load Audio Throughput (qps)"] + record.metrics.customized["feature_extractor_latency_s"] = row["Feature Extractor Latency (s)"] + record.metrics.customized["feature_extractor_throughput_qps"] = row["Feature Extractor Throughput (qps)"] + record.metrics.customized["per_token_latency_ms"] = row["Per Token Latency (ms/token)"] + record.metrics.customized["rtf"] = row["Real Time Factor (RTF)"] + + record.metrics.latency_ms_mean = row["Latency (s)"] * 1000 + record.metrics.throughput_qps = row["Throughput (qps)"] + record.metrics.max_memory_usage_GB = row["Memory (GB)"] + + records.append(record) + + BenchmarkRecord.save_as_csv(filename, records) + BenchmarkRecord.save_as_json(filename.replace(".csv", ".json"), records) + logger.info(f"Results saved in {filename}!") + + +def benchmark(args, benchmark_cmd, engine, audio_file, duration): + log_filename = f"{engine}_{datetime.datetime.now():%Y-%m-%d_%H:%M:%S}.log" + log_path = os.path.join(args.log_folder, log_filename) + with open(log_path, "w") as log_file: + process = subprocess.Popen(benchmark_cmd, stdout=log_file, stderr=log_file) + try: + process.wait(args.timeout) + except subprocess.TimeoutExpired: + process.kill() + + # Create entries for csv + logger.info("Gathering data from log files...") + base_results = [ + args.warmup_runs, + args.num_runs, + args.model_name, + engine, + args.precision, + args.device, + audio_file, + duration, + ] + results = process_log_file(args.device_id, log_path, base_results) + + return results + + +def main(): + args = get_args() + setup_logger(args.verbose) + logger.info(args.__dict__) + torch.backends.cudnn.benchmark = True + + config = WhisperConfig.from_pretrained(args.model_name) + processor = WhisperProcessor.from_pretrained(args.model_name) + + # Calculate forced decoder input ids + hf_forced_decoder_ids = processor.get_decoder_prompt_ids(language=args.language, task=args.task) + ort_forced_decoder_ids = [config.decoder_start_token_id] + [token_id[1] for token_id in hf_forced_decoder_ids] + hf_decoder_input_ids_cmd = ( + ["--decoder-input-ids", str(hf_forced_decoder_ids)] if args.language and args.task else [] + ) + ort_decoder_input_ids_cmd = ( + ["--decoder-input-ids", str(ort_forced_decoder_ids)] if args.language and args.task else [] + ) + ort_tune_cmd = ["--tune"] if args.tune else [] + + all_results = [] + for audio_file in os.listdir(args.audio_path): + audio_path = os.path.join(args.audio_path, audio_file) + try: + duration = librosa.get_duration(path=audio_path) + except Exception as e: + duration = -1 + logger.warning(f"An error occurred while trying to calculate the audio duration: {e}", exc_info=True) + logger.warning( + f"If you get an error that says:\n\tsoundfile.LibsndfileError: Error opening '{audio_file}': File contains data in an unknown format.\nyou may not have installed `ffmpeg` in addition to installing `librosa`." + ) + logger.info(f"Testing {audio_path}...") + + # Benchmark PyTorch without torch.compile + if args.hf_pt_eager: + benchmark_cmd = [ # noqa: RUF005 + "python", + "-m", + "models.whisper.benchmark", + "--audio-path", + audio_path, + "--benchmark-type", + "hf-pt-eager", + "--model-name", + args.model_name, + "--precision", + args.precision, + "--device", + args.device, + "--device-id", + str(args.device_id), + "--warmup-runs", + str(args.warmup_runs), + "--num-runs", + str(args.num_runs), + "--log-folder", + args.log_folder, + ] + hf_decoder_input_ids_cmd + logger.info("Benchmark PyTorch without torch.compile") + results = benchmark(args, benchmark_cmd, "pytorch-eager", audio_file, duration) + all_results.extend(results) + + # Benchmark PyTorch with torch.compile + if args.hf_pt_compile: + benchmark_cmd = [ # noqa: RUF005 + "python", + "-m", + "models.whisper.benchmark", + "--audio-path", + audio_path, + "--benchmark-type", + "hf-pt-compile", + "--model-name", + args.model_name, + "--precision", + args.precision, + "--device", + args.device, + "--device-id", + str(args.device_id), + "--warmup-runs", + str(args.warmup_runs), + "--num-runs", + str(args.num_runs), + "--log-folder", + args.log_folder, + ] + hf_decoder_input_ids_cmd + logger.info("Benchmark PyTorch with torch.compile") + results = benchmark(args, benchmark_cmd, "pytorch-compile", audio_file, duration) + all_results.extend(results) + + # Benchmark Optimum + ONNX Runtime + if args.hf_ort_dir_path: + benchmark_cmd = [ # noqa: RUF005 + "python", + "-m", + "models.whisper.benchmark", + "--audio-path", + audio_path, + "--benchmark-type", + "hf-ort", + "--hf-ort-dir-path", + args.hf_ort_dir_path, + "--model-name", + args.model_name, + "--precision", + args.precision, + "--device", + args.device, + "--device-id", + str(args.device_id), + "--warmup-runs", + str(args.warmup_runs), + "--num-runs", + str(args.num_runs), + "--log-folder", + args.log_folder, + ] + hf_decoder_input_ids_cmd + logger.info("Benchmark Optimum + ONNX Runtime") + results = benchmark(args, benchmark_cmd, "optimum-ort", audio_file, duration) + all_results.extend(results) + + # Benchmark ONNX Runtime + if args.ort_model_path: + benchmark_cmd = ( + [ # noqa: RUF005 + "python", + "-m", + "models.whisper.benchmark", + "--audio-path", + audio_path, + "--benchmark-type", + "ort", + "--ort-model-path", + args.ort_model_path, + "--model-name", + args.model_name, + "--precision", + args.precision, + "--device", + args.device, + "--device-id", + str(args.device_id), + "--warmup-runs", + str(args.warmup_runs), + "--num-runs", + str(args.num_runs), + "--log-folder", + args.log_folder, + ] + + ort_decoder_input_ids_cmd + + ort_tune_cmd + ) + logger.info("Benchmark ONNX Runtime") + results = benchmark(args, benchmark_cmd, "onnxruntime", audio_file, duration) + all_results.extend(results) + + csv_file = f"{args.model_size}-{args.precision}_{datetime.datetime.now():%Y-%m-%d_%H:%M:%S}.csv" + save_results(all_results, os.path.join(args.log_folder, csv_file)) + + +if __name__ == "__main__": + main() diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/whisper/convert_to_onnx.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/whisper/convert_to_onnx.py new file mode 100644 index 0000000000000000000000000000000000000000..0b763fff8fe8c06e0de9161c1a1e6be64c7b657b --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/whisper/convert_to_onnx.py @@ -0,0 +1,609 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +import argparse +import logging +import os +import warnings + +import onnx +import torch +from benchmark_helper import Precision, create_onnxruntime_session, prepare_environment, setup_logger +from whisper_chain import chain_model +from whisper_encoder import WhisperEncoder +from whisper_helper import PRETRAINED_WHISPER_MODELS, WhisperHelper + +from onnxruntime.quantization.matmul_nbits_quantizer import ( + KQuantWeightOnlyQuantConfig, + MatMulNBitsQuantizer, + QuantFormat, +) + +logger = logging.getLogger("") + +PROVIDERS = { + "cpu": "CPUExecutionProvider", + "cuda": "CUDAExecutionProvider", +} + + +def parse_arguments(argv=None): + parser = argparse.ArgumentParser() + + conversion_args = parser.add_argument_group("Conversion Process Args") + optional_inputs = parser.add_argument_group("Optional Inputs (for WhisperBeamSearch op)") + optional_outputs = parser.add_argument_group("Optional Outputs (for WhisperBeamSearch op)") + quant_args = parser.add_argument_group("INT8 Quantization Args") + + ################################# + # Conversion options for Whisper + ################################# + + conversion_args.add_argument( + "-m", + "--model_name_or_path", + required=False, + default=PRETRAINED_WHISPER_MODELS[0], + type=str, + help="Model path, or pretrained model name in the list: " + ", ".join(PRETRAINED_WHISPER_MODELS), + ) + + conversion_args.add_argument( + "--model_impl", + required=False, + default="hf", + choices=["hf", "openai"], + type=str, + help="Select implementation for export of encoder and decoder subgraphs", + ) + + conversion_args.add_argument( + "--cache_dir", + required=False, + type=str, + default=os.path.join(".", "cache_models"), + help="Directory to cache pre-trained models", + ) + + conversion_args.add_argument( + "--output", + required=False, + type=str, + default=os.path.join(".", "onnx_models"), + help="Output directory", + ) + + conversion_args.add_argument( + "-o", + "--optimize_onnx", + required=False, + action="store_true", + help="Use optimizer.py to optimize onnx model", + ) + conversion_args.set_defaults(optimize_onnx=False) + + conversion_args.add_argument( + "--use_gpu", + required=False, + action="store_true", + help="Use GPU for model inference", + ) + conversion_args.set_defaults(use_gpu=False) + + conversion_args.add_argument( + "-p", + "--precision", + required=False, + type=Precision, + default=Precision.FLOAT32, + choices=[Precision.FLOAT32, Precision.FLOAT16, Precision.INT8, Precision.INT4], + help="Precision of model to run. fp32 for full precision, fp16 for half precision, int8/int4 for quantization", + ) + + conversion_args.add_argument( + "--use_int64_inputs", + required=False, + action="store_true", + help="Use int64 instead of int32 for input_ids and attention_mask.", + ) + conversion_args.set_defaults(use_int64_inputs=False) + + conversion_args.add_argument( + "-r", + "--provider", + required=False, + type=str, + default="cpu", + choices=list(PROVIDERS.keys()), + help="Provider to benchmark. Default is CPUExecutionProvider.", + ) + + conversion_args.add_argument( + "--verbose", + required=False, + action="store_true", + help="Enable verbose logging", + ) + conversion_args.set_defaults(verbose=False) + + conversion_args.add_argument( + "-e", + "--use_external_data_format", + required=False, + action="store_true", + help="Save weights in external file. Necessary for 'small', 'medium', and 'large' models. Optional for 'tiny' and 'base' models.", + ) + conversion_args.set_defaults(use_external_data_format=False) + + conversion_args.add_argument( + "-w", + "--overwrite", + required=False, + action="store_true", + help="Overwrite existing ONNX model", + ) + conversion_args.set_defaults(overwrite=False) + + conversion_args.add_argument( + "--separate_encoder_and_decoder_init", + required=False, + action="store_true", + help="Do not merge encoder and decoder init to initialize past KV caches. Output 3 instead of 2 ONNX models.", + ) + conversion_args.set_defaults(separate_encoder_and_decoder_init=False) + + conversion_args.add_argument( + "--no_beam_search_op", + required=False, + action="store_true", + help="Do not produce model with WhisperBeamSearch op, which chains encdecinit and decoder models into one op.", + ) + conversion_args.set_defaults(no_beam_search_op=False) + + conversion_args.add_argument( + "--use_decoder_masked_mha", + required=False, + action="store_true", + help="Use DecoderMaskedMultiHeadAttention kernel for improved performance. This is currently an experimental feature.", + ) + conversion_args.set_defaults(use_decoder_masked_mha=False) + + ############################################################# + # Optional inputs for Whisper + # (listed below in the order that WhisperBeamSearch expects) + ############################################################# + + optional_inputs.add_argument( + "-v", + "--use_vocab_mask", + required=False, + action="store_true", + help="Use vocab_mask as an extra graph input to enable specific logits processing", + ) + optional_inputs.set_defaults(use_vocab_mask=False) + + optional_inputs.add_argument( + "-u", + "--use_prefix_vocab_mask", + required=False, + action="store_true", + help="Use prefix_vocab_mask as an extra graph input to enable specific logits processing", + ) + optional_inputs.set_defaults(use_prefix_vocab_mask=False) + + optional_inputs.add_argument( + "-f", + "--use_forced_decoder_ids", + required=False, + action="store_true", + help="Use decoder_input_ids as an extra graph input to the beam search op", + ) + optional_inputs.set_defaults(use_forced_decoder_ids=False) + + optional_inputs.add_argument( + "-l", + "--use_logits_processor", + required=False, + action="store_true", + help="Use logits_processor as an extra graph input to enable specific logits processing", + ) + optional_inputs.set_defaults(use_specific_logits_processor=False) + + optional_inputs.add_argument( + "--collect_cross_qk", + required=False, + action="store_true", + help="Beam search model collect stacked cross QK.", + ) + optional_inputs.set_defaults(collect_cross_qk=False) + + optional_inputs.add_argument( + "--extra_decoding_ids", + required=False, + action="store_true", + help="Need extra starting decoding ids for some feature like cross qk. Default if false.", + ) + optional_inputs.set_defaults(extra_decoding_ids=False) + + optional_inputs.add_argument( + "-t", + "--use_temperature", + required=False, + action="store_true", + help="Use temperature as an extra graph input for the WhisperBeamSearch op", + ) + optional_inputs.set_defaults(use_temperature=False) + + optional_inputs.add_argument( + "--no_repeat_ngram_size", + type=int, + default=0, + help="default to 0", + ) + + ############################################################# + # Optional outputs for Whisper + # (listed below in the order that WhisperBeamSearch expects) + ############################################################# + + optional_outputs.add_argument( + "--output_sequence_scores", + required=False, + action="store_true", + help="Beam search model output scores for each generated sequence.", + ) + optional_outputs.set_defaults(output_sequence_scores=False) + + optional_outputs.add_argument( + "--output_scores", + required=False, + action="store_true", + help="Beam search model output scores over vocab per generated token.", + ) + optional_outputs.set_defaults(output_scores=False) + + optional_outputs.add_argument( + "--output_cross_qk", + required=False, + action="store_true", + help="Beam search model output collected qk as output. Also hint collect_cross_qk", + ) + optional_outputs.set_defaults(output_cross_qk=False) + + optional_outputs.add_argument( + "--cross_qk_onnx_model", + required=False, + type=str, + default=None, + help="The model which consumes cross_qk outputs.", + ) + + optional_outputs.add_argument( + "--output_no_speech_probs", + required=False, + action="store_true", + help="Beam search model output no speech probs which is computed from the encoder/context-decoder graph.", + ) + optional_outputs.set_defaults(output_no_speech_probs=False) + + ################################### + # Quantization options for Whisper + ################################### + + quant_args.add_argument( + "--accuracy_level", + default=0, + required=False, + type=int, + help="Accuracy level of the 4-bit quantized MatMul computation.", + ) + + quant_args.add_argument( + "--quantize_symmetric", + required=False, + action="store_true", + help="Quantize weights symmetrically", + ) + quant_args.set_defaults(quantize_symmetric=False) + + args = parser.parse_args(argv) + + # Collect cross QKs if either flag is enabled + args.collect_cross_qk = args.collect_cross_qk or args.output_cross_qk + + # FP32 CPU can be supported here once the DMMHA CPU kernel bugs are fixed + args.use_decoder_masked_mha = args.use_decoder_masked_mha and args.provider == "cuda" + + return args + + +# quant_method is reserved for mixed precision in future +def make_quant_algo_config(precision, quant_method: str, matmul_nodes=None): + customized_weight_config = {} + quant_algo_config = None + + # need to use k_quant for int8 + if precision == Precision.INT8: + for node_name in matmul_nodes: + customized_weight_config[node_name] = {"bits": 8} + quant_algo_config = KQuantWeightOnlyQuantConfig(customized_weight_config=customized_weight_config) + else: + quant_algo_config = KQuantWeightOnlyQuantConfig(customized_weight_config=customized_weight_config) + + return quant_algo_config + + +def export_onnx_models( + model_name_or_path, + model_impl, + cache_dir, + output_dir, + use_gpu, + use_external_data_format, + optimize_onnx, + precision, + verbose, + use_forced_decoder_ids: bool = False, + merge_encoder_and_decoder_init: bool = True, + no_beam_search_op: bool = False, + use_decoder_masked_mha: bool = False, + output_qk: bool = False, + overwrite: bool = False, + use_int32_inputs: bool = True, + accuracy_level: int = 0, + quantize_symmetric: bool = False, + provider: str = "cpu", +): + device = torch.device("cuda" if use_gpu else "cpu") + if not use_gpu: + accuracy_level = 4 # change to 4 for CPU EP + use_fp16_inputs = precision == Precision.FLOAT16 or (precision in (Precision.INT8, Precision.INT4) and use_gpu) + + models = WhisperHelper.load_model( + model_name_or_path, + model_impl, + cache_dir, + device, + torch.float16 if use_fp16_inputs else torch.float32, + merge_encoder_and_decoder_init, + no_beam_search_op, + output_qk, + ) + config = models["decoder"].config + + if (not use_external_data_format) and (config.num_hidden_layers > 24): + logger.warning("You MUST pass `--use_external_data_format` because model size > 2GB") + raise Exception("Please pass `--use_external_data_format` for this model.") + + output_paths = [] + for name, model in models.items(): + print(f"========> Handling {name} model......") + filename_suffix = "_" + name + + onnx_path = WhisperHelper.get_onnx_path( + output_dir, + model_name_or_path, + suffix=filename_suffix, + new_folder=False, + ) + + # Export to ONNX + if overwrite or not os.path.exists(onnx_path): + logger.info(f"Exporting ONNX model to {onnx_path}") + WhisperHelper.export_onnx( + model, + onnx_path, + PROVIDERS[provider], + verbose, + use_external_data_format, + use_fp16_inputs=use_fp16_inputs, + use_int32_inputs=use_int32_inputs, + use_encoder_hidden_states=(name == "decoder_init"), + use_kv_cache_inputs=(name == "decoder"), + ) + else: + logger.info(f"Skip exporting: existing ONNX model {onnx_path}") + + # Optimize ONNX model + if optimize_onnx or precision != Precision.FLOAT32: + output_path = WhisperHelper.get_onnx_path( + output_dir, + model_name_or_path, + suffix=filename_suffix + "_" + str(precision), + new_folder=False, + ) + + if overwrite or not os.path.exists(output_path): + if optimize_onnx: + logger.info(f"Optimizing model to {output_path}") + WhisperHelper.optimize_onnx( + onnx_path, + output_path, + precision == Precision.FLOAT16, + model.config.encoder_attention_heads, + model.config.d_model, + model.config.decoder_layers, + use_external_data_format, + use_gpu=use_gpu, + provider=provider, + is_decoder=(name == "decoder"), + no_beam_search_op=no_beam_search_op, + use_decoder_masked_mha=use_decoder_masked_mha, + output_qk=output_qk, + ) + # Remove old ONNX model and old data file + if os.path.exists(onnx_path): + os.remove(onnx_path) + if os.path.exists(onnx_path + ".data"): + os.remove(onnx_path + ".data") + onnx_path = output_path + + if isinstance(model, WhisperEncoder): + model.verify_onnx( + onnx_path, + PROVIDERS[provider], + use_fp16_inputs=use_fp16_inputs, + ) + else: + model.verify_onnx( + onnx_path, + PROVIDERS[provider], + use_fp16_inputs=use_fp16_inputs, + use_int32_inputs=use_int32_inputs, + ) + + if precision in (Precision.INT8, Precision.INT4): + onnx_model = onnx.load(onnx_path, load_external_data=True) + matmul_nodes = [node.name for node in onnx_model.graph.node if node.op_type == "MatMul"] + quant_algo_config = make_quant_algo_config(precision, "k_quant", matmul_nodes) + + quant = MatMulNBitsQuantizer( + model=onnx_model, + block_size=32, + is_symmetric=quantize_symmetric, + accuracy_level=accuracy_level, + quant_format=QuantFormat.QOperator, + op_types_to_quantize=("MatMul",), + algo_config=quant_algo_config, + ) + quant.process() + if os.path.exists(output_path): + os.remove(output_path) + if os.path.exists(output_path + ".data"): + os.remove(output_path + ".data") + onnx.save_model( + quant.model.model, + output_path, + save_as_external_data=True, + all_tensors_to_one_file=True, + location=os.path.basename(output_path) + ".data", + size_threshold=0, + convert_attribute=False, + ) + else: + logger.info(f"Skip optimizing: existing ONNX model {onnx_path}") + else: + output_path = onnx_path + + output_paths.append(output_path) + + return output_paths + + +def main(argv=None): + warnings.warn( + "This example is deprecated. Use the Olive recipe instead: " + "https://github.com/microsoft/olive-recipes/tree/main", + DeprecationWarning, + stacklevel=2, + ) + args = parse_arguments(argv) + + setup_logger(args.verbose) + + logger.info(f"Arguments:{args}") + + cache_dir = args.cache_dir + output_dir = args.output if not args.output.endswith(".onnx") else os.path.dirname(args.output) + prepare_environment(cache_dir, output_dir, args.use_gpu) + + if args.precision == Precision.FLOAT16: + assert args.use_gpu, "fp16 requires --use_gpu" + + output_paths = export_onnx_models( + args.model_name_or_path, + args.model_impl, + cache_dir, + output_dir, + args.use_gpu, + args.use_external_data_format, + args.optimize_onnx, + args.precision, + args.verbose, + args.use_forced_decoder_ids, + not args.separate_encoder_and_decoder_init, + args.no_beam_search_op, + args.use_decoder_masked_mha, + args.output_cross_qk, + args.overwrite, + not args.use_int64_inputs, + args.accuracy_level, + args.quantize_symmetric, + args.provider, + ) + + max_diff = 0 + if not args.no_beam_search_op: + logger.info("Chaining model ... :") + args.beam_model_output_dir = WhisperHelper.get_onnx_path( + output_dir, + args.model_name_or_path, + suffix="_beamsearch", + new_folder=False, + ) + for path in output_paths: + if "encoder_decoder" in path or "encoder" in path: + args.encoder_path = path + elif "decoder" in path: + args.decoder_path = path + chain_model(args) + output_paths.append(args.beam_model_output_dir) + + # Check chained model + ort_session = create_onnxruntime_session( + args.beam_model_output_dir, + use_gpu=args.use_gpu, + provider=args.provider, + ) + device = torch.device("cuda" if args.use_gpu else "cpu") + + # Wrap parity check in try-except to allow export to continue in case this produces an error + try: + with torch.no_grad(): + # Verify batched decoding with prompts for OpenAI implementation + if args.model_impl == "openai" and args.use_forced_decoder_ids: + max_diff = WhisperHelper.verify_onnx( + args.model_name_or_path, cache_dir, ort_session, device, batch_size=2, prompt_mode=True + ) + else: + max_diff = WhisperHelper.verify_onnx(args.model_name_or_path, cache_dir, ort_session, device) + if max_diff > 1e-4: + logger.warning("PyTorch and ONNX Runtime results are NOT close") + else: + logger.info("PyTorch and ONNX Runtime results are close") + except Exception as e: + logger.warning( + f"An error occurred while trying to verify parity between PyTorch and ONNX Runtime: {e}", exc_info=True + ) + + # Remove extra ONNX models saved in output directory + for _file in os.listdir(output_dir): + if "_beamsearch" not in _file and "_jump_times" not in _file: + path = os.path.join(output_dir, _file) + os.remove(path) + if path in output_paths: + output_paths.remove(path) + + else: + # Create ancillary JSON files for ONNX Runtime GenAI and/or Hugging Face's Optimum + WhisperHelper.save_processing( + args.model_name_or_path, + args.provider, + args.separate_encoder_and_decoder_init, + args.use_decoder_masked_mha, + args.output_cross_qk, + next(iter(filter(lambda path: "encoder" in path, output_paths))), + next(iter(filter(lambda path: "decoder" in path, output_paths))), + output_dir, + cache_dir, + ) + + logger.info(f"Done! Outputs: {output_paths}") + return max_diff + + +if __name__ == "__main__": + main() diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/whisper/whisper_chain.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/whisper/whisper_chain.py new file mode 100644 index 0000000000000000000000000000000000000000..2ba6d47d36610b7eb4cb6286354816960d84adc2 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/whisper/whisper_chain.py @@ -0,0 +1,334 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +import logging +import os + +import onnx +from benchmark_helper import Precision +from convert_generation import ( + get_shared_initializers, + update_decoder_subgraph_output_cross_attention, + update_decoder_subgraph_share_buffer_and_use_decoder_masked_mha, +) +from onnx import TensorProto, helper +from transformers import WhisperConfig, WhisperTokenizer + +logger = logging.getLogger(__name__) + + +def verify_inputs(beam_inputs, graph_inputs): + # Verify that ONNX graph's inputs match beam search op's inputs + beam_required_inputs = list(filter(lambda beam_input: beam_input, beam_inputs)) + assert len(graph_inputs) == len(beam_required_inputs) + for graph_input, beam_input in zip(graph_inputs, beam_required_inputs, strict=False): + # Check if graph_input is in beam_input to handle beam_input names with the "_fp16" suffix + assert graph_input.name in beam_input + + +def clean_list(arr, remove_all_strings=True): + if remove_all_strings: + # Remove all empty strings in list + return list(filter(lambda elm: elm != "", arr)) + + # Remove empty strings at end of list + while len(arr) > 0: + if arr[-1] == "": + arr.pop() + else: + break + return arr + + +def chain_model(args): + # Load encoder/decoder and insert necessary (but unused) graph inputs expected by WhisperBeamSearch op + encoder_model = onnx.load_model(args.encoder_path, load_external_data=True) + encoder_model.graph.name = "encoderdecoderinit subgraph" + + decoder_model = onnx.load_model(args.decoder_path, load_external_data=True) + decoder_model.graph.name = "decoder subgraph" + + config = WhisperConfig.from_pretrained(args.model_name_or_path, cache_dir=args.cache_dir) + tokenizer = WhisperTokenizer.from_pretrained(args.model_name_or_path, cache_dir=args.cache_dir) + + use_fp16_inputs = args.precision == Precision.FLOAT16 or ( + args.precision in (Precision.INT8, Precision.INT4) and args.use_gpu + ) + # Create inputs/outputs for WhisperBeamSearch op + temperature_name = "temperature_fp16" if use_fp16_inputs else "temperature" + beam_inputs = [ + "input_features_fp16" if use_fp16_inputs else "input_features", + "max_length", + "min_length", + "num_beams", + "num_return_sequences", + "length_penalty_fp16" if use_fp16_inputs else "length_penalty", + "repetition_penalty_fp16" if use_fp16_inputs else "repetition_penalty", + "vocab_mask" if args.use_vocab_mask else "", + "prefix_vocab_mask" if args.use_prefix_vocab_mask else "", + "", # attention mask + "decoder_input_ids" if args.use_forced_decoder_ids else "", + "logits_processor" if args.use_logits_processor else "", + "cross_qk_layer_head" if args.collect_cross_qk else "", + "extra_decoding_ids" if args.extra_decoding_ids else "", + temperature_name if args.use_temperature else "", + ] + + sequence_scores_name = "sequence_scores_fp16" if use_fp16_inputs else "sequence_scores" + scores_name = "scores_fp16" if use_fp16_inputs else "scores" + beam_outputs = [ + "sequences", + sequence_scores_name if args.output_sequence_scores else "", + scores_name if args.output_scores else "", + "cross_qk" if args.collect_cross_qk else "", + "no_speech_probs_beam" if args.output_no_speech_probs else "", + ] + + graph_nodes = [] + if use_fp16_inputs: + input_features_cast_node = helper.make_node( + "Cast", + inputs=["input_features"], + outputs=["input_features_fp16"], + name="CastInputFeaturesToFp16", + to=TensorProto.FLOAT16, + ) + len_pen_cast_node = helper.make_node( + "Cast", + inputs=["length_penalty"], + outputs=["length_penalty_fp16"], + name="CastLengthPenaltyToFp16", + to=TensorProto.FLOAT16, + ) + rep_pen_cast_node = helper.make_node( + "Cast", + inputs=["repetition_penalty"], + outputs=["repetition_penalty_fp16"], + name="CastRepetitionPenaltyToFp16", + to=TensorProto.FLOAT16, + ) + graph_nodes.extend([input_features_cast_node, len_pen_cast_node, rep_pen_cast_node]) + + if args.use_temperature: + temp_cast_node = helper.make_node( + "Cast", + inputs=["temperature"], + outputs=["temperature_fp16"], + name="temperature_to_fp16", + to=TensorProto.FLOAT16, + ) + graph_nodes.append(temp_cast_node) + + if args.output_sequence_scores: + output_sequence_scores_cast_node = helper.make_node( + "Cast", + inputs=["sequence_scores_fp16"], + outputs=["sequence_scores"], + name="CastOutputSequenceScoresToFp32", + to=TensorProto.FLOAT, + ) + graph_nodes.append(output_sequence_scores_cast_node) + + if args.output_scores: + output_scores_cast_node = helper.make_node( + "Cast", + inputs=["scores_fp16"], + outputs=["scores"], + name="CastScoresToFp32", + to=TensorProto.FLOAT, + ) + graph_nodes.append(output_scores_cast_node) + + # Create WhisperBeamSearch op + beam_search_attrs = [ + helper.make_attribute("eos_token_id", config.eos_token_id), + helper.make_attribute("pad_token_id", config.pad_token_id), + helper.make_attribute( + "decoder_start_token_id", config.decoder_start_token_id + ), # same as tokenizer.convert_tokens_to_ids(['<|startoftranscript|>'])[0] + helper.make_attribute("translate_token_id", tokenizer.convert_tokens_to_ids(["<|translate|>"])[0]), + helper.make_attribute("transcribe_token_id", tokenizer.convert_tokens_to_ids(["<|transcribe|>"])[0]), + helper.make_attribute("start_of_lm_token_id", tokenizer.convert_tokens_to_ids(["<|startoflm|>"])[0]), + ( + helper.make_attribute("no_speech_token_id", tokenizer.convert_tokens_to_ids(["<|nospeech|>"])[0]) + if args.output_no_speech_probs + else "" + ), + helper.make_attribute("no_timestamps_token_id", tokenizer.convert_tokens_to_ids(["<|notimestamps|>"])[0]), + helper.make_attribute("beginning_timestamp_token_id", tokenizer.convert_tokens_to_ids(["<|0.00|>"])[0]), + helper.make_attribute("no_repeat_ngram_size", args.no_repeat_ngram_size), + helper.make_attribute("early_stopping", True), + helper.make_attribute("model_type", 2), + helper.make_attribute("decoder_output_cross_qk", 1) if args.collect_cross_qk else "", + ] + node = helper.make_node( + "WhisperBeamSearch", + inputs=clean_list(beam_inputs, remove_all_strings=False), + outputs=clean_list(beam_outputs, remove_all_strings=False), + name="BeamSearch", + domain="com.microsoft", + ) + node.attribute.extend(clean_list(beam_search_attrs, remove_all_strings=True)) + + # Graph inputs + input_features = helper.make_tensor_value_info( + "input_features", TensorProto.FLOAT, ["batch_size", "feature_size", "sequence_length"] + ) + max_length = helper.make_tensor_value_info("max_length", TensorProto.INT32, [1]) + min_length = helper.make_tensor_value_info("min_length", TensorProto.INT32, [1]) + num_beams = helper.make_tensor_value_info("num_beams", TensorProto.INT32, [1]) + num_return_sequences = helper.make_tensor_value_info("num_return_sequences", TensorProto.INT32, [1]) + length_penalty = helper.make_tensor_value_info("length_penalty", TensorProto.FLOAT, [1]) + repetition_penalty = helper.make_tensor_value_info("repetition_penalty", TensorProto.FLOAT, [1]) + vocab_mask = helper.make_tensor_value_info("vocab_mask", TensorProto.INT32, [config.vocab_size]) + prefix_vocab_mask = helper.make_tensor_value_info( + "prefix_vocab_mask", TensorProto.INT32, ["batch_size", config.vocab_size] + ) + decoder_input_ids = helper.make_tensor_value_info( + "decoder_input_ids", TensorProto.INT32, ["batch_size", "initial_sequence_length"] + ) + logits_processor = helper.make_tensor_value_info("logits_processor", TensorProto.INT32, [1]) + cross_qk_layer_head = helper.make_tensor_value_info("cross_qk_layer_head", TensorProto.INT32, ["num_layer_head", 2]) + extra_decoding_ids = helper.make_tensor_value_info( + "extra_decoding_ids", TensorProto.INT32, ["batch_size", "extra_decoding_ids_len"] + ) + temperature = helper.make_tensor_value_info("temperature", TensorProto.FLOAT, [1]) + + graph_inputs = clean_list( + [ + input_features, + max_length, + min_length, + num_beams, + num_return_sequences, + length_penalty, + repetition_penalty, + vocab_mask if args.use_vocab_mask else "", + prefix_vocab_mask if args.use_prefix_vocab_mask else "", + decoder_input_ids if args.use_forced_decoder_ids else "", + logits_processor if args.use_logits_processor else "", + cross_qk_layer_head if args.collect_cross_qk else "", + extra_decoding_ids if args.extra_decoding_ids else "", + temperature if args.use_temperature else "", + ] + ) + + # Graph outputs + sequences = helper.make_tensor_value_info( + "sequences", TensorProto.INT32, ["batch_size", "num_return_sequences", "max_length"] + ) + sequence_scores = helper.make_tensor_value_info("sequence_scores", TensorProto.FLOAT, ["batch_size"]) + scores = helper.make_tensor_value_info("scores", TensorProto.FLOAT, ["batch_size"]) + cross_qk = helper.make_tensor_value_info( + "cross_qk", + TensorProto.FLOAT, + ["batch_size", "num_return_sequences", "num_layer_head_cross_qk", "max_length", "frames"], + ) + no_speech_probs = helper.make_tensor_value_info("no_speech_probs", TensorProto.FLOAT, ["batch_size"]) + + graph_outputs = clean_list( + [ + sequences, + sequence_scores if args.output_sequence_scores else "", + scores if args.output_scores else "", + cross_qk if args.output_cross_qk or (not args.cross_qk_onnx_model and args.collect_cross_qk) else "", + no_speech_probs if args.output_no_speech_probs else "", + ] + ) + + # Replace MultiHeadAttention with DecoderMaskedMultiHeadAttention for CUDA EP inference + if hasattr(args, "use_gpu") and args.use_gpu: + if update_decoder_subgraph_share_buffer_and_use_decoder_masked_mha(decoder_model.graph): + logger.info("Updated whisper decoder subgraph to use DecoderMaskedMultiHeadAttention successfully!") + else: + logger.warning("DecoderMaskedMultiHeadAttention could not be applied to whisper decoder subgraph") + if hasattr(args, "collect_cross_qk") and args.collect_cross_qk: + update_decoder_subgraph_output_cross_attention(decoder_model.graph) + + # Initializers/opsets + # Delete shared data between decoder/encoder and move to larger graph initializers + initializers = get_shared_initializers(encoder_model, decoder_model) + node.attribute.extend( + [ + helper.make_attribute("decoder", decoder_model.graph), + helper.make_attribute("encoder", encoder_model.graph), + ] + ) + + opset_import = [helper.make_opsetid(domain="com.microsoft", version=1), helper.make_opsetid(domain="", version=17)] + + graph_nodes.append(node) + if args.output_no_speech_probs: + prob_cast_node = helper.make_node( + "Cast", + inputs=["no_speech_probs_beam"], + outputs=["no_speech_probs"], + name="no_speech_probs_cast_to_fp32", + to=TensorProto.FLOAT, + ) + graph_nodes.append(prob_cast_node) + + # Make graph with WhisperBeamSearch op + beam_graph = helper.make_graph( + graph_nodes, + name="WhisperBeamSearch Graph", + inputs=graph_inputs, + outputs=graph_outputs, + initializer=initializers, + ) + beam_graph_input_names = [gi.name for gi in graph_inputs] + beam_graph_output_names = [go.name for go in graph_outputs] + + if args.cross_qk_onnx_model: + post_qk_model = onnx.load_model(args.cross_qk_onnx_model, load_external_data=True) + post_qk_graph = post_qk_model.graph + beam_graph.initializer.extend(post_qk_graph.initializer) + beam_graph.node.extend(post_qk_graph.node) + # If tensor from cross_qk_onnx_model has same name as tensor in beamsearch graph, treat them as same tensor. + # User should notice this rule when provide cross_qk_onnx_model to append to the beamsearch node. + for pgi in post_qk_graph.input: + if ( + (pgi.name not in beam_graph_input_names) + and (pgi.name not in beam_graph_output_names) + and (pgi.name != "cross_qk") + ): + beam_graph.input.extend([pgi]) + beam_graph.output.extend(post_qk_graph.output) + + # Verify graph's inputs match beam search's inputs + verify_inputs(beam_inputs, graph_inputs) + + assert decoder_model.ir_version == encoder_model.ir_version + logger.info(f"Using IR version {decoder_model.ir_version} for chained model") + + # Set IR version of chained model to IR version of subgraphs in order to generate a working E2E model + beam_model = helper.make_model_gen_version( + beam_graph, + producer_name="onnxruntime.transformers", + opset_imports=opset_import, + ir_version=decoder_model.ir_version, + ) + + # Save WhisperBeamSearch graph and external data + if os.path.isfile(args.beam_model_output_dir): + logger.info(f"Overwriting {args.beam_model_output_dir} and {args.beam_model_output_dir + '.data'}") + if os.path.exists(args.beam_model_output_dir): + os.remove(args.beam_model_output_dir) + if os.path.exists(args.beam_model_output_dir + ".data"): + os.remove(args.beam_model_output_dir + ".data") + + onnx.save( + beam_model, + args.beam_model_output_dir, + save_as_external_data=args.use_external_data_format, + all_tensors_to_one_file=True, + convert_attribute=True, + location=f"{os.path.basename(args.beam_model_output_dir)}.data", + ) + try: + onnx.checker.check_model(args.beam_model_output_dir, full_check=True) + except Exception as e: + logger.error(f"An error occurred while running the ONNX checker: {e}", exc_info=True) # noqa: G201 diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/whisper/whisper_decoder.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/whisper/whisper_decoder.py new file mode 100644 index 0000000000000000000000000000000000000000..98f9f8e61139c3195826ebd852ec0c7868a5b19e --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/whisper/whisper_decoder.py @@ -0,0 +1,465 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +import logging +import os +import tempfile +from itertools import chain +from pathlib import Path + +import numpy as np +import onnx +import torch +from float16 import convert_float_to_float16 +from google.protobuf.internal.containers import RepeatedCompositeFieldContainer +from onnx import ModelProto, ValueInfoProto +from onnx_model import OnnxModel +from past_helper import PastKeyValuesHelper +from transformers import WhisperConfig +from whisper_inputs import ( + convert_inputs_for_ort, + get_model_dynamic_axes, + get_sample_decoder_inputs, + group_past_key_values, +) + +from onnxruntime import InferenceSession + +logger = logging.getLogger(__name__) + + +class WhisperDecoder(torch.nn.Module): + """A Whisper decoder with optional past key values""" + + def __init__(self, config: WhisperConfig, model: torch.nn.Module, model_impl: str, no_beam_search_op: bool = False): + super().__init__() + self.config = config + self.device = model.device + self.model_impl = model_impl + self.no_beam_search_op = no_beam_search_op + + self.decoder = None if model_impl == "openai" else model.model.decoder + self.proj_out = None if model_impl == "openai" else model.proj_out + self.model = model if model_impl == "openai" else None + + self.max_source_positions = self.config.max_source_positions + self.num_heads = self.config.decoder_attention_heads + self.head_size = self.config.d_model // self.num_heads + + def hf_forward( + self, + decoder_input_ids: torch.Tensor, + encoder_hidden_states: torch.Tensor | None = None, + past_key_values: list[tuple[torch.Tensor]] | None = None, + ): + outputs = self.decoder( + encoder_hidden_states=encoder_hidden_states, + input_ids=decoder_input_ids, + past_key_values=past_key_values, + use_cache=True, + ) + logits = self.proj_out(outputs.last_hidden_state) + present_key_values = outputs.past_key_values + + if past_key_values is None: + # Return present_self_* and present_cross_* for decoder-init + return logits, present_key_values + + # Before: (past_key_self_0, past_value_self_0, past_key_cross_0, past_value_cross_0), + # (past_key_self_1, past_value_self_1, past_key_cross_1, past_value_cross_1), + # After: (past_key_self_0, past_value_self_0, past_key_self_1, past_value_self_1), ..., + # (past_key_cross_0, past_value_cross_0, past_key_cross_1, past_value_cross_1), ... + present_self, present_cross = PastKeyValuesHelper.group_by_self_and_cross(present_key_values) + + # Return present_self_* for decoder-with-past since past_cross_* and present_cross_* are identical + return logits, present_self + + def oai_forward( + self, + decoder_input_ids: torch.Tensor, + encoder_hidden_states: torch.Tensor | None = None, + past_key_values: list[tuple[torch.Tensor]] | None = None, + ): + past_kv_cache = {} + if past_key_values is not None: + # Convert past KV caches (BxNxSxH --> BxSxNxH --> BxSxD) for OpenAI's forward pass + self_attn_kv_caches, cross_attn_kv_caches = group_past_key_values(past_key_values) + self_attn_kv_caches = [past_kv.transpose(1, 2) for past_kv in self_attn_kv_caches] + self_attn_kv_caches = [past_kv.reshape((*past_kv.shape[:2], -1)) for past_kv in self_attn_kv_caches] + cross_attn_kv_caches = [past_kv.transpose(1, 2) for past_kv in cross_attn_kv_caches] + cross_attn_kv_caches = [past_kv.reshape((*past_kv.shape[:2], -1)) for past_kv in cross_attn_kv_caches] + + for idx, block in enumerate(self.model.decoder.blocks): + past_kv_cache[block.attn.key] = self_attn_kv_caches[2 * idx] + past_kv_cache[block.attn.value] = self_attn_kv_caches[2 * idx + 1] + past_kv_cache[block.cross_attn.key] = cross_attn_kv_caches[2 * idx] + past_kv_cache[block.cross_attn.value] = cross_attn_kv_caches[2 * idx + 1] + + # Install OpenAI's hooks on the forward pass of each nn.Linear for key and value + # since the hooks will capture the output of the key and value MatMuls, which + # represent the current keys and values. + # + # For OpenAI's forward pass, the hook function will also perform the concat + # operation (past_kv + curr_kv --> pres_kv) if needed. However, the ONNX model + # will not contain this concat operation because the present KV caches aren't + # returned by OpenAI's forward pass. + kv_cache, hooks = self.model.install_kv_cache_hooks() + + # Run forward pass + # NOTE: There is a bug with openai-whisper==20240930 with the introduction of SDPA. + # In the Whisper codebase, the following line + # + # is_causal = mask is not None and n_ctx > 1 + # + # has been added where `mask` is a torch tensor. The right-hand side evaluates to `tensor(True/False)` + # but `is_causal` only accepts the boolean value. The fix is to apply `.item()` after the right-hand + # side has been evaluated. In other words, the line should be + # + # is_causal = (mask is not None and n_ctx > 1).item() + # + # instead. + logits = self.model.decoder(x=decoder_input_ids, xa=encoder_hidden_states, kv_cache=past_kv_cache) + + # Re-do concat operation on self attention KV caches for ONNX export (if past self attention KV caches exist) + if past_key_values is not None: + for block in self.model.decoder.blocks: + kv_cache[block.attn.key] = torch.cat( + [past_kv_cache[block.attn.key], kv_cache[block.attn.key]], dim=1 + ).detach() + kv_cache[block.attn.value] = torch.cat( + [past_kv_cache[block.attn.value], kv_cache[block.attn.value]], dim=1 + ).detach() + + present_self, present_cross = [], [] + for block in self.model.decoder.blocks: + # Group self and cross values + present_self.append(kv_cache[block.attn.key]) + present_self.append(kv_cache[block.attn.value]) + if past_key_values is None: + # Return present_self_* and present_cross_* for decoder-init + present_cross.append(kv_cache[block.cross_attn.key]) + present_cross.append(kv_cache[block.cross_attn.value]) + + # Convert present KV caches (BxSxD --> BxSxNxH --> BxNxSxH) after OpenAI's forward pass + present_self = [ + present_kv.reshape((*present_kv.shape[:2], -1, self.head_size)).transpose(1, 2) + for present_kv in present_self + ] + present_cross = [ + present_kv.reshape((*present_kv.shape[:2], -1, self.head_size)).transpose(1, 2) + for present_kv in present_cross + ] + + # Remove OpenAI's hooks since they can persist after this function completes + for hook in hooks: + hook.remove() + + if past_key_values is None: + # Return present_self_* and present_cross_* for decoder-init + present_key_values = PastKeyValuesHelper.group_by_layer( + present_self + present_cross, len(present_self) // 2 + ) + return logits, present_key_values + + # Return present_self_* for decoder-with-past since past_cross_* and present_cross_* are identical + return logits, present_self + + def forward( + self, + decoder_input_ids: torch.Tensor, + encoder_hidden_states: torch.Tensor | None = None, + past_key_values: list[tuple[torch.Tensor]] | None = None, + ): + if self.model_impl == "openai": + return self.oai_forward(decoder_input_ids, encoder_hidden_states, past_key_values) + return self.hf_forward(decoder_input_ids, encoder_hidden_states, past_key_values) + + def input_names(self): + if self.first_pass: + input_names = ["input_ids", "encoder_hidden_states"] + else: + input_names = [ + "input_ids", + "encoder_hidden_states", + *list( + chain.from_iterable( + (f"past_key_self_{i}", f"past_value_self_{i}", f"past_key_cross_{i}", f"past_value_cross_{i}") + for i in range(self.config.decoder_layers) + ) + ), + ] + return input_names + + def output_names(self): + if self.first_pass: + output_names = [ + "logits", + *list( + chain.from_iterable( + ( + f"present_key_self_{i}", + f"present_value_self_{i}", + f"present_key_cross_{i}", + f"present_value_cross_{i}", + ) + for i in range(self.config.decoder_layers) + ) + ), + ] + else: + output_names = [ + "logits", + *list( + chain.from_iterable( + (f"present_key_self_{i}", f"present_value_self_{i}") for i in range(self.config.decoder_layers) + ) + ), + ] + return output_names + + def dynamic_axes(self, input_names, output_names): + dynamic_axes = get_model_dynamic_axes(self.config, input_names, output_names) + if "input_ids" in dynamic_axes and not self.no_beam_search_op: + # Set dynamic axes for `input_ids` when using beam search op to {0: "batch_size"} only + del dynamic_axes["input_ids"][1] + return dynamic_axes + + def inputs(self, use_fp16_inputs: bool, use_int32_inputs: bool, return_dict: bool = False): + inputs = get_sample_decoder_inputs( + self.config, + self.device, + batch_size=2, + past_sequence_length=(0 if self.first_pass else 6), + sequence_length=(6 if self.first_pass else 1), + use_fp16=use_fp16_inputs, + use_int32=use_int32_inputs, + ) + if return_dict: + if self.first_pass: + del inputs["past_key_values"] + return inputs + + if self.first_pass: + return ( + inputs["decoder_input_ids"], + inputs["encoder_hidden_states"], + ) + return ( + inputs["decoder_input_ids"], + inputs["encoder_hidden_states"], + inputs["past_key_values"], + ) + + def fix_key_value_cache_dims(self, io: ValueInfoProto, is_cross: bool = False, is_output: bool = False): + # Shape should be (batch_size, num_heads, sequence_length, head_size) for self attention KV caches + # and (batch_size, num_heads, num_frames // 2, head_size) for cross attention KV caches + num_heads = io.type.tensor_type.shape.dim[1] + if "_dim_" in num_heads.dim_param: + num_heads.Clear() + num_heads.dim_value = self.num_heads + sequence_length = io.type.tensor_type.shape.dim[2] + if "_dim_" in sequence_length.dim_param: + sequence_length.Clear() + if is_cross: + sequence_length.dim_value = self.max_source_positions + else: + sequence_length.dim_param = "total_sequence_length" if is_output else "past_sequence_length" + head_size = io.type.tensor_type.shape.dim[3] + if "_dim_" in head_size.dim_param: + head_size.Clear() + head_size.dim_value = self.head_size + return io + + def fix_io(self, io_list: RepeatedCompositeFieldContainer, is_output: bool = False): + # Fix order of inputs/outputs and each dim_value of input/output + reordered_io = [] + self_attn_kv_caches = [] + cross_attn_kv_caches = [] + + for io in io_list: + if "past" not in io.name and "present" not in io.name: + reordered_io.append(io) + elif "self" in io.name: + # Self attention KV caches + new_io = self.fix_key_value_cache_dims(io, is_cross=False, is_output=is_output) + if self.no_beam_search_op: + reordered_io.append(new_io) + else: + self_attn_kv_caches.append(new_io) + else: + # Cross attention KV caches + new_io = self.fix_key_value_cache_dims(io, is_cross=True, is_output=is_output) + if self.no_beam_search_op: + reordered_io.append(new_io) + else: + cross_attn_kv_caches.append(new_io) + + if not self.no_beam_search_op: + reordered_io += self_attn_kv_caches + cross_attn_kv_caches + return reordered_io + + def fix_inputs_and_outputs(self, model: ModelProto): + # ONNX exporter might mark dimensions like 'Transposepresent_value_self_1_dim_2' in shape inference. + # We now change the dim_values to the correct one. + reordered_inputs = self.fix_io(model.graph.input, is_output=False) + while len(model.graph.input) > 0: + model.graph.input.pop() + model.graph.input.extend(reordered_inputs) + + reordered_outputs = self.fix_io(model.graph.output, is_output=True) + while len(model.graph.output) > 0: + model.graph.output.pop() + model.graph.output.extend(reordered_outputs) + return model + + def fix_layernorm_weights(self, model: ModelProto, use_fp16_inputs: bool): + if self.model_impl == "openai" and use_fp16_inputs: + # Cast ONNX model to float16 to ensure LayerNorm weights are converted from + # float32 to float16 since exported model already has float16 weights everywhere + # except for LayerNorm ops. This happens because OpenAI always upcasts to float32 + # when computing LayerNorm. + # + # Reference: + # https://github.com/openai/whisper/blob/90db0de1896c23cbfaf0c58bc2d30665f709f170/whisper/model.py#L41 + model = convert_float_to_float16(model) + return model + + def export_onnx( + self, + onnx_model_path: str, + provider: str, + verbose: bool = True, + use_external_data_format: bool = False, + use_fp16_inputs: bool = False, + use_int32_inputs: bool = True, + use_encoder_hidden_states: bool = False, + use_kv_cache_inputs: bool = True, + ): + """Export decoder to ONNX + + Args: + onnx_model_path (str): path to save ONNX model + provider (str): provider to use for verifying parity on ONNX model + verbose (bool, optional): print verbose information. Defaults to True. + use_external_data_format (bool, optional): use external data format or not. Defaults to False. + use_fp16_inputs (bool, optional): use float16 inputs for the KV caches. Defaults to False. + use_int32_inputs (bool, optional): use int32 inputs for the decoder_input_ids. Defaults to True. + use_encoder_hidden_states (bool, optional): use encoder_hidden_states as model input for decoder-init/decoder-without-past models. Defaults to False. + use_kv_cache_inputs (bool, optional): use KV caches as model inputs for decoder-with-past models. Defaults to True. + """ + # Shape of decoder's tensors: + # Required Inputs: + # decoder_input_ids: (batch_size, sequence_length) + # Optional Inputs: + # encoder_hidden_states (comes from encoder's outputs): (batch_size, num_frames // 2, hidden_size) + # past_{key/value}_self_* (past self attention KV caches): (batch_size, num_heads, past_sequence_length, head_size) + # past_{key/value}_cross_* (past cross attention KV caches): (batch_size, num_heads, num_frames // 2, head_size) + # Outputs: + # logits: (batch_size, sequence_length, vocab_size) + # present_{key/value}_self_* (present self attention KV caches): (batch_size, num_heads, past_sequence_length + sequence_length, head_size) + # present_{key/value}_cross_* (present cross attention KV caches): (batch_size, num_heads, num_frames // 2, head_size) + + # For the first pass through the decoder (i.e. decoder-init/decoder-without-past) + self.first_pass = use_encoder_hidden_states and not use_kv_cache_inputs + + # For subsequent passes through the decoder (i.e. decoder-with-past) + self.later_pass = not use_encoder_hidden_states and use_kv_cache_inputs + + assert self.first_pass or self.later_pass, ( + "Only one of `use_encoder_hidden_states` and `use_kv_cache_inputs` can be true at once." + ) + + inputs = self.inputs(use_fp16_inputs=use_fp16_inputs, use_int32_inputs=use_int32_inputs) + input_names = self.input_names() + output_names = self.output_names() + dynamic_axes = self.dynamic_axes(input_names, output_names) + + Path(onnx_model_path).parent.mkdir(parents=True, exist_ok=True) + with tempfile.TemporaryDirectory() as tmp_dir_name: + temp_onnx_model_path = os.path.join(tmp_dir_name, "decoder.onnx") + Path(temp_onnx_model_path).parent.mkdir(parents=True, exist_ok=True) + out_path = temp_onnx_model_path if use_external_data_format else onnx_model_path + + torch.onnx.export( + self, + args=inputs, + f=out_path, + export_params=True, + input_names=input_names, + output_names=output_names, + dynamic_axes=dynamic_axes, + opset_version=18, + do_constant_folding=True, + dynamo=False, + verbose=verbose, + ) + + model = onnx.load_model(out_path, load_external_data=use_external_data_format) + model = self.fix_inputs_and_outputs(model) + model = self.fix_layernorm_weights(model, use_fp16_inputs) + OnnxModel.save( + model, + onnx_model_path, + save_as_external_data=use_external_data_format, + all_tensors_to_one_file=True, + ) + + self.verify_onnx(onnx_model_path, provider, use_fp16_inputs, use_int32_inputs) + + def verify_onnx( + self, + onnx_model_path: str, + provider: str, + use_fp16_inputs: bool, + use_int32_inputs: bool, + ): + """Verify ONNX model outputs and PyTorch model outputs match + + Args: + onnx_model_path (str): path to save ONNX model + provider (str): execution provider for ONNX model + use_fp16_inputs (bool, optional): use float16 inputs for the KV caches + use_int32_inputs (bool, optional): use int32 inputs for the decoder_input_ids + """ + # Shape of decoder's tensors: + # Required Inputs: + # decoder_input_ids: (batch_size, sequence_length) + # Optional Inputs: + # encoder_hidden_states (comes from encoder's outputs): (batch_size, num_frames // 2, hidden_size) + # past_{key/value}_self_* (past self attention KV caches): (batch_size, num_heads, past_sequence_length, head_size) + # past_{key/value}_cross_* (past cross attention KV caches): (batch_size, num_heads, num_frames // 2, head_size) + # Outputs: + # logits: (batch_size, sequence_length, vocab_size) + # present_{key/value}_self_* (present self attention KV caches): (batch_size, num_heads, past_sequence_length + sequence_length, head_size) + # present_{key/value}_cross_* (present cross attention KV caches): (batch_size, num_heads, num_frames // 2, head_size) + + # Run PyTorch model + inputs = self.inputs(use_fp16_inputs=use_fp16_inputs, use_int32_inputs=use_int32_inputs, return_dict=True) + pt_outputs = [] + if self.first_pass: + out = self.forward(**inputs) + pt_outputs.append(out[0].detach().cpu().numpy()) + for present_key_value_layer in out[1]: + for present_key_value in present_key_value_layer: + pt_outputs.append(present_key_value.detach().cpu().numpy()) + else: + out = self.forward(**inputs) + pt_outputs.append(out[0].detach().cpu().numpy()) + for present_self_key_value in out[1]: + pt_outputs.append(present_self_key_value.detach().cpu().numpy()) + + # Run ONNX model + sess = InferenceSession(onnx_model_path, providers=[provider]) + ort_outputs = sess.run(None, convert_inputs_for_ort(inputs, sess)) + + # Calculate output difference + try: + for i, output_name in enumerate(self.output_names()): + diff = np.abs(pt_outputs[i] - ort_outputs[i]) + logger.warning(f"Comparing {output_name}...") + logger.warning(f"Max diff: {np.max(diff)}") + except: # noqa: E722 + pass diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/whisper/whisper_encoder.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/whisper/whisper_encoder.py new file mode 100644 index 0000000000000000000000000000000000000000..e234715467e79de73b40a16593cbfb6840008df1 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/whisper/whisper_encoder.py @@ -0,0 +1,165 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +import logging +import os +import tempfile +from pathlib import Path + +import numpy as np +import onnx +import torch +from float16 import convert_float_to_float16 +from onnx import ModelProto +from onnx_model import OnnxModel +from transformers import WhisperConfig +from whisper_inputs import get_model_dynamic_axes, get_sample_encoder_inputs + +from onnxruntime import InferenceSession + +logger = logging.getLogger(__name__) + + +class WhisperEncoder(torch.nn.Module): + """Whisper encoder component""" + + def __init__(self, config: WhisperConfig, model: torch.nn.Module, model_impl: str): + super().__init__() + self.config = config + self.device = model.device + self.model_impl = model_impl + + self.encoder = model.encoder if model_impl == "openai" else model.model.encoder + + def forward(self, audio_features: torch.Tensor): + outputs = self.encoder(audio_features) + return outputs if self.model_impl == "openai" else outputs.last_hidden_state + + def input_names(self): + input_names = ["audio_features"] + return input_names + + def output_names(self): + output_names = ["encoder_hidden_states"] + return output_names + + def dynamic_axes(self, input_names, output_names): + dynamic_axes = get_model_dynamic_axes(self.config, input_names, output_names) + return dynamic_axes + + def fix_layernorm_weights(self, model: ModelProto, use_fp16_inputs: bool): + if self.model_impl == "openai" and use_fp16_inputs: + # Cast ONNX model to float16 to ensure LayerNorm weights are converted from + # float32 to float16 since exported model already has float16 weights everywhere + # except for LayerNorm ops. This happens because OpenAI always upcasts to float32 + # when computing LayerNorm. + # + # Reference: + # https://github.com/openai/whisper/blob/90db0de1896c23cbfaf0c58bc2d30665f709f170/whisper/model.py#L41 + model = convert_float_to_float16(model) + return model + + def export_onnx( + self, + onnx_model_path: str, + provider: str, + verbose: bool = True, + use_external_data_format: bool = False, + use_fp16_inputs: bool = False, + ): + """Export encoder to ONNX + + Args: + onnx_model_path (str): path to save ONNX model + provider (str): provider to use for verifying parity on ONNX model + verbose (bool, optional): print verbose information. Defaults to True. + use_external_data_format (bool, optional): use external data format or not. Defaults to False. + use_fp16_inputs (bool, optional): use float16 inputs for the audio_features. Defaults to False. + """ + # Shape of encoder's tensors: + # Inputs: + # audio_features: (batch_size, num_mels, num_frames) + # Outputs: + # encoder_hidden_states: (batch_size, num_frames // 2, hidden_size) + + inputs = get_sample_encoder_inputs( + self.config, + self.device, + batch_size=2, + use_fp16=use_fp16_inputs, + ) + + input_names = self.input_names() + output_names = self.output_names() + dynamic_axes = self.dynamic_axes(input_names, output_names) + + Path(onnx_model_path).parent.mkdir(parents=True, exist_ok=True) + with tempfile.TemporaryDirectory() as tmp_dir_name: + temp_onnx_model_path = os.path.join(tmp_dir_name, "encoder.onnx") + Path(temp_onnx_model_path).parent.mkdir(parents=True, exist_ok=True) + out_path = temp_onnx_model_path if use_external_data_format else onnx_model_path + + torch.onnx.export( + self, + args=(inputs["audio_features"]), + f=out_path, + export_params=True, + input_names=input_names, + output_names=output_names, + dynamic_axes=dynamic_axes, + opset_version=18, + do_constant_folding=True, + dynamo=False, + verbose=verbose, + ) + + model = onnx.load_model(out_path, load_external_data=use_external_data_format) + model = self.fix_layernorm_weights(model, use_fp16_inputs) + OnnxModel.save( + model, + onnx_model_path, + save_as_external_data=use_external_data_format, + all_tensors_to_one_file=True, + ) + + self.verify_onnx(onnx_model_path, provider, use_fp16_inputs) + + def verify_onnx( + self, + onnx_model_path: str, + provider: str, + use_fp16_inputs: bool, + ): + """Verify ONNX model outputs and PyTorch model outputs match + + Args: + onnx_model_path (str): path to save ONNX model + provider (str): execution provider for ONNX model + use_fp16_inputs (bool, optional): use float16 inputs for the audio_features + """ + # Shape of encoder's tensors: + # Inputs: + # audio_features: (batch_size, num_mels, num_frames) + # Outputs: + # encoder_hidden_states: (batch_size, num_frames // 2, hidden_size) + inputs = get_sample_encoder_inputs( + self.config, + self.device, + batch_size=2, + use_fp16=use_fp16_inputs, + ) + + # Run PyTorch model + pt_outputs = self.forward(inputs["audio_features"]).detach().cpu().numpy() + + # Run ONNX model + sess = InferenceSession(onnx_model_path, providers=[provider]) + ort_outputs = sess.run(None, {"audio_features": inputs["audio_features"].detach().cpu().numpy()})[0] + + # Calculate output difference + diff = np.abs(pt_outputs - ort_outputs) + logger.warning("Comparing encoder_hidden_states...") + logger.warning(f"Max diff: {np.max(diff)}") diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/whisper/whisper_encoder_decoder_init.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/whisper/whisper_encoder_decoder_init.py new file mode 100644 index 0000000000000000000000000000000000000000..3dbaa1f7c4c4a543a9a951a1571b8ae0d62b1ce9 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/whisper/whisper_encoder_decoder_init.py @@ -0,0 +1,372 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +import logging +import os +import tempfile +from itertools import chain +from pathlib import Path + +import numpy as np +import onnx +import torch +from float16 import convert_float_to_float16 +from onnx import ModelProto, ValueInfoProto +from onnx_model import OnnxModel +from transformers import WhisperConfig +from whisper_decoder import WhisperDecoder +from whisper_encoder import WhisperEncoder +from whisper_inputs import ( + convert_inputs_for_ort, + get_model_dynamic_axes, + get_sample_encoder_decoder_init_inputs, + group_past_key_values, +) + +from onnxruntime import InferenceSession + +logger = logging.getLogger(__name__) + + +class WhisperEncoderDecoderInit(torch.nn.Module): + """Whisper encoder component + first pass through Whisper decoder component to initialize KV caches""" + + def __init__(self, config: WhisperConfig, model: torch.nn.Module, model_impl: str, no_beam_search_op: bool = False): + super().__init__() + self.config = config + self.device = model.device + self.model_impl = model_impl + self.no_beam_search_op = no_beam_search_op + + self.encoder = WhisperEncoder(config, model, model_impl) + self.decoder = WhisperDecoder(config, model, model_impl, no_beam_search_op) + + self.max_source_positions = self.config.max_source_positions + self.num_heads = self.config.decoder_attention_heads + self.head_size = self.config.d_model // self.num_heads + + def hf_forward_for_beam_search_op(self, audio_features: torch.Tensor, decoder_input_ids: torch.Tensor): + encoder_hidden_states = self.encoder(audio_features) + logits, present_key_values = self.decoder(decoder_input_ids, encoder_hidden_states) + return logits, encoder_hidden_states, present_key_values + + def hf_forward_for_no_beam_search_op(self, audio_features: torch.Tensor): + encoder_hidden_states = self.encoder(audio_features) + + # Get cross attention KV caches and return them for this model + # We do this because these MatMuls are only run once before their outputs are being re-used in the decoder + present_cross_attention_key_value_caches = [] + for layer in self.decoder.decoder.layers: + cross_attn_key_cache = ( + layer.encoder_attn.k_proj(encoder_hidden_states) + .view(-1, self.max_source_positions, self.num_heads, self.head_size) + .transpose(1, 2) + ) + cross_attn_value_cache = ( + layer.encoder_attn.v_proj(encoder_hidden_states) + .view(-1, self.max_source_positions, self.num_heads, self.head_size) + .transpose(1, 2) + ) + present_cross_attention_key_value_caches.append(cross_attn_key_cache) + present_cross_attention_key_value_caches.append(cross_attn_value_cache) + + return encoder_hidden_states, present_cross_attention_key_value_caches + + def oai_forward_for_beam_search_op(self, audio_features: torch.Tensor, decoder_input_ids: torch.Tensor): + encoder_hidden_states = self.encoder(audio_features) + logits, present_key_values = self.decoder(decoder_input_ids, encoder_hidden_states) + return logits, encoder_hidden_states, present_key_values + + def oai_forward_for_no_beam_search_op(self, audio_features: torch.Tensor): + encoder_hidden_states = self.encoder(audio_features) + + # Get cross attention KV caches and return them for this model + # We do this because these MatMuls are only run once before their outputs are being re-used in the decoder + present_cross_attention_key_value_caches = [] + for block in self.decoder.model.decoder.blocks: + cross_attn_key_cache = ( + block.cross_attn.key(encoder_hidden_states) + .view(-1, self.max_source_positions, self.num_heads, self.head_size) + .transpose(1, 2) + ) + cross_attn_value_cache = ( + block.cross_attn.value(encoder_hidden_states) + .view(-1, self.max_source_positions, self.num_heads, self.head_size) + .transpose(1, 2) + ) + present_cross_attention_key_value_caches.append(cross_attn_key_cache) + present_cross_attention_key_value_caches.append(cross_attn_value_cache) + + return encoder_hidden_states, present_cross_attention_key_value_caches + + def forward(self, audio_features: torch.Tensor, decoder_input_ids: torch.Tensor | None = None): + if self.model_impl == "openai": + if self.no_beam_search_op: + return self.oai_forward_for_no_beam_search_op(audio_features) + return self.oai_forward_for_beam_search_op(audio_features, decoder_input_ids) + + # Hugging Face implementation + if self.no_beam_search_op: + return self.hf_forward_for_no_beam_search_op(audio_features) + return self.hf_forward_for_beam_search_op(audio_features, decoder_input_ids) + + def input_names(self): + if self.no_beam_search_op: + input_names = ["audio_features"] + else: + input_names = ["encoder_input_ids", "decoder_input_ids"] + return input_names + + def output_names(self): + if self.no_beam_search_op: + output_names = [ + "encoder_hidden_states", + *list( + chain.from_iterable( + (f"present_key_cross_{i}", f"present_value_cross_{i}") + for i in range(self.config.decoder_layers) + ) + ), + ] + else: + output_names = [ + "logits", + "encoder_hidden_states", + *list( + chain.from_iterable( + ( + f"present_key_self_{i}", + f"present_value_self_{i}", + f"present_key_cross_{i}", + f"present_value_cross_{i}", + ) + for i in range(self.config.decoder_layers) + ) + ), + ] + return output_names + + def dynamic_axes(self, input_names, output_names): + dynamic_axes = get_model_dynamic_axes(self.config, input_names, output_names) + return dynamic_axes + + def inputs(self, use_fp16_inputs: bool, use_int32_inputs: bool, return_dict: bool = False): + inputs = get_sample_encoder_decoder_init_inputs( + self.config, + self.device, + batch_size=2, + decoder_sequence_length=6, + use_fp16=use_fp16_inputs, + use_int32=use_int32_inputs, + ) + if return_dict: + if self.no_beam_search_op: + del inputs["decoder_input_ids"] + return inputs + + if self.no_beam_search_op: + return (inputs["audio_features"],) + return ( + inputs["audio_features"], + inputs["decoder_input_ids"], + ) + + def fix_key_value_cache_dims(self, output: ValueInfoProto, is_cross: bool = False): + # Shape should be (batch_size, num_heads, sequence_length, head_size) for self attention KV caches + # and (batch_size, num_heads, num_frames // 2, head_size) for cross attention KV caches + num_heads = output.type.tensor_type.shape.dim[1] + if "_dim_" in num_heads.dim_param: + num_heads.Clear() + num_heads.dim_value = self.num_heads + sequence_length = output.type.tensor_type.shape.dim[2] + if "_dim_" in sequence_length.dim_param: + sequence_length.Clear() + if is_cross: + sequence_length.dim_value = self.max_source_positions + else: + sequence_length.dim_param = "total_sequence_length" + head_size = output.type.tensor_type.shape.dim[3] + if "_dim_" in head_size.dim_param: + head_size.Clear() + head_size.dim_value = self.head_size + return output + + def fix_outputs(self, model: ModelProto): + # ONNX exporter might mark dimensions like 'Transposepresent_value_self_1_dim_2' in shape inference. + # We now change the dim_values to the correct one. + reordered_outputs = [] + self_attn_kv_caches = [] + cross_attn_kv_caches = [] + + for output in model.graph.output: + if "present" not in output.name: + reordered_outputs.append(output) + + elif "self" in output.name: + # Self attention KV caches + new_output = self.fix_key_value_cache_dims(output, is_cross=False) + if self.no_beam_search_op: + reordered_outputs.append(new_output) + else: + self_attn_kv_caches.append(new_output) + else: + # Cross attention KV caches + new_output = self.fix_key_value_cache_dims(output, is_cross=True) + if self.no_beam_search_op: + reordered_outputs.append(new_output) + else: + cross_attn_kv_caches.append(new_output) + + if not self.no_beam_search_op: + reordered_outputs += self_attn_kv_caches + cross_attn_kv_caches + + while len(model.graph.output) > 0: + model.graph.output.pop() + model.graph.output.extend(reordered_outputs) + return model + + def fix_layernorm_weights(self, model: ModelProto, use_fp16_inputs: bool): + if self.model_impl == "openai" and use_fp16_inputs: + # Cast ONNX model to float16 to ensure LayerNorm weights are converted from + # float32 to float16 since exported model already has float16 weights everywhere + # except for LayerNorm ops. This happens because OpenAI always upcasts to float32 + # when computing LayerNorm. + # + # Reference: + # https://github.com/openai/whisper/blob/90db0de1896c23cbfaf0c58bc2d30665f709f170/whisper/model.py#L41 + model = convert_float_to_float16(model) + return model + + def export_onnx( + self, + onnx_model_path: str, + provider: str, + verbose: bool = True, + use_external_data_format: bool = False, + use_fp16_inputs: bool = False, + use_int32_inputs: bool = True, + ): + """Export encoder-decoder-init to ONNX + + Args: + onnx_model_path (str): path to save ONNX model + provider (str): provider to use for verifying parity on ONNX model + verbose (bool, optional): print verbose information. Defaults to True. + use_external_data_format (bool, optional): use external data format or not. Defaults to False. + use_fp16_inputs (bool, optional): use float16 inputs for the audio_features. Defaults to False. + use_int32_inputs (bool, optional): use int32 inputs for the decoder_input_ids. Defaults to True. + """ + # Shape of encoder's tensors: + # Inputs: + # audio_features: (batch_size, num_mels, num_frames) + # Outputs: + # encoder_hidden_states: (batch_size, num_frames // 2, hidden_size) + + # Shape of decoder's tensors: + # Inputs: + # decoder_input_ids: (batch_size, sequence_length) + # encoder_hidden_states (comes from encoder's outputs): (batch_size, num_frames // 2, hidden_size) + # Outputs: + # logits: (batch_size, sequence_length, vocab_size) + # present_{key/value}_self_* (present self attention KV caches): (batch_size, num_heads, past_sequence_length + sequence_length, head_size) + # present_{key/value}_cross_* (present cross attention KV caches): (batch_size, num_heads, num_frames // 2, head_size) + + inputs = self.inputs(use_fp16_inputs=use_fp16_inputs, use_int32_inputs=use_int32_inputs) + input_names = self.input_names() + output_names = self.output_names() + dynamic_axes = self.dynamic_axes(input_names, output_names) + + Path(onnx_model_path).parent.mkdir(parents=True, exist_ok=True) + with tempfile.TemporaryDirectory() as tmp_dir_name: + temp_onnx_model_path = os.path.join(tmp_dir_name, "encoder_decoder_init.onnx") + Path(temp_onnx_model_path).parent.mkdir(parents=True, exist_ok=True) + out_path = temp_onnx_model_path if use_external_data_format else onnx_model_path + + torch.onnx.export( + self, + args=inputs, + f=out_path, + export_params=True, + input_names=input_names, + output_names=output_names, + dynamic_axes=dynamic_axes, + opset_version=18, + do_constant_folding=True, + dynamo=False, + verbose=verbose, + ) + + model = onnx.load_model(out_path, load_external_data=use_external_data_format) + model = self.fix_outputs(model) + model = self.fix_layernorm_weights(model, use_fp16_inputs) + OnnxModel.save( + model, + onnx_model_path, + save_as_external_data=use_external_data_format, + all_tensors_to_one_file=True, + ) + + self.verify_onnx(onnx_model_path, provider, use_fp16_inputs, use_int32_inputs) + + def verify_onnx( + self, + onnx_model_path: str, + provider: str, + use_fp16_inputs: bool, + use_int32_inputs: bool, + ): + """Verify ONNX model outputs and PyTorch model outputs match + + Args: + onnx_model_path (str): path to save ONNX model + provider (str): execution provider for ONNX model + use_fp16_inputs (bool, optional): use float16 inputs for the audio_features + use_int32_inputs (bool, optional): use int32 inputs for the decoder_input_ids + """ + # Shape of encoder's tensors: + # Inputs: + # audio_features: (batch_size, num_mels, num_frames) + # Outputs: + # encoder_hidden_states: (batch_size, num_frames // 2, hidden_size) + + # Shape of decoder's tensors: + # Inputs: + # decoder_input_ids: (batch_size, sequence_length) + # encoder_hidden_states (comes from encoder's outputs): (batch_size, num_frames // 2, hidden_size) + # Outputs: + # logits: (batch_size, sequence_length, vocab_size) + # present_{key/value}_self_* (present self attention KV caches): (batch_size, num_heads, past_sequence_length + sequence_length, head_size) + # present_{key/value}_cross_* (present cross attention KV caches): (batch_size, num_heads, num_frames // 2, head_size) + + inputs = self.inputs(use_fp16_inputs=use_fp16_inputs, use_int32_inputs=use_int32_inputs, return_dict=True) + + # Run PyTorch model + pt_outputs = [] + if self.no_beam_search_op: + out = self.forward(**inputs) + pt_outputs.append(out[0].detach().cpu().numpy()) + for present_cross_attn_cache in out[1]: + pt_outputs.append(present_cross_attn_cache.detach().cpu().numpy()) + else: + out = self.forward(**inputs) + pt_outputs.append(out[0].detach().cpu().numpy()) + pt_outputs.append(out[1].detach().cpu().numpy()) + + (self_attn_kv_caches, cross_attn_kv_caches) = group_past_key_values(out[2]) + pt_outputs.extend([self_attn_kv_cache.detach().cpu().numpy() for self_attn_kv_cache in self_attn_kv_caches]) + pt_outputs.extend( + [cross_attn_kv_cache.detach().cpu().numpy() for cross_attn_kv_cache in cross_attn_kv_caches] + ) + + # Run ONNX model + sess = InferenceSession(onnx_model_path, providers=[provider]) + ort_outputs = sess.run(None, convert_inputs_for_ort(inputs, sess)) + + # Calculate output difference + for i, output_name in enumerate(self.output_names()): + diff = np.abs(pt_outputs[i] - ort_outputs[i]) + logger.warning(f"Comparing {output_name}...") + logger.warning(f"Max diff: {np.max(diff)}") diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/whisper/whisper_helper.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/whisper/whisper_helper.py new file mode 100644 index 0000000000000000000000000000000000000000..883e9508e4f345bf519a44da89e7e02ed523b920 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/whisper/whisper_helper.py @@ -0,0 +1,1035 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- +import json +import logging +import os +from pathlib import Path + +import numpy as np +import torch +from convert_generation import add_cache_indirection_to_mha, add_output_qk_to_mha, fix_past_sequence_length +from optimizer import optimize_model +from transformers import AutoTokenizer, WhisperConfig, WhisperForConditionalGeneration, WhisperProcessor +from whisper_decoder import WhisperDecoder +from whisper_encoder import WhisperEncoder +from whisper_encoder_decoder_init import WhisperEncoderDecoderInit +from whisper_jump_times import WhisperJumpTimes + +from onnxruntime import InferenceSession + +logger = logging.getLogger(__name__) + +PRETRAINED_WHISPER_MODELS = [ + "whisper-tiny", + "whisper-tiny.en", + "whisper-base", + "whisper-base.en", + "whisper-small", + "whisper-small.en", + "whisper-medium", + "whisper-medium.en", + "whisper-large", + "whisper-large-v2", + "whisper-large-v3", + "whisper-large-v3-turbo", +] + + +class WhisperHelper: + @staticmethod + def get_onnx_path( + output_dir: str, + model_name_or_path: str, + suffix: str = "", + new_folder: bool = False, + ) -> str: + """Build onnx path + + Args: + output_dir (str): output directory + model_name_or_path (str): pretrained model name, or path to the model checkpoint + suffix (str, optional): suffix like "_encoder" or "_decoder_fp16" will be appended to file name. Defaults to None. + new_folder (bool, optional): create a new directory for the model. Defaults to False. + Returns: + str: path of onnx model + """ + model_name = model_name_or_path + if os.path.isdir(model_name_or_path): + model_name = Path(model_name_or_path).parts[-1] + else: + model_name = model_name.split("/")[-1] + + model_name += suffix + + directory = os.path.join(output_dir, model_name) if new_folder else output_dir + return os.path.join(directory, model_name + ".onnx") + + @staticmethod + def save_processing( + model_name_or_path: str, + provider: str, + separate_encoder_and_decoder_init: bool, + use_decoder_masked_mha: bool, + output_qk: bool, + encoder_path: str, + decoder_path: str, + output_dir: str, + cache_dir: str, + ) -> None: + config = WhisperConfig.from_pretrained(model_name_or_path, cache_dir=cache_dir) + config.save_pretrained(output_dir) + + tokenizer = AutoTokenizer.from_pretrained(model_name_or_path, cache_dir=cache_dir) + tokenizer.save_pretrained(output_dir) + + processor = WhisperProcessor.from_pretrained(model_name_or_path, cache_dir=cache_dir) + processor.save_pretrained(output_dir) + + # Return early since the next files are for ONNX Runtime GenAI + if separate_encoder_and_decoder_init: + return + + audio_processor_cfg = { + "feature_extraction": { + "sequence": [ + {"operation": {"name": "audio_decoder", "type": "AudioDecoder"}}, + { + "operation": { + "name": "STFT", + "type": "STFTNorm", + "attrs": { + "n_fft": 400, + "frame_length": 400, + "hop_length": 160, + "_comment": [ + 0.0, + 0.0000616908073425293, + 0.0002467334270477295, + 0.0005550682544708252, + 0.000986635684967041, + 0.0015413463115692139, + 0.0022190213203430176, + 0.0030195116996765137, + 0.003942638635635376, + 0.004988163709640503, + 0.006155818700790405, + 0.007445335388183594, + 0.008856385946273804, + 0.010388582944869995, + 0.012041628360748291, + 0.013815045356750488, + 0.01570841670036316, + 0.01772129535675049, + 0.019853144884109497, + 0.022103488445281982, + 0.02447172999382019, + 0.026957333087921143, + 0.029559612274169922, + 0.03227800130844116, + 0.03511175513267517, + 0.03806024789810181, + 0.0411226749420166, + 0.044298380613327026, + 0.04758647084236145, + 0.05098623037338257, + 0.05449673533439636, + 0.058117181062698364, + 0.06184667348861694, + 0.0656842589378357, + 0.06962898373603821, + 0.07367992401123047, + 0.0778360664844513, + 0.08209633827209473, + 0.08645972609519958, + 0.09092515707015991, + 0.09549149870872498, + 0.10015767812728882, + 0.10492250323295593, + 0.1097848117351532, + 0.11474338173866272, + 0.11979702115058899, + 0.12494447827339172, + 0.13018447160720825, + 0.1355157196521759, + 0.14093685150146484, + 0.1464466154575348, + 0.15204361081123352, + 0.1577264666557312, + 0.16349375247955322, + 0.16934409737586975, + 0.1752760112285614, + 0.18128803372383118, + 0.18737870454788208, + 0.19354650378227234, + 0.1997898817062378, + 0.20610737800598145, + 0.21249738335609436, + 0.21895831823349, + 0.2254886031150818, + 0.23208662867546082, + 0.23875075578689575, + 0.24547931551933289, + 0.2522706985473633, + 0.25912320613861084, + 0.26603513956069946, + 0.27300477027893066, + 0.2800304591655731, + 0.2871103882789612, + 0.29424285888671875, + 0.30142611265182495, + 0.30865830183029175, + 0.31593772768974304, + 0.3232625722885132, + 0.3306310474872589, + 0.3380413055419922, + 0.34549152851104736, + 0.352979838848114, + 0.3605044484138489, + 0.3680635094642639, + 0.37565508484840393, + 0.38327735662460327, + 0.3909284174442291, + 0.39860638976097107, + 0.4063093662261963, + 0.41403549909591675, + 0.42178282141685486, + 0.4295494258403778, + 0.43733343482017517, + 0.44513291120529175, + 0.45294591784477234, + 0.46077051758766174, + 0.46860480308532715, + 0.4764467775821686, + 0.4842946231365204, + 0.492146372795105, + 0.5, + 0.5078536868095398, + 0.515705406665802, + 0.5235532522201538, + 0.5313953161239624, + 0.5392295718193054, + 0.5470541715621948, + 0.5548672080039978, + 0.562666654586792, + 0.5704506635665894, + 0.5782172679901123, + 0.5859646201133728, + 0.5936906933784485, + 0.6013936996459961, + 0.609071671962738, + 0.6167227625846863, + 0.6243450045585632, + 0.6319366097450256, + 0.6394955515861511, + 0.6470202207565308, + 0.6545085310935974, + 0.6619587540626526, + 0.6693689823150635, + 0.6767374277114868, + 0.6840623021125793, + 0.691341757774353, + 0.6985740065574646, + 0.7057572603225708, + 0.7128896713256836, + 0.719969630241394, + 0.7269952893257141, + 0.7339649796485901, + 0.7408769130706787, + 0.7477294206619263, + 0.7545207738876343, + 0.761249303817749, + 0.7679134607315063, + 0.774511456489563, + 0.7810417413711548, + 0.7875027060508728, + 0.7938927412033081, + 0.800210177898407, + 0.8064535856246948, + 0.8126214146614075, + 0.8187121152877808, + 0.8247240781784058, + 0.8306560516357422, + 0.8365063667297363, + 0.8422735929489136, + 0.8479564785957336, + 0.8535534143447876, + 0.8590631484985352, + 0.8644843101501465, + 0.8698155879974365, + 0.8750555515289307, + 0.8802030086517334, + 0.8852566480636597, + 0.8902152180671692, + 0.8950775265693665, + 0.899842381477356, + 0.9045084714889526, + 0.9090749025344849, + 0.9135403037071228, + 0.9179036617279053, + 0.9221639633178711, + 0.9263200759887695, + 0.9303710460662842, + 0.9343158006668091, + 0.9381533861160278, + 0.941882848739624, + 0.945503294467926, + 0.9490138292312622, + 0.9524135589599609, + 0.9557017087936401, + 0.9588773250579834, + 0.961939811706543, + 0.9648882746696472, + 0.9677220582962036, + 0.9704403877258301, + 0.9730427265167236, + 0.9755282998085022, + 0.9778965711593628, + 0.9801468849182129, + 0.9822787046432495, + 0.9842916131019592, + 0.9861849546432495, + 0.9879584312438965, + 0.9896113872528076, + 0.9911436438560486, + 0.9925546646118164, + 0.9938441514968872, + 0.9950118064880371, + 0.996057391166687, + 0.9969804883003235, + 0.997780978679657, + 0.9984586238861084, + 0.999013364315033, + 0.9994449615478516, + 0.9997532367706299, + 0.9999383091926575, + 1, + 0.9999383091926575, + 0.9997532367706299, + 0.9994449615478516, + 0.999013364315033, + 0.9984586238861084, + 0.997780978679657, + 0.9969804286956787, + 0.9960573315620422, + 0.9950118064880371, + 0.9938441514968872, + 0.9925546646118164, + 0.9911435842514038, + 0.9896113872528076, + 0.9879583716392517, + 0.9861849546432495, + 0.9842915534973145, + 0.9822787046432495, + 0.9801468253135681, + 0.9778964519500732, + 0.9755282402038574, + 0.9730426073074341, + 0.9704403877258301, + 0.9677219390869141, + 0.9648882150650024, + 0.9619396924972534, + 0.9588772654533386, + 0.9557015895843506, + 0.9524134397506714, + 0.9490137100219727, + 0.9455032348632812, + 0.9418827295303345, + 0.9381532669067383, + 0.9343156814575195, + 0.9303709268569946, + 0.9263200759887695, + 0.9221639633178711, + 0.9179036617279053, + 0.913540244102478, + 0.9090747833251953, + 0.9045084714889526, + 0.8998422622680664, + 0.8950774669647217, + 0.8902151584625244, + 0.8852565884590149, + 0.8802029490470886, + 0.8750554919242859, + 0.869815468788147, + 0.8644842505455017, + 0.8590630888938904, + 0.853553295135498, + 0.8479562997817993, + 0.842273473739624, + 0.836506187915802, + 0.8306558728218079, + 0.8247239589691162, + 0.8187118768692017, + 0.8126212358474731, + 0.8064534664154053, + 0.8002099990844727, + 0.793892502784729, + 0.7875025272369385, + 0.7810416221618652, + 0.7745113372802734, + 0.767913281917572, + 0.7612491846084595, + 0.7545205950737, + 0.7477291822433472, + 0.7408767342567444, + 0.7339648008346558, + 0.7269951105117798, + 0.7199694514274597, + 0.7128894925117493, + 0.7057570219039917, + 0.6985738277435303, + 0.6913415789604187, + 0.684062123298645, + 0.6767372488975525, + 0.6693688035011292, + 0.6619585752487183, + 0.6545083522796631, + 0.6470199823379517, + 0.6394953727722168, + 0.6319363117218018, + 0.6243447661399841, + 0.6167224645614624, + 0.6090714335441589, + 0.601393461227417, + 0.5936904549598694, + 0.5859643220901489, + 0.5782170295715332, + 0.5704504251480103, + 0.5626664161682129, + 0.5548669099807739, + 0.5470539331436157, + 0.5392293334007263, + 0.5313950181007385, + 0.5235530138015747, + 0.5157051682472229, + 0.507853627204895, + 0.5, + 0.4921463429927826, + 0.484294593334198, + 0.4764467477798462, + 0.46860471367836, + 0.4607704281806946, + 0.4529458284378052, + 0.4451328217983246, + 0.437333345413208, + 0.42954933643341064, + 0.4217827320098877, + 0.4140354096889496, + 0.4063093066215515, + 0.3986063003540039, + 0.39092832803726196, + 0.3832772672176361, + 0.37565499544143677, + 0.36806342005729675, + 0.3605043888092041, + 0.35297977924346924, + 0.3454914391040802, + 0.338041216135025, + 0.33063095808029175, + 0.3232625126838684, + 0.3159376382827759, + 0.3086581826210022, + 0.3014259934425354, + 0.2942427396774292, + 0.28711026906967163, + 0.2800303101539612, + 0.2730046510696411, + 0.2660350203514099, + 0.2591230869293213, + 0.25227057933807373, + 0.24547919631004333, + 0.2387506067752838, + 0.23208650946617126, + 0.22548848390579224, + 0.21895819902420044, + 0.2124972641468048, + 0.2061072587966919, + 0.19978976249694824, + 0.1935463547706604, + 0.18737855553627014, + 0.18128788471221924, + 0.17527586221694946, + 0.1693439483642578, + 0.16349363327026367, + 0.15772631764411926, + 0.15204349160194397, + 0.14644649624824524, + 0.1409367322921753, + 0.13551557064056396, + 0.1301843225955963, + 0.12494435906410217, + 0.11979690194129944, + 0.11474326252937317, + 0.10978469252586365, + 0.10492238402366638, + 0.10015755891799927, + 0.09549137949943542, + 0.09092503786087036, + 0.08645960688591003, + 0.08209621906280518, + 0.07783591747283936, + 0.07367980480194092, + 0.06962886452674866, + 0.06568413972854614, + 0.06184655427932739, + 0.0581170916557312, + 0.0544966459274292, + 0.05098611116409302, + 0.04758638143539429, + 0.044298261404037476, + 0.04112258553504944, + 0.038060128688812256, + 0.03511166572570801, + 0.03227788209915161, + 0.02955952286720276, + 0.02695724368095398, + 0.024471670389175415, + 0.02210339903831482, + 0.01985308527946472, + 0.017721205949783325, + 0.015708357095718384, + 0.0138150155544281, + 0.012041598558425903, + 0.010388582944869995, + 0.008856356143951416, + 0.007445335388183594, + 0.006155818700790405, + 0.004988163709640503, + 0.003942638635635376, + 0.0030195116996765137, + 0.0022190213203430176, + 0.0015413165092468262, + 0.000986635684967041, + 0.0005550682544708252, + 0.0002467334270477295, + 0.0000616908073425293, + ], + }, + } + }, + { + "operation": { + "name": "log_mel_spectrogram", + "type": "LogMelSpectrum", + "attrs": {"chunk_size": 30, "hop_length": 160, "n_fft": 400, "n_mel": config.num_mel_bins}, + } + }, + ] + } + } + audio_processor_json = json.dumps(audio_processor_cfg, indent=4) + + with open(os.path.join(output_dir, "audio_processor_config.json"), "w") as f: + f.write(audio_processor_json) + + provider_options = [] if "cpu" in provider else [{f"{provider}": {}}] + genai_config = { + "model": { + "bos_token_id": config.bos_token_id, + "context_length": config.max_length, + "decoder": { + "session_options": { + "log_id": "onnxruntime-genai", + "provider_options": provider_options, + }, + "filename": os.path.basename(decoder_path), + "head_size": config.d_model // config.decoder_attention_heads, + "hidden_size": config.d_model, + "inputs": { + "input_ids": "input_ids", + "past_key_names": "past_key_self_%d", + "past_value_names": "past_value_self_%d", + "cross_past_key_names": "past_key_cross_%d", + "cross_past_value_names": "past_value_cross_%d", + }, + "outputs": { + "logits": "logits", + "present_key_names": "present_key_self_%d", + "present_value_names": "present_value_self_%d", + }, + "num_attention_heads": config.decoder_attention_heads, + "num_hidden_layers": config.decoder_layers, + "num_key_value_heads": config.decoder_attention_heads, + }, + "encoder": { + "session_options": { + "log_id": "onnxruntime-genai", + "provider_options": provider_options, + }, + "filename": os.path.basename(encoder_path), + "head_size": config.d_model // config.encoder_attention_heads, + "hidden_size": config.d_model, + "inputs": {"audio_features": "audio_features"}, + "outputs": { + "encoder_hidden_states": "encoder_hidden_states", + "cross_present_key_names": "present_key_cross_%d", + "cross_present_value_names": "present_value_cross_%d", + }, + "num_attention_heads": config.encoder_attention_heads, + "num_hidden_layers": config.encoder_layers, + "num_key_value_heads": config.encoder_attention_heads, + }, + "eos_token_id": config.eos_token_id, + "pad_token_id": config.pad_token_id, + "type": "whisper", + "vocab_size": config.vocab_size, + }, + "search": { + "diversity_penalty": 0.0, + "do_sample": False, + "early_stopping": True, + "length_penalty": 1.0, + "max_length": config.max_length, + "min_length": 0, + "no_repeat_ngram_size": 0, + "num_beams": 1, + "num_return_sequences": 1, + "past_present_share_buffer": use_decoder_masked_mha, + "repetition_penalty": 1.0, + "temperature": 1.0, + "top_k": 1, + "top_p": 1.0, + }, + } + + # Requirements for the DMMHA kernel: + # - Buffer sharing = true + # - New input: past_sequence_length + # - New input: cache_indirection + # Otherwise, buffer sharing should be false and the new inputs should not be added + # for beam search to work in ORT GenAI. + if use_decoder_masked_mha: + genai_config["model"]["decoder"]["inputs"].update( + { + "past_sequence_length": "past_sequence_length", + "cache_indirection": "cache_indirection", + } + ) + + if output_qk: + genai_config["model"]["decoder"]["outputs"].update( + { + "output_cross_qk_names": "output_cross_qk_%d", + } + ) + + with open(os.path.join(output_dir, "genai_config.json"), "w") as f: + json.dump(genai_config, f, indent=4) + + @staticmethod + def load_model( + model_name_or_path: str, + model_impl: str, + cache_dir: str, + device: torch.device, + dtype: torch.dtype, + merge_encoder_and_decoder_init: bool = True, + no_beam_search_op: bool = False, + output_qk: bool = False, + ) -> dict[str, torch.nn.Module]: + """Load model given a pretrained name or path, then build models for ONNX conversion. + + Args: + model_name_or_path (str): pretrained model name or path + model_impl (str): library to load model from + cache_dir (str): cache directory + device (torch.device): device to run the model + dtype (torch.dtype): dtype to run the model + merge_encoder_and_decoder_init (bool, optional): Whether merge encoder and decoder initialization into one ONNX model. Defaults to True. + no_beam_search_op (bool, optional): Whether to use beam search op or not. Defaults to False. + output_qk (bool, optional): Whether to output QKs to calculate batched jump times for word-level timestamps. Defaults to False. + Returns: + Dict[str, torch.nn.Module]: mapping from name to modules for ONNX conversion. + """ + # Load PyTorch model + if model_impl == "hf": + # Load from Hugging Face + model = WhisperForConditionalGeneration.from_pretrained( + model_name_or_path, cache_dir=cache_dir, attn_implementation="eager" + ) + else: + # Load from OpenAI + import whisper # noqa: PLC0415 + + if not os.path.exists(model_name_or_path): + name_or_path = model_name_or_path.split("/")[-1][8:] + else: + name_or_path = model_name_or_path + model = whisper.load_model(name_or_path, device, download_root=cache_dir, in_memory=True) + + # Set PyTorch model properties + model.eval().to(device=device) + if model_impl == "hf": + model.to(dtype=dtype) + config = WhisperConfig.from_pretrained(model_name_or_path, cache_dir=cache_dir) + + # Load each component of PyTorch model + decoder = WhisperDecoder(config, model, model_impl, no_beam_search_op).eval() + components = {"decoder": decoder} + if merge_encoder_and_decoder_init: + encoder_decoder_init = WhisperEncoderDecoderInit(config, model, model_impl, no_beam_search_op).eval() + components.update({"encoder": encoder_decoder_init}) + else: + encoder = WhisperEncoder(config, model, model_impl).eval() + components.update({"encoder": encoder, "decoder_init": decoder}) + + if output_qk: + batched_jump_times = WhisperJumpTimes(config, device, cache_dir).eval() + components.update({"jump_times": batched_jump_times}) + return components + + @staticmethod + def export_onnx( + model: WhisperEncoder | WhisperEncoderDecoderInit | WhisperDecoder, + onnx_model_path: str, + provider: str, + verbose: bool, + use_external_data_format: bool, + use_fp16_inputs: bool, + use_int32_inputs: bool, + use_encoder_hidden_states: bool, + use_kv_cache_inputs: bool, + ): + """Export model component to ONNX + + Args: + model (class): PyTorch class to export + onnx_model_path (str): path to save ONNX model + provider (str): provider to use for verifying parity on ONNX model + verbose (bool): print verbose information. + use_external_data_format (bool): use external data format or not. + use_fp16_inputs (bool): use float16 inputs for the audio_features, encoder_hidden_states, logits, and KV caches. + use_int32_inputs (bool): use int32 inputs for the decoder_input_ids. + use_encoder_hidden_states (bool): use encoder_hidden_states as model input for decoder-init/decoder-without-past models. + use_kv_cache_inputs (bool): use KV caches as model inputs for decoder-with-past models. + """ + if isinstance(model, WhisperEncoder): + model.export_onnx( + onnx_model_path, + provider, + verbose, + use_external_data_format, + use_fp16_inputs, + ) + elif isinstance(model, WhisperEncoderDecoderInit): + model.export_onnx( + onnx_model_path, + provider, + verbose, + use_external_data_format, + use_fp16_inputs, + use_int32_inputs, + ) + elif isinstance(model, WhisperDecoder): + model.export_onnx( + onnx_model_path, + provider, + verbose, + use_external_data_format, + use_fp16_inputs, + use_int32_inputs, + use_encoder_hidden_states, + use_kv_cache_inputs, + ) + elif isinstance(model, WhisperJumpTimes): + model.export_onnx( + onnx_model_path, + provider, + verbose, + use_external_data_format, + use_fp16_inputs, + use_int32_inputs, + ) + else: + raise ValueError(f"Unknown instance for model detected: {type(model)}") + + @staticmethod + def optimize_onnx( + onnx_model_path: str, + optimized_model_path: str, + is_float16: bool, + num_attention_heads: int, + hidden_size: int, + num_decoder_layers: int, + use_external_data_format: bool = False, + use_gpu: bool = False, + provider: str = "cpu", + is_decoder: bool = False, + no_beam_search_op: bool = False, + use_decoder_masked_mha: bool = False, + output_qk: bool = False, + ): + """Optimize ONNX model with an option to convert it to use mixed precision.""" + + from fusion_options import FusionOptions # noqa: PLC0415 + + optimization_options = FusionOptions("bart") + optimization_options.use_multi_head_attention = True + optimization_options.disable_multi_head_attention_bias = False + + m = optimize_model( + onnx_model_path, + model_type="bart", + num_heads=num_attention_heads, + hidden_size=hidden_size, + opt_level=0, + optimization_options=optimization_options, + use_gpu=use_gpu, + only_onnxruntime=False, + ) + + # Add `past_sequence_length`, `cache_indirection`, and `output_qk` to `MultiHeadAttention` ops + if is_decoder and no_beam_search_op: + if use_decoder_masked_mha: + # FP16 CUDA, FP32 CUDA, and FP32 CPU use the `DecoderMaskedMultiHeadAttention` kernel + # via `MultiHeadAttention`, which requires the `past_sequence_length` and + # `cache_indirection` inputs + m, past_seq_len_name = fix_past_sequence_length(m) + m = add_cache_indirection_to_mha(m, past_seq_len_name) + + if output_qk: + m = add_output_qk_to_mha(m, skip_node_idxs=list(range(0, 2 * num_decoder_layers, 2))) + + m.save_model_to_file(optimized_model_path, use_external_data_format, all_tensors_to_one_file=True) + + @staticmethod + def pt_transcription_for_verify_onnx( + processor: WhisperProcessor, + pt_model: torch.nn.Module, + device: torch.device, + batch_size: int = 1, + prompt_mode: bool = False, + ): + # Try to import `datasets` pip package + try: + from datasets import load_dataset # noqa: PLC0415 + except Exception as e: + logger.error(f"An error occurred while importing `datasets`: {e}", exc_info=True) # noqa: G201 + install_cmd = "pip install datasets" + logger.warning(f"Could not import `datasets`. Attempting to install `datasets` via `{install_cmd}`.") + os.system(install_cmd) + + from datasets import load_dataset # noqa: PLC0415 + + ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") + input_features_ = [] + if batch_size == 1: + input_features = processor([ds[0]["audio"]["array"]], return_tensors="pt").input_features + else: + input_features_ = [ + processor([ds[3]["audio"]["array"]], return_tensors="pt").input_features, + processor([ds[3]["audio"]["array"]], return_tensors="pt").input_features, + ] + assert len(input_features_) == batch_size + input_features = torch.cat((input_features_[0], input_features_[1])) + + max_length, min_length, num_beams, num_return_sequences = 30, 0, 1, 1 + length_penalty, repetition_penalty = 1.0, 1.0 + inputs = { + "input_features": input_features.to(device), + "max_length": max_length, + "min_length": min_length, + "num_beams": num_beams, + "num_return_sequences": num_return_sequences, + "length_penalty": length_penalty, + "repetition_penalty": repetition_penalty, + "early_stopping": True, + "use_cache": True, + } + + if prompt_mode: + prompts = ["John has doubts", "Maria has grave doubts"] + prompt_ids = [processor.get_prompt_ids(p) for p in prompts] + pt_transcription = [] + pt_outputs = [] + # The looping for model.generate is necessary here due to the limitation as per + # https://huggingface.co/docs/transformers/model_doc/whisper#transformers.WhisperForConditionalGeneration.generate.prompt_ids + # prompt_ids input requires a tensor of rank 1 + for i in range(batch_size): + inputs["prompt_ids"] = torch.from_numpy(prompt_ids[i]).to(device=device) + inputs["input_features"] = input_features_[i].to(device) + pt_output = pt_model.generate(**inputs).detach().cpu().numpy() + pt_outputs.append(pt_output) + pt_transcription.append(processor.batch_decode(pt_output, skip_special_tokens=True)[0]) + inputs["input_features"] = input_features + del inputs["prompt_ids"] + else: + prompt_ids = [] + pt_outputs = pt_model.generate(**inputs).detach().cpu().numpy() + pt_transcription = [processor.batch_decode(pt_outputs, skip_special_tokens=True)[0]] + pt_outputs = list(pt_outputs) + del inputs["early_stopping"] + del inputs["use_cache"] + return inputs, pt_transcription, pt_outputs, prompt_ids + + @staticmethod + def select_transcription_options( + batch_size: int, + prompt_mode: bool, + ): + if batch_size > 1 and prompt_mode: + expected_transcription_no_comma_prompt1 = " John has doubts whether Sir Frederick Layton's work is really Greek after all and can discover in it but little of Rocky I" + expected_transcription_misspelled_prompt1 = " John has doubts whether Sir Frederick Latins work is really Greek after all and can discover in it but little of Rocky I" + expected_transcription_no_comma_prompt2 = " Maria has grave doubts whether Sir Frederick Layton's work is really Greek after all and can discover in it but little of Rocky" + expected_transcription_misspelled_prompt2 = " Maria has grave doubts whether Sir Frederick Latins work is really Greek after all and can discover in it but little of Rocky I" + expected_transcription_options = { + expected_transcription_no_comma_prompt1, + expected_transcription_no_comma_prompt2, + expected_transcription_misspelled_prompt1, + expected_transcription_misspelled_prompt2, + } + else: + expected_transcription_no_comma = ( + " Mr. Quilter is the apostle of the middle classes and we are glad to welcome his gospel." + ) + expected_transcription_with_comma = ( + " Mr. Quilter is the apostle of the middle classes, and we are glad to welcome his gospel." + ) + expected_transcription_with_quote_and_comma = ( + ' "Mr. Quilter is the apostle of the middle classes, and we are glad to welcome his gospel.' + ) + expected_transcription_options = { + expected_transcription_no_comma, + expected_transcription_with_comma, + expected_transcription_with_quote_and_comma, + } + return expected_transcription_options + + @staticmethod + def get_outputs( + pt_outputs: np.ndarray, + ort_outputs: np.ndarray, + i: int, + ): + """Get PyTorch and ONNX Runtime output token ids at index i""" + pt_output, ort_output = pt_outputs[i], ort_outputs[i] + pt_shape, ort_shape = pt_output.shape, ort_output.shape + + # Hugging Face impl. + Beam Search op: PyTorch = (26,) and ORT = (30,) + # OpenAI impl. + Beam Search op: PyTorch = (1, 30) and ORT = (30,) + if pt_shape != ort_shape: + if len(pt_shape) > 1: + pt_output = pt_output[0] + pt_shape = pt_output.shape + if len(ort_shape) > 1: + ort_output = ort_output[0] + ort_shape = ort_output.shape + if pt_shape[0] != ort_shape[0]: + min_len = min(pt_shape[0], ort_shape[0]) + pt_output = pt_output[:min_len] + ort_output = ort_output[:min_len] + + assert pt_output.shape == ort_output.shape + return pt_output, ort_output + + @staticmethod + def verify_onnx( + model_name_or_path: str, + cache_dir: str, + ort_session: InferenceSession, + device: torch.device, + batch_size: int = 1, + prompt_mode: bool = False, + ): + """Compare the result from PyTorch and ONNX Runtime to verify the ONNX model is good.""" + pt_model = WhisperForConditionalGeneration.from_pretrained( + model_name_or_path, cache_dir=cache_dir, attn_implementation="eager" + ).to(device) + processor = WhisperProcessor.from_pretrained(model_name_or_path, cache_dir=cache_dir) + config = WhisperConfig.from_pretrained(model_name_or_path, cache_dir=cache_dir) + + inputs, pt_transcription, pt_outputs, decoder_prompt_ids = WhisperHelper.pt_transcription_for_verify_onnx( + processor, + pt_model, + device, + batch_size=batch_size, + prompt_mode=prompt_mode, + ) + + start_id = [config.decoder_start_token_id] # ex: [50258] + prompt_ids = processor.get_decoder_prompt_ids(language="english", task="transcribe") + prompt_ids = [token[1] for token in prompt_ids] # ex: [50259, 50358, 50363] + forced_decoder_ids = start_id + prompt_ids # ex: [50258, 50259, 50358, 50363] + + ort_names = [entry.name for entry in ort_session.get_inputs()] + ort_dtypes = [entry.type for entry in ort_session.get_inputs()] + ort_to_np = { + "tensor(float)": np.float32, + "tensor(float16)": np.float16, + "tensor(int64)": np.int64, + "tensor(int32)": np.int32, + "tensor(int8)": np.int8, + "tensor(uint8)": np.uint8, + } + + use_extra_decoding_ids = "extra_decoding_ids" in ort_names + for name, dtype in zip(ort_names, ort_dtypes, strict=False): + if name == "input_features": + inputs[name] = inputs[name].detach().cpu().numpy() + elif name == "vocab_mask": + inputs[name] = np.ones(config.vocab_size, dtype=ort_to_np[dtype]) + elif name == "prefix_vocab_mask": + inputs[name] = np.ones((batch_size, config.vocab_size), dtype=ort_to_np[dtype]) + elif name == "decoder_input_ids": + if not prompt_mode: + raw_input_ids = [start_id] if use_extra_decoding_ids else [forced_decoder_ids] + inputs[name] = np.array(raw_input_ids, dtype=ort_to_np[dtype]) + else: + # This logic handles the scenario for when prompts are not of the same size + # For example if our prompt ids are [p1_id_1, p1_id_2] and [p2_id_1] + # The final decoder_input_ids will look as such after padding + # [prev_token, p1_id_1, p1_id_2, start_token, lang_token, transcribe_token] + # [prev_token, p2_id_1, PAD_TOKEN, start_token, lang_token, transcribe_token] + ort_prompts = [] + for i in range(batch_size): + ort_prompts.append(decoder_prompt_ids[i].tolist()) + max_len = max(len(p) for p in ort_prompts) + padded_prompts = [] + for p in ort_prompts: + padded_prompt = [*p, *([config.pad_token_id] * (max_len - len(p)))] + padded_prompts.append(padded_prompt + forced_decoder_ids) + inputs[name] = np.array(padded_prompts, dtype=ort_to_np[dtype]) + elif name == "logits_processor": + inputs[name] = np.array([1], dtype=ort_to_np[dtype]) + elif name == "cross_qk_layer_head": + inputs[name] = np.array([[0, 0]], dtype=ort_to_np[dtype]) + elif name == "extra_decoding_ids": + inputs[name] = np.repeat(np.array([prompt_ids], dtype=ort_to_np[dtype]), batch_size, 0) + elif name == "temperature": + inputs[name] = np.array([1.0], dtype=ort_to_np[dtype]) + else: + inputs[name] = np.array([inputs[name]], dtype=ort_to_np[dtype]) + + ort_outputs = ort_session.run(None, inputs)[0][:, 0, :] + ort_transcription = processor.batch_decode(ort_outputs, skip_special_tokens=True) + expected_transcription_options = WhisperHelper.select_transcription_options(batch_size, prompt_mode) + + parity = 1 + for i in range(batch_size): + pt_output, ort_output = WhisperHelper.get_outputs(pt_outputs, ort_outputs, i) + + # Check if token ids match + parity *= np.allclose(pt_output, ort_output) + + # Check if transcribed outputs match + parity *= ( + pt_transcription[i] in expected_transcription_options + and ort_transcription[i] in expected_transcription_options + ) + max_diff = 0 + + if not parity: + for i in range(batch_size): + pt_output, ort_output = WhisperHelper.get_outputs(pt_outputs, ort_outputs, i) + diff = pt_output - ort_output + + max_diff_i = max(diff.min(), diff.max(), key=abs) + max_diff = max(max_diff, max_diff_i) + + if max_diff != 0: + logger.warning(f"PyTorch outputs: {pt_transcription}") + logger.warning(f"ONNX Runtime outputs: {ort_transcription}") + + return 0 diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/whisper/whisper_inputs.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/whisper/whisper_inputs.py new file mode 100644 index 0000000000000000000000000000000000000000..4be914689492e16788799404153f27ea1f959367 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/whisper/whisper_inputs.py @@ -0,0 +1,380 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +import logging + +import numpy as np +import torch +from transformers import WhisperConfig + +from onnxruntime import InferenceSession + +logger = logging.getLogger(__name__) + + +# Create audio_features for encoder +# Shape is (batch_size, feature_size, sequence_length) = (batch_size, num_mel_filters, num_frames) +# where num_mel_filters is a model attribute and num_frames = (chunk_length * sample_rate) // hop_length. +# +# Hard-coded audio hyperparameters: +# SAMPLE_RATE = 16000 +# N_FFT = 400 +# HOP_LENGTH = 160 +# CHUNK_LENGTH = 30 (i.e. 30-second chunk of audio) +# N_SAMPLES = CHUNK_LENGTH * SAMPLE_RATE = 30 * 16000 = 480000 (i.e. 480,000 samples in a 30-second chunk of audio) +# N_FRAMES = N_SAMPLES // HOP_LENGTH = 480000 // 160 = 3000 (i.e. 3000 frames in a mel spectrogram input) +# +# N_SAMPLES_PER_TOKEN = HOP_LENGTH * 2 = 160 * 2 = 320 +# FRAMES_PER_TOKEN = SAMPLE_RATE // HOP_LENGTH = 16000 // 160 = 100 (i.e. 10 ms per audio frame) +# TOKENS_PER_SECOND = SAMPLE_RATE // N_SAMPLES_PER_TOKEN = 16000 // 320 = 50 (i.e. 20 ms per audio token) +def get_sample_audio_features( + config: WhisperConfig, + device: torch.device, + batch_size: int, + sequence_length: int = 3000, + use_fp16: bool = False, +): + torch_dtype = torch.float16 if use_fp16 else torch.float32 + audio_features = torch.randn(batch_size, config.num_mel_bins, sequence_length, device=device, dtype=torch_dtype) + return audio_features + + +# Create input_ids for decoder +# Shape is (batch_size, sequence_length) where sequence_length is the initial decoder sequence length +def get_sample_decoder_input_ids( + config: WhisperConfig, + device: torch.device, + batch_size: int, + sequence_length: int, + use_int32: bool = True, +): + torch_dtype = torch.int32 if use_int32 else torch.int64 + decoder_input_ids = torch.randint( + low=0, high=config.vocab_size, size=(batch_size, sequence_length), device=device, dtype=torch_dtype + ) + return decoder_input_ids + + +# Create encoder_hidden_states for decoder-init +# Shape is (batch_size, num_frames // 2, hidden_size) +def get_sample_encoder_hidden_states( + config: WhisperConfig, + device: torch.device, + batch_size: int, + use_fp16: bool = False, +): + torch_dtype = torch.float16 if use_fp16 else torch.float32 + encoder_hidden_states = torch.randn( + batch_size, config.max_source_positions, config.d_model, device=device, dtype=torch_dtype + ) + return encoder_hidden_states + + +# Create past_key_values +# Self-attention KV caches are of shape (batch_size, num_heads, past_sequence_length, head_size) +# Cross-attention KV caches are of shape (batch_size, num_heads, num_frames // 2, head_size) +def get_sample_past_key_values( + config: WhisperConfig, + device: torch.device, + batch_size: int, + past_seq_len: int, + use_fp16: bool = False, +): + num_heads = config.decoder_attention_heads + head_size = config.d_model // num_heads + max_source_positions = ( + config.max_source_positions + ) # equal to num_frames // 2 = encoder's sequence_length // 2 = 3000 // 2 = 1500 + torch_dtype = torch.float16 if use_fp16 else torch.float32 + self_attention_kv_caches = [ + ( + torch.rand(batch_size, num_heads, past_seq_len, head_size, device=device, dtype=torch_dtype), + torch.rand(batch_size, num_heads, past_seq_len, head_size, device=device, dtype=torch_dtype), + ) + for _ in range(config.decoder_layers) + ] + cross_attention_kv_caches = [ + ( + torch.rand(batch_size, num_heads, max_source_positions, head_size, device=device, dtype=torch_dtype), + torch.rand(batch_size, num_heads, max_source_positions, head_size, device=device, dtype=torch_dtype), + ) + for _ in range(config.decoder_layers) + ] + return flatten_past_key_values(self_attention_kv_caches, cross_attention_kv_caches) + + +# Flatten KV caches into pairs-of-4 where each pair is defined as: +# (self_attn_key_cache, self_attn_value_cache, cross_attn_key_cache, cross_attn_value_cache) +def flatten_past_key_values( + self_attn_kv_caches: list[tuple[torch.Tensor, torch.Tensor]], + cross_attn_kv_caches: list[tuple[torch.Tensor, torch.Tensor]], +): + past_key_values = [] + for (self_k_cache, self_v_cache), (cross_k_cache, cross_v_cache) in zip( + self_attn_kv_caches, cross_attn_kv_caches, strict=False + ): + layer_kv_caches = (self_k_cache, self_v_cache, cross_k_cache, cross_v_cache) + past_key_values.append(layer_kv_caches) + return past_key_values + + +# Group KV caches into two 1D lists where one list contains the self attention KV caches and +# one list contains the cross attention KV caches +def group_past_key_values( + kv_caches: list[tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]], +): + self_attn_kv_caches, cross_attn_kv_caches = [], [] + for self_k_cache, self_v_cache, cross_k_cache, cross_v_cache in kv_caches: + self_attn_kv_caches.append(self_k_cache) + self_attn_kv_caches.append(self_v_cache) + cross_attn_kv_caches.append(cross_k_cache) + cross_attn_kv_caches.append(cross_v_cache) + return self_attn_kv_caches, cross_attn_kv_caches + + +# Create alignment heads for timestamps +# Shape is (num_alignment_heads, 2) +def get_sample_alignment_heads( + config: WhisperConfig, + device: torch.device, + num_alignment_heads: int = 6, + use_int32: bool = True, +): + torch_dtype = torch.int32 if use_int32 else torch.int64 + alignment_heads = torch.ones((num_alignment_heads, 2), device=device, dtype=torch_dtype) + return alignment_heads + + +# Create length of start-of-transcription sequence for timestamps +# Shape is (1) +def get_sample_sot_sequence_length( + device: torch.device, + sot_sequence_length: int, + use_int32: bool = False, +): + torch_dtype = torch.int32 if use_int32 else torch.int64 + sot_length = torch.tensor([sot_sequence_length], device=device, dtype=torch_dtype) + return sot_length + + +# Create segment length for timestamps +# Shape is (1) +def get_sample_segment_length( + device: torch.device, + segment_length: int, + use_int32: bool = False, +): + torch_dtype = torch.int32 if use_int32 else torch.int64 + segment_size = torch.tensor([segment_length], device=device, dtype=torch_dtype) + return segment_size + + +# Create QKs for timestamps +# Shape is (batch_size, num_heads, sequence_length, num_frames // 2) +def get_sample_QKs( # noqa: N802 + config: WhisperConfig, + device: torch.device, + batch_size: int, + sequence_length: int, + use_fp16: bool = False, +): + num_heads = config.decoder_attention_heads + torch_dtype = torch.float16 if use_fp16 else torch.float32 + QKs = [ # noqa: N806 + torch.rand( + batch_size, num_heads, sequence_length, config.max_source_positions, device=device, dtype=torch_dtype + ) + for _ in range(config.decoder_layers) + ] + return QKs + + +# Create inputs for encoder component of Whisper +def get_sample_encoder_inputs( + config: WhisperConfig, + device: torch.device, + batch_size: int, + sequence_length: int = 3000, + use_fp16: bool = False, +): + audio_features = get_sample_audio_features(config, device, batch_size, sequence_length, use_fp16) + return {"audio_features": audio_features} + + +# Create inputs for encoder component + first pass through decoder component of Whisper +def get_sample_encoder_decoder_init_inputs( + config: WhisperConfig, + device: torch.device, + batch_size: int, + decoder_sequence_length: int, + encoder_sequence_length: int = 3000, + use_fp16: bool = False, + use_int32: bool = True, +): + audio_features = get_sample_audio_features(config, device, batch_size, encoder_sequence_length, use_fp16) + decoder_input_ids = get_sample_decoder_input_ids(config, device, batch_size, decoder_sequence_length, use_int32) + return {"audio_features": audio_features, "decoder_input_ids": decoder_input_ids} + + +# Create inputs for decoder component of Whisper +# Inputs for first pass through the decoder (i.e. decoder-init): decoder_input_ids, encoder_hidden_states +# Inputs for subsequent passes through the decoder (i.e. decoder-with-past): decoder_input_ids, past_key_values +def get_sample_decoder_inputs( + config: WhisperConfig, + device: torch.device, + batch_size: int, + past_sequence_length: int, + sequence_length: int, + use_fp16: bool = False, + use_int32: bool = True, +): + decoder_input_ids = get_sample_decoder_input_ids(config, device, batch_size, sequence_length, use_int32) + encoder_hidden_states = get_sample_encoder_hidden_states(config, device, batch_size, use_fp16) + past_key_values = get_sample_past_key_values(config, device, batch_size, past_sequence_length, use_fp16) + return { + "decoder_input_ids": decoder_input_ids, + "encoder_hidden_states": encoder_hidden_states, + "past_key_values": past_key_values, + } + + +# Create inputs for timestamps component of Whisper +def get_sample_jump_times_inputs( + config: WhisperConfig, + device: torch.device, + batch_size: int, + sequence_length: int, + num_alignment_heads: int, + sot_sequence_length: int, + segment_length: int, + use_fp16: bool = False, + use_int32: bool = True, +): + alignment_heads = get_sample_alignment_heads(config, device, num_alignment_heads, use_int32) + # lengths need to be int64 because subsequent 'Slice' ops only take int64 inputs + sot_sequence_length = get_sample_sot_sequence_length(device, sot_sequence_length) + segment_length = get_sample_segment_length(device, segment_length) + QKs = get_sample_QKs(config, device, batch_size, sequence_length, use_fp16) # noqa: N806 + return { + "alignment_heads": alignment_heads, + "sot_sequence_length": sot_sequence_length, + "segment_length": segment_length, + "QKs": QKs, + } + + +# Convert PyTorch inputs to ONNX Runtime inputs +def convert_inputs_for_ort( + inputs: dict, + model: InferenceSession, +): + self_attn_kv_caches, cross_attn_kv_caches = None, None + batch_size, num_heads, past_seq_len, head_size = 0, 0, 0, 0 + num_beams, max_seq_len = 1, 448 + if "past_key_values" in inputs: + (self_attn_kv_caches, cross_attn_kv_caches) = group_past_key_values(inputs["past_key_values"]) + batch_size, num_heads, past_seq_len, head_size = self_attn_kv_caches[0].shape + + ort_inputs = {} + model_inputs = list(map(lambda i: i.name, model.get_inputs())) # noqa: C417 + use_buffer_sharing = "cache_indirection" in model_inputs + for name in model_inputs: + if name in {"audio_features", "encoder_input_ids"}: + # Encoder input + ort_inputs[name] = inputs["audio_features"].detach().cpu().numpy() + elif name == "encoder_hidden_states": + # Encoder output + ort_inputs[name] = inputs["encoder_hidden_states"].detach().cpu().numpy() + elif name in {"decoder_input_ids", "input_ids"}: + # Decoder input + ort_inputs[name] = inputs["decoder_input_ids"].detach().cpu().numpy() + elif "past_key_self" in name or "past_value_self" in name: + # Decoder input + orig_kv_cache = self_attn_kv_caches.pop(0).detach().cpu().numpy() + if use_buffer_sharing: + new_kv_cache = np.zeros((batch_size, num_heads, max_seq_len, head_size), dtype=orig_kv_cache.dtype) + new_kv_cache[:batch_size, :num_heads, :past_seq_len, :head_size] = orig_kv_cache + ort_inputs[name] = new_kv_cache + else: + ort_inputs[name] = orig_kv_cache + elif "past_key_cross" in name or "past_value_cross" in name: + # Decoder input + orig_kv_cache = cross_attn_kv_caches.pop(0).detach().cpu().numpy() + ort_inputs[name] = orig_kv_cache + elif name == "past_sequence_length": + # Decoder input + ort_inputs[name] = np.array([past_seq_len], dtype=np.int32) + elif name == "cache_indirection": + # Decoder input + ort_inputs[name] = np.zeros((batch_size, num_beams, max_seq_len), dtype=np.int32) + elif name == "alignment_heads": + # Jump times input + ort_inputs[name] = inputs["alignment_heads"].detach().cpu().numpy() + elif name == "sot_sequence_length": + # Jump times input + ort_inputs[name] = inputs["sot_sequence_length"].detach().cpu().numpy() + elif name == "segment_length": + # Jump times input + ort_inputs[name] = inputs["segment_length"].detach().cpu().numpy() + elif "cross_qk" in name: + # Jump times input + ort_inputs[name] = inputs["QKs"].pop(0).detach().cpu().numpy() + else: + raise ValueError(f"Unknown name not recognized: {name}") + + return ort_inputs + + +# Get dynamic axes for all inputs and outputs to the model +def get_model_dynamic_axes( + config: WhisperConfig, + input_names: list[str], + output_names: list[str], +): + dynamic_axes = {} + for name in input_names + output_names: + if name in {"audio_features", "encoder_input_ids"}: + # shape is (batch_size, num_mels, num_frames) + dynamic_axes[name] = {0: "batch_size"} + elif name in {"input_ids", "decoder_input_ids"}: + # shape is (batch_size, sequence_length) + dynamic_axes[name] = {0: "batch_size", 1: "sequence_length"} + elif name == "alignment_heads": + # shape is (num_alignment_heads, 2) + dynamic_axes[name] = {0: "num_alignment_heads"} + elif name in {"sot_sequence_length", "segment_length"}: + # shape is (1) + pass + elif name == "logits": + # shape is (batch_size, sequence_length, vocab_size) + dynamic_axes[name] = {0: "batch_size", 1: "sequence_length"} + elif name == "encoder_hidden_states": + # shape is (batch_size, num_frames // 2, hidden_size) + dynamic_axes[name] = {0: "batch_size"} + elif "past_key_self" in name or "past_value_self" in name: + # shape is (batch_size, num_heads, past_sequence_length, head_size) + dynamic_axes[name] = {0: "batch_size", 2: "past_sequence_length"} + elif "present_key_self" in name or "present_value_self" in name: + # shape is (batch_size, num_heads, past_sequence_length + sequence_length, head_size), + # which is equal to (batch_size, num_heads, total_sequence_length, head_size) + dynamic_axes[name] = {0: "batch_size", 2: "total_sequence_length"} + elif ( + "past_key_cross" in name + or "past_value_cross" in name + or "present_key_cross" in name + or "present_value_cross" in name + ): + # shape is (batch_size, num_heads, num_frames // 2, head_size) + dynamic_axes[name] = {0: "batch_size"} + elif "cross_qk" in name: + # shape is (batch_size, num_heads, source_sequence_length, target_sequence_length) + dynamic_axes[name] = {0: "batch_size", 2: "sequence_length"} + elif "jump_times" in name: + # shape is (batch_size, max_length) + dynamic_axes[name] = {0: "batch_size", 1: "max_length"} + else: + raise Exception(f"Unknown input or output name found: {name}") + return dynamic_axes diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/whisper/whisper_jump_times.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/whisper/whisper_jump_times.py new file mode 100644 index 0000000000000000000000000000000000000000..5c81867a4f7a7b7d1d39b44154fb0e06fdc9da61 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/models/whisper/whisper_jump_times.py @@ -0,0 +1,479 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +import logging +import os +import subprocess +import sys +import tempfile +import textwrap +from pathlib import Path + +import numpy as np +import onnx +import torch +import torch.nn.functional as F +import torch.utils.cpp_extension +from onnx_model import OnnxModel +from transformers import WhisperConfig +from whisper_inputs import convert_inputs_for_ort, get_model_dynamic_axes, get_sample_jump_times_inputs + +from onnxruntime import InferenceSession +from onnxruntime.tools import pytorch_export_contrib_ops + +logger = logging.getLogger(__name__) + +################################################## +# Functions that have to be outside of the class +# for torch.jit.script_if_tracing to work +################################################## + + +@torch.jit.script_if_tracing +def index_QKs(alignment_heads: torch.Tensor, QKs: list[torch.Tensor]): # noqa: N802 + """ + Compute the following to get stacked QK tensor that has been indexed for the desired attention heads: + weights = torch.stack([QKs[_l][:, _h] for _l, _h in alignment_heads], dim=1) + """ + indexed_QKs = [] # noqa: N806 + for pair in alignment_heads: + # Each QK is of shape (batch_size, num_heads, sequence_length, num_frames // 2) + # The `QKs[_l]` selects the right QK from the list of QKs + # The `QKs[_l][:, _h]` selects the right attention heads from the chosen QK. The `:` is to do this for the batch dim. + # + # PyTorch: + # QKs[_l] is of shape (batch_size, num_heads, sequence_length, num_frames // 2) + # QKs[_l][:, _h] is of shape (batch_size, sequence_length, num_frames // 2) + # + # ONNX: + # QKs[_l] is of shape (batch_size, num_heads, sequence_length, num_frames // 2) + # QKs[_l][:, _h] is of shape (batch_size, 1, sequence_length, num_frames // 2) because + # the `[:, _h]` operation maps to a Gather op and that op does not reduce dimensions + _l, _h = pair[0], pair[1] + indexed_QKs.append(QKs[_l][:, _h]) + + # PyTorch: + # torch.stack will return a tensor of shape (batch_size, num_alignment_heads, sequence_length, num_frames // 2). + # + # ONNX: + # torch.stack will return a tensor of shape (batch_size, num_alignment_heads, 1, sequence_length, num_frames // 2) + # because the Gather op does not reduce dimensions. To remove the unneeded dimension, torch.squeeze with a specified + # dim (dim = 2) is added. The torch.squeeze op with a specified dim only runs if the specified dim has a size of 1. + # Since the dim won't be of size 1 in the PyTorch tensor but it is of size 1 in the ONNX tensor, it will be a no-op + # in PyTorch and an op in ONNX. Thus, the Squeeze op will only affect the ONNX model. + weights = torch.stack(indexed_QKs, dim=1) + weights = torch.squeeze(weights, dim=2) + return weights + + +def jump_timings(text_indices, time_indices): + """ + Calculate jump times from text_indices and time_indices where + text_indices and time_indices are both 1d vectors + """ + TOKENS_PER_SECOND = 50.0 # noqa: N806 + diff = text_indices[1:] - text_indices[:-1] + padding = torch.tensor([1], dtype=torch.int32) + jumps = torch.cat((padding, diff)).to(torch.bool) + jump_times = time_indices[jumps].to(torch.float) / TOKENS_PER_SECOND + return jump_times + + +def padded_jump_from_dtw(matrix_2d: torch.Tensor, max_length: torch.Tensor): + """ + Run Dynamic Time Warping (DTW) on batched tensor + """ + trace = torch.ops.onnxruntime.DynamicTimeWarping(matrix_2d) + text_indices = trace[0, :] + time_indices = trace[1, :] + jump_times = jump_timings(text_indices, time_indices) + return F.pad(jump_times, [0, int((max_length - jump_times.size(-1)).item())], mode="constant", value=-1.0) + + +@torch.jit.script_if_tracing +def batch_jump_times(matrix: torch.Tensor, max_decoded_length: torch.Tensor): + """ + Compute the following to calculate jump times for all batches: + batched_jump_times = torch.stack([self.padded_jump_from_dtw(matrix[b], max_decoded_length) for b in range(matrix.size(0))]) + """ + list_of_jump_times = [] + for b in range(matrix.size(0)): + jump_times = padded_jump_from_dtw(matrix[b], max_decoded_length) + list_of_jump_times.append(jump_times) + batched_jump_times = torch.stack(list_of_jump_times) + return batched_jump_times + + +class WhisperJumpTimes(torch.nn.Module): + """Whisper jump times component""" + + def __init__(self, config: WhisperConfig, device: torch.device, cache_dir: str | os.PathLike): + super().__init__() + self.config = config + self.device = device + self.cache_dir = cache_dir + + self.filter_width = 7 + self.qk_scale = 1.0 + + def median_filter(self, weights: torch.Tensor): + """ + Apply a median filter of width `filter_width` along the last dimension of `weights` + """ + pad_width = self.filter_width // 2 + x = F.pad(weights, (pad_width, pad_width, 0, 0), mode="reflect") + x_unfolded = torch.ops.onnxruntime.UnfoldTensor(x, -1, self.filter_width, 1) + result = torch.select(x_unfolded.sort()[0], dim=-1, index=pad_width) + return result + + def forward( + self, + alignment_heads: torch.Tensor, + sot_sequence_length: torch.Tensor, + segment_length: torch.Tensor, + QKs: list[torch.Tensor], + ): + # Get stacked QKs tensor + weights = index_QKs(alignment_heads, QKs) + weights = weights[:, :, : segment_length // 2] + weights = weights.to(torch.float32) + + weights = (weights * self.qk_scale).softmax(dim=-1) + std, mean = torch.std_mean(weights, dim=-2, keepdim=True, unbiased=False) + weights = (weights - mean) / std + weights = self.median_filter(weights) + + matrix = torch.mean(weights, 1) + matrix = -matrix[:, sot_sequence_length:-1] + + max_decoded_length = torch.tensor([matrix.size(1)], dtype=torch.int64) + batched_jump_times = batch_jump_times(matrix, max_decoded_length) + return batched_jump_times + + def input_names(self): + input_names = [ + "alignment_heads", + "sot_sequence_length", + "segment_length", + *[f"cross_qk_{i}" for i in range(self.config.decoder_layers)], + ] + return input_names + + def output_names(self): + output_names = ["jump_times"] + return output_names + + def inputs(self, use_fp16_inputs: bool, use_int32_inputs: bool, return_dict: bool = False): + inputs = get_sample_jump_times_inputs( + self.config, + self.device, + batch_size=2, + sequence_length=8, + num_alignment_heads=6, + sot_sequence_length=3, + segment_length=1332, + use_fp16=use_fp16_inputs, + use_int32=use_int32_inputs, + ) + if return_dict: + return inputs + return ( + inputs["alignment_heads"], + inputs["sot_sequence_length"], + inputs["segment_length"], + inputs["QKs"], + ) + + def create_torch_ops(self): + """ + 1) Create UnfoldTensor and DynamicTimeWarping as torch ops + 3) Provide a symbolic mapping from torch ops to ORT contrib ops + + See https://pytorch.org/tutorials/advanced/torch_script_custom_ops.html#building-with-jit-compilation + for more details on how this works. + """ + # Set torch extensions directory to cache directory + os.environ["TORCH_EXTENSIONS_DIR"] = self.cache_dir + + # Try to import `ninja` pip package + try: + assert torch.utils.cpp_extension.verify_ninja_availability() + except Exception as e: + logger.error(f"An error occurred while verifying `ninja` is available: {e}", exc_info=True) # noqa: G201 + install_cmd = [sys.executable, "-m", "pip", "install", "ninja"] + logger.warning("Could not import `ninja`. Attempting to install `ninja` via `%s`.", " ".join(install_cmd)) + subprocess.run(install_cmd, check=True) + + # Create UnfoldTensor torch op + unfold_op_source = textwrap.dedent("""\ + #include "torch/script.h" + + torch::Tensor UnfoldTensor(torch::Tensor input, int64_t dim, int64_t size, int64_t step) { + return input.unfold(dim, size, step); + } + + // namespace is onnxruntime + static auto registry = torch::RegisterOperators("onnxruntime::UnfoldTensor", &UnfoldTensor); + """) + + torch.utils.cpp_extension.load_inline( + name="UnfoldTensor", + cpp_sources=unfold_op_source, + is_python_module=False, + verbose=True, + ) + + # Create DynamicTimeWarping torch op + dtw_op_source = textwrap.dedent("""\ + #include "torch/script.h" + #include "torch/torch.h" + #include + #include + #include + + torch::Tensor Backtrace(torch::Tensor trace) { + int64_t i = trace.size(0) - 1; + int64_t j = trace.size(1) - 1; + trace.index({0, torch::indexing::Slice()}) = 2; + trace.index({torch::indexing::Slice(), 0}) = 1; + + std::vector result_vec; + while (i > 0 || j > 0) { + result_vec.push_back(static_cast(i - 1)); + result_vec.push_back(static_cast(j - 1)); + int value = trace[i][j].item(); + + if (value == 0) { + i--; + j--; + } else if (value == 1) { + i--; + } else if (value == 2) { + j--; + } else { + throw std::runtime_error("Unexpected trace[i, j]"); + } + } + + // Compute result[::-1, :].T + torch::Tensor result = torch::from_blob(result_vec.data(), {static_cast(result_vec.size() / 2), 2}, torch::kInt32).clone(); + torch::Tensor reversed = result.flip(0); // result[::-1, :] + torch::Tensor transposed = reversed.transpose(0, 1); // .T + return transposed; + } + + torch::Tensor DynamicTimeWarping(torch::Tensor x) { + int64_t N = x.size(0); + int64_t M = x.size(1); + torch::Tensor cost = torch::full({N + 1, M + 1}, std::numeric_limits::infinity(), torch::dtype(torch::kFloat32)); + torch::Tensor trace = torch::full({N + 1, M + 1}, -1, torch::dtype(torch::kFloat32)); + + cost[0][0] = 0; + for (int j = 1; j < M + 1; j++) { + for (int i = 1; i < N + 1; i++) { + float c0 = cost[i - 1][j - 1].item(); + float c1 = cost[i - 1][j].item(); + float c2 = cost[i][j - 1].item(); + + float c = 0; + float t = 0; + + if (c0 < c1 && c0 < c2) { + c = c0; + t = 0; + } else if (c1 < c0 && c1 < c2) { + c = c1; + t = 1; + } else { + c = c2; + t = 2; + } + + cost[i][j] = x[i - 1][j - 1].item() + c; + trace[i][j] = t; + } + } + + return Backtrace(trace); + } + + // namespace is onnxruntime + static auto registry = torch::RegisterOperators("onnxruntime::DynamicTimeWarping", &DynamicTimeWarping); + """) + + torch.utils.cpp_extension.load_inline( + name="DynamicTimeWarping", + cpp_sources=dtw_op_source, + is_python_module=False, + verbose=True, + ) + + # Create symbolic mapping from torch ops to ORT contrib ops + pytorch_export_contrib_ops.register() + + def export_onnx( + self, + onnx_model_path: str, + provider: str, + verbose: bool = True, + use_external_data_format: bool = False, + use_fp16_inputs: bool = False, + use_int32_inputs: bool = True, + ): + """Export word-level timestamps to ONNX + + Args: + onnx_model_path (str): path to save ONNX model + provider (str): provider to use for verifying parity on ONNX model + verbose (bool, optional): print verbose information. Defaults to True. + use_external_data_format (bool, optional): use external data format or not. Defaults to False. + use_fp16_inputs (bool, optional): use float16 inputs for the audio_features. Defaults to False. + use_int32_inputs (bool, optional): use int32 inputs for the decoder_input_ids. Defaults to True. + """ + # Shape of timestamps's tensors: + # Inputs: + # alignment_heads: (num_alignment_heads, 2) + # sot_sequence_length: (1) + # segment_length: (1) + # cross_qk_*: (batch_size, num_heads, sequence_length, num_frames // 2) + # Outputs: + # jump_times: (batch_size, max_length) + + # Definitions: + # alignment_heads: the attention head indices where the Q*K values are highly correlated with word-level timestamps + # (i.e. the alignment between audio and text tokens) + # This is calculated as follows: + # + # ``` + # import base64 + # import gzip + # import numpy as np + # import torch + # + # # base85-encoded (n_layers, n_heads) boolean arrays indicating the cross-attention heads that are + # # highly correlated to the word-level timing, i.e. the alignment between audio and text tokens. + # _ALIGNMENT_HEADS = { + # "tiny.en": b"ABzY8J1N>@0{>%R00Bk>$p{7v037`oCl~+#00", + # "tiny": b"ABzY8bu8Lr0{>%RKn9Fp%m@SkK7Kt=7ytkO", + # "base.en": b"ABzY8;40c<0{>%RzzG;p*o+Vo09|#PsxSZm00", + # "base": b"ABzY8KQ!870{>%RzyTQH3`Q^yNP!>##QT-?_)10{>%RpeA61k&I|OI3I$65C{;;pbCHh0B{qLQ;+}v00", + # "small": b"ABzY8DmU6=0{>%Rpa?J`kvJ6qF(V^F86#Xh7JUGMK}P%R7%R7}kK1fFL7w6%<-Pf*t^=N)Qr&0RR9", + # "large-v1": b"ABzY8r9j$a0{>%R7#4sLmoOs{s)o3~84-RPdcFk!JR%R7=D0pU<_bnWW*tkYAhobTNnu$jnkEkXqp)j;w1Tzk)UH3X%SZd&fFZ2fC2yj", + # "large-v3": b"ABzY8gWO1E0{>%R7(9S+Kn!D~%ngiGaR?*L!iJG9p-nab0JQ=-{D1-g00", + # "large": b"ABzY8gWO1E0{>%R7(9S+Kn!D~%ngiGaR?*L!iJG9p-nab0JQ=-{D1-g00", + # "large-v3-turbo": b"ABzY8j^C+e0{>%RARaKHP%t(lGR*)0g!tONPyhe`", + # "turbo": b"ABzY8j^C+e0{>%RARaKHP%t(lGR*)0g!tONPyhe`", + # } + # + # model_name = "large-v3-turbo" + # array = np.frombuffer( + # gzip.decompress(base64.b85decode(_ALIGNMENT_HEADS[model_name])), dtype=bool + # ).copy() + # mask = torch.from_numpy(array).reshape( + # self.dims.n_text_layer, self.dims.n_text_head + # ) + # self.alignment_heads = mask.to_sparse().indices().T + # ``` + # + # sot_sequence_length: the length of the start-of-transcription sequence before the first token is generated + # Typically the start-of-transcription sequence is [<|startoftranscription|>, <|language_token|>, <|task_token|>] + # so its length is 3. + # + # segment_length: the length (in frames) of the audio segment that is being transcribed + # + # cross_qk_*: the Q*K values for the cross-attention blocks in the decoder + # Every decoder layer has a self-attention block and a cross-attention block so there are `n` cross-attention blocks + # where `n` is the number of decoder layers. + # + # jump_times: the timings where jumps occur in speech + # This allows us to detect when a word began to be spoken by the speaker (start_times) and when a word was finished + # being spoken by the speaker (end_times). + + inputs = self.inputs(use_fp16_inputs=use_fp16_inputs, use_int32_inputs=use_int32_inputs) + input_names = self.input_names() + output_names = self.output_names() + dynamic_axes = get_model_dynamic_axes(self.config, input_names, output_names) + + Path(onnx_model_path).parent.mkdir(parents=True, exist_ok=True) + with tempfile.TemporaryDirectory() as tmp_dir_name: + temp_onnx_model_path = os.path.join(tmp_dir_name, "encoder.onnx") + Path(temp_onnx_model_path).parent.mkdir(parents=True, exist_ok=True) + out_path = temp_onnx_model_path if use_external_data_format else onnx_model_path + + # Create torch ops and map them to ORT contrib ops before export + self.create_torch_ops() + torch.onnx.export( + self, + args=inputs, + f=out_path, + export_params=True, + input_names=input_names, + output_names=output_names, + dynamic_axes=dynamic_axes, + opset_version=17, + do_constant_folding=True, + verbose=verbose, + custom_opsets={"com.microsoft": 1}, + ) + + if use_external_data_format: + model = onnx.load_model(out_path, load_external_data=use_external_data_format) + OnnxModel.save( + model, + onnx_model_path, + save_as_external_data=True, + all_tensors_to_one_file=True, + ) + + self.verify_onnx(onnx_model_path, provider, use_fp16_inputs, use_int32_inputs) + + def verify_onnx( + self, + onnx_model_path: str, + provider: str, + use_fp16_inputs: bool, + use_int32_inputs: bool, + ): + """Verify ONNX model outputs and PyTorch model outputs match + + Args: + onnx_model_path (str): path to save ONNX model + provider (str): execution provider for ONNX model + use_fp16_inputs (bool, optional): use float16 inputs for the cross_qk_{i} + use_int32_inputs (bool, optional): use int32 inputs for the alignment_heads and sot_sequence_length + """ + # Shape of jump times's tensors: + # Inputs: + # alignment_heads: (num_alignment_heads, 2) + # sot_sequence_length: (1) + # segment_length: (1) + # cross_qk_*: (batch_size, num_heads, sequence_length, num_frames // 2) + # Outputs: + # jump_times: (batch_size, max_length) + inputs = self.inputs(use_fp16_inputs=use_fp16_inputs, use_int32_inputs=use_int32_inputs, return_dict=True) + + # Run PyTorch model + pt_outputs = ( + self.forward( + inputs["alignment_heads"], inputs["sot_sequence_length"], inputs["segment_length"], inputs["QKs"] + ) + .detach() + .cpu() + .numpy() + ) + + # Run ONNX model + sess = InferenceSession(onnx_model_path, providers=[provider]) + ort_outputs = sess.run(None, convert_inputs_for_ort(inputs, sess)) + + # Calculate output difference + diff = np.abs(pt_outputs - ort_outputs) + print("Comparing batched jump_times...", flush=True) + print(f"Max diff: {np.max(diff)}", flush=True) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/onnx_exporter.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/onnx_exporter.py new file mode 100644 index 0000000000000000000000000000000000000000..6b8cadc41c3b3eba2c9103cb3ed23233b07262ca --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/onnx_exporter.py @@ -0,0 +1,719 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +import logging +import os +from pathlib import Path + +import numpy +import torch +from affinity_helper import AffinitySetting +from benchmark_helper import OptimizerInfo, Precision, create_onnxruntime_session +from huggingface_models import MODEL_CLASSES +from quantize_helper import QuantizeHelper +from torch_onnx_export_helper import torch_onnx_export +from transformers import AutoConfig, AutoFeatureExtractor, AutoTokenizer, LxmertConfig, TransfoXLConfig + +from onnxruntime.transformers.models.gpt2.gpt2_helper import ( + PRETRAINED_GPT2_MODELS, + GPT2ModelNoPastState, + TFGPT2ModelNoPastState, +) + +os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2" + +logger = logging.getLogger(__name__) + +# Workaround by replacing torch.triu using self-defined op +# Since torch.triu cannot be exported to ONNX. See https://github.com/pytorch/pytorch/issues/32968 +torch_func = {"triu": torch.triu} + + +def triu_onnx(x, diagonal=0, out=None): + assert out is None + assert len(x.shape) == 2 and x.size(0) == x.size(1) + + torch_triu = torch_func["triu"] + template = torch_triu(torch.ones((1024, 1024), dtype=torch.uint8), diagonal) + mask = template[: x.size(0), : x.size(1)] + return torch.where(mask.bool(), x, torch.zeros_like(x)) + + +def replace_torch_functions(): + torch.triu = triu_onnx + + +def restore_torch_functions(): + torch.triu = torch_func["triu"] + + +def create_onnxruntime_input(vocab_size, batch_size, sequence_length, input_names, config, data_type=numpy.int64): + if config.model_type in ["vit", "swin"]: + input_ids = numpy.random.rand(batch_size, 3, config.image_size, config.image_size).astype(numpy.float32) + inputs = {"pixel_values": input_ids} + return inputs + + input_ids = numpy.random.randint(low=0, high=vocab_size - 1, size=(batch_size, sequence_length), dtype=data_type) + inputs = {"input_ids": input_ids} + + if "attention_mask" in input_names: + attention_mask = numpy.ones([batch_size, sequence_length], dtype=data_type) + inputs["attention_mask"] = attention_mask + + if "token_type_ids" in input_names: + segment_ids = numpy.zeros([batch_size, sequence_length], dtype=data_type) + inputs["token_type_ids"] = segment_ids + + if config.is_encoder_decoder: + inputs["decoder_input_ids"] = input_ids + + if isinstance(config, LxmertConfig): + inputs["visual_feats"] = numpy.random.randn(1, 1, config.visual_feat_dim).astype(numpy.float32) + inputs["visual_pos"] = numpy.random.randn(1, 1, config.visual_pos_dim).astype(numpy.float32) + if isinstance(config, TransfoXLConfig): + inputs["tf_transfo_xl_model/transformer/pos_emb/einsum/Einsum/inputs_1:0"] = numpy.zeros( + [config.hidden_size], dtype=numpy.float32 + ) + return inputs + + +def filter_inputs(inputs, input_names): + remaining_model_inputs = {} + for input_name in input_names: + if input_name in inputs: + remaining_model_inputs[input_name] = inputs[input_name] + return remaining_model_inputs + + +def flatten(inputs): + return [[flatten(i) for i in inputs] if isinstance(inputs, (list, tuple)) else inputs] + + +def update_flatten_list(inputs, res_list): + for i in inputs: + res_list.append(i) if not isinstance(i, (list, tuple)) else update_flatten_list(i, res_list) + return res_list + + +def build_dynamic_axes(example_inputs, outputs_flatten): + sequence_length = example_inputs["input_ids"].shape[-1] + + dynamic_axes = {key: {0: "batch_size", 1: "seq_len"} for key in example_inputs} + + output_names = ["output_" + str(i + 1) for i in range(len(outputs_flatten))] + for i, output_name in enumerate(output_names): + dynamic_axes[output_name] = {0: "batch_size"} + dims = outputs_flatten[i].shape + for j, dim in enumerate(dims): + if dim == sequence_length: + dynamic_axes[output_name].update({j: "seq_len"}) + return dynamic_axes, output_names + + +def validate_onnx_model( + onnx_model_path, + example_inputs, + example_outputs_flatten, + use_gpu, + fp16, + output_names=None, +): + test_session = create_onnxruntime_session(onnx_model_path, use_gpu, enable_all_optimization=False) + if test_session is None: + logger.error(f"{onnx_model_path} is an invalid ONNX model") + return False + + logger.info(f"{onnx_model_path} is a valid ONNX model") + + # Compare the inference result with PyTorch or Tensorflow + example_ort_inputs = {k: t.numpy() for k, t in example_inputs.items()} + example_ort_outputs = test_session.run(output_names, example_ort_inputs) + if len(example_outputs_flatten) != len(example_ort_outputs): + logger.error( + f"Number of output tensors expected {len(example_outputs_flatten)}, got {len(example_ort_outputs)}" + ) + return False + + for i in range(len(example_outputs_flatten)): + abs_diff = numpy.amax(numpy.abs(example_ort_outputs[i] - example_outputs_flatten[i].cpu().numpy())) + if abs_diff > 1e-4: + logger.info(f"Max absolute diff={abs_diff} for output tensor {i}") + + rtol = 5e-02 if fp16 else 1e-4 + atol = 1e-01 if fp16 else 1e-4 + if not numpy.allclose( + example_ort_outputs[i], + example_outputs_flatten[i].cpu().numpy(), + rtol=rtol, + atol=atol, + ): + logger.error(f"Output tensor {i} is not close: rtol={rtol}, atol={atol}") + return False + + logger.info(f"inference result of onnxruntime is validated on {onnx_model_path}") + return True + + +def get_onnx_file_path( + onnx_dir: str, + model_name: str, + input_count: int, + optimized_by_script: bool, + use_gpu: bool, + precision: Precision, + optimized_by_onnxruntime: bool, + use_external_data: bool, +): + from re import sub # noqa: PLC0415 + + normalized_model_name = sub(r"[^a-zA-Z0-9_]", "_", model_name) + + if not optimized_by_script: + filename = f"{normalized_model_name}_{input_count}" + else: + device = "gpu" if use_gpu else "cpu" + filename = f"{normalized_model_name}_{input_count}_{precision}_{device}" + + if optimized_by_onnxruntime: + filename += "_ort" + + directory = onnx_dir + # ONNXRuntime will not write external data so the raw and optimized models shall be in same directory. + if use_external_data and not optimized_by_onnxruntime: + directory = os.path.join(onnx_dir, filename) + if not os.path.exists(directory): + os.makedirs(directory) + + return os.path.join(directory, f"{filename}.onnx") + + +def add_filename_suffix(file_path: str, suffix: str) -> str: + """ + Append a suffix at the filename (before the extension). + Args: + path: pathlib.Path The actual path object we would like to add a suffix + suffix: The suffix to add + Returns: path with suffix appended at the end of the filename and before extension + """ + path = Path(file_path) + return str(path.parent.joinpath(path.stem + suffix).with_suffix(path.suffix)) + + +def optimize_onnx_model_by_ort(onnx_model_path, ort_model_path, use_gpu, overwrite, model_fusion_statistics): + if overwrite or not os.path.exists(ort_model_path): + Path(ort_model_path).parent.mkdir(parents=True, exist_ok=True) + from optimizer import get_fusion_statistics, optimize_by_onnxruntime # noqa: PLC0415 + + # Use onnxruntime to optimize model, which will be saved to *_ort.onnx + _ = optimize_by_onnxruntime( + onnx_model_path, + use_gpu=use_gpu, + optimized_model_path=ort_model_path, + opt_level=99, + ) + model_fusion_statistics[ort_model_path] = get_fusion_statistics(ort_model_path) + else: + logger.info(f"Skip optimization since model existed: {ort_model_path}") + + +def optimize_onnx_model( + onnx_model_path, + optimized_model_path, + model_type, + num_attention_heads, + hidden_size, + use_gpu, + precision, + use_raw_attention_mask, + overwrite, + model_fusion_statistics, + use_external_data_format, + optimization_options=None, +): + if overwrite or not os.path.exists(optimized_model_path): + Path(optimized_model_path).parent.mkdir(parents=True, exist_ok=True) + + from fusion_options import FusionOptions # noqa: PLC0415 + from optimizer import optimize_model # noqa: PLC0415 + + if optimization_options is None: + optimization_options = FusionOptions(model_type) + optimization_options.use_raw_attention_mask(use_raw_attention_mask) + if precision == Precision.FLOAT16: + optimization_options.enable_gelu_approximation = True + if precision == Precision.INT8: + optimization_options.enable_embed_layer_norm = False + + # For swin models, the num_attention_heads is a list, which isn't supported yet, so set to 0 for now + if model_type == "swin": + num_attention_heads = 0 + hidden_size = 0 + + # Use script to optimize model. + # Use opt_level <= 1 for models to be converted to fp16, because some fused op (like FusedGemm) has only fp32 and no fp16. + # It is better to be conservative so we use opt_level=0 here, in case MemcpyFromHost is added to the graph by OnnxRuntime. + opt_model = optimize_model( + onnx_model_path, + model_type, + num_heads=num_attention_heads, + hidden_size=hidden_size, + opt_level=0, + optimization_options=optimization_options, + use_gpu=use_gpu, + only_onnxruntime=False, + ) + if model_type == "bert_keras" or model_type == "bert_tf": + opt_model.use_dynamic_axes() + + model_fusion_statistics[optimized_model_path] = opt_model.get_fused_operator_statistics() + + if precision == Precision.FLOAT16: + opt_model.convert_float_to_float16(keep_io_types=True) + + opt_model.save_model_to_file(optimized_model_path, use_external_data_format) + else: + logger.info(f"Skip optimization since model existed: {optimized_model_path}") + + +def modelclass_dispatcher(model_name, custom_model_class): + if custom_model_class is not None: + if custom_model_class in MODEL_CLASSES: + return custom_model_class + else: + raise Exception("Valid model class: " + " ".join(MODEL_CLASSES)) + + if model_name in PRETRAINED_GPT2_MODELS: + return "GPT2ModelNoPastState" + + import re # noqa: PLC0415 + + if re.search("-squad$", model_name) is not None: + return "AutoModelForQuestionAnswering" + elif re.search("-mprc$", model_name) is not None: + return "AutoModelForSequenceClassification" + elif re.search("gpt2", model_name) is not None: + return "AutoModelWithLMHead" + + return "AutoModel" + + +def load_pretrained_model(model_name, config, cache_dir, custom_model_class, is_tf_model=False): + model_class_name = modelclass_dispatcher(model_name, custom_model_class) + + if model_class_name == "GPT2ModelNoPastState": + if is_tf_model: + return TFGPT2ModelNoPastState.from_pretrained(model_name, config=config, cache_dir=cache_dir) + else: + return GPT2ModelNoPastState.from_pretrained(model_name, config=config, cache_dir=cache_dir) + + if is_tf_model: + model_class_name = "TF" + model_class_name + + transformers_module = __import__("transformers", fromlist=[model_class_name]) + logger.info(f"Model class name: {model_class_name}") + model_class = getattr(transformers_module, model_class_name) + + return model_class.from_pretrained(model_name, config=config, cache_dir=cache_dir) + + +def load_pt_model(model_name, model_class, cache_dir, config_modifier): + config = AutoConfig.from_pretrained(model_name, cache_dir=cache_dir) + if hasattr(config, "return_dict"): + config.return_dict = False + + config_modifier.modify(config) + + model = load_pretrained_model(model_name, config=config, cache_dir=cache_dir, custom_model_class=model_class) + + return config, model + + +def load_tf_model(model_name, model_class, cache_dir, config_modifier): + config = AutoConfig.from_pretrained(model_name, cache_dir=cache_dir) + + config_modifier.modify(config) + # Loading tf model from transformers limits the cpu affinity to {0} when KMP_AFFINITY is set + # Restore the affinity after model loading for expected ORT performance + affinity_setting = AffinitySetting() + affinity_setting.get_affinity() + model = load_pretrained_model( + model_name, + config=config, + cache_dir=cache_dir, + custom_model_class=model_class, + is_tf_model=True, + ) + affinity_setting.set_affinity() + + return config, model + + +# For test only +def load_pt_model_from_tf(model_name): + # Note that we could get pt model from tf, but model source and its structure in this case is different from directly using + # load_pt_model() and load_tf_model() even with the same name. Therefore it should not be used for comparing with them + from convert_tf_models_to_pytorch import tf2pt_pipeline # noqa: PLC0415 + + config, model = tf2pt_pipeline(model_name) + + return config, model + + +def validate_and_optimize_onnx( + model_name, + use_external_data_format, + model_type, + onnx_dir, + input_names, + use_gpu, + precision, + optimize_info, + validate_onnx, + use_raw_attention_mask, + overwrite, + config, + model_fusion_statistics, + onnx_model_path, + example_inputs, + example_outputs_flatten, + output_names, + fusion_options, +): + is_valid_onnx_model = True + if validate_onnx: + is_valid_onnx_model = validate_onnx_model( + onnx_model_path, + example_inputs, + example_outputs_flatten, + use_gpu, + False, + output_names, + ) + if optimize_info.name == OptimizerInfo.NOOPT.name: + return onnx_model_path, is_valid_onnx_model, config.vocab_size + + if ( + optimize_info.name == OptimizerInfo.BYSCRIPT.name + or precision == Precision.FLOAT16 + or precision == Precision.INT8 + ): # Use script (optimizer.py) to optimize + optimized_model_path = get_onnx_file_path( + onnx_dir, + model_name, + len(input_names), + True, + use_gpu, + precision, + False, + use_external_data_format, + ) + optimize_onnx_model( + onnx_model_path, + optimized_model_path, + model_type, + config.num_attention_heads, + config.hidden_size, + use_gpu, + precision, + use_raw_attention_mask, + overwrite, + model_fusion_statistics, + use_external_data_format, + fusion_options, + ) + + onnx_model_path = optimized_model_path + if validate_onnx: + is_valid_onnx_model = validate_onnx_model( + onnx_model_path, + example_inputs, + example_outputs_flatten, + use_gpu, + precision == Precision.FLOAT16, + output_names, + ) + + if precision == Precision.INT8: + logger.info(f"Quantizing model: {onnx_model_path}") + QuantizeHelper.quantize_onnx_model(onnx_model_path, onnx_model_path, use_external_data_format) + logger.info(f"Finished quantizing model: {onnx_model_path}") + + if optimize_info.name == OptimizerInfo.BYORT.name: # Use OnnxRuntime to optimize + if is_valid_onnx_model: + ort_model_path = add_filename_suffix(onnx_model_path, "_ort") + optimize_onnx_model_by_ort( + onnx_model_path, + ort_model_path, + use_gpu, + overwrite, + model_fusion_statistics, + ) + + return ( + onnx_model_path, + is_valid_onnx_model, + config.num_labels if model_type in ["vit", "swin"] else config.vocab_size, + ) + + +def export_onnx_model_from_pt( + model_name, + opset_version, + use_external_data_format, + model_type, + model_class, + config_modifier, + cache_dir, + onnx_dir, + input_names, + use_gpu, + precision, + optimizer_info, + validate_onnx, + use_raw_attention_mask, + overwrite, + model_fusion_statistics, + fusion_options, +): + config, model = load_pt_model(model_name, model_class, cache_dir, config_modifier) + # config, model = load_pt_model_from_tf(model_name) + model.cpu() + + example_inputs = None + max_input_size = None + + if model_type in ["vit", "swin"]: + image_processor = AutoFeatureExtractor.from_pretrained(model_name, cache_dir=cache_dir) + data = numpy.random.randint( + low=0, high=256, size=config.image_size * config.image_size * 3, dtype=numpy.uint8 + ).reshape(config.image_size, config.image_size, 3) + + example_inputs = image_processor(data, return_tensors="pt") + else: + tokenizer = AutoTokenizer.from_pretrained(model_name, cache_dir=cache_dir) + max_input_size = tokenizer.model_max_length + example_inputs = tokenizer.encode_plus("This is a sample input", return_tensors="pt") + + example_inputs = filter_inputs(example_inputs, input_names) + + example_outputs = model(**example_inputs) + + assert isinstance(example_outputs, (list, tuple)), f"type of output is not list or tuple: {type(example_outputs)}" + + # Flatten is needed for gpt2 and distilgpt2. + example_outputs_flatten = flatten(example_outputs) + example_outputs_flatten = update_flatten_list(example_outputs_flatten, []) + + onnx_model_path = get_onnx_file_path( + onnx_dir, + model_name, + len(input_names), + False, + use_gpu, + precision, + False, + use_external_data_format, + ) + + if overwrite or not os.path.exists(onnx_model_path): + logger.info(f"Exporting ONNX model to {onnx_model_path}") + Path(onnx_model_path).parent.mkdir(parents=True, exist_ok=True) + + dynamic_axes = None + output_names = None + + if model_type in ["vit", "swin"]: + dynamic_axes, output_names = {key: {0: "pixel_values"} for key in example_inputs}, ["logits"] + else: + dynamic_axes, output_names = build_dynamic_axes(example_inputs, example_outputs_flatten) + + replace_torch_functions() + torch_onnx_export( + model=model, + args=tuple(example_inputs.values()), + f=onnx_model_path, + input_names=list(example_inputs.keys()), + output_names=output_names, + dynamic_axes=dynamic_axes, + do_constant_folding=True, + opset_version=opset_version, + use_external_data_format=use_external_data_format, + ) + restore_torch_functions() + else: + logger.info(f"Skip export since model existed: {onnx_model_path}") + + onnx_model_file, is_valid_onnx_model, vocab_size = validate_and_optimize_onnx( + model_name, + use_external_data_format, + model_type, + onnx_dir, + input_names, + use_gpu, + precision, + optimizer_info, + validate_onnx, + use_raw_attention_mask, + overwrite, + config, + model_fusion_statistics, + onnx_model_path, + example_inputs, + example_outputs_flatten, + None, + fusion_options, + ) + + return onnx_model_file, is_valid_onnx_model, vocab_size, max_input_size + + +def export_onnx_model_from_tf( + model_name, + opset_version, + use_external_data_format, + model_type, + model_class, + config_modifier, + cache_dir, + onnx_dir, + input_names, + use_gpu, + precision, + optimizer_info, + validate_onnx, + use_raw_attention_mask, + overwrite, + model_fusion_statistics, + fusion_options, +): + # Use CPU to export + import tensorflow as tf # noqa: PLC0415 + + tf.config.set_visible_devices([], "GPU") + + tokenizer = AutoTokenizer.from_pretrained(model_name, cache_dir=cache_dir) + # Fix "Using pad_token, but it is not set yet" error. + if tokenizer.pad_token is None: + tokenizer.add_special_tokens({"pad_token": "[PAD]"}) + max_input_size = tokenizer.model_max_length + + config, model = load_tf_model(model_name, model_class, cache_dir, config_modifier) + model.resize_token_embeddings(len(tokenizer)) + + example_inputs = tokenizer.encode_plus( + "This is a sample input", + return_tensors="tf", + max_length=max_input_size, + padding="max_length", + truncation=True, + ) + example_inputs = filter_inputs(example_inputs, input_names) + + if config.is_encoder_decoder: + example_inputs["decoder_input_ids"] = tokenizer.encode_plus( + "This is a sample input", + return_tensors="tf", + max_length=max_input_size, + padding="max_length", + truncation=True, + ).input_ids + if model_name == "unc-nlp/lxmert-base-uncased": + example_inputs["visual_feats"] = tf.random.normal([1, 1, config.visual_feat_dim]) + example_inputs["visual_pos"] = tf.random.normal([1, 1, config.visual_pos_dim]) + + try: + # Use no past state for these models + if config.use_cache: + config.use_cache = False + except Exception: + pass + + example_outputs = model(example_inputs, training=False) + output_names = None + + # For xlnet models, only compare the last_hidden_state output. + if model_name == "xlnet-base-cased" or model_name == "xlnet-large-cased": + output_names = ["last_hidden_state"] + example_outputs = example_outputs["last_hidden_state"] + + # Flatten is needed for gpt2 and distilgpt2. Output name sorting is needed for tf2onnx outputs to match onnx outputs. + from tensorflow.python.util import nest # noqa: PLC0415 + + example_outputs_flatten = nest.flatten(example_outputs) + + onnx_model_path = get_onnx_file_path( + onnx_dir, + model_name, + len(input_names), + False, + use_gpu, + precision, + False, + use_external_data_format, + ) + tf_internal_model_path = onnx_model_path[:-5] if use_external_data_format else onnx_model_path + + if overwrite or not os.path.exists(tf_internal_model_path): + logger.info(f"Exporting ONNX model to {onnx_model_path}") + if not use_external_data_format: + Path(tf_internal_model_path).parent.mkdir(parents=True, exist_ok=True) + + import zipfile # noqa: PLC0415 + + import tf2onnx # noqa: PLC0415 + + tf2onnx.logging.set_level(tf2onnx.logging.ERROR) + specs = [] + for name, value in example_inputs.items(): + dims = [None] * len(value.shape) + specs.append(tf.TensorSpec(tuple(dims), value.dtype, name=name)) + _, _ = tf2onnx.convert.from_keras( + model, + input_signature=tuple(specs), + opset=opset_version, + large_model=use_external_data_format, + output_path=tf_internal_model_path, + ) + if use_external_data_format: + # need to unpack the zip for run_onnxruntime() + with zipfile.ZipFile(tf_internal_model_path, "r") as z: + z.extractall(os.path.dirname(tf_internal_model_path)) + tf_internal_model_path = os.path.join(os.path.dirname(tf_internal_model_path), "__MODEL_PROTO.onnx") + if os.path.exists(onnx_model_path): + os.remove(onnx_model_path) + os.rename(tf_internal_model_path, onnx_model_path) + + else: + logger.info(f"Skip export since model existed: {onnx_model_path}") + + model_type = model_type + "_tf" + optimized_onnx_path, is_valid_onnx_model, vocab_size = validate_and_optimize_onnx( + model_name, + use_external_data_format, + model_type, + onnx_dir, + input_names, + use_gpu, + precision, + optimizer_info, + validate_onnx, + use_raw_attention_mask, + overwrite, + config, + model_fusion_statistics, + onnx_model_path, + example_inputs, + example_outputs_flatten, + output_names, + fusion_options, + ) + + return ( + optimized_onnx_path, + is_valid_onnx_model, + vocab_size, + max_input_size, + ) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/onnx_model.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/onnx_model.py new file mode 100644 index 0000000000000000000000000000000000000000..ad1151b216b1b7817703a82d9ecf06d8ed56e21d --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/onnx_model.py @@ -0,0 +1,1636 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +# -------------------------------------------------------------------------- + +import itertools +import logging +import os +import sys +from collections import deque +from pathlib import Path + +from float16 import convert_float_to_float16 +from onnx import ( + AttributeProto, + GraphProto, + ModelProto, + NodeProto, + TensorProto, + ValueInfoProto, + helper, + numpy_helper, + save_model, +) +from onnx.external_data_helper import load_external_data_for_tensor, uses_external_data +from shape_infer_helper import SymbolicShapeInferenceHelper + +logger = logging.getLogger(__name__) + + +class OnnxModel: + def __init__(self, model): + self.initialize(model) + + def initialize(self, model): + self.model: ModelProto = model + self._node_name_suffix: dict[str, int] = {} # key is node name prefix, value is the last suffix generated + self.shape_infer_helper: SymbolicShapeInferenceHelper = None + self.enable_shape_infer: bool = True + self.all_graphs: list[GraphProto] | None = None + + # Cache of shape and data type from onnx graph to speed up optimization. + # Be careful that fusion shall not reuse node output name for different shape/type (in adding/removing nodes) + # Note that these do not cache the symbolic shape inference result. + self._dtype_dict: dict[str, int] | None = None + self._shape_dict: dict[str, list] | None = None + + def disable_shape_inference(self): + self.enable_shape_infer = False + + def infer_runtime_shape(self, dynamic_axis_mapping={}, update=False): # noqa: B006 + if self.enable_shape_infer: + if self.shape_infer_helper is None or update: + self.shape_infer_helper = SymbolicShapeInferenceHelper(self.model) + + try: + if self.shape_infer_helper.infer(dynamic_axis_mapping): + return self.shape_infer_helper + except Exception: + self.enable_shape_infer = False # disable shape inference to suppress same error message. + print("failed in shape inference", sys.exc_info()[0]) + + return None + + def input_name_to_nodes(self, exclude_subgraphs=False): + input_name_to_nodes = {} + nodes_to_search = self.nodes() if not exclude_subgraphs else self.model.graph.node + for node in nodes_to_search: + for input_name in node.input: + if input_name: # could be empty when it is optional + if input_name not in input_name_to_nodes: + input_name_to_nodes[input_name] = [node] + else: + input_name_to_nodes[input_name].append(node) + return input_name_to_nodes + + def output_name_to_node(self, exclude_subgraphs=False): + output_name_to_node = {} + nodes_to_search = self.nodes() if not exclude_subgraphs else self.model.graph.node + for node in nodes_to_search: + for output_name in node.output: + if output_name: # could be empty when it is optional + output_name_to_node[output_name] = node + return output_name_to_node + + def functions(self): + all_functions = [list(self.model.functions)] + return all_functions + + def nodes(self): + all_nodes = [] + for graph in self.graphs(): + for node in graph.node: + all_nodes.append(node) # noqa: PERF402 + return all_nodes + + def graph(self): + return self.model.graph + + def graphs(self): + if self.all_graphs is not None: + return self.all_graphs + self.all_graphs = [] + graph_queue = [self.model.graph] + while graph_queue: + graph = graph_queue.pop(0) + self.all_graphs.append(graph) + for node in graph.node: + for attr in node.attribute: + if attr.type == AttributeProto.AttributeType.GRAPH: + assert isinstance(attr.g, GraphProto) + graph_queue.append(attr.g) + if attr.type == AttributeProto.AttributeType.GRAPHS: + for g in attr.graphs: + assert isinstance(g, GraphProto) + graph_queue.append(g) + return self.all_graphs + + def get_graphs_input_names(self): + input_names = [] + for graph in self.graphs(): + for input in graph.input: + input_names.append(input.name) + return input_names + + def get_graphs_output_names(self): + output_names = [] + for graph in self.graphs(): + for output in graph.output: + output_names.append(output.name) + return output_names + + def get_graph_by_node(self, node): + for graph in self.graphs(): + if node in graph.node: + return graph + return None + + def get_graph_by_name(self, graph_name): + for graph in self.graphs(): + if graph_name == graph.name: + return graph + return None + + def get_topological_insert_id(self, graph, outputs): + for idx, node in enumerate(graph.node): + for input in node.input: + if input in outputs: + return idx + return len(graph.node) + + def remove_node(self, node): + for graph in self.graphs(): + if node in graph.node: + graph.node.remove(node) + return + logger.warning("Failed to remove node %s", node) # It might be a bug to hit this line. + + def remove_nodes(self, nodes_to_remove): + for node in nodes_to_remove: + self.remove_node(node) + + def add_node(self, node, graph_name=None): + if graph_name is None or graph_name == self.model.graph.name: + self.model.graph.node.extend([node]) + else: + graph = self.get_graph_by_name(graph_name) + insert_idx = self.get_topological_insert_id(graph, node.output) + graph.node.insert(insert_idx, node) + + def add_nodes(self, nodes_to_add, node_name_to_graph_name=None): + if node_name_to_graph_name is None: + self.model.graph.node.extend(nodes_to_add) + else: + for node in nodes_to_add: + graph_name = node_name_to_graph_name[node.name] + self.add_node(node, graph_name) + + def add_initializer(self, tensor, graph_name=None): + if graph_name is None or graph_name == self.model.graph.name: + self.model.graph.initializer.extend([tensor]) + else: + graph = self.get_graph_by_name(graph_name) + graph.initializer.extend([tensor]) + + def add_input(self, input, graph_name=None): + if graph_name is None or graph_name == self.model.graph.name: + self.model.graph.input.extend([input]) + else: + graph = self.get_graph_by_name(graph_name) + graph.input.extend([input]) + + @staticmethod + def replace_node_input(node, old_input_name, new_input_name): + assert isinstance(old_input_name, str) and isinstance(new_input_name, str) + for j in range(len(node.input)): + if node.input[j] == old_input_name: + node.input[j] = new_input_name + + def replace_input_of_all_nodes(self, old_input_name, new_input_name): + for node in self.nodes(): + OnnxModel.replace_node_input(node, old_input_name, new_input_name) + + @staticmethod + def replace_node_output(node, old_output_name, new_output_name): + assert isinstance(old_output_name, str) and isinstance(new_output_name, str) + for j in range(len(node.output)): + if node.output[j] == old_output_name: + node.output[j] = new_output_name + + def replace_output_of_all_nodes(self, old_output_name, new_output_name): + # This function shall be used carefully. For example: + # Add --[old_name]--> Cast ---> [new_name] + # | + # +----[old_name]--> Transpose --> + # If we want to remove the Cast node: replace output of Add to new_name is not enough; + # The input of Transpose shall also be updated to new_name. + for node in self.model.graph.node: + OnnxModel.replace_node_output(node, old_output_name, new_output_name) + + def get_initializer(self, name): + for graph in self.graphs(): + for tensor in graph.initializer: + if tensor.name == name: + return tensor + return None + + def get_nodes_by_op_type(self, op_type): + nodes = [] + for node in self.nodes(): + if node.op_type == op_type: + nodes.append(node) + return nodes + + def get_children(self, node, input_name_to_nodes=None, output_index=None): + if input_name_to_nodes is None: + input_name_to_nodes = self.input_name_to_nodes() + + children = [] + if output_index is not None: + if output_index < len(node.output): + output = node.output[output_index] + if output in input_name_to_nodes: + children = list(input_name_to_nodes[output]) + else: + for output in node.output: + if output in input_name_to_nodes: + children.extend(input_name_to_nodes[output]) + + return children + + def get_parents(self, node, output_name_to_node=None): + if output_name_to_node is None: + output_name_to_node = self.output_name_to_node() + + parents = [] + for input in node.input: + if input in output_name_to_node: + parents.append(output_name_to_node[input]) + return parents + + def get_parent(self, node, i, output_name_to_node=None): + if output_name_to_node is None: + output_name_to_node = self.output_name_to_node() + + if len(node.input) <= i: + return None + + input = node.input[i] + if input not in output_name_to_node: + return None + + return output_name_to_node[input] + + def match_first_parent(self, node, parent_op_type, output_name_to_node, exclude=[]): # noqa: B006 + """ + Find parent node based on constraints on op_type. + + Args: + node (str): current node name. + parent_op_type (str): constraint of parent node op_type. + output_name_to_node (dict): dictionary with output name as key, and node as value. + exclude (list): list of nodes that are excluded (not allowed to match as parent). + + Returns: + parent: The matched parent node. None if not found. + index: The input index of matched parent node. None if not found. + """ + for i, input in enumerate(node.input): + if input in output_name_to_node: + parent = output_name_to_node[input] + if parent.op_type == parent_op_type and parent not in exclude: + return parent, i + else: + logger.debug(f"To find first {parent_op_type}, current {parent.op_type}") + return None, None + + def match_parent( + self, + node, + parent_op_type, + input_index=None, + output_name_to_node=None, + exclude=[], # noqa: B006 + return_indice=None, + ): + """ + Find parent node based on constraints on op_type and index. + When input_index is None, we will find the first parent node based on constraints, + and return_indice will be appended the corresponding input index. + + Args: + node (str): current node name. + parent_op_type (str): constraint of parent node op_type. + input_index (int or None): only check the parent given input index of current node. + output_name_to_node (dict): dictionary with output name as key, and node as value. + exclude (list): list of nodes that are excluded (not allowed to match as parent). + return_indice (list): a list to append the input index when input_index is None. + + Returns: + parent: The matched parent node. + """ + assert node is not None + assert input_index is None or input_index >= 0 + + if output_name_to_node is None: + output_name_to_node = self.output_name_to_node() + + if input_index is None: + parent, index = self.match_first_parent(node, parent_op_type, output_name_to_node, exclude) + if return_indice is not None: + return_indice.append(index) + return parent + + if input_index >= len(node.input): + logger.debug(f"input_index {input_index} >= node inputs {len(node.input)}") + return None + + parent = self.get_parent(node, input_index, output_name_to_node) + if parent is not None and parent.op_type == parent_op_type and parent not in exclude: + return parent + + if parent is not None: + logger.debug(f"Expect {parent_op_type}, Got {parent.op_type}") + + return None + + def match_parent_paths(self, node, paths, output_name_to_node): + for i, path in enumerate(paths): + assert isinstance(path, (list, tuple)) + return_indice = [] + matched = self.match_parent_path(node, path[0], path[1], output_name_to_node, return_indice) + if matched: + return i, matched, return_indice + return -1, None, None + + def match_parent_paths_all(self, node, paths, output_name_to_node): + match_i, matches, return_indices = [], [], [] + for i, path in enumerate(paths): + assert isinstance(path, (list, tuple)) + return_indice = [] + matched = self.match_parent_path(node, path[0], path[1], output_name_to_node, return_indice) + if matched: + match_i.append(i) + matches.append(matched) + return_indices.append(return_indice) + return match_i, matches, return_indices + + def match_parent_path( + self, + node, + parent_op_types, + parent_input_index=None, + output_name_to_node=None, + return_indice=None, + ): + """ + Find a sequence of input edges based on constraints on parent op_type and index. + When input_index is None, we will find the first parent node based on constraints, + and return_indice will be appended the corresponding input index. + + Args: + node (str): current node name. + parent_op_types (str): constraint of parent node op_type of each input edge. + parent_input_index (list): constraint of input index of each input edge. None means no constraint. + output_name_to_node (dict): dictionary with output name as key, and node as value. + return_indice (list): a list to append the input index + When there is no constraint on input index of an edge. + + Returns: + parents: a list of matched parent node. + """ + if parent_input_index is not None: + assert len(parent_input_index) == len(parent_op_types) + + if output_name_to_node is None: + output_name_to_node = self.output_name_to_node() + + current_node = node + matched_parents = [] + for i, op_type in enumerate(parent_op_types): + matched_parent = self.match_parent( + current_node, + op_type, + parent_input_index[i] if parent_input_index is not None else None, + output_name_to_node, + exclude=[], + return_indice=return_indice, + ) + if matched_parent is None: + if parent_input_index is not None: + logger.debug( + f"Failed to match index={i} parent_input_index={parent_input_index[i]} op_type={op_type}", + stack_info=True, + ) + else: + logger.debug(f"Failed to match index={i} op_type={op_type}", stack_info=True) + return None + + matched_parents.append(matched_parent) + current_node = matched_parent + + return matched_parents + + def find_first_child_by_type(self, node, child_type, input_name_to_nodes=None, recursive=True): + children = self.get_children(node, input_name_to_nodes) + dq = deque(children) + while len(dq) > 0: + current_node = dq.pop() + if current_node.op_type == child_type: + return current_node + + if recursive: + children = self.get_children(current_node, input_name_to_nodes) + for child in children: + dq.appendleft(child) + + return None + + def match_child_path( + self, + node, + child_op_types, + edges: list[tuple[int, int]] | None = None, + input_name_to_nodes=None, + exclude=[], # noqa: B006 + ): + """ + Find a sequence of input edges based on constraints on parent op_type and index. + Note that we use greedy approach and only consider the first matched child, so it has chance to miss matching. + + Args: + node (str): current node name. + child_op_types (str): constraint of child node op_type of each input edge. + edges (list): each edge is represented by two integers: output index of parent node, input index of child node. + None means no constraint. + exclude(list): list of nodes that are excluded (not allowed to match as child). + + Returns: + children: a list of matched children node. + """ + if edges is not None: + assert len(edges) == len(child_op_types) + for edge in edges: + assert ( + isinstance(edge, tuple) and len(edge) == 2 and isinstance(edge[0], int) and isinstance(edge[1], int) + ) + + if input_name_to_nodes is None: + input_name_to_nodes = self.input_name_to_nodes() + + current_node = node + matched_children = [] + for i, op_type in enumerate(child_op_types): + matched_child = None + + if edges is None: + children_nodes = self.get_children(current_node, input_name_to_nodes=input_name_to_nodes) + else: + children_nodes = self.get_children( + current_node, input_name_to_nodes=input_name_to_nodes, output_index=edges[i][0] + ) + + for child in children_nodes: + if child.op_type == op_type and child not in exclude: + if edges is not None and child.input[edges[i][1]] != current_node.output[edges[i][0]]: + continue + + # Here we use greedy approach and only consider the first matched child. + # TODO: match recursively if we encounter cases that the correct child is not the first matched. + matched_child = child + break + + if matched_child is None: + logger.debug(f"Failed to match child {i} op_type={op_type}", stack_info=True) + return None + + matched_children.append(matched_child) + current_node = matched_child + + return matched_children + + def find_first_parent_by_type(self, node, parent_type, output_name_to_node=None, recursive=True): + if output_name_to_node is None: + output_name_to_node = self.output_name_to_node() + + parents = self.get_parents(node, output_name_to_node) + dq = deque(parents) + while len(dq) > 0: + current_node = dq.pop() + if current_node.op_type == parent_type: + return current_node + + if recursive: + parents = self.get_parents(current_node, output_name_to_node) + for parent in parents: + dq.appendleft(parent) + + return None + + def get_constant_value(self, output_name): + for node in self.get_nodes_by_op_type("Constant"): + if node.output[0] == output_name: + for att in node.attribute: + if att.name == "value": + return numpy_helper.to_array(att.t) + + # Fall back to intializer since constant folding might have been applied. + initializer = self.get_initializer(output_name) + if initializer is not None: + return numpy_helper.to_array(initializer) + + return None + + def get_constant_input(self, node): + for i, input in enumerate(node.input): + value = self.get_constant_value(input) + if value is not None: + return i, value + + return None, None + + def find_constant_input(self, node, expected_value, delta=0.000001): + i, value = self.get_constant_input(node) + if value is not None and value.size == 1 and abs(value - expected_value) < delta: + return i + + return -1 + + def is_constant_with_specified_dimension(self, output_name, dimensions, description): + value = self.get_constant_value(output_name) + if value is None: + logger.debug(f"{description} {output_name} is not initializer.") + return False + + if len(value.shape) != dimensions: + logger.debug(f"{description} {output_name} shall have {dimensions} dimensions. Got shape {value.shape}") + return False + + return True + + def has_constant_input(self, node, expected_value, delta=0.000001): + return self.find_constant_input(node, expected_value, delta) >= 0 + + def get_children_subgraph_nodes(self, root_node, stop_nodes, input_name_to_nodes=None): + if input_name_to_nodes is None: + input_name_to_nodes = self.input_name_to_nodes() + + children = input_name_to_nodes[root_node.output[0]] + + unique_nodes = [] + + dq = deque(children) + while len(dq) > 0: + current_node = dq.pop() + if current_node in stop_nodes: + continue + + if current_node not in unique_nodes: + unique_nodes.append(current_node) + + for output in current_node.output: + if output in input_name_to_nodes: + children = input_name_to_nodes[output] + for child in children: + dq.appendleft(child) + + return unique_nodes + + def tensor_shape_to_list(self, tensor_type): + """Convert tensor shape to list""" + shape_list = [] + for d in tensor_type.shape.dim: + if d.HasField("dim_value"): + shape_list.append(d.dim_value) # known dimension + elif d.HasField("dim_param"): + shape_list.append(d.dim_param) # unknown dimension with symbolic name + else: + shape_list.append("?") # shall not happen + return shape_list + + def get_dtype(self, name: str, symbolic_shape_helper: SymbolicShapeInferenceHelper | None = None): + """Try get data type given a name (could be initializer, input or output of graph or node).""" + + if self._dtype_dict is None: + self._dtype_dict = {} + for value_info in itertools.chain( + self.model.graph.value_info, + self.model.graph.input, + self.model.graph.output, + ): + self._dtype_dict[value_info.name] = value_info.type.tensor_type.elem_type + + for initializer in self.model.graph.initializer: + if initializer.name not in self._dtype_dict: + self._dtype_dict[initializer.name] = initializer.data_type + + if name in self._dtype_dict: + return self._dtype_dict[name] + + if symbolic_shape_helper is not None and name in symbolic_shape_helper.known_vi_: + value_info = symbolic_shape_helper.known_vi_[name] + return value_info.type.tensor_type.elem_type + + return None + + def get_shape(self, name: str, symbolic_shape_helper: SymbolicShapeInferenceHelper | None = None): + """Try get shape given a name (could be initializer, input or output of graph or node).""" + + if self._shape_dict is None: + self._shape_dict = {} + for value_info in itertools.chain( + self.model.graph.value_info, + self.model.graph.input, + self.model.graph.output, + ): + if value_info.type.tensor_type.HasField("shape"): + shape = [] + for dim in value_info.type.tensor_type.shape.dim: + if dim.dim_param: + shape.append(dim.dim_param) + else: + shape.append(dim.dim_value) + self._shape_dict[value_info.name] = shape + + for initializer in self.model.graph.initializer: + if initializer.name not in self._shape_dict: + self._shape_dict[initializer.name] = initializer.dims + + if name in self._shape_dict: + return self._shape_dict[name] + + if symbolic_shape_helper is not None and name in symbolic_shape_helper.known_vi_: + value_info = symbolic_shape_helper.known_vi_[name] + return value_info.type.tensor_type.elem_type + + return None + + @staticmethod + def get_node_attribute(node: NodeProto, attribute_name: str): + for attr in node.attribute: + if attr.name == attribute_name: + value = helper.get_attribute_value(attr) + return value + return None + + def remove_cascaded_cast_nodes(self): + """Remove Cast node that are followed by another Cast node like --> Cast --> Cast --> + Note that this shall be used carefully since it might introduce semantic change. + For example, float -> int -> float could get different value than the original float value. + So, it is recommended to used only in post-processing of mixed precision conversion. + """ + output_name_to_node = self.output_name_to_node() + removed_count = 0 + for node in self.nodes(): + if node.op_type == "Cast": + parent = self.get_parent(node, 0, output_name_to_node=output_name_to_node) + if parent and parent.op_type == "Cast": + node.input[0] = parent.input[0] + removed_count += 1 + + if removed_count > 0: + logger.info("Removed %d cascaded Cast nodes", removed_count) + self.prune_graph() + + def remove_useless_cast_nodes(self): + """Remove cast nodes that are not needed: input and output has same data type.""" + shape_infer = self.infer_runtime_shape(update=True) + if self.enable_shape_infer and shape_infer is None: + logger.warning("shape inference failed which might impact useless cast node detection.") + + nodes_to_remove = [] + for node in self.nodes(): + if node.op_type == "Cast": + input_dtype = self.get_dtype(node.input[0], shape_infer) + output_dtype = self.get_dtype(node.output[0], shape_infer) + if input_dtype and input_dtype == output_dtype: + nodes_to_remove.append(node) + + if nodes_to_remove: + graph_input_names = set(self.get_graphs_input_names()) + graph_output_names = set(self.get_graphs_output_names()) + for node in nodes_to_remove: + if bool(set(node.output) & graph_output_names): + if (not bool(set(node.input) & graph_input_names)) and len( + self.input_name_to_nodes()[node.input[0]] + ) == 1: + self.replace_output_of_all_nodes(node.input[0], node.output[0]) + else: + continue + else: + self.replace_input_of_all_nodes(node.output[0], node.input[0]) + self.remove_node(node) + + logger.info( + "Removed %d Cast nodes with output type same as input", + len(nodes_to_remove), + ) + + def convert_model_float32_to_float16(self, cast_input_output=True): + logger.warning( + "The function convert_model_float32_to_float16 is deprecated. Use convert_float_to_float16 instead!" + ) + self.convert_float_to_float16(use_symbolic_shape_infer=True, keep_io_types=cast_input_output) + + def convert_float_to_float16(self, use_symbolic_shape_infer=True, **kwargs): + """Convert a model to half (default) or mixed precision. + To use mixed precision, user need specify which graph inputs, outputs, operator type + or list of nodes shall keep in float32. + + Note that the conversion might not proceed without type information for the whole graph. + + By default, we use symbolic shape inference to get type information. The benefit of symbolic shape inference + is that it could handle fused operators in com.microsoft domain. Those operators cannot be handled in onnx shape + inference so symbolic shape inference is recommended for optimized model. + + When symbolic shape inference is used (even if it failed), ONNX shape inference will be disabled. + + Note that onnx shape inference will fail for model larger than 2GB. For large model, you have to enable + symbolic shape inference. If your model is not optimized, you can also use model path to call + convert_float_to_float16 in float16.py (see https://github.com/microsoft/onnxruntime/pull/15067) to + avoid the 2GB limit. + + Args: + use_symbolic_shape_infer (bool, optional): use symbolic shape inference instead of onnx shape inference. + Defaults to True. + keep_io_types (Union[bool, List[str]], optional): boolean or a list of float32 input/output names. + If True, model inputs/outputs should be left as float32. + Defaults to True. + op_block_list (List[str], optional): List of operator types to leave as float32. + Defaults to None, which will use `float16.DEFAULT_OP_BLOCK_LIST`. + node_block_list (List[str], optional): List of node names to leave as float32. Defaults to None. + force_fp16_initializers(bool): force converting all float initializers to float16. + Default to false. + min_positive_val (float, optional): minimal positive value. Defaults to 1e-7. + max_finite_val (float, optional): maximal finite value. Defaults to 1e4. + force_fp16_inputs(Dict[str, List[int]]): Force the conversion of the inputs of some operators to float16, even if + this script's preference it to keep them in float32. + """ + if "keep_io_types" not in kwargs: + kwargs["keep_io_types"] = True + + model = self.model + if use_symbolic_shape_infer: + # Use symbolic shape inference since custom operators (like Gelu, SkipLayerNormalization etc) + # are not recognized by onnx shape inference. + shape_infer_helper = SymbolicShapeInferenceHelper(model) + try: + model_with_shape = shape_infer_helper.infer_shapes(model, auto_merge=True, guess_output_rank=False) + + # auto_merge might cause issue (see https://github.com/microsoft/onnxruntime/issues/15521) + # we only merge tensor data type but not shape information back to the original onnx model. + # Note that float16 conversion need data type but not shape information. + if model_with_shape is not None: + name_vi = {} + for vi in model_with_shape.graph.value_info: + if ( + hasattr(vi.type, "tensor_type") + and hasattr(vi.type.tensor_type, "elem_type") + and vi.type.tensor_type.elem_type != TensorProto.UNDEFINED + and vi.name + ): + vi_copy = ValueInfoProto() + vi_copy.CopyFrom(vi) + if hasattr(vi_copy.type.tensor_type, "shape"): + vi_copy.type.tensor_type.ClearField("shape") + name_vi[vi.name] = vi_copy + for vi in model.graph.value_info: + if vi.name in name_vi: + del name_vi[vi.name] + for vi in name_vi.values(): + model.graph.value_info.append(vi) + except Exception: + logger.warning( + "Failed to run symbolic shape inference. Please file an issue in https://github.com/microsoft/onnxruntime." + ) + + parameters = {"disable_shape_infer": use_symbolic_shape_infer} + parameters.update( + { + key: kwargs[key] + for key in [ + "keep_io_types", + "min_positive_val", + "max_finite_val", + "op_block_list", + "node_block_list", + "force_fp16_initializers", + "force_fp16_inputs", + "use_bfloat16_as_blocked_nodes_dtype", + ] + if key in kwargs + } + ) + + fp16_model = convert_float_to_float16(model, **parameters) + self.initialize(fp16_model) + + self.remove_cascaded_cast_nodes() + + self.remove_useless_cast_nodes() + + def create_node_name(self, op_type, name_prefix=None): + """Create a unique node name that starts with a prefix (default is operator type). + The name will not be duplicated with any name that generated or existed in current graphs. + Args: + op_type (str): operator type + name_prefix (str, optional): prefix of node name. Defaults to None. + + Returns: + str: node name + """ + + if name_prefix: + prefix = name_prefix if name_prefix.endswith("_") else (name_prefix + "_") + else: + prefix = op_type + "_" + + suffix: int = 0 + if prefix in self._node_name_suffix: + suffix = self._node_name_suffix[prefix] + 1 + else: + # Check existed node name only once for a prefix + # as we assume create_node_name is called for every new node in fusion. + for node in self.nodes(): + if node.name and node.name.startswith(prefix): + try: + index = int(node.name[len(prefix) :]) + suffix = max(index + 1, suffix) + except ValueError: + continue + + # Record the generated suffix so that we can avoid generating duplicated name. + self._node_name_suffix[prefix] = suffix + + return prefix + str(suffix) + + def find_graph_input(self, input_name): + for input in self.model.graph.input: + if input.name == input_name: + return input + return None + + def find_graph_output(self, output_name): + for output in self.model.graph.output: + if output.name == output_name: + return output + return None + + def get_parent_subgraph_nodes(self, node, stop_nodes, output_name_to_node=None): + if output_name_to_node is None: + output_name_to_node = self.output_name_to_node() + + unique_nodes = [] + + parents = self.get_parents(node, output_name_to_node) + dq = deque(parents) + while len(dq) > 0: + current_node = dq.pop() + if current_node in stop_nodes: + continue + + if current_node not in unique_nodes: + unique_nodes.append(current_node) + + for input in current_node.input: + if input in output_name_to_node: + dq.appendleft(output_name_to_node[input]) + + return unique_nodes + + def get_graph_inputs(self, current_node, recursive=False): + """ + Find graph inputs that linked to current node. + """ + graph_inputs = [] + for input in current_node.input: + if self.find_graph_input(input) and input not in graph_inputs: + graph_inputs.append(input) + + if recursive: + parent_nodes = self.get_parent_subgraph_nodes(current_node, []) + for node in parent_nodes: + for input in node.input: + if self.find_graph_input(input) and input not in graph_inputs: + graph_inputs.append(input) + return graph_inputs + + @staticmethod + def input_index(node_output, child_node): + for index, input in enumerate(child_node.input): + if input == node_output: + return index + return -1 + + def remove_unused_constant(self): + input_name_to_nodes = self.input_name_to_nodes() + + # remove unused constant + unused_nodes = [] + nodes = self.nodes() + for node in nodes: + if node.op_type == "Constant" and node.output[0] not in input_name_to_nodes: + unused_nodes.append(node) + + self.remove_nodes(unused_nodes) + + if len(unused_nodes) > 0: + logger.debug(f"Removed unused constant nodes: {len(unused_nodes)}") + + def _get_subgraph_inputs_of_node(self, node): + """ + Get inputs to all nodes in all subgraphs of a node + """ + # Note: This function only handles one-level subgraphs of child nodes. + subgraph_nodes_inputs = set() + for attr in node.attribute: + if attr.type == AttributeProto.GRAPH: + child_nodes = attr.g.node + for child_node in child_nodes: + subgraph_nodes_inputs.update(child_node.input) + return subgraph_nodes_inputs + + def _get_subgraph_nodes_and_inputs(self, ops_with_graph_attrs): + """ + Get input names to all nodes in all subgraphs where subgraphs are + graph attributes of a node in the main graph + """ + subgraph_nodes = list(filter(lambda node: node.op_type in ops_with_graph_attrs, self.model.graph.node)) + subgraph_nodes_inputs = set() + for parent_node in subgraph_nodes: + subgraph_inputs_of_parent_node = self._get_subgraph_inputs_of_node(parent_node) + subgraph_nodes_inputs.update(subgraph_inputs_of_parent_node) + return subgraph_nodes, subgraph_nodes_inputs + + def prune_graph(self, outputs=None, allow_remove_graph_inputs=True): + """ + Prune graph to keep only required outputs. It removes unnecessary nodes that are not linked + (directly or indirectly) to any required output. + + There is also an option to remove graph inputs that are not used to generate any required output. + + Args: + outputs (list): a list of graph outputs to retain. If it is None, all graph outputs will be kept. + allow_remove_graph_inputs (bool): allow remove graph inputs. + """ + + keep_outputs = [output.name for output in self.model.graph.output] if outputs is None else outputs + + input_name_to_nodes_for_main_graph = self.input_name_to_nodes(exclude_subgraphs=True) + output_name_to_node = self.output_name_to_node() + + def get_first_output(node): + if node.output[0]: + return node.output[0] + return next(iter([o for o in node.output if o]), None) + + if len(self.graphs()) > 1: + # Get input names for all nodes in all subgraphs + subgraph_nodes, subgraph_nodes_inputs = self._get_subgraph_nodes_and_inputs( + ops_with_graph_attrs={"Loop", "Scan", "If"} + ) + if len(subgraph_nodes) == 0: + # TODO: support other ops such as `BeamSearch` that have subgraphs as op attributes + logger.debug("Skip prune_graph since graph has subgraph") + return + + # For graphs with subgraphs, add dangling outputs from parent graph nodes to list of outputs to keep + for node in self.model.graph.node: + # TODO: This for-loop logic currently assumes that Loop/Scan/If nodes will not be + # pruned because their subgraphs are needed for computations. This might not be + # true in all cases. + if node in subgraph_nodes: + continue + + # Check if node output is an input of a subgraph node and not an input to a node in the main graph + for output in node.output: + if output in subgraph_nodes_inputs and output not in input_name_to_nodes_for_main_graph: + keep_outputs += [output] + + # Keep track of nodes to keep. The key is first output of node, and the value is the node. + output_to_node = {} + + # Start from graph outputs, and find parent nodes recursively, and add nodes to the output_to_node dictionary. + dq = deque() + for output in keep_outputs: + if output in output_name_to_node: + dq.append(output_name_to_node[output]) + while len(dq) > 0: + node = dq.pop() + first_output = get_first_output(node) + if first_output and (first_output not in output_to_node): + output_to_node[first_output] = node + for name in node.input: + if len(name) > 0 and (name in output_name_to_node) and (name not in output_to_node): + dq.appendleft(output_name_to_node[name]) + + # Keep only those nodes in the output_to_node dictionary. + nodes_to_keep = [] + num_nodes_removed = 0 + for node in self.model.graph.node: + first_output = get_first_output(node) + kept_node = output_to_node.get(first_output) + + # Need to double check the node since fused node might reuse output name of some nodes to be removed. + # It is slow to compare whole node, so we compare op_type first to avoid comparing node in most cases. + if kept_node and kept_node.op_type == node.op_type and kept_node == node: + nodes_to_keep.append(node) + else: + num_nodes_removed += 1 + + self.all_graphs = ( + None # to prevent pass-by-copy after ClearField(), forces the use of pass-by-reference instead + ) + self.model.graph.ClearField("node") + self.model.graph.node.extend(nodes_to_keep) + + # Remove graph outputs not in list + output_to_remove = [] + if outputs is not None: + for output in self.model.graph.output: + if output.name not in outputs: + output_to_remove.append(output) + for output in output_to_remove: + self.model.graph.output.remove(output) + + # Remove graph inputs not used by any node. + input_to_remove = [] + if allow_remove_graph_inputs: + input_name_to_nodes = self.input_name_to_nodes() + input_to_remove = [input for input in self.model.graph.input if input.name not in input_name_to_nodes] + for name in input_to_remove: + self.model.graph.input.remove(name) + + if input_to_remove or output_to_remove or num_nodes_removed > 0: + removed = [] + if input_to_remove: + removed.append(f"{len(input_to_remove)} inputs") + if output_to_remove: + removed.append(f"{len(output_to_remove)} outputs") + if num_nodes_removed > 0: + removed.append(f"{num_nodes_removed} nodes") + logger.info("Removed %s", ", ".join(removed)) + + self.update_graph() + + def update_graph(self, verbose=False, allow_remove_graph_inputs=False): + graph = self.model.graph + + remaining_input_names = set() + for node in graph.node: + if node.op_type in ["Loop", "Scan", "If"]: + # Add input names of nodes in subgraphs + subgraph_inputs_of_node = self._get_subgraph_inputs_of_node(node) + remaining_input_names.update(subgraph_inputs_of_node) + + if node.op_type != "Constant": + remaining_input_names.update(node.input) + if verbose: + logger.debug(f"remaining input names: {remaining_input_names}") + + # remove graph input that is not used + inputs_to_remove = [] + if allow_remove_graph_inputs: + for input in graph.input: + if input.name not in remaining_input_names: + inputs_to_remove.append(input) + for input in inputs_to_remove: + graph.input.remove(input) + + names_to_remove = [input.name for input in inputs_to_remove] + logger.debug(f"remove {len(inputs_to_remove)} unused inputs: {names_to_remove}") + + # remove weights that are not used + weights_to_remove = [] + weights_to_keep = [] + for initializer in graph.initializer: + if initializer.name not in remaining_input_names and not self.find_graph_output(initializer.name): + weights_to_remove.append(initializer) + else: + weights_to_keep.append(initializer.name) + for initializer in weights_to_remove: + graph.initializer.remove(initializer) + + names_to_remove = [initializer.name for initializer in weights_to_remove] + logger.debug(f"remove {len(weights_to_remove)} unused initializers: {names_to_remove}") + if verbose: + logger.debug(f"remaining initializers:{weights_to_keep}") + + self.remove_unused_constant() + + def is_safe_to_fuse_nodes(self, nodes_to_remove, keep_outputs, input_name_to_nodes, output_name_to_node): + for node_to_remove in nodes_to_remove: + for output_to_remove in node_to_remove.output: + if output_to_remove in keep_outputs: + continue + + if output_to_remove in input_name_to_nodes: + for impacted_node in input_name_to_nodes[output_to_remove]: + if impacted_node not in nodes_to_remove: + logger.debug( + "it is not safe to remove nodes since output %s is used by %s", + output_to_remove, + impacted_node, + ) + return False + return True + + @staticmethod + def graph_topological_sort(graph, is_deterministic=False): + deps_set = set() # dependency set of all node + sorted_node_set = set() # sorted node set + sorted_nodes = [] # initialize sorted_nodes + + initializer_names = [init.name for init in graph.initializer] + graph_input_names = [input.name for input in graph.input] + input_names = initializer_names + graph_input_names + + if is_deterministic: + input_names.sort() + + for input_name in input_names: + deps_set.add(input_name) + + sorted_node_set_len = -1 + graph_nodes = graph.node if not is_deterministic else sorted(graph.node, key=lambda x: x.name) + + last_node_name = None + while len(sorted_node_set) != len(graph_nodes): + if len(sorted_node_set) == sorted_node_set_len: + break + sorted_node_set_len = len(sorted_node_set) + for node_idx, node in enumerate(graph_nodes): + if node_idx in sorted_node_set: + continue + input_count = sum(1 for _ in node.input if _) + if input_count == 0: + sorted_nodes.append(node) + sorted_node_set.add(node_idx) + for output in node.output: + if output: + deps_set.add(output) + continue + failed = False + for input_name in node.input: + if input_name and input_name not in deps_set: + failed = True + last_node_name = node.name + if not failed: + sorted_nodes.append(node) + sorted_node_set.add(node_idx) + for output in node.output: + if output: + deps_set.add(output) + else: + continue + + if len(sorted_node_set) != len(graph.node): + raise RuntimeError( + f"Graph is not a DAG: len(sorted_node_set)={len(sorted_node_set)}, len(graph.node)={len(graph.node)}, failed at node {last_node_name}" + ) + + graph.ClearField("node") + graph.node.extend(sorted_nodes) + + def topological_sort(self, is_deterministic=False, dump_model_on_failure=False): + # TODO: support graph_topological_sort() in subgraphs + # for graph in self.graphs(): + # self.graph_topological_sort(graph) + try: + OnnxModel.graph_topological_sort(self.model.graph, is_deterministic) + except RuntimeError as e: + if dump_model_on_failure: + logger.info( + "Failed to sort graph in topological order. Dumping model to _topo_sort_failed.onnx for debugging." + ) + OnnxModel.save( + self.model, "_topo_sort_failed.onnx", save_as_external_data=True, all_tensors_to_one_file=True + ) + raise e + + @staticmethod + def save( + model, + output_path, + save_as_external_data=False, + all_tensors_to_one_file=True, + size_threshold=1024, + convert_attribute=False, + ): + Path(output_path).parent.mkdir(parents=True, exist_ok=True) + + # Add ms domain if needed + ms_opset = [opset for opset in model.opset_import if opset.domain == "com.microsoft"] + # Check whether there is custom op in top level graph (our fusion is on top level right now). + # May need to extend to subgraph if our fusion are extended to subgraphs. + ms_node = [node for node in model.graph.node if node.domain == "com.microsoft"] + if ms_node and not ms_opset: + opset = model.opset_import.add() + opset.version = 1 + opset.domain = "com.microsoft" + + if save_as_external_data: + # Save model to external data, which is needed for model size > 2GB + output_dir = Path(output_path).parent + output_dir.mkdir(parents=True, exist_ok=True) + external_data_path = output_path + ".data" + location = Path(external_data_path).name if all_tensors_to_one_file else None + + if os.path.exists(output_path): + logger.info(f"Delete the existing onnx file: {output_path}") + os.remove(output_path) + + if all_tensors_to_one_file: + if os.path.exists(external_data_path): + # Delete the external data file. Otherwise, data will be appended to existing file. + logger.info(f"Delete the existing external data file: {external_data_path}") + os.remove(external_data_path) + else: + if os.listdir(output_dir): + raise RuntimeError(f"Output directory ({output_dir}) for external data is not empty.") + + save_model( + model, + output_path, + save_as_external_data=True, + all_tensors_to_one_file=all_tensors_to_one_file, + location=location, + size_threshold=size_threshold, + convert_attribute=convert_attribute, + ) + else: + save_model(model, output_path) + + def save_model_to_file( + self, + output_path, + use_external_data_format=False, + all_tensors_to_one_file=True, + size_threshold=1024, + convert_attribute=False, + ): + logger.info("Sort graphs in topological order") + self.topological_sort() + + # Note: After the model is saved to another directory with external data, + # You need reload the onnx model if you want to read tensor from self.model object. + # It is because the base directory is not updated for self.model object so attempt to read tensor data + # might encounter error since external data cannot be located. + OnnxModel.save( + self.model, + output_path, + use_external_data_format, + all_tensors_to_one_file, + size_threshold, + convert_attribute, + ) + logger.info(f"Model saved to {output_path}") + + def get_graph_inputs_excluding_initializers(self): + """ + Returns real graph inputs (excluding initializers from older onnx model). + """ + graph_inputs = [] + for input in self.model.graph.input: + if self.get_initializer(input.name) is None: + graph_inputs.append(input) + return graph_inputs + + def get_opset_version(self): + """Get opset version of onnx domain + + Raises: + RuntimeError: ONNX model has no opset for default domain. + + Returns: + int: opset version of onnx domain. + """ + for opset in self.model.opset_import: + if opset.domain in ["", "ai.onnx"]: + return opset.version + raise RuntimeError("ONNX model has no opset for default domain") + + def get_operator_statistics(self, include_domain=False): + """ + Returns node count of operators. + """ + op_count = {} + for node in self.nodes(): + op = (node.domain + ":" if include_domain and node.domain else "") + node.op_type + op_count[op] = 1 if op not in op_count else (op_count[op] + 1) + + # Sorted by count in the descending order, then by key in alphabetical order. + logger.info(f"Operators:{sorted(op_count.items(), key=lambda kv: (-kv[1], kv[0]))}") + + return op_count + + @staticmethod + def to_data_hash(tensor: TensorProto, base_dir: str = "") -> int: + """Converts a tensor def object to a hash for data comparison purposes. + Args: + tensor: a TensorProto object. + base_dir: if external tensor exists, base_dir can help to find the path to it + Returns: + hash: a hash of the data. + """ + if tensor.HasField("segment"): + raise ValueError("Currently not supporting loading segments.") + if tensor.data_type == TensorProto.UNDEFINED: + raise TypeError("The element type in the input tensor is not defined.") + tensor_dtype = tensor.data_type + storage_field = helper.tensor_dtype_to_field(tensor_dtype) + + if tensor.data_type == TensorProto.STRING: + utf8_strings = getattr(tensor, storage_field) + return hash(tuple(s.decode("utf-8") for s in utf8_strings)) + # Load raw data from external tensor if it exists + if uses_external_data(tensor): + load_external_data_for_tensor(tensor, base_dir) + if tensor.HasField("raw_data"): + return hash(tensor.raw_data) + else: + np_data = numpy_helper.to_array(tensor) + return hash(np_data.tobytes()) + + @staticmethod + def has_same_value( + tensor1: TensorProto, + tensor2: TensorProto, + signature_cache1: dict | None = None, + signature_cache2: dict | None = None, + rtol: float = 1e-05, + atol: float = 1e-08, + ) -> bool: + """Returns True when two tensors have same value. + Note that name can be different. + + Args: + tensor1 (TensorProto): initializer 1 + tensor2 (TensorProto): initializer 2 + signature_cache1 (dict): Optional dictionary to store data signatures of tensor1 in order to speed up comparison. + signature_cache2 (dict): Optional dictionary to store data signatures of tensor2 in order to speed up comparison. + rtol (float): Optional relative difference threshold for minor precision differences + atol (float): Optional absolute difference threshold for minor precision differences + Returns: + bool: True when two initializers has same value. + """ + sig1 = ( + signature_cache1[tensor1.name] + if signature_cache1 and tensor1.name in signature_cache1 + else OnnxModel.to_data_hash(tensor1) + ) + sig2 = ( + signature_cache2[tensor2.name] + if signature_cache2 and tensor2.name in signature_cache2 + else OnnxModel.to_data_hash(tensor2) + ) + if signature_cache1 is not None: + signature_cache1[tensor1.name] = sig1 + if signature_cache2 is not None: + signature_cache2[tensor2.name] = sig2 + if tensor1.data_type == tensor2.data_type and tensor1.dims == tensor2.dims: + n1 = numpy_helper.to_array(tensor1) + n2 = numpy_helper.to_array(tensor2) + if sig1 == sig2: + # Same signature, now do the expensive check to confirm the data is the same + return (n1 == n2).all() + else: + # Check if tensors are allclose + from numpy import allclose # noqa: PLC0415 + + return allclose(n1, n2, rtol=rtol, atol=atol) + + return False + + def remove_initializer(self, tensor): + for graph in self.graphs(): + if tensor in graph.initializer: + graph.initializer.remove(tensor) + return + logger.warning("Failed to remove initializer %s", tensor) # It might be a bug to hit this line. + + def remove_duplicated_initializer(self, cache: dict | None): + """Remove initializers with duplicated values, and only keep the first one. + It could help reduce size of models (like ALBert) with shared weights. + If require_raw_data passed, method will only compare raw_data initializers to speed runtime + Note: this function does not process subgraph. + """ + if len(self.graphs()) > 1: + logger.warning("remove_duplicated_initializer does not process subgraphs.") + + initializer_count = len(self.model.graph.initializer) + + same = [-1] * initializer_count + for i in range(initializer_count - 1): + if same[i] >= 0: + continue + for j in range(i + 1, initializer_count): + if OnnxModel.has_same_value( + self.model.graph.initializer[i], + self.model.graph.initializer[j], + cache, + cache, + ): + same[j] = i + + count = 0 + for i in range(initializer_count): + if same[i] >= 0: + count += 1 + self.replace_input_of_all_nodes( + self.model.graph.initializer[i].name, + self.model.graph.initializer[same[i]].name, + ) + + if count > 0: + self.update_graph() + print(f"Removed {count} initializers with duplicated value") + + def add_prefix_to_names(self, prefix: str): + """Add prefix to initializer or intermediate outputs in graph. Main graph inputs and outputs are excluded. + It could help avoid conflicting in name of node_args when merging two graphs. + Note: this function does not process subgraph. + """ + if len(self.graphs()) > 1: + logger.warning("add_prefix_to_names does not process subgraphs.") + + # Exclude the names of inputs and outputs of main graph (but not subgraphs) + # and empty names ("") as they have special meaning to denote missing optional inputs + excluded = [i.name for i in self.model.graph.input] + [o.name for o in self.model.graph.output] + [""] + + for initializer in self.model.graph.initializer: + if initializer.name not in excluded: + if prefix + initializer.name not in excluded: + initializer.name = prefix + initializer.name + + for node in self.model.graph.node: + # update name of node inputs + for j in range(len(node.input)): + if node.input[j] not in excluded: + if prefix + node.input[j] not in excluded: + node.input[j] = prefix + node.input[j] + + # update name of node outputs + for j in range(len(node.output)): + if node.output[j] not in excluded: + if prefix + node.output[j] not in excluded: + node.output[j] = prefix + node.output[j] + + for value_info in self.model.graph.value_info: + if value_info.name not in excluded: + value_info.name = prefix + value_info.name + + def clean_shape_infer(self): + self.model.graph.ClearField("value_info") + + def use_float16(self): + """Check whether the model uses float16""" + queue = [] # queue for BFS + queue.append(self.model.graph) + while queue: + sub_graphs = [] + for graph in queue: + if not isinstance(graph, GraphProto): + continue + + for v in itertools.chain(graph.input, graph.output, graph.value_info): + if v.type.tensor_type.elem_type == TensorProto.FLOAT16: + return True + if v.type.HasField("sequence_type"): + if v.type.sequence_type.elem_type.tensor_type.elem_type == TensorProto.FLOAT16: + return True + + for t in graph.initializer: + if t.data_type == TensorProto.FLOAT16: + return True + + for node in graph.node: + if node.op_type == "Cast": + for attr in node.attribute: + if attr.name == "to" and attr.i == TensorProto.FLOAT16: + return True + + for attr in node.attribute: + if attr.type == AttributeProto.GRAPH: + sub_graphs.append(attr.g) + + for g in attr.graphs: + sub_graphs.append(g) # noqa: PERF402 + + if isinstance(attr.t, TensorProto) and attr.t.data_type == TensorProto.FLOAT16: + return True + + for t in attr.tensors: + if isinstance(t, TensorProto) and t.data_type == TensorProto.FLOAT16: + return True + + queue = sub_graphs + + return False + + def change_graph_input_type( + self, + graph_input: ValueInfoProto, + new_type: int, + ): + """Change graph input type, and add Cast node if needed. + + Args: + graph_input (ValueInfoProto): input of the graph + new_type (int): new data type like TensorProto.INT32. + + Returns: + NodeProto: a new Cast node that added. None if Cast node is not added. + List[NodeProto]: Cast nodes that have been removed. + """ + assert isinstance(graph_input, ValueInfoProto) + assert self.find_graph_input(graph_input.name) + + if graph_input.type.tensor_type.elem_type == int(new_type): + return None, [] + + graph = self.graph() + new_cast_node = None + nodes_to_remove = [] + + input_name_to_nodes = self.input_name_to_nodes() + if graph_input.name in input_name_to_nodes: + nodes = input_name_to_nodes[graph_input.name] + + # For children that is not Cast node, insert a Cast node to convert int32 to original data type. + nodes_not_cast = [node for node in nodes if node.op_type != "Cast"] + if nodes_not_cast: + node_name = self.create_node_name("Cast") + output_name = node_name + "_" + graph_input.name + new_value_info = graph.value_info.add() + new_value_info.CopyFrom(graph_input) + new_value_info.name = output_name + new_cast_node = helper.make_node( + "Cast", + [graph_input.name], + [output_name], + to=int(graph_input.type.tensor_type.elem_type), + name=node_name, + ) + graph.node.extend([new_cast_node]) + + for node in nodes_not_cast: + OnnxModel.replace_node_input(node, graph_input.name, output_name) + + # For children that is Cast node, no need to insert Cast. + # When the children is Cast to int32, we can remove that Cast node since input type is int32 now. + nodes_cast = [node for node in nodes if node.op_type == "Cast"] + for node in nodes_cast: + if OnnxModel.get_node_attribute(node, "to") == int(new_type): + self.replace_input_of_all_nodes(node.output[0], graph_input.name) + if not self.find_graph_output(node.output[0]): + nodes_to_remove.append(node) + if nodes_to_remove: + self.remove_nodes(nodes_to_remove) + + graph_input.type.tensor_type.elem_type = int(new_type) + return new_cast_node, nodes_to_remove + + def change_graph_output_type( + self, + graph_output: ValueInfoProto, + new_type: int, + ): + """Change graph input type, and add Cast node if needed. + + Args: + graph_input (str | ValueInfoProto): output of the graph + new_type (int): new data type. + + Returns: + NodeProto: a new Cast node that added. None if Cast node is not added. + """ + assert isinstance(graph_output, ValueInfoProto) + assert self.find_graph_output(graph_output.name) + + if graph_output.type.tensor_type.elem_type == int(new_type): + return None + + cast_node = None + graph = self.graph() + + # Add a cast node + node_name = self.create_node_name("Cast") + input_name = node_name + "_" + graph_output.name + self.replace_input_of_all_nodes(graph_output.name, input_name) + new_value_info = graph.value_info.add() + new_value_info.CopyFrom(graph_output) + new_value_info.name = input_name + cast_node = helper.make_node( + "Cast", + [input_name], + [graph_output.name], + to=int(new_type), + name=node_name, + ) + graph.node.extend([cast_node]) + graph_output.type.tensor_type.elem_type = int(new_type) + return cast_node + + def rename_graph_output(self, old_name: str, new_name: str): + if new_name in self.output_name_to_node(): + raise RuntimeError("{new_name} exists in graph") + + graph = self.graph() + for output in graph.output: + if output.name == old_name: + logger.debug("replace output name from %s to %s", old_name, new_name) + self.replace_input_of_all_nodes(old_name, new_name) + self.replace_output_of_all_nodes(old_name, new_name) + output.name = new_name diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/onnx_model_bart.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/onnx_model_bart.py new file mode 100644 index 0000000000000000000000000000000000000000..5971c2432259971af6f040f4323d2e6cbc8704f4 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/onnx_model_bart.py @@ -0,0 +1,141 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +# -------------------------------------------------------------------------- +import logging + +from fusion_attention import AttentionMask +from fusion_bart_attention import FusionBartAttention +from fusion_options import FusionOptions +from fusion_reshape import FusionReshape +from onnx import numpy_helper +from onnx_model import OnnxModel +from onnx_model_bert import BertOnnxModel + +logger = logging.getLogger(__name__) + + +class FusionBartReshape(FusionReshape): + def __init__(self, model: OnnxModel): + super().__init__(model) + + def fuse(self, reshape_node, input_name_to_nodes, output_name_to_node): + if reshape_node.input[1] not in output_name_to_node: + return + + concat_node = output_name_to_node[reshape_node.input[1]] + if concat_node.op_type != "Concat" or len(concat_node.input) != 4: + return + + path0 = self.model.match_parent_path( + concat_node, + ["Unsqueeze", "Gather", "Shape"], + [0, 0, 0], + output_name_to_node, + ) + if path0 is None: + return + + (_, gather_0, shape_0) = path0 + + shape = [] + gather_value = self.model.get_constant_value(gather_0.input[1]) + if gather_value == 0: + shape.append(0) + + path1 = self.model.match_parent_path( + concat_node, + ["Unsqueeze", "Gather", "Shape"], + [1, 0, 0], + output_name_to_node, + ) + if path1 is None: + input_1_proto = self.model.get_initializer(concat_node.input[1]) + input_2_proto = self.model.get_initializer(concat_node.input[2]) + input_3_proto = self.model.get_initializer(concat_node.input[3]) + if input_1_proto is None or input_2_proto is None or input_3_proto is None: + return + + input_1 = numpy_helper.to_array(input_1_proto) + input_2 = numpy_helper.to_array(input_2_proto) + input_3 = numpy_helper.to_array(input_3_proto) + if len(input_1) != 1 or len(input_2) != 1 or len(input_3) != 1: + return + + if not (input_1[0] == -1 and input_2[0] > 0 and input_3[0] > 0): + return + + shape.extend(input_1) + shape.extend(input_2) + shape.extend(input_3) + gemm_path_with_bias = self.model.match_parent_path( + reshape_node, ["Add", "MatMul"], [0, 1], output_name_to_node + ) + gemm_path_no_bias = self.model.match_parent_path(reshape_node, ["MatMul"], [0], output_name_to_node) + if gemm_path_with_bias is not None: + gemm_path = gemm_path_with_bias + elif gemm_path_no_bias is not None: + gemm_path = gemm_path_no_bias + else: + return + + top_matmul = gemm_path[-1] + root_input = top_matmul.input[0] + + self.replace_reshape_node(shape, reshape_node, concat_node) + else: + (_, gather_1, shape_1) = path1 + + gather_value = self.model.get_constant_value(gather_1.input[1]) + if gather_value == 1: + shape.append(0) + + input_2_proto = self.model.get_initializer(concat_node.input[2]) + input_3_proto = self.model.get_initializer(concat_node.input[3]) + if input_2_proto is None or input_3_proto is None: + return + + input_2 = numpy_helper.to_array(input_2_proto) + input_3 = numpy_helper.to_array(input_3_proto) + if len(input_2) != 1 or len(input_3) != 1: + return + + if not (input_2[0] > 0 and input_3[0] > 0): + return + + shape.extend(input_2) + shape.extend(input_3) + gemm_path = self.model.match_parent_path( + reshape_node, ["Mul", "Add", "MatMul"], [0, 0, 1], output_name_to_node + ) + if gemm_path is None: + return + + top_matmul = gemm_path[-1] + root_input = top_matmul.input[0] + if shape_0.input[0] != root_input or shape_1.input[0] != root_input: + return + + self.replace_reshape_node(shape, reshape_node, concat_node) + + +class BartOnnxModel(BertOnnxModel): + def __init__(self, model, num_heads, hidden_size, model_impl="hf"): + super().__init__(model, num_heads, hidden_size) + self.attention_mask = AttentionMask(self) + self.attention_fusion = FusionBartAttention(self, self.hidden_size, self.num_heads, self.attention_mask) + self.bart_reshape_fusion_preprocess = FusionBartReshape(self) + + def optimize(self, options: FusionOptions | None = None, add_dynamic_axes: bool = False): + self.attention_fusion.use_multi_head_attention = False if options is None else options.use_multi_head_attention + self.attention_fusion.disable_multi_head_attention_bias = ( + False if options is None else options.disable_multi_head_attention_bias + ) + super().optimize(options, add_dynamic_axes) + + def fuse_attention(self): + self.attention_fusion.apply() + + def preprocess(self): + self.adjust_reshape_and_expand() + self.bart_reshape_fusion_preprocess.apply() diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/onnx_model_bert.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/onnx_model_bert.py new file mode 100644 index 0000000000000000000000000000000000000000..79ebc2723b8825dfd5998b66530667d49e729271 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/onnx_model_bert.py @@ -0,0 +1,512 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +# -------------------------------------------------------------------------- + +from logging import getLogger + +import numpy as np +from convert_to_packing_mode import PackingMode +from fusion_attention import AttentionMask, FusionAttention +from fusion_bart_attention import FusionBartAttention +from fusion_biasgelu import FusionBiasGelu +from fusion_constant_fold import FusionConstantFold +from fusion_embedlayer import FusionEmbedLayerNormalization +from fusion_fastgelu import FusionFastGelu +from fusion_gelu import FusionGelu +from fusion_gelu_approximation import FusionGeluApproximation +from fusion_gemmfastgelu import FusionGemmFastGelu +from fusion_layernorm import FusionLayerNormalization, FusionLayerNormalizationTF +from fusion_options import AttentionMaskFormat, FusionOptions +from fusion_qordered_attention import FusionQOrderedAttention +from fusion_qordered_gelu import FusionQOrderedGelu +from fusion_qordered_layernorm import FusionQOrderedLayerNormalization +from fusion_qordered_matmul import FusionQOrderedMatMul +from fusion_quickgelu import FusionQuickGelu +from fusion_reshape import FusionReshape +from fusion_rotary_attention import FusionRotaryEmbeddings +from fusion_shape import FusionShape +from fusion_simplified_layernorm import FusionSimplifiedLayerNormalization, FusionSkipSimplifiedLayerNormalization +from fusion_skiplayernorm import FusionBiasSkipLayerNormalization, FusionSkipLayerNormalization +from fusion_utils import FusionUtils +from onnx import ModelProto, TensorProto, helper, numpy_helper +from onnx_model import OnnxModel + +logger = getLogger(__name__) + + +class BertOnnxModel(OnnxModel): + def __init__(self, model: ModelProto, num_heads: int = 0, hidden_size: int = 0): + """Initialize BERT ONNX Model. + + Args: + model (ModelProto): the ONNX model + num_heads (int, optional): number of attention heads. Defaults to 0 (detect the parameter automatically). + hidden_size (int, optional): hidden dimension. Defaults to 0 (detect the parameter automatically). + """ + assert (num_heads == 0 and hidden_size == 0) or (num_heads > 0 and hidden_size % num_heads == 0) + + super().__init__(model) + self.num_heads = num_heads + self.hidden_size = hidden_size + + self.attention_mask = AttentionMask(self) + self.attention_fusion = FusionAttention(self, self.hidden_size, self.num_heads, self.attention_mask) + self.qordered_attention_fusion = FusionQOrderedAttention( + self, self.hidden_size, self.num_heads, self.attention_mask + ) + self.utils = FusionUtils(self) + + def fuse_constant_fold(self): + fusion = FusionConstantFold(self) + fusion.apply() + + def fuse_attention(self): + self.attention_fusion.apply() + # Only relevant in models with Q-DQ nodes + self.qordered_attention_fusion.apply() + + def fuse_gelu(self): + fusion = FusionGelu(self) + fusion.apply() + fusion = FusionFastGelu(self) + fusion.apply() + fusion = FusionQuickGelu(self) + fusion.apply() + # Only relevant in models with Q-DQ nodes + fusion = FusionQOrderedGelu(self) + fusion.apply() + + def fuse_bias_gelu(self, is_fastgelu): + fusion = FusionBiasGelu(self, is_fastgelu) + fusion.apply() + + def gelu_approximation(self): + fusion = FusionGeluApproximation(self) + fusion.apply() + + def fuse_gemm_fast_gelu(self): + fusion = FusionGemmFastGelu(self) + fusion.apply() + + def fuse_add_bias_skip_layer_norm(self): + fusion = FusionBiasSkipLayerNormalization(self) + fusion.apply() + + def fuse_reshape(self): + fusion = FusionReshape(self) + fusion.apply() + + def fuse_shape(self): + fusion = FusionShape(self) + fusion.apply() + + def fuse_embed_layer(self, use_mask_index): + fusion = FusionEmbedLayerNormalization(self, use_mask_index) + fusion.apply() + + def fuse_layer_norm(self): + fusion = FusionLayerNormalization(self) + fusion.apply() + + fusion = FusionLayerNormalizationTF(self) + fusion.apply() + + # Only relevant in models with Q-DQ nodes + fusion = FusionQOrderedLayerNormalization(self) + fusion.apply() + + def fuse_simplified_layer_norm(self): + fusion = FusionSimplifiedLayerNormalization(self) + fusion.apply() + + def fuse_skip_layer_norm(self, shape_infer=True): + fusion = FusionSkipLayerNormalization(self, shape_infer=shape_infer) + fusion.apply() + + def fuse_skip_simplified_layer_norm(self): + fusion = FusionSkipSimplifiedLayerNormalization(self) + fusion.apply() + + def fuse_rotary_embeddings(self): + fusion = FusionRotaryEmbeddings(self) + fusion.apply() + # Remove non-MS domain functions + rot_emb_nodes = list( + filter( + lambda node: node.op_type == "RotaryEmbedding" and node.domain != "com.microsoft", + self.model.graph.node, + ) + ) + non_ms_domains_to_keep = {node.domain for node in rot_emb_nodes} + i = 0 + while i < len(self.model.functions): + fn = self.model.functions[i] + if "RotaryEmbedding" in fn.name and fn.domain not in non_ms_domains_to_keep: + self.model.functions.remove(fn) + else: + i += 1 + + # Only relevant in models with Q-DQ nodes + def fuse_qordered_mamtul(self): + fusion = FusionQOrderedMatMul(self) + fusion.apply() + + def get_graph_inputs_from_node_type(self, op_type: str, input_indices: list[int], casted: bool): + """ + Get graph inputs that feed into node type (like EmbedLayerNormalization or Attention). + Returns a list of the graph input names based on the filter whether it is casted or not. + """ + graph_inputs = [] + + output_name_to_node = self.output_name_to_node() + nodes = self.get_nodes_by_op_type(op_type) + for node in nodes: + bert_inputs = [node.input[i] for i in input_indices if i < len(node.input)] + for bert_input in bert_inputs: + if self.find_graph_input(bert_input): + if not casted: + graph_inputs.append(bert_input) + elif bert_input in output_name_to_node: + parent = output_name_to_node[bert_input] + if parent.op_type == "Cast" and self.find_graph_input(parent.input[0]) is not None: + if casted: + graph_inputs.append(parent.input[0]) + return graph_inputs + + def get_graph_inputs_from_fused_nodes(self, casted: bool): + inputs = self.get_graph_inputs_from_node_type("EmbedLayerNormalization", [0, 1, 7], casted) + inputs += self.get_graph_inputs_from_node_type("Attention", [3], casted) + return inputs + + def change_graph_inputs_to_int32(self): + """Change data type of all graph inputs to int32 type, and add Cast node if needed.""" + graph = self.graph() + add_cast_count = 0 + remove_cast_count = 0 + for graph_input in graph.input: + new_node, removed_nodes = self.change_graph_input_type(graph_input, TensorProto.INT32) + if new_node: + add_cast_count += 1 + remove_cast_count += len(removed_nodes) + logger.info( + f"Graph inputs are changed to int32. Added {add_cast_count} Cast nodes, and removed {remove_cast_count} Cast nodes." + ) + + def use_dynamic_axes(self, dynamic_batch_dim="batch_size", dynamic_seq_len="max_seq_len"): + """ + Update input and output shape to use dynamic axes. + """ + bert_graph_inputs = self.get_graph_inputs_from_fused_nodes( + casted=True + ) + self.get_graph_inputs_from_fused_nodes(casted=False) + + for input in self.model.graph.input: + if input.name in bert_graph_inputs: + dim_proto = input.type.tensor_type.shape.dim[0] + dim_proto.dim_param = dynamic_batch_dim + if dynamic_seq_len is not None: + dim_proto = input.type.tensor_type.shape.dim[1] + dim_proto.dim_param = dynamic_seq_len + + for output in self.model.graph.output: + dim_proto = output.type.tensor_type.shape.dim[0] + dim_proto.dim_param = dynamic_batch_dim + + def preprocess(self): + self.adjust_reshape_and_expand() + return + + def adjust_reshape_and_expand(self): + nodes_to_remove = [] + for node in self.nodes(): + if node.op_type == "Reshape": + # Clean up unnecessary reshape nodes. + # Find reshape nodes with no actually data in "shape" attribute and remove. + reshape_shape = self.get_constant_value(node.input[1]) + if reshape_shape is not None and reshape_shape.size == 0: + nodes_to_remove.extend([node]) + self.replace_input_of_all_nodes(node.output[0], node.input[0]) + continue + + # Find path "Slice" -> "Reshape" -> "Expand" -> "Expand" -> current "Reshape", simplify the graph by + # changing current reshape's input to output of slice. + reshape_path = self.match_parent_path( + node, + ["Expand", "Expand", "Reshape", "Slice"], + [0, 0, 0, 0], + self.output_name_to_node(), + ) + if reshape_path is not None: + expand_node = reshape_path[-3] + expand_shape_value = self.get_constant_value(expand_node.input[1]) + + reshape_before_expand = reshape_path[-2] + shape_value = self.get_constant_value(reshape_before_expand.input[1]) + + slice_node = reshape_path[-1] + if ( + expand_shape_value is not None + and shape_value is not None + and len(expand_shape_value) == 2 + and len(shape_value) == 1 + and expand_shape_value[1] == shape_value[0] + ): + node.input[0] = slice_node.output[0] + + if nodes_to_remove: + self.remove_nodes(nodes_to_remove) + logger.info(f"Removed Reshape and Expand count: {len(nodes_to_remove)}") + + def clean_graph(self): + output_name_to_node = self.output_name_to_node() + nodes_to_remove = [] + for node in self.nodes(): + # Before: + # input_ids --> Shape --> Gather(indices=0) --> Unsqueeze ------+ + # | | + # | v + # +----> Shape --> Gather(indices=1) --> Unsqueeze---> Concat --> ConstantOfShape -->Cast --> EmbedLayerNormaliation/ReduceSum + # After (Concat path simplified, Cast merged into ConstantOfShape): + # input_ids --> Shape --> ConstantOfShape --> EmbedLayerNormalization/ReduceSum + op_input_id = {"EmbedLayerNormalization": 1, "ReduceSum": 0, "Attention": 3} + if node.op_type in op_input_id: + i = op_input_id[node.op_type] + parent_nodes = self.match_parent_path( + node, + [ + "Cast", + "ConstantOfShape", + "Concat", + "Unsqueeze", + "Gather", + "Shape", + ], + [i, 0, 0, 0, 0, 0], + output_name_to_node, + ) + if parent_nodes is not None: + ( + cast, + constant_of_shape, + concat, + unsqueeze, + gather, + shape, + ) = parent_nodes + if shape.input[0] == self.graph().input[0].name: + constant_of_shape.input[0] = shape.output[0] + + # Merge ConstantOfShape → Cast: update the value attribute dtype + # so ConstantOfShape directly produces the target type. + cast_to_type = OnnxModel.get_node_attribute(cast, "to") + cos_tensor = OnnxModel.get_node_attribute(constant_of_shape, "value") + if cast_to_type is not None and cos_tensor is not None: + fill_val = numpy_helper.to_array(cos_tensor).flat[0] + np_dtype = helper.tensor_dtype_to_np_dtype(cast_to_type) + new_val = numpy_helper.from_array(np.array([fill_val], dtype=np_dtype)) + for i, attr in enumerate(constant_of_shape.attribute): + if attr.name == "value": + constant_of_shape.attribute[i].CopyFrom(helper.make_attribute("value", new_val)) + break + self.replace_input_of_all_nodes(cast.output[0], constant_of_shape.output[0]) + nodes_to_remove.append(cast) + + output_name_to_node = self.output_name_to_node() + + if node.op_type == "Attention": + # Before (Cast present or already merged into ConstantOfShape): + # input_ids --> Shape --> ConstantOfShape [--> Cast] --> ReduceSum --> Attention + # After: + # remove this path, and remove the optional mask_index input of Attention node. + parent_nodes = self.match_parent_path( + node, + ["ReduceSum", "Cast", "ConstantOfShape", "Shape"], + [3, 0, 0, 0], + output_name_to_node, + ) + if parent_nodes is None: + # Also try merged pattern (Cast already folded into ConstantOfShape). + parent_nodes = self.match_parent_path( + node, + ["ReduceSum", "ConstantOfShape", "Shape"], + [3, 0, 0], + output_name_to_node, + ) + if parent_nodes is not None: + if parent_nodes[-1].input[0] == self.graph().input[0].name: + attention_node = helper.make_node( + "Attention", + inputs=node.input[0 : len(node.input) - 1], + outputs=node.output, + name=node.name + "_remove_mask", + ) + attention_node.domain = "com.microsoft" + attention_node.attribute.extend([helper.make_attribute("num_heads", self.num_heads)]) + self.add_node(attention_node, self.get_graph_by_node(node).name) + nodes_to_remove.append(node) + self.remove_nodes(nodes_to_remove) + + def postprocess(self): + self.clean_graph() + self.prune_graph() + + def optimize(self, options: FusionOptions | None = None, add_dynamic_axes: bool = False): + if (options is not None) and not options.enable_shape_inference: + self.disable_shape_inference() + + self.utils.remove_identity_nodes() + + # Remove cast nodes that having same data type of input and output based on symbolic shape inference. + self.utils.remove_useless_cast_nodes() + + # Apply any missed constant-folding model optimizations (e.g. for Dynamo-exported models) + self.fuse_constant_fold() + + if (options is None) or options.enable_layer_norm: + self.fuse_layer_norm() + self.fuse_simplified_layer_norm() + + if (options is None) or options.enable_gelu: + self.fuse_gelu() + + self.preprocess() + + self.fuse_reshape() + + if (options is None) or options.enable_skip_layer_norm: + self.fuse_skip_layer_norm(options.enable_shape_inference) + self.fuse_skip_simplified_layer_norm() + + if (options is None) or options.enable_rotary_embeddings: + self.fuse_rotary_embeddings() + + if options is not None: + self.attention_mask.set_mask_format(options.attention_mask_format) + if options.use_multi_head_attention and not isinstance(self.attention_fusion, FusionBartAttention): + self.attention_fusion = FusionAttention( + self, + self.hidden_size, + self.num_heads, + self.attention_mask, + options.use_multi_head_attention, + ) + + if (options is None) or options.enable_attention: + self.fuse_attention() + + # Perform the MatMul fusion after the Attention fusion as we do not + # want to fuse the MatMuls inside the Attention subgraphs + if (options is None) or options.enable_qordered_matmul: + self.fuse_qordered_mamtul() + + self.fuse_shape() + + if (options is None) or options.enable_embed_layer_norm: + use_mask_index = options.attention_mask_format == AttentionMaskFormat.MaskIndexEnd + self.fuse_embed_layer(use_mask_index) + + # Remove reshape nodes that having same shape of input and output based on symbolic shape inference. + self.utils.remove_useless_reshape_nodes() + + self.postprocess() + + # Bias fusion is done after postprocess to avoid extra Reshape between bias and Gelu/FastGelu/SkipLayerNormalization + if (options is None) or options.enable_bias_gelu: + # Fuse Gelu and Add Bias before it. + self.fuse_bias_gelu(is_fastgelu=True) + self.fuse_bias_gelu(is_fastgelu=False) + + if (options is None) or options.enable_bias_skip_layer_norm: + # Fuse SkipLayerNormalization and Add Bias before it. + self.fuse_add_bias_skip_layer_norm() + + if options is not None and options.enable_gelu_approximation: + self.gelu_approximation() + + if options is not None and options.enable_gemm_fast_gelu: + self.fuse_gemm_fast_gelu() + + self.remove_unused_constant() + + # Use symbolic batch dimension in input and output. + if add_dynamic_axes: + self.use_dynamic_axes() + + logger.info(f"opset version: {self.get_opset_version()}") + + def get_fused_operator_statistics(self): + """ + Returns node count of fused operators. + """ + op_count = {} + ops = [ + "EmbedLayerNormalization", + "Attention", + "MultiHeadAttention", + "Gelu", + "FastGelu", + "BiasGelu", + "GemmFastGelu", + "LayerNormalization", + "SimplifiedLayerNormalization", + "SkipLayerNormalization", + "SkipSimplifiedLayerNormalization", + "RotaryEmbedding", + ] + q_ops = [ + "QOrderedAttention", + "QOrderedGelu", + "QOrderedLayerNormalization", + "QOrderedMatMul", + ] + for op in ops + q_ops: + nodes = self.get_nodes_by_op_type(op) + op_count[op] = len(nodes) + + logger.info(f"Optimized operators: {op_count}") + return op_count + + def is_fully_optimized(self, fused_op_count=None): + """ + Returns True when the model is fully optimized. + """ + if fused_op_count is None: + fused_op_count = self.get_fused_operator_statistics() + + def op_count(op_name: str): + return fused_op_count.get(op_name) or 0 + + embed = op_count("EmbedLayerNormalization") + attention = op_count("Attention") + op_count("MultiHeadAttention") + op_count("QOrderedAttention") + gelu = op_count("Gelu") + op_count("BiasGelu") + op_count("FastGelu") + layer_norm = op_count("LayerNormalization") + op_count("SkipLayerNormalization") + simple_layer_norm = op_count("SimplifiedLayerNormalization") + op_count("SkipSimplifiedLayerNormalization") + + is_perfect = ( + (embed > 0) + and (attention > 0) + and (attention == gelu) + and ((layer_norm >= 2 * attention) or (simple_layer_norm >= 2 * attention)) + ) + + if layer_norm == 0: + logger.debug("Layer Normalization not fused") + + if simple_layer_norm == 0: + logger.debug("Simple Layer Normalization not fused") + + if gelu == 0: + logger.debug("Gelu (or FastGelu) not fused") + + if embed == 0: + logger.debug("EmbedLayerNormalization not fused") + + if attention == 0: + logger.warning("Attention (or MultiHeadAttention) not fused") + + return is_perfect + + def convert_to_packing_mode(self, use_symbolic_shape_infer: bool = False): + packing_mode = PackingMode(self) + packing_mode.convert(use_symbolic_shape_infer) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/onnx_model_bert_keras.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/onnx_model_bert_keras.py new file mode 100644 index 0000000000000000000000000000000000000000..a4e885c5aad10dac705b23b34042f0b5f7758a2e --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/onnx_model_bert_keras.py @@ -0,0 +1,474 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +# -------------------------------------------------------------------------- + +import logging + +import onnx +from onnx import numpy_helper +from onnx_model_bert_tf import BertOnnxModelTF + +logger = logging.getLogger(__name__) + + +class BertOnnxModelKeras(BertOnnxModelTF): + def __init__(self, model, num_heads, hidden_size): + super().__init__(model, num_heads, hidden_size) + + def match_mask_path(self, add_or_sub_before_softmax): + mask_nodes = self.match_parent_path( + add_or_sub_before_softmax, + ["Mul", "Sub", "Reshape", "Cast"], + [1, None, 1, 0], + ) + if mask_nodes is not None: + return mask_nodes + + mask_nodes = self.match_parent_path( + add_or_sub_before_softmax, + ["Mul", "Sub", "Cast", "Slice", "Unsqueeze"], + [1, 1, 1, 0, 0], + ) + if mask_nodes is not None: + return mask_nodes + + mask_nodes = self.match_parent_path( + add_or_sub_before_softmax, + ["Mul", "Sub", "Cast", "Unsqueeze", "Unsqueeze"], + [1, None, 1, 0, 0], + ) + return mask_nodes + + def check_attention_input(self, matmul_q, matmul_k, matmul_v, parent, output_name_to_node): + reshape_nodes = [] + + for x in [matmul_q, matmul_k, matmul_v]: + root_input = x.input[0] + root_node = output_name_to_node[root_input] + if root_node == parent: + continue + if root_node.op_type == "Reshape" and root_node.input[0] == parent.output[0]: + reshape_nodes.append(root_node) + continue + logger.debug(f"Check attention input failed:{root_input}, {parent.output[0]}") + return False, [] + + return True, reshape_nodes + + def fuse_attention(self): + self.input_name_to_nodes() + output_name_to_node = self.output_name_to_node() + + nodes_to_remove = [] + attention_count = 0 + + skip_layer_norm_nodes = self.get_nodes_by_op_type("SkipLayerNormalization") + for normalize_node in skip_layer_norm_nodes: + # SkipLayerNormalization has two inputs, and one of them is the root input for attention. + parent = self.get_parent(normalize_node, 0) + if parent is None or parent.op_type not in [ + "SkipLayerNormalization", + "EmbedLayerNormalization", + ]: + if parent.op_type == "Add": + parent = self.get_parent(normalize_node, 1) + if parent is None or parent.op_type not in [ + "SkipLayerNormalization", + "EmbedLayerNormalization", + ]: + logger.debug(f"First input for skiplayernorm: {parent.op_type if parent is not None else None}") + continue + else: + logger.debug(f"First input for skiplayernorm: {parent.op_type if parent is not None else None}") + continue + else: + # TODO: shall we add back the checking of children op types. + pass + + qkv_nodes = self.match_parent_path( + normalize_node, + ["Add", "Reshape", "MatMul", "Reshape", "Transpose", "MatMul"], + [None, 0, 0, 0, 0, 0], + ) + if qkv_nodes is None: + logger.debug("Failed to match qkv nodes") + continue + ( + add, + extra_reshape_0, + matmul, + reshape_qkv, + transpose_qkv, + matmul_qkv, + ) = qkv_nodes + logger.debug("Matched qkv nodes") + + v_nodes = self.match_parent_path( + matmul_qkv, + ["Transpose", "Reshape", "Add", "Reshape", "MatMul"], + [1, 0, 0, 0, 0], + ) + if v_nodes is None: + logger.debug("Failed to match v path") + continue + (transpose_v, reshape_v, add_v, extra_reshape_1, matmul_v) = v_nodes + + qk_nodes = self.match_parent_path(matmul_qkv, ["Softmax", "Sub", "MatMul"], [0, 0, 0]) + if qk_nodes is not None: + (softmax_qk, sub_qk, matmul_qk) = qk_nodes + q_nodes = self.match_parent_path( + matmul_qk, + ["Mul", "Transpose", "Reshape", "Add", "Reshape", "MatMul"], + [0, None, 0, 0, 0, 0], + ) + if q_nodes is not None: + ( + mul_q, + transpose_q, + reshape_q, + add_q, + extra_reshape_2, + matmul_q, + ) = q_nodes + + else: + qk_nodes = self.match_parent_path(matmul_qkv, ["Softmax", "Add", "Mul", "MatMul"], [0, 0, 0, None]) + if qk_nodes is None: + qk_nodes = self.match_parent_path(matmul_qkv, ["Softmax", "Add", "Div", "MatMul"], [0, 0, 0, None]) + if qk_nodes is None: + logger.debug("Failed to match qk path") + continue + (softmax_qk, add_qk, mul_qk, matmul_qk) = qk_nodes + + q_nodes = self.match_parent_path( + matmul_qk, + ["Transpose", "Reshape", "Add", "Reshape", "MatMul"], + [0, 0, 0, 0, 0], + ) + if q_nodes is not None: + (transpose_q, reshape_q, add_q, extra_reshape_2, matmul_q) = q_nodes + + if q_nodes is None: + logger.debug("Failed to match q path") + continue + + k_nodes = self.match_parent_path( + matmul_qk, + ["Transpose", "Reshape", "Add", "Reshape", "MatMul"], + [1, 0, 0, 0, 0], + ) + if k_nodes is None: + logger.debug("Failed to match k path") + continue + (transpose_k, reshape_k, add_k, extra_reshape_3, matmul_k) = k_nodes + + mask_nodes = self.match_mask_path(qk_nodes[1]) + if mask_nodes is None: + logger.debug("Failed to match mask path") + continue + if not self.has_constant_input(mask_nodes[1], 1): + logger.debug("Sub node expected to have an input with constant value 1.0.") + continue + + is_same_root, reshape_nodes = self.check_attention_input( + matmul_q, matmul_k, matmul_v, parent, output_name_to_node + ) + if is_same_root: + mask_index = self.attention_mask.process_mask(mask_nodes[-1].input[0]) + logger.debug("Create an Attention node.") + attention_node = self.attention_fusion.create_attention_node( + mask_index=mask_index, + q_matmul=matmul_q, + k_matmul=matmul_k, + v_matmul=matmul_v, + q_add=add_q, + k_add=add_k, + v_add=add_v, + num_heads=self.num_heads, + hidden_size=self.hidden_size, + first_input=parent.output[0], + output=reshape_qkv.output[0], + ) + if attention_node is None: + continue + + self.add_node(attention_node) + attention_count += 1 + + nodes_to_remove.extend([reshape_qkv, transpose_qkv, matmul_qkv]) + nodes_to_remove.extend(qk_nodes) + nodes_to_remove.extend(q_nodes) + nodes_to_remove.extend(k_nodes) + nodes_to_remove.extend(v_nodes) + nodes_to_remove.extend(mask_nodes) + nodes_to_remove.extend(reshape_nodes) + nodes_to_remove.append(extra_reshape_0) + self.replace_node_input(add, extra_reshape_0.output[0], matmul.output[0]) + else: + logger.debug("Root node not matched.") + continue + self.remove_nodes(nodes_to_remove) + self.update_graph() + logger.info(f"Fused Attention count:{attention_count}") + + def preprocess(self): + self.process_embedding() + self.fuse_mask() + self.skip_reshape() + + def skip_reshape(self): + self.input_name_to_nodes() + self.output_name_to_node() + + count = 0 + reshape_nodes = self.get_nodes_by_op_type("Reshape") + for reshape_node in reshape_nodes: + parent = self.get_parent(reshape_node, 0) + if parent is not None and parent.op_type == "Reshape": + reshape_node.input[0] = parent.input[0] + count += 1 + + if count > 0: + logger.info(f"Skip consequent Reshape count: {count}") + + def fuse_embedding(self, node, output_name_to_node): + assert node.op_type == "LayerNormalization" + logger.debug(f"start fusing embedding from node with output={node.output[0]}...") + word_embed_path = self.match_parent_path(node, ["Add", "Add", "Gather"], [0, 0, 0], output_name_to_node) + if word_embed_path is None: + logger.debug("failed to match word_embed_path") + return False + + skip_node, add_node, gather_node = word_embed_path + + word_initializer = self.get_initializer(gather_node.input[0]) + if word_initializer is None: + logger.debug("failed to get word initializer") + return False + + temp = numpy_helper.to_array(word_initializer) + if len(temp.shape) == 2: + logger.info(f"Found word embedding. name:{word_initializer.name}, shape:{temp.shape}") + word_embedding = word_initializer.name + else: + logger.info(f"Failed to find word embedding. name:{word_initializer.name}, shape:{temp.shape}") + return False + + pos_initializer = self.get_initializer(add_node.input[1]) + if pos_initializer is not None: + temp = numpy_helper.to_array(pos_initializer) + if len(temp.shape) == 3 and temp.shape[0] == 1: + tensor = numpy_helper.from_array(temp.reshape((temp.shape[1], temp.shape[2])), "position_embedding") + self.add_initializer(tensor) + logger.info(f"Found position embedding. name:{pos_initializer.name}, shape:{temp.shape[1:]}") + position_embedding = "position_embedding" + else: + logger.info(f"Failed to find position embedding. name:{pos_initializer.name}, shape:{temp.shape}") + return False + else: + pos_embed_path = self.match_parent_path(add_node, ["Gather", "Slice"], [1, 1], output_name_to_node) + if pos_embed_path is None: + logger.debug("failed to match pos_embed_path") + return False + + pos_gather, pos_slice = pos_embed_path + pos_initializer = self.get_initializer(pos_gather.input[0]) + if pos_initializer is None: + logger.debug("failed to get pos initializer") + return False + + temp = numpy_helper.to_array(pos_initializer) + if len(temp.shape) == 2: + logger.info(f"Found word embedding. name:{pos_initializer.name}, shape:{temp.shape}") + position_embedding = pos_initializer.name + else: + logger.info(f"Failed to find position embedding. name:{pos_initializer.name}, shape:{temp.shape}") + return False + + gather = self.get_parent(skip_node, 1, output_name_to_node) + if gather is None or gather.op_type != "Gather": + logger.debug("failed to get gather") + return False + + segment_initializer = self.get_initializer(gather.input[0]) + if segment_initializer is None: + logger.debug("failed to get segment initializer") + return False + + temp = numpy_helper.to_array(segment_initializer) + if len(temp.shape) == 2: + logger.info(f"Found segment embedding. name:{segment_initializer.name}, shape:{temp.shape}") + segment_embedding = segment_initializer.name + else: + logger.info(f"Failed to find segment embedding. name:{segment_initializer.name}, shape:{temp.shape}") + return False + + logger.info("Create Embedding node") + self.create_embedding_subgraph(node, word_embedding, segment_embedding, position_embedding) + return True + + def process_embedding(self): + """ + Automatically detect word, segment and position embeddings. + """ + logger.info("start processing embedding layer...") + output_name_to_node = self.output_name_to_node() + for node in self.nodes(): + if node.op_type == "LayerNormalization": + if self.fuse_embedding(node, output_name_to_node): + return + break + + def fuse_mask(self): + nodes_to_remove = [] + for node in self.nodes(): + if node.op_type == "Mul" and self.has_constant_input(node, -10000): + mask_path = self.match_parent_path(node, ["Sub", "Cast", "Slice", "Unsqueeze"], [0, 1, 0, 0]) + if mask_path is None: + continue + sub_node, cast_node, slice_node, unsqueeze_node = mask_path + + mask_input_name = self.attention_mask.get_first_mask() + if unsqueeze_node.input[0] != mask_input_name: + print(f"Cast input {unsqueeze_node.input[0]} is not mask input {mask_input_name}") + continue + + unsqueeze_added_1 = onnx.helper.make_node( + "Unsqueeze", + inputs=[mask_input_name], + outputs=["mask_fuse_unsqueeze1_output"], + name="Mask_UnSqueeze_1", + axes=[1], + ) + + unsqueeze_added_2 = onnx.helper.make_node( + "Unsqueeze", + inputs=["mask_fuse_unsqueeze1_output"], + outputs=["mask_fuse_unsqueeze2_output"], + name="Mask_UnSqueeze_2", + axes=[2], + ) + + # self.replace_node_input(cast_node, cast_node.input[0], 'mask_fuse_unsqueeze2_output') + cast_node_2 = onnx.helper.make_node( + "Cast", + inputs=["mask_fuse_unsqueeze2_output"], + outputs=["mask_fuse_cast_output"], + ) + cast_node_2.attribute.extend([onnx.helper.make_attribute("to", 1)]) + self.replace_node_input(sub_node, sub_node.input[1], "mask_fuse_cast_output") + + nodes_to_remove.extend([slice_node, unsqueeze_node, cast_node]) + self.add_node(unsqueeze_added_1) + self.add_node(unsqueeze_added_2) + self.add_node(cast_node_2) + + self.remove_nodes(nodes_to_remove) + + # Prune graph is done after removing nodes to remove island nodes. + if len(nodes_to_remove) > 0: + self.prune_graph() + + logger.info("Fused mask" if len(nodes_to_remove) > 0 else "Failed to fuse mask") + + def remove_extra_reshape(self): + skiplayernorm_nodes = self.get_nodes_by_op_type("SkipLayerNormalization") + reshape_removed = 0 + for skiplayernorm_node in skiplayernorm_nodes: + path = self.match_parent_path( + skiplayernorm_node, + [ + "Add", + "Reshape", + "MatMul", + "Reshape", + "Gelu", + "Add", + "Reshape", + "MatMul", + "SkipLayerNormalization", + ], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + ) + if path is None: + continue + + ( + add_1, + reshape_1, + matmul_1, + reshape_2, + gelu, + add_2, + reshape_3, + matmul_2, + skiplayernorm, + ) = path + add_2.input[0] = matmul_2.output[0] + self.remove_node(reshape_3) + matmul_1.input[0] = gelu.output[0] + self.remove_node(reshape_2) + add_1.input[0] = matmul_1.output[0] + self.remove_node(reshape_1) + reshape_removed += 3 + + return reshape_removed + + def remove_extra_reshape_2(self): + skiplayernorm_nodes = self.get_nodes_by_op_type("SkipLayerNormalization") + reshape_removed = 0 + for skiplayernorm_node in skiplayernorm_nodes: + path = self.match_parent_path( + skiplayernorm_node, + [ + "Add", + "Reshape", + "MatMul", + "Reshape", + "Gelu", + "Add", + "Reshape", + "MatMul", + "Reshape", + "SkipLayerNormalization", + ], + [None, 0, 0, 0, 0, 0, 0, 0, 0, 0], + ) + if path is None: + continue + + ( + add_1, + reshape_1, + matmul_1, + reshape_2, + gelu, + add_2, + reshape_3, + matmul_2, + reshape_4, + skiplayernorm, + ) = path + + matmul_2.input[0] = skiplayernorm.output[0] + self.remove_node(reshape_4) + + add_2.input[0] = matmul_2.output[0] + self.remove_node(reshape_3) + + matmul_1.input[0] = gelu.output[0] + self.remove_node(reshape_2) + + add_1.input[0] = matmul_1.output[0] + self.remove_node(reshape_1) + + reshape_removed += 4 + + return reshape_removed + + def postprocess(self): + reshape_removed = self.remove_extra_reshape() + self.remove_extra_reshape_2() + logger.info(f"Remove {reshape_removed} Reshape nodes.") + + self.prune_graph() diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/onnx_model_bert_tf.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/onnx_model_bert_tf.py new file mode 100644 index 0000000000000000000000000000000000000000..80d1cab7ba05f381418425205b82edcadb2ecb32 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/onnx_model_bert_tf.py @@ -0,0 +1,588 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +# -------------------------------------------------------------------------- + +import logging + +import numpy as np +import onnx +from onnx import TensorProto, helper, numpy_helper +from onnx_model_bert import BertOnnxModel + +logger = logging.getLogger(__name__) + + +class BertOnnxModelTF(BertOnnxModel): + def __init__(self, model, num_heads, hidden_size): + super().__init__(model, num_heads, hidden_size) + + def remove_identity(self): + nodes_to_remove = [] + for node in self.nodes(): + if node.op_type == "Identity": + if not self.find_graph_output(node.output[0]): + self.replace_input_of_all_nodes(node.output[0], node.input[0]) + nodes_to_remove.append(node) + self.remove_nodes(nodes_to_remove) + logger.info(f"Removed Identity count: {len(nodes_to_remove)}") + + def match_mask_path(self, add_or_sub_before_softmax): + mask_nodes = self.match_parent_path( + add_or_sub_before_softmax, + ["Mul", "Sub", "Reshape", "Cast"], + [1, None, 1, 0], + ) + if mask_nodes is not None: + return mask_nodes + + mask_nodes = self.match_parent_path( + add_or_sub_before_softmax, + ["Mul", "Sub", "Cast", "Slice", "Unsqueeze"], + [1, 0, 1, 0, 0], + ) + if mask_nodes is not None: + return mask_nodes + + mask_nodes = self.match_parent_path( + add_or_sub_before_softmax, + ["Mul", "Sub", "Cast", "Unsqueeze", "Unsqueeze"], + [1, None, 1, 0, 0], + ) + + return mask_nodes + + def get_2d_initializers_from_parent_subgraphs(self, current_node): + """ + Find initializers that is 2D. Returns a dictionary with name as key and shape as value. + """ + parent_nodes = self.get_parent_subgraph_nodes(current_node, []) + initializers = {} + for node in parent_nodes: + for input in node.input: + initializer = self.get_initializer(input) + if initializer: + temp = numpy_helper.to_array(initializer) + if len(temp.shape) == 2: + initializers[initializer.name] = temp.shape + + return initializers + + def find_segment_ids(self, segment_embedding, input_ids): + input_name_to_nodes = self.input_name_to_nodes() + if segment_embedding not in input_name_to_nodes: + return None + + nodes = input_name_to_nodes[segment_embedding] + if len(nodes) != 1: + return None + + graph_inputs = self.get_graph_inputs(nodes[0], recursive=True) + if len(graph_inputs) > 1: + print("Found multiple candidates of segment_ids", graph_inputs) + return None + # Find segment ids in graph inputs. The segment id input must not be the same as input_ids. + if len(graph_inputs) == 1 and graph_inputs[0] != input_ids: + return graph_inputs[0] + + # If the segment id candidate is the same as the input_ids, try to assign alternative segment ids and simplify the graph if needed. + segment_ids = nodes[0].input[1] + _, segment_id_path, _ = self.match_parent_paths( + nodes[0], + [ + ( + ["ConstantOfShape", "Cast", "Concat", "Slice", "Cast", "Shape"], + [1, 0, 0, 0, 0, 0], + ), + ( + [ + "ConstantOfShape", + "Cast", + "Concat", + "Unsqueeze", + "Squeeze", + "Slice", + "Cast", + "Shape", + ], + [1, 0, 0, 0, 0, 0, 0, 0], + ), + ], + None, + ) + + if segment_id_path and input_ids and input_ids == segment_id_path[-1].input[0]: + logger.debug("Simplify semgent id path...") + constantofshape_node = segment_id_path[0] + graph_name = self.get_graph_by_node(constantofshape_node).name + self.add_node( + helper.make_node("Shape", inputs=[input_ids], outputs=["input_shape"]), + graph_name, + ) + constantofshape_value = helper.get_attribute_value(constantofshape_node.attribute[0]) + self.add_node( + helper.make_node( + "ConstantOfShape", + inputs=["input_shape"], + outputs=["zeros_for_input_shape"], + value=constantofshape_value, + ), + graph_name, + ) + segment_ids = "zeros_for_input_shape" + return segment_ids + + def find_input_ids(self, word_embedding): + input_name_to_nodes = self.input_name_to_nodes() + if word_embedding not in input_name_to_nodes: + return None + + nodes = input_name_to_nodes[word_embedding] + if len(nodes) != 1: + return None + + graph_inputs = self.get_graph_inputs(nodes[0], recursive=True) + if len(graph_inputs) == 1: + return graph_inputs[0] + + print("Found multiple candidates of input_ids", graph_inputs) + return None + + def find_mask_input(self, excluded_graph_inputs): + for node in self.nodes(): + if node.op_type == "Softmax": + mask_path = self.match_parent_path( + node, + ["Add", "Mul", "Sub", "Cast", "Slice", "Unsqueeze"], + [0, 1, None, 1, 0, 0], + ) + if mask_path is None: + continue + ( + add_node, + mul_node, + sub_node, + cast_node, + slice_node, + unsqueeze_node, + ) = mask_path + if self.has_constant_input(mul_node, -10000) and self.has_constant_input(sub_node, 1): + graph_inputs = self.get_graph_inputs(sub_node, recursive=True) + inputs = [input for input in graph_inputs if input not in excluded_graph_inputs] + if len(inputs) > 1: + print("Found multiple candidates of mask input", inputs) + return None + if len(inputs) == 1: + return inputs[0] + # Duplicated input found. Try to simplify the graph. + path_to_be_simplified = self.match_parent_path( + mask_path[-1], + [ + "ConstantOfShape", + "Cast", + "Concat", + "Unsqueeze", + "Squeeze", + "Slice", + "Cast", + "Shape", + ], + [0, 0, 0, 0, 0, 0, 0, 0], + ) + duplicated_inputs = [input for input in graph_inputs if input in excluded_graph_inputs] + # Simplify graph for dynamic axes. + if ( + path_to_be_simplified + and duplicated_inputs + and len(duplicated_inputs) == 1 + and duplicated_inputs[0] == path_to_be_simplified[-1].input[0] + ): + logger.debug("Simplify semgent id path...") + constantofshape_node = path_to_be_simplified[0] + constantofshape_value = helper.get_attribute_value(constantofshape_node.attribute[0]) + graph_name = self.get_graph_by_node(constantofshape_node).name + self.add_node( + helper.make_node( + "Shape", + inputs=[duplicated_inputs[0]], + outputs=["input_shape_for_mask"], + ), + graph_name, + ) + self.add_node( + helper.make_node( + "ConstantOfShape", + inputs=["input_shape_for_mask"], + outputs=[unsqueeze_node.input[0]], + value=constantofshape_value, + ), + graph_name, + ) + return unsqueeze_node.input[0] + return None + + def create_embedding_subgraph(self, normalize_node, word_embedding, segment_embedding, position_embedding): + input_ids = self.find_input_ids(word_embedding) + if input_ids is None: + logger.info("Failed to find input_ids. Cannot fuse embedding layer.") + return False + + segment_ids = self.find_segment_ids(segment_embedding, input_ids) + if segment_ids is None: + logger.info("Failed to find segment_ids. Cannot fuse embedding layer.") + return False + + mask_input = self.find_mask_input([segment_ids, input_ids]) + if mask_input is None: + logger.info("Failed to find input_mask. Cannot fuse embedding layer.") + return False + + self.bert_inputs = [input_ids, segment_ids, mask_input] + + mask_index = self.create_node_name("mask_index") + self.attention_mask.set_mask_indice(mask_input, mask_index) + + if self.find_graph_input(input_ids).type.tensor_type.elem_type != TensorProto.INT32: + casted, input_ids = self.utils.cast_graph_input_to_int32(input_ids) + + if self.find_graph_input(segment_ids): + casted, segment_ids = self.utils.cast_graph_input_to_int32(segment_ids) + else: + segment_ids, segment_id_cast_node = self.utils.cast_input_to_int32(segment_ids) + + if self.find_graph_input(mask_input): + casted, mask_input = self.utils.cast_graph_input_to_int32(mask_input) + else: + mask_input, mask_input_cast_node = self.utils.cast_input_to_int32(mask_input) + + embed_output = self.create_node_name("embed_output") + embed_node = onnx.helper.make_node( + "EmbedLayerNormalization", + inputs=[ + input_ids, + segment_ids, + word_embedding, + position_embedding, + segment_embedding, + normalize_node.input[1], # gamma + normalize_node.input[2], # beta + mask_input, + ], + outputs=[embed_output, mask_index], + name="EmbedLayer", + ) + embed_node.domain = "com.microsoft" + self.replace_input_of_all_nodes(normalize_node.output[0], embed_output) + self.add_node(embed_node, self.get_graph_by_node(normalize_node).name) + + def process_embedding(self): + """ + Automatically detect word, segment and position embeddings. + """ + logger.info("start processing embedding layer...") + output_name_to_node = self.output_name_to_node() + + layer_norm_nodes = self.get_nodes_by_op_type("LayerNormalization") + for layer_norm_node in layer_norm_nodes: + pos_embed_path = self.match_parent_path( + layer_norm_node, + ["Add", "Reshape", "Slice"], + [0, 1, 0], + output_name_to_node, + ) + if pos_embed_path is None: + continue + + add_node, reshape_node, slice_node = pos_embed_path + initializer = self.get_initializer(slice_node.input[0]) + if initializer is None: + continue + + temp = numpy_helper.to_array(initializer) + if len(temp.shape) == 2: + logger.info(f"Found position embedding. name:{initializer.name}, shape:{temp.shape}") + position_embedding = initializer.name + else: + logger.info(f"Failed to find position embedding. name:{initializer.name}, shape:{temp.shape}") + return + + first_parent = self.get_parent(add_node, 0, output_name_to_node) + if first_parent is not None and first_parent.op_type == "Add": + embeddings = self.get_2d_initializers_from_parent_subgraphs(first_parent) + if len(embeddings) != 2: + logger.warning( + f"Failed to find two embeddings (word and segment) from Add node. Found {embeddings}" + ) + return + + word_embedding = None + segment_embedding = None + for name, shape in embeddings.items(): + if shape[0] == 2: + segment_embedding = name + logger.info(f"Found segment embedding. name:{name}, shape:{shape}") + else: + word_embedding = name + logger.info(f"Found words embedding. name:{name}, shape:{shape}") + + if word_embedding is None or segment_embedding is None: + logger.info("Failed to find both word and segment embedding") + return + + logger.info("Create Embedding node") + self.create_embedding_subgraph( + layer_norm_node, + word_embedding, + segment_embedding, + position_embedding, + ) + # Prune graph to remove those original embedding nodes. + self.prune_graph() + break + + def check_attention_input(self, matmul_q, matmul_k, matmul_v, parent, output_name_to_node): + for x in [matmul_q, matmul_k, matmul_v]: + root_input = x.input[0] + root_node = output_name_to_node[root_input] + if root_node == parent: + continue + logger.debug(f"Check attention input failed:{root_input}, {parent.output[0]}") + return False + + return True + + def fuse_attention(self): + output_name_to_node = self.output_name_to_node() + + nodes_to_remove = [] + attention_count = 0 + + start_nodes = [] + skip_layer_norm_nodes = self.get_nodes_by_op_type("SkipLayerNormalization") + layer_norm_nodes = self.get_nodes_by_op_type("LayerNormalization") + # Sometimes we can not fuse skiplayernormalization since the add before layernorm has an output that used by nodes outside skiplayernorm + # Conceptually we treat add before layernorm as skiplayernorm node since they share the same pattern + start_nodes.extend(skip_layer_norm_nodes) + start_nodes.extend(layer_norm_nodes) + + for normalize_node in start_nodes: + graph_name = self.get_graph_by_node(normalize_node).name + # SkipLayerNormalization has two inputs, and one of them is the root input for attention. + if normalize_node.op_type == "LayerNormalization": + add_before_layernorm = self.match_parent(normalize_node, "Add", 0) + if add_before_layernorm is not None: + normalize_node = add_before_layernorm # noqa: PLW2901 + else: + continue + parent = self.get_parent(normalize_node, 1) + if parent is None or parent.op_type not in [ + "SkipLayerNormalization", + "LayerNormalization", + "Reshape", + ]: + parent = self.get_parent(normalize_node, 0) + if parent is None or parent.op_type not in [ + "SkipLayerNormalization", + "LayerNormalization", + "Reshape", + ]: + logger.debug("Failed to match parent of normalize_node") + continue + + qkv_nodes = self.match_parent_path( + normalize_node, + ["Add", "MatMul", "Reshape", "Transpose", "MatMul"], + [0, 0, 0, 0, 0], + ) + if qkv_nodes is None: + qkv_nodes = self.match_parent_path( + normalize_node, + ["MatMul", "Reshape", "Transpose", "MatMul"], + [1, 0, 0, 0], + ) + if qkv_nodes is None: + qkv_nodes = self.match_parent_path(normalize_node, ["Add", "Einsum", "Einsum"], [0, 0, 0]) + if qkv_nodes is None: + logger.debug("Failed to match qkv nodes") + continue + + matmul_qkv = qkv_nodes[-1] + v_nodes = self.match_parent_path(matmul_qkv, ["Transpose", "Reshape", "Add", "MatMul"], [1, 0, 0, 0]) + if v_nodes is None: + v_nodes = self.match_parent_path(matmul_qkv, ["Add", "Einsum"], [1, 0]) + if v_nodes is None: + logger.debug("Failed to match v path") + continue + + add_v = v_nodes[-2] + matmul_v = v_nodes[-1] + qk_nodes = self.match_parent_path(matmul_qkv, ["Softmax", "Add", "Mul", "MatMul"], [0, 0, 0, 0]) + if qk_nodes is None: + qk_nodes = self.match_parent_path(matmul_qkv, ["Softmax", "Add", "Einsum"], [0, 0, 0]) + if qk_nodes is None: + logger.debug("Failed to match qk_paths") + continue + matmul_qk = qk_nodes[-1] + + q_nodes = self.match_parent_path(matmul_qk, ["Transpose", "Reshape", "Add", "MatMul"], [0, 0, 0, 0]) + if q_nodes is None: + q_nodes = self.match_parent_path(matmul_qk, ["Add", "Einsum"], [0, 0]) + if q_nodes is None: + logger.debug("Failed to match q path") + continue + + add_q = q_nodes[-2] + matmul_q = q_nodes[-1] + + k_nodes = self.match_parent_path(matmul_qk, ["Transpose", "Reshape", "Add", "MatMul"], [1, 0, 0, 0]) + if k_nodes is None: + k_nodes = self.match_parent_path(matmul_qk, ["Mul", "Add", "Einsum"], [1, 0, 0]) + if k_nodes is None: + logger.debug("Failed to match k path") + continue + add_k = k_nodes[-2] + matmul_k = k_nodes[-1] + + mask_nodes = self.match_mask_path(qk_nodes[1]) + + if mask_nodes is None: + logger.debug("Cannot find mask_nodes.") + continue + + if not self.has_constant_input(mask_nodes[1], 1): + logger.debug("Sub node expected to have an input with constant value 1.0.") + continue + + # add a squeeze node to convert a 3-d mask to 2-d + squeeze_node = self.match_parent_path(mask_nodes[-1], ["Squeeze"], [0]) or self.match_parent_path( + mask_nodes[-1], ["Expand"], [0] + ) + squeeze_node_name = "Squeeze_3d_to_2d_mask" + squeeze_output_name = squeeze_node_name + "_output" + if squeeze_node is None and len(mask_nodes) == 5 and self.find_graph_input(mask_nodes[-1].input[0]) is None: + mask_input = mask_nodes[-1].input[1] + self.add_node( + helper.make_node( + "Squeeze", + [mask_input], + [squeeze_output_name], + squeeze_node_name, + axes=[1], + ), + graph_name, + ) + mask_nodes[-1].input[0] = squeeze_output_name + + is_same_root = self.check_attention_input(matmul_q, matmul_k, matmul_v, parent, output_name_to_node) + if is_same_root: + mask_index = self.attention_mask.process_mask(mask_nodes[-1].input[0]) + logger.debug("Create an Attention node.") + + # For tf models, q and v are flipped. + attention_node = self.attention_fusion.create_attention_node( + mask_index=mask_index, + q_matmul=matmul_k, + k_matmul=matmul_q, + v_matmul=matmul_v, + q_add=add_k, + k_add=add_q, + v_add=add_v, + num_heads=self.num_heads, + hidden_size=self.hidden_size, + first_input=parent.output[0], + output=qkv_nodes[2].output[0], + ) + if attention_node is None: + continue + + if qkv_nodes[1].op_type == "Einsum": + # add reshape before einsum + tensor = helper.make_tensor( + name=qkv_nodes[1].name + "_newshape", + data_type=TensorProto.INT64, + dims=[4], + vals=np.int64( + [ + [ + 0, + 0, + self.num_heads, + int(self.hidden_size / self.num_heads), + ] + ] + ).tobytes(), + raw=True, + ) + self.add_initializer(tensor, graph_name) + reshape_ = helper.make_node( + "Reshape", + inputs=[ + attention_node.output[0], + qkv_nodes[1].name + "_newshape", + ], + outputs=[qkv_nodes[1].name + "_reshape_output"], + name=qkv_nodes[1].name + "_reshape", + ) + qkv_nodes[1].input[0] = qkv_nodes[1].name + "_reshape_output" + self.add_node(reshape_, graph_name) + if parent.op_type == "Reshape": + # Temporary work around: we require the skiplayernorm and attention op be fed with 3-d input + hidden_size = numpy_helper.to_array(self.get_initializer(parent.input[1]))[1] + tensor = helper.make_tensor( + name=parent.name + "_modified", + data_type=TensorProto.INT64, + dims=[3], + vals=np.int64([[1, -1, hidden_size]]).tobytes(), + raw=True, + ) + self.add_initializer(tensor, graph_name) + parent.input[1] = parent.name + "_modified" + + self.add_node(attention_node, graph_name) + attention_count += 1 + + nodes_to_remove.extend(qkv_nodes[2:]) + nodes_to_remove.extend(qk_nodes) + nodes_to_remove.extend(q_nodes) + nodes_to_remove.extend(k_nodes) + nodes_to_remove.extend(v_nodes) + nodes_to_remove.extend(mask_nodes) + else: + logger.debug("Root node not matched.") + continue + self.remove_nodes(nodes_to_remove) + self.update_graph() + logger.info(f"Fused Attention count:{attention_count}") + + def preprocess(self): + self.remove_identity() + self.process_embedding() + self.skip_reshape() + + def skip_reshape(self): + count = 0 + reshape_nodes = self.get_nodes_by_op_type("Reshape") + for reshape_node in reshape_nodes: + parent = self.get_parent(reshape_node, 0) + if parent is not None and parent.op_type == "Reshape": + reshape_node.input[0] = parent.input[0] + count += 1 + + if count > 0: + logger.info(f"Skip consequent Reshape count: {count}") + + def remove_reshape_before_first_attention(self): + attention_nodes = self.get_nodes_by_op_type("Attention") + for attention_node in attention_nodes: + path = self.match_parent_path(attention_node, ["Reshape", "EmbedLayerNormalization"], [0, 0]) + if path is None: + continue + logger.info("Remove Reshape before first Attention node.") + reshape, _ = path + self.replace_input_of_all_nodes(reshape.output[0], reshape.input[0]) + self.remove_node(reshape) + break + + def postprocess(self): + self.remove_reshape_before_first_attention() + self.prune_graph() diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/onnx_model_clip.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/onnx_model_clip.py new file mode 100644 index 0000000000000000000000000000000000000000..5f3a5e9bf81410d59b5ae5ef4758009c6434713a --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/onnx_model_clip.py @@ -0,0 +1,42 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +# -------------------------------------------------------------------------- + +from logging import getLogger + +from fusion_attention_clip import FusionAttentionClip +from onnx import ModelProto +from onnx_model_bert import BertOnnxModel + +logger = getLogger(__name__) + + +class ClipOnnxModel(BertOnnxModel): + def __init__(self, model: ModelProto, num_heads: int = 0, hidden_size: int = 0): + super().__init__(model, num_heads=num_heads, hidden_size=hidden_size) + self.clip_attention_fusion = FusionAttentionClip(self, self.hidden_size, self.num_heads) + + def get_fused_operator_statistics(self): + """ + Returns node count of fused operators. + """ + op_count = {} + ops = [ + "Attention", + "FastGelu", + "Gelu", + "LayerNormalization", + "QuickGelu", + "BiasGelu", + "SkipLayerNormalization", + ] + for op in ops: + nodes = self.get_nodes_by_op_type(op) + op_count[op] = len(nodes) + + logger.info(f"Optimized operators:{op_count}") + return op_count + + def fuse_attention(self): + self.clip_attention_fusion.apply() diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/onnx_model_conformer.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/onnx_model_conformer.py new file mode 100644 index 0000000000000000000000000000000000000000..1135e4ac36bb0c0c636a45dc49b72a31b36fc430 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/onnx_model_conformer.py @@ -0,0 +1,32 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +# -------------------------------------------------------------------------- +import logging + +from fusion_attention import AttentionMask +from fusion_conformer_attention import FusionConformerAttention +from fusion_options import FusionOptions +from onnx_model_bert import BertOnnxModel + +logger = logging.getLogger(__name__) + + +class ConformerOnnxModel(BertOnnxModel): + def __init__(self, model, num_heads, hidden_size): + super().__init__(model, num_heads, hidden_size) + self.attention_mask = AttentionMask(self) + self.attention_fusion = FusionConformerAttention(self, self.hidden_size, self.num_heads, self.attention_mask) + + def optimize(self, options: FusionOptions | None = None, add_dynamic_axes: bool = False): + self.attention_fusion.use_multi_head_attention = False if options is None else options.use_multi_head_attention + self.attention_fusion.disable_multi_head_attention_bias = ( + False if options is None else options.disable_multi_head_attention_bias + ) + super().optimize(options, add_dynamic_axes) + + def fuse_attention(self): + self.attention_fusion.apply() + + def preprocess(self): + self.adjust_reshape_and_expand() diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/onnx_model_gpt2.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/onnx_model_gpt2.py new file mode 100644 index 0000000000000000000000000000000000000000..3d1d5465fa8adc7207ae4dfd934d30f0e5fd92e3 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/onnx_model_gpt2.py @@ -0,0 +1,101 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +# -------------------------------------------------------------------------- +import logging + +import onnx +from fusion_gpt_attention import FusionGptAttention +from fusion_gpt_attention_megatron import FusionGptAttentionMegatron +from fusion_gpt_attention_no_past import FusionGptAttentionNoPast +from fusion_rotary_attention import FusionRotaryAttention +from onnx_model_bert import BertOnnxModel + +logger = logging.getLogger(__name__) + + +class Gpt2OnnxModel(BertOnnxModel): + def __init__(self, model, num_heads, hidden_size): + super().__init__(model, num_heads, hidden_size) + + def fuse_attention(self): + if len(self.model.graph.input) == 1 or len(self.model.graph.output) == 1: + fusion = FusionGptAttentionNoPast(self, self.num_heads) + fusion.apply() + else: + fusion = FusionGptAttention(self, self.num_heads) + fusion.apply() + fusion = FusionGptAttentionMegatron(self, self.num_heads) + fusion.apply() + + fusion = FusionRotaryAttention(self, self.hidden_size, self.num_heads) + fusion.apply() + + def postprocess(self): + """ + Remove extra reshape nodes. + """ + logger.debug("start postprocessing...") + + input_name_to_nodes = self.input_name_to_nodes() + output_name_to_node = self.output_name_to_node() + + reshape_count = 0 + for gemm_node in self.get_nodes_by_op_type("Gemm"): + reshape_after_gemm = self.find_first_child_by_type( + gemm_node, "Reshape", input_name_to_nodes, recursive=False + ) + + nodes = self.match_parent_path(gemm_node, ["Reshape", "FastGelu"], [0, 0], output_name_to_node) + if nodes is None: + nodes = self.match_parent_path( + gemm_node, + ["Reshape", "LayerNormalization"], + [0, 0], + output_name_to_node, + ) + + if nodes is None: + nodes = self.match_parent_path( + gemm_node, + ["Reshape", "SkipLayerNormalization"], + [0, 0], + output_name_to_node, + ) + + if nodes is None: + continue + + (reshape_before_gemm, root_node) = nodes + + matmul_node_name = self.create_node_name("MatMul", "FullyConnect_MatMul") + matmul_node = onnx.helper.make_node( + "MatMul", + inputs=[matmul_node_name + "_input", gemm_node.input[1]], + outputs=[matmul_node_name + "_output"], + name=matmul_node_name, + ) + + add_node_name = self.create_node_name("Add", "FullyConnect_Add") + add_node = onnx.helper.make_node( + "Add", + inputs=[matmul_node_name + "_output", gemm_node.input[2]], + outputs=[add_node_name + "_output"], + name=add_node_name, + ) + + self.replace_input_of_all_nodes(reshape_after_gemm.output[0], add_node_name + "_output") + + # Link root node output with MatMul + self.replace_input_of_all_nodes(root_node.output[0], matmul_node_name + "_input") + root_node.output[0] = matmul_node_name + "_input" + + self.replace_input_of_all_nodes(reshape_after_gemm.output[0], add_node_name + "_output") + + self.add_node(matmul_node) + self.add_node(add_node) + + reshape_count += 2 + + self.prune_graph() + logger.info(f"postprocess: remove Reshape count: {reshape_count}") diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/onnx_model_mmdit.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/onnx_model_mmdit.py new file mode 100644 index 0000000000000000000000000000000000000000..70fed087acc46a442b4ad4688dc0edb16375982e --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/onnx_model_mmdit.py @@ -0,0 +1,112 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +# -------------------------------------------------------------------------- + +import logging + +from fusion_layernorm import FusionLayerNormalization +from fusion_mha_mmdit import FusionMultiHeadAttentionMMDit +from fusion_options import FusionOptions +from import_utils import is_installed +from onnx import ModelProto +from onnx_model_bert import BertOnnxModel + +logger = logging.getLogger(__name__) + + +class MmditOnnxModel(BertOnnxModel): + def __init__(self, model: ModelProto, num_heads: int = 0, hidden_size: int = 0): + """Initialize Multimodal Diffusion Transformer (MMDiT) ONNX Model. + + Args: + model (ModelProto): the ONNX model + num_heads (int, optional): number of attention heads. Defaults to 0 (detect the parameter automatically). + hidden_size (int, optional): hidden dimension. Defaults to 0 (detect the parameter automatically). + """ + assert (num_heads == 0 and hidden_size == 0) or (num_heads > 0 and hidden_size % num_heads == 0) + super().__init__(model, num_heads=num_heads, hidden_size=hidden_size) + + def postprocess(self): + self.prune_graph() + self.remove_unused_constant() + + def fuse_layer_norm(self): + layernorm_support_broadcast = True + logger.warning( + "The optimized model requires LayerNormalization with broadcast support. " + "Please use onnxruntime-gpu>=1.21 for inference." + ) + fusion = FusionLayerNormalization( + self, check_constant_and_dimension=not layernorm_support_broadcast, force=True + ) + fusion.apply() + + def fuse_multi_head_attention(self): + fusion = FusionMultiHeadAttentionMMDit(self) + fusion.apply() + + def optimize(self, options: FusionOptions | None = None, add_dynamic_axes: bool = False): + assert not add_dynamic_axes + + if is_installed("tqdm"): + import tqdm # noqa: PLC0415 + from tqdm.contrib.logging import logging_redirect_tqdm # noqa: PLC0415 + + with logging_redirect_tqdm(): + steps = 5 + progress_bar = tqdm.tqdm(range(steps), initial=0, desc="fusion") + self._optimize(options, progress_bar) + else: + logger.info("tqdm is not installed. Run optimization without progress bar") + self._optimize(options, None) + + def _optimize(self, options: FusionOptions | None = None, progress_bar=None): + if (options is not None) and not options.enable_shape_inference: + self.disable_shape_inference() + + # Remove cast nodes that having same data type of input and output based on symbolic shape inference. + self.utils.remove_useless_cast_nodes() + if progress_bar: + progress_bar.update(1) + + if (options is None) or options.enable_layer_norm: + self.fuse_layer_norm() + self.fuse_simplified_layer_norm() + if progress_bar: + progress_bar.update(1) + + if (options is None) or options.enable_gelu: + self.fuse_gelu() + if progress_bar: + progress_bar.update(1) + + if (options is None) or options.enable_attention: + self.fuse_multi_head_attention() + if progress_bar: + progress_bar.update(1) + + self.postprocess() + if progress_bar: + progress_bar.update(1) + + logger.info(f"opset version: {self.get_opset_version()}") + + def get_fused_operator_statistics(self): + """ + Returns node count of fused operators. + """ + op_count = {} + ops = [ + "FastGelu", + "MultiHeadAttention", + "LayerNormalization", + "SimplifiedLayerNormalization", + ] + + for op in ops: + nodes = self.get_nodes_by_op_type(op) + op_count[op] = len(nodes) + + logger.info(f"Optimized operators:{op_count}") + return op_count diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/onnx_model_phi.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/onnx_model_phi.py new file mode 100644 index 0000000000000000000000000000000000000000..b84d541c1547f8ee9a62dbbca94722a5ea354dfe --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/onnx_model_phi.py @@ -0,0 +1,929 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +# -------------------------------------------------------------------------- + +from logging import getLogger + +import numpy as np +from dynamo_onnx_helper import DynamoOnnxHelper +from fusion_base import Fusion +from fusion_options import AttentionOpType, FusionOptions +from fusion_skiplayernorm import FusionBiasSkipLayerNormalization, FusionSkipLayerNormalization +from fusion_utils import NumpyHelper +from onnx import ModelProto, NodeProto, TensorProto, helper, numpy_helper +from onnx_model import OnnxModel + +logger = getLogger(__name__) + + +class ProcessGemmWFunc: + def __call__(self, x): + return np.transpose(x, (1, 0)) + + +class ProcessMatMulQFunc: + def __call__(self, x): + return np.transpose(np.split(x, 3, 0)[0], (1, 0)) + + +class ProcessMatMulKFunc: + def __call__(self, x): + return np.transpose(np.split(x, 3, 0)[1], (1, 0)) + + +class ProcessMatMulVFunc: + def __call__(self, x): + return np.transpose(np.split(x, 3, 0)[2], (1, 0)) + + +class ProcessBiasQFunc: + def __call__(self, x): + x = np.split(x, 3, -1)[0] + return x + + +class ProcessBiasKFunc: + def __call__(self, x): + x = np.split(x, 3, -1)[1] + return x + + +class ProcessBiasVFunc: + def __call__(self, x): + x = np.split(x, 3, -1)[2] + return x + + +class ProcessRotCacheFunc: + def __call__(self, x): + # half rotary embedding + assert len(x.shape) == 2 + if x.shape[1] == 32: + return x[:, 0:16] + return x + + +# TODO: move to a separate file +class Fission(Fusion): + def __init__( + self, + model: OnnxModel, + nodes_to_find: list[str], + ): + super().__init__(model, "DONOTUSE", nodes_to_find) + + def set_attention_op_type(self, attn_op_type: AttentionOpType): + self.attn_op_type = attn_op_type + + def get_uname(self, layer_id, name): + return name + "_" + str(layer_id) + + def get_edge_by_name(self, edges, name): + for edge in edges: + if edge == name or edge.endswith(name) or edge.startswith(name): + return edge + raise ValueError(f"Edge {name} not found") + + def get_input_by_name(self, node, name): + return self.get_edge_by_name(node.input, name) + + def get_output_by_name(self, node, name): + return self.get_edge_by_name(node.output, name) + + def process_initializer(self, initializer_name, functor, custom_name=None): + i = self.model.get_initializer(initializer_name) + i_np_array = NumpyHelper.to_array(i) + processed_i_np_array = functor(i_np_array) + new_tensor = helper.make_tensor( + initializer_name + "_processed" if custom_name is None else custom_name, + data_type=TensorProto.FLOAT, + dims=processed_i_np_array.shape, + vals=processed_i_np_array.flatten().tobytes(), + raw=True, + ) + self.model.add_initializer(new_tensor, self.this_graph_name) + return new_tensor.name + + def add_fp32_value_info(self, name): + new_value_info = self.model.graph().value_info.add() + new_value_info.name = name + new_value_info.type.tensor_type.elem_type = TensorProto.FLOAT + + def add_int64_value_info(self, name): + new_value_info = self.model.graph().value_info.add() + new_value_info.name = name + new_value_info.type.tensor_type.elem_type = TensorProto.INT64 + + def replace_fp32_value_info(self, name, shape): + for value_info in self.model.graph().value_info: + if value_info.name == name: + self.model.graph().value_info.remove(value_info) + break + new_value_info = helper.make_tensor_value_info( + name, + elem_type=TensorProto.FLOAT, + shape=shape, + ) + self.model.graph().value_info.extend([new_value_info]) + + def set_unique_name_and_add_nodes( + self, subgraph_nodes: list[NodeProto], layer_id: int, layer_known_edges_names: list[str] + ): + for new_node in subgraph_nodes: + for i, name in enumerate(new_node.input): + if name == "": + continue + elif name not in layer_known_edges_names: + new_node.input[i] = self.get_uname(layer_id, name) + self.add_fp32_value_info(new_node.input[i]) + for i, name in enumerate(new_node.output): + if name == "": + continue + elif name not in layer_known_edges_names: + new_node.output[i] = self.get_uname(layer_id, name) + self.add_fp32_value_info(new_node.output[i]) + new_node.name = self.get_uname(layer_id, new_node.name) + self.nodes_to_add.append(new_node) + self.node_name_to_graph_name[new_node.name] = self.this_graph_name + + def layernorm(self, inputs: list[str], outputs: list[str], prefix: str = ""): + assert len(inputs) == 3 + assert len(outputs) == 1 + node = helper.make_node( + "LayerNormalization", + inputs=inputs, + outputs=outputs, + name=prefix + "_LayerNormalization", + epsilon=9.999999747378752e-06, + ) + return [node] + + def gemm(self, inputs: list[str], outputs: list[str], prefix: str = ""): + assert len(inputs) == 3 + assert len(outputs) == 1 + matmul = helper.make_node( + "MatMul", + inputs=[inputs[0], inputs[1]], + outputs=[prefix + "matmul_out"], + name=prefix + "MatMul", + ) + add = helper.make_node( + "Add", + inputs=[prefix + "matmul_out", inputs[2]], + outputs=outputs, + name=prefix + "Bias", + ) + return [matmul, add] + + def rotary(self, inputs: list[str], outputs: list[str], prefix: str = "", rot_dim=32, num_heads=32): + assert len(inputs) == 4 + assert len(outputs) == 1 + node = helper.make_node( + "RotaryEmbedding", + inputs=inputs, + outputs=outputs, + name=prefix + "RotaryEmbedding", + domain="com.microsoft", + rotary_embedding_dim=rot_dim, + num_heads=num_heads, + ) + return [node] + + def fastgelu(self, inputs: list[str], outputs: list[str], prefix: str = ""): + assert len(inputs) == 1 + assert len(outputs) == 1 + node = helper.make_node( + "FastGelu", + inputs=inputs, + outputs=outputs, + name=prefix + "FastGelu", + domain="com.microsoft", + ) + return [node] + + def add(self, inputs: list[str], outputs: list[str], prefix: str = ""): + assert len(inputs) == 2 + assert len(outputs) == 1 + node = helper.make_node( + "Add", + inputs=inputs, + outputs=outputs, + name=prefix + "Add", + ) + return [node] + + def mha(self, inputs: list[str], outputs: list[str], prefix: str = "", num_heads=32): + assert len(inputs) == 8 + assert len(outputs) == 3 + node = helper.make_node( + "MultiHeadAttention", + inputs=inputs, + outputs=outputs, + name=prefix + "MultiHeadAttention", + domain="com.microsoft", + num_heads=num_heads, + unidirectional=1, + ) + return [node] + + def gqa(self, inputs: list[str], outputs: list[str], prefix: str = "", num_heads=32): + assert len(inputs) == 7 + assert len(outputs) == 3 + node = helper.make_node( + "GroupQueryAttention", + inputs=inputs, + outputs=outputs, + name=prefix + "GroupQueryAttention", + domain="com.microsoft", + num_heads=num_heads, + kv_num_heads=num_heads, + ) + return [node] + + def attention(self, inputs: list[str], outputs: list[str], prefix: str = "", num_heads=32): + assert len(inputs) == 5 + assert len(outputs) == 2 + node = helper.make_node( + "Attention", + inputs=inputs, + outputs=outputs, + name=prefix + "Attention", + domain="com.microsoft", + num_heads=num_heads, + unidirectional=1, + do_rotary=1, + rotary_embedding_dim=32, + ) + return [node] + + def paged_attn( + self, + inputs: list[str], + outputs: list[str], + prefix: str = "", + num_heads=32, + head_size=80, + scale=0.11180339753627777, + ): + assert len(inputs) == 6 + assert len(outputs) == 1 + node = helper.make_node( + "PagedAttention", + inputs=inputs, + outputs=outputs, + name=prefix + "PagedAttention", + domain="vllm.ort.ext", + num_heads=num_heads, + num_kv_heads=num_heads, + head_size=head_size, + scale=scale, + ) + return [node] + + +class Phi2PreProcessor(DynamoOnnxHelper): + def __init__(self, model: ModelProto, num_heads: int, hidden_size: int): + super().__init__(model) + self.num_hidden_layers = 32 + self.num_attention_heads = num_heads + self.hidden_size = hidden_size + + self.func_name = "modeling_phi_PhiModel_model_1" + + def get_phi2_edge_dict(self) -> dict: + edge_dict = {} + edge_dict["lm_head_1"] = "logits" + edge_dict["l_input_ids_"] = "input_ids" + edge_dict["key_states"] = "past_key_0" + edge_dict["value_states"] = "past_value_0" + for i in range(1, self.num_hidden_layers, 1): + edge_dict[f"key_states_{i}"] = f"past_key_{i}" + edge_dict[f"value_states_{i}"] = f"past_value_{i}" + edge_dict[f"model_layers_{i}_1"] = f"present_key_{i}" + edge_dict[f"model_layers_{i}_1_1"] = f"present_value_{i}" + + outputs = [o.name for o in self.model.graph.output] + if "model_layers_0_1_1" in outputs and "model_layers_0_1_2" in outputs: + edge_dict["model_layers_0_1_1"] = "present_key_0" + edge_dict["model_layers_0_1_2"] = "present_value_0" + else: + assert "model_layers_0_1" in outputs and "model_layers_0_1_1" in outputs + edge_dict["model_layers_0_1"] = "present_key_0" + edge_dict["model_layers_0_1_1"] = "present_value_0" + return edge_dict + + def simplify_phi2_op_type(self): + phi2_transformer_layer_name = "modeling_phi_PhiDecoderLayer_model_layers" + for node in self.model.graph.node: + index = node.op_type.find(phi2_transformer_layer_name) + if index != -1: + node.op_type = node.op_type[index:] + + def process_graph_io(self, attn_op_type: AttentionOpType): + self.use_attn = attn_op_type == AttentionOpType.Attention + self.use_vllm = attn_op_type == AttentionOpType.PagedAttention + graph = self.model.graph + new_inputs = [] + for vi in graph.input: + if "input_ids" in vi.name: + vi_iid = helper.make_tensor_value_info( + vi.name, + elem_type=TensorProto.INT32 if not self.use_vllm else TensorProto.INT64, + shape=["batch_size", "seq_len"], + ) + vi_step = helper.make_tensor_value_info( + "step", + elem_type=TensorProto.INT64, + shape=[1], + ) + vi_pid = helper.make_tensor_value_info( + "position_ids", + elem_type=TensorProto.INT64, + shape=["batch_size", "seq_len"], + ) + vi_mask = helper.make_tensor_value_info( + "attention_mask", + elem_type=TensorProto.INT32, + shape=["batch_size", "seq_len"], + ) + vi_meta = helper.make_tensor_value_info( + "input_metadata", + elem_type=TensorProto.INT64, + shape=[1], + ) + ( + new_inputs.extend([vi_iid, vi_step, vi_mask]) + if not self.use_vllm + else new_inputs.extend([vi_iid, vi_pid, vi_meta]) + ) + if self.use_attn: + if "past_key" in vi.name: + vi_cache = helper.make_tensor_value_info( + vi.name.replace("past_key", "past"), + elem_type=vi.type.tensor_type.elem_type, + shape=[ + 2, + "batch_size", + self.num_attention_heads, + "past_seq_len", + self.hidden_size // self.num_attention_heads, + ], + ) + new_inputs.extend([vi_cache]) + elif self.use_vllm: + if "past_key" in vi.name: + vi_cache = helper.make_tensor_value_info( + vi.name, + elem_type=vi.type.tensor_type.elem_type, + shape=["num_blocks", "num_heads", "head_size_x", "block_size", "block_x"], + ) + new_inputs.extend([vi_cache]) + if "past_value" in vi.name: + vi_cache = helper.make_tensor_value_info( + vi.name, + elem_type=vi.type.tensor_type.elem_type, + shape=[ + "num_blocks", + "num_heads", + "head_size", + "block_size", + ], + ) + new_inputs.extend([vi_cache]) + else: + if "past_key" in vi.name or "past_value" in vi.name: + vi_cache = helper.make_tensor_value_info( + vi.name, + elem_type=vi.type.tensor_type.elem_type, + shape=[ + "batch_size", + self.num_attention_heads, + "past_seq_len", + self.hidden_size // self.num_attention_heads, + ], + ) + new_inputs.extend([vi_cache]) + + graph.ClearField("input") + graph.input.extend(new_inputs) + + new_outputs = [] + for i, vi in enumerate(graph.output): + if i == 0: + new_outputs.extend([vi]) + else: + if self.use_attn: + if "present_key" in vi.name: + vi_cache = helper.make_tensor_value_info( + vi.name.replace("present_key", "present"), + elem_type=vi.type.tensor_type.elem_type, + shape=[ + 2, + "batch_size", + self.num_attention_heads, + "total_seq_len", + self.hidden_size // self.num_attention_heads, + ], + ) + new_outputs.extend([vi_cache]) + elif self.use_vllm: + pass + else: + vi_cache = helper.make_tensor_value_info( + vi.name, + elem_type=vi.type.tensor_type.elem_type, + shape=[ + "batch_size", + self.num_attention_heads, + "total_seq_len", + self.hidden_size // self.num_attention_heads, + ], + ) + new_outputs.extend([vi_cache]) + + graph.ClearField("output") + graph.output.extend(new_outputs) + + def preprocess_onnx(self, attn_op_type: AttentionOpType): + function_name = None + for func in self.model.functions: + if func.name.endswith(self.func_name): + function_name = func.name + break + assert function_name is not None + self.unroll_function(function_name) + self.update_edges(self.get_phi2_edge_dict()) + self.simplify_phi2_op_type() + self.remove_dropout_layer() + if attn_op_type == AttentionOpType.PagedAttention: + self.remove_lm_head_layer() + self.process_graph_io(attn_op_type) + + +class FissionTransformerEmbeddingPhi(Fission): + def __init__( + self, + model: OnnxModel, + ): + super().__init__(model, ["torch_nn_modules_sparse_Embedding_model_embed_tokens_1"]) + + def fuse(self, node, input_name_to_nodes, output_name_to_node): + logger.info("Optimizing %s...", node.name) + + assert len(node.input) == 2 + assert len(node.output) == 1 + + input = node.input[0] + output = node.output[0] + + embedding = self.get_input_by_name(node, "embed_tokens.weight") + + layer_known_edges_names = [input, output, embedding] + + subgraph_nodes = [ + helper.make_node( + "Gather", + inputs=[embedding, input], + outputs=[output], + name="Embedding_Gather", + ), + ] + + self.set_unique_name_and_add_nodes(subgraph_nodes, 0, layer_known_edges_names) + self.nodes_to_remove.append(node) + self.prune_graph = True + + +class FissionTransformerLayerNormPhi(Fission): + def __init__( + self, + model: OnnxModel, + ): + super().__init__(model, ["torch_nn_modules_normalization_LayerNorm_model_final_layernorm_1"]) + + def fuse(self, node, input_name_to_nodes, output_name_to_node): + logger.info("Optimizing %s...", node.name) + + assert len(node.input) == 3 + assert len(node.output) == 1 + + input = node.input[0] + output = node.output[0] + + ln_weight = self.get_input_by_name(node, "final_layernorm.weight") + ln_bias = self.get_input_by_name(node, "final_layernorm.bias") + + layer_known_edges_names = [input, output, ln_weight, ln_bias] + + subgraph_nodes = [] + subgraph_nodes.extend(self.layernorm([input, ln_weight, ln_bias], [output], "Final")) + + self.set_unique_name_and_add_nodes(subgraph_nodes, 99, layer_known_edges_names) + + self.replace_fp32_value_info(input, ["batch_size", "seq_len", "hidden_size"]) + self.replace_fp32_value_info(output, ["batch_size", "seq_len", "hidden_size"]) + + self.nodes_to_remove.append(node) + self.prune_graph = True + + +class FissionTransformerCausalLMHeadPhi(Fission): + def __init__( + self, + model: OnnxModel, + ): + super().__init__(model, ["torch_nn_modules_linear_Linear_lm_head_1"]) + + def fuse(self, node, input_name_to_nodes, output_name_to_node): + logger.info("Optimizing %s...", node.name) + + assert len(node.input) == 5 + assert len(node.output) == 1 + + input = node.input[2] + output = node.output[0] + + fc_weight = self.process_initializer(self.get_input_by_name(node, "lm_head.weight"), ProcessGemmWFunc()) + fc_bias = self.get_input_by_name(node, "lm_head.bias") + + layer_known_edges_names = [input, output, fc_weight, fc_bias] + + subgraph_nodes = [] + subgraph_nodes.extend(self.gemm([input, fc_weight, fc_bias], [output], "LMHead_")) + + self.set_unique_name_and_add_nodes(subgraph_nodes, 99, layer_known_edges_names) + + self.replace_fp32_value_info(input, ["batch_size", "seq_len", "hidden_size"]) + self.replace_fp32_value_info(output, ["batch_size", "seq_len", 51200]) + + self.nodes_to_remove.append(node) + self.prune_graph = True + + +class FissionTransformerBlockPhi(Fission): + def __init__( + self, + model: OnnxModel, + num_heads: int, + ): + self.num_heads = num_heads + max_num_layers = 32 + self.func_to_layer_id = {} + nodes_to_find = [] + for layer in range(max_num_layers): + func_name = f"modeling_phi_PhiDecoderLayer_model_layers_{layer}_1" + nodes_to_find.append(func_name) + self.func_to_layer_id[func_name] = layer + + super().__init__(model, nodes_to_find) + + def get_layer_id(self, node): + return self.func_to_layer_id[node.op_type] + + def get_gqa_aux_nodes(self): + gqa_aux_nodes = [ + helper.make_node( + "Cast", + inputs=["attention_mask"], + outputs=["mask_int64"], + name="Cast_gqa_aux_0", + to=TensorProto.INT64, + ), + helper.make_node( + "ReduceSum", + inputs=["mask_int64", "one"], + outputs=["mask_row_sums"], + name="ReduceSum_gqa_aux", + ), + helper.make_node( + "Sub", + inputs=["mask_row_sums", "one"], + outputs=["seqlens_k_int64"], + name="Sub_gqa_aux", + ), + helper.make_node( + "Cast", + inputs=["seqlens_k_int64"], + outputs=["seqlens_k"], + name="Cast_gqa_aux_1", + to=TensorProto.INT32, + ), + helper.make_node("Shape", inputs=["mask_int64"], outputs=["mask_shape"], name="Shape_gqa_aux_0"), + helper.make_node( + "Gather", + inputs=["mask_shape", "one"], + outputs=["total_seq_len_int64"], + name="Gather_gqa_aux_0", + axis=0, + ), + helper.make_node( + "Cast", + inputs=["total_seq_len_int64"], + outputs=["total_sequence_length"], + name="Cast_gqa_aux_2", + to=TensorProto.INT32, + ), + ] + return gqa_aux_nodes + + def pack_qkv_gemm(self, q_w, k_w, v_w, q_b, k_b, v_b, weight_name, bias_name): + q_weight = self.model.get_initializer(q_w) + k_weight = self.model.get_initializer(k_w) + v_weight = self.model.get_initializer(v_w) + qw = np.transpose(NumpyHelper.to_array(q_weight), (1, 0)) + kw = np.transpose(NumpyHelper.to_array(k_weight), (1, 0)) + vw = np.transpose(NumpyHelper.to_array(v_weight), (1, 0)) + qkv_weight = np.stack((qw, kw, vw), axis=1) + + q_bias = self.model.get_initializer(q_b) + k_bias = self.model.get_initializer(k_b) + v_bias = self.model.get_initializer(v_b) + qb = NumpyHelper.to_array(q_bias) + kb = NumpyHelper.to_array(k_bias) + vb = NumpyHelper.to_array(v_bias) + qkv_bias = np.stack((qb, kb, vb), axis=0) + + hidden_size = qkv_weight.shape[0] + + weight = helper.make_tensor( + weight_name, + data_type=TensorProto.FLOAT, + dims=[hidden_size, hidden_size * 3], + vals=qkv_weight.flatten().tobytes(), + raw=True, + ) + self.model.add_initializer(weight, self.this_graph_name) + + bias = helper.make_tensor( + bias_name, + data_type=TensorProto.FLOAT, + dims=[hidden_size * 3], + vals=qkv_bias.flatten().tobytes(), + raw=True, + ) + self.model.add_initializer(bias, self.this_graph_name) + + self.add_fp32_value_info(weight.name) + self.add_fp32_value_info(bias.name) + + return weight_name, bias_name + + def fuse( + self, + node, + input_name_to_nodes, + output_name_to_node, + ): + logger.info("Optimizing %s...", node.name) + + logger.info(f"AttentionOpType: {self.attn_op_type}") + + layer_id = self.get_layer_id(node) + + i_hidden_states = node.input[0] + i_key_cache = self.get_input_by_name(node, "past_key") + i_value_cache = self.get_input_by_name(node, "past_value") + + o_hidden_states = node.output[-1] + o_key_cache = self.get_output_by_name(node, "present_key") + o_value_cache = self.get_output_by_name(node, "present_value") + + ln_weight = self.get_input_by_name(node, "input_layernorm.weight") + ln_bias = self.get_input_by_name(node, "input_layernorm.bias") + + attn_q_weight, attn_q_bias, attn_k_weight, attn_k_bias, attn_v_weight, attn_v_bias = ( + None, + None, + None, + None, + None, + None, + ) + attn_qkv_weight, attn_qkv_bias = None, None + cos_cache, sin_cache = None, None + + if self.attn_op_type != AttentionOpType.Attention: + attn_q_weight = self.process_initializer( + self.get_input_by_name(node, "self_attn.q_proj.weight"), ProcessGemmWFunc() + ) + attn_k_weight = self.process_initializer( + self.get_input_by_name(node, "self_attn.k_proj.weight"), ProcessGemmWFunc() + ) + attn_v_weight = self.process_initializer( + self.get_input_by_name(node, "self_attn.v_proj.weight"), ProcessGemmWFunc() + ) + attn_q_bias = self.get_input_by_name(node, "self_attn.q_proj.bias") + attn_k_bias = self.get_input_by_name(node, "self_attn.k_proj.bias") + attn_v_bias = self.get_input_by_name(node, "self_attn.v_proj.bias") + + cos_cache = self.process_initializer( + self.get_input_by_name(node, "rotary_emb.cos_cached"), ProcessRotCacheFunc() + ) + sin_cache = self.process_initializer( + self.get_input_by_name(node, "rotary_emb.sin_cached"), ProcessRotCacheFunc() + ) + else: + attn_qkv_weight, attn_qkv_bias = self.pack_qkv_gemm( + self.get_input_by_name(node, "self_attn.q_proj.weight"), + self.get_input_by_name(node, "self_attn.k_proj.weight"), + self.get_input_by_name(node, "self_attn.v_proj.weight"), + self.get_input_by_name(node, "self_attn.q_proj.bias"), + self.get_input_by_name(node, "self_attn.k_proj.bias"), + self.get_input_by_name(node, "self_attn.v_proj.bias"), + self.get_uname(layer_id, "attn_qkv_weight"), + self.get_uname(layer_id, "attn_qkv_bias"), + ) + + attn_out_weight = self.process_initializer( + self.get_input_by_name(node, "self_attn.dense.weight"), ProcessGemmWFunc() + ) + attn_out_bias = self.get_input_by_name(node, "self_attn.dense.bias") + + mlp_fc1_weight = self.process_initializer(self.get_input_by_name(node, "mlp.fc1.weight"), ProcessGemmWFunc()) + mlp_fc2_weight = self.process_initializer(self.get_input_by_name(node, "mlp.fc2.weight"), ProcessGemmWFunc()) + mlp_fc1_bias = self.get_input_by_name(node, "mlp.fc1.bias") + mlp_fc2_bias = self.get_input_by_name(node, "mlp.fc2.bias") + + layer_known_edges_names = [] + layer_known_edges_names.extend([i_hidden_states, i_key_cache, i_value_cache]) + layer_known_edges_names.extend([o_hidden_states, o_key_cache, o_value_cache]) + layer_known_edges_names.extend([ln_weight, ln_bias]) + if self.attn_op_type != AttentionOpType.Attention: + layer_known_edges_names.extend( + [ + attn_q_weight, + attn_q_bias, + attn_k_weight, + attn_k_bias, + attn_v_weight, + attn_v_bias, + cos_cache, + sin_cache, + ] + ) + else: + layer_known_edges_names.extend([attn_qkv_weight, attn_qkv_bias]) + layer_known_edges_names.extend( + [attn_out_weight, attn_out_bias, mlp_fc1_weight, mlp_fc1_bias, mlp_fc2_weight, mlp_fc2_bias] + ) + layer_known_edges_names.extend( + ["attention_mask", "step", "seqlens_k", "total_sequence_length", "input_metadata", "position_ids"] + ) + + subgraph_nodes = [] + subgraph_nodes.extend(self.layernorm([i_hidden_states, ln_weight, ln_bias], ["ln_out"])) + subgraph_nodes.extend(self.gemm(["attn_out", attn_out_weight, attn_out_bias], ["attn_add_out"], "OutProj_")) + subgraph_nodes.extend(self.gemm(["ln_out", mlp_fc1_weight, mlp_fc1_bias], ["fc1_out"], "FC1_")) + subgraph_nodes.extend(self.fastgelu(["fc1_out"], ["gelu_out"])) + subgraph_nodes.extend(self.gemm(["gelu_out", mlp_fc2_weight, mlp_fc2_bias], ["fc2_out"], "FC2_")) + subgraph_nodes.extend(self.add(["attn_add_out", "fc2_out"], ["residual_1_out"], "Residual_1")) + subgraph_nodes.extend(self.add([i_hidden_states, "residual_1_out"], [o_hidden_states], "Residual_2")) + if self.attn_op_type != AttentionOpType.Attention: + subgraph_nodes.extend(self.gemm(["ln_out", attn_q_weight, attn_q_bias], ["query"], "Q_")) + subgraph_nodes.extend(self.gemm(["ln_out", attn_k_weight, attn_k_bias], ["key"], "K_")) + subgraph_nodes.extend(self.gemm(["ln_out", attn_v_weight, attn_v_bias], ["value"], "V_")) + # vllm engine requires full position ids as the input + pos_ids_name = "position_ids" if self.attn_op_type == AttentionOpType.PagedAttention else "step" + subgraph_nodes.extend(self.rotary(["query", pos_ids_name, cos_cache, sin_cache], ["query_rot"], "Q_")) + subgraph_nodes.extend(self.rotary(["key", pos_ids_name, cos_cache, sin_cache], ["key_rot"], "K_")) + if self.attn_op_type == AttentionOpType.MultiHeadAttention: + subgraph_nodes.extend( + self.mha( + ["query_rot", "key_rot", "value", "", "attention_mask", "", i_key_cache, i_value_cache], + ["attn_out", o_key_cache, o_value_cache], + ) + ) + elif self.attn_op_type == AttentionOpType.GroupQueryAttention: + subgraph_nodes.extend( + self.gqa( + [ + "query_rot", + "key_rot", + "value", + i_key_cache, + i_value_cache, + "seqlens_k", + "total_sequence_length", + ], + ["attn_out", o_key_cache, o_value_cache], + ) + ) + if layer_id == 0: + gqa_aux_nodes = self.get_gqa_aux_nodes() + for new_node in gqa_aux_nodes: + self.nodes_to_add.append(new_node) + self.node_name_to_graph_name[new_node.name] = self.this_graph_name + self.model.add_initializer( + numpy_helper.from_array(np.array([1], dtype="int64"), name="one"), self.this_graph_name + ) + elif self.attn_op_type == AttentionOpType.PagedAttention: + subgraph_nodes.extend( + self.paged_attn( + ["query_rot", "key_rot", "value", i_key_cache, i_value_cache, "input_metadata"], + ["attn_out"], + ) + ) + else: + past_name = f"past_{layer_id}" + present_name = f"present_{layer_id}" + layer_known_edges_names.extend([past_name, present_name]) + subgraph_nodes.extend( + self.attention( + ["ln_out", attn_qkv_weight, attn_qkv_bias, "attention_mask", past_name], ["attn_out", present_name] + ) + ) + + self.set_unique_name_and_add_nodes(subgraph_nodes, layer_id, layer_known_edges_names) + + self.replace_fp32_value_info(i_hidden_states, ["batch_size", "seq_len", "hidden_size"]) + self.replace_fp32_value_info(o_hidden_states, ["batch_size", "seq_len", "hidden_size"]) + + self.nodes_to_remove.append(node) + self.prune_graph = True + + +class PhiOnnxModel(OnnxModel): + def __init__(self, model: ModelProto, num_heads: int, hidden_size: int): + super().__init__(model) + self.phi2_preprocessor = Phi2PreProcessor(self.model, num_heads, hidden_size) + self.fission_transformer_block = FissionTransformerBlockPhi(self, num_heads) + self.fission_causal_lm_head = FissionTransformerCausalLMHeadPhi(self) + self.fission_transformer_layernorm = FissionTransformerLayerNormPhi(self) + self.fission_transformer_embedding = FissionTransformerEmbeddingPhi(self) + + def optimize(self, options: FusionOptions | None = None, add_dynamic_axes: bool = False): + assert options is not None + attn_op_type = options.attention_op_type + + self.fission_transformer_block.set_attention_op_type(attn_op_type) + + self.phi2_preprocessor.preprocess_onnx(attn_op_type) + + self.fission_transformer_block.apply() + self.fission_transformer_layernorm.apply() + self.fission_causal_lm_head.apply() + self.fission_transformer_embedding.apply() + + super().prune_graph() + + # SLN ctor is placed here intentionally to delay the symbolic shape inference + self.fuse_sln = FusionSkipLayerNormalization(self) + self.fuse_bias_sln = FusionBiasSkipLayerNormalization(self) + self.fuse_sln.apply() + self.fuse_bias_sln.apply() + + def get_fused_operator_statistics(self): + """ + Returns node count of fused operators. + """ + op_count = {} + ops = [ + "Attention", + "MultiHeadAttention", + "GroupQueryAttention", + "PagedAttention", + "Gelu", + "BiasGelu", + "FastGelu", + "LayerNormalization", + "SkipLayerNormalization", + ] + for op in ops: + nodes = self.get_nodes_by_op_type(op) + op_count[op] = len(nodes) + + logger.info(f"Optimized operators: {op_count}") + return op_count + + def is_fully_optimized(self, fused_op_count=None): + """ + Returns True when the model is fully optimized. + """ + if fused_op_count is None: + fused_op_count = self.get_fused_operator_statistics() + + def op_count(op_name: str): + return fused_op_count.get(op_name) or 0 + + attention = ( + op_count("Attention") + + op_count("MultiHeadAttention") + + op_count("GroupQueryAttention") + + op_count("PagedAttention") + ) + gelu = op_count("Gelu") + op_count("BiasGelu") + op_count("FastGelu") + layer_norm = op_count("LayerNormalization") + op_count("SkipLayerNormalization") + + is_perfect = (attention > 0) and (attention == gelu) and (layer_norm >= attention) + + if layer_norm == 0: + logger.debug("Layer Normalization not fused") + + if gelu == 0: + logger.debug("Gelu (or FastGelu) not fused") + + if attention == 0: + logger.warning("Attention (or MultiHeadAttention) not fused") + + return is_perfect diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/onnx_model_sam2.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/onnx_model_sam2.py new file mode 100644 index 0000000000000000000000000000000000000000..2f83e89849e7f677a174801747e6f5a8cac1602f --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/onnx_model_sam2.py @@ -0,0 +1,137 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +# -------------------------------------------------------------------------- + +import logging + +from fusion_attention_sam2 import FusionMultiHeadAttentionSam2 +from fusion_layernorm import FusionLayerNormalizationNCHW +from fusion_options import FusionOptions +from import_utils import is_installed +from onnx import ModelProto +from onnx_model_bert import BertOnnxModel + +logger = logging.getLogger(__name__) + + +class Sam2OnnxModel(BertOnnxModel): + def __init__(self, model: ModelProto, num_heads: int = 0, hidden_size: int = 0): + """Initialize SAM2 ONNX Model. + + Args: + model (ModelProto): the ONNX model + num_heads (int, optional): number of attention heads. Defaults to 0 (detect the parameter automatically). + hidden_size (int, optional): hidden dimension. Defaults to 0 (detect the parameter automatically). + """ + assert (num_heads == 0 and hidden_size == 0) or (num_heads > 0 and hidden_size % num_heads == 0) + + super().__init__(model, num_heads=num_heads, hidden_size=hidden_size) + + def postprocess(self): + self.prune_graph() + self.remove_unused_constant() + + def fuse_layer_norm(self): + super().fuse_layer_norm() + + fusion = FusionLayerNormalizationNCHW(self) + fusion.apply() + + def fuse_multi_head_attention(self, options: FusionOptions | None = None): + mha_fusion = FusionMultiHeadAttentionSam2(self, self.hidden_size, self.num_heads) + mha_fusion.apply() + + def optimize(self, options: FusionOptions | None = None, add_dynamic_axes: bool = False): + if is_installed("tqdm"): + import tqdm # noqa: PLC0415 + from tqdm.contrib.logging import logging_redirect_tqdm # noqa: PLC0415 + + with logging_redirect_tqdm(): + steps = 12 + progress_bar = tqdm.tqdm(range(steps), initial=0, desc="sam2 fusion") + self._optimize(options, progress_bar) + else: + logger.info("tqdm is not installed. Run optimization without progress bar") + self._optimize(options, None) + + def _optimize(self, options: FusionOptions | None = None, progress_bar=None): + if (options is not None) and not options.enable_shape_inference: + self.disable_shape_inference() + + self.utils.remove_identity_nodes() + if progress_bar: + progress_bar.update(1) + + # Remove cast nodes that having same data type of input and output based on symbolic shape inference. + self.utils.remove_useless_cast_nodes() + if progress_bar: + progress_bar.update(1) + + if (options is None) or options.enable_layer_norm: + self.fuse_layer_norm() + if progress_bar: + progress_bar.update(1) + + if (options is None) or options.enable_gelu: + self.fuse_gelu() + if progress_bar: + progress_bar.update(1) + + self.fuse_reshape() + if progress_bar: + progress_bar.update(1) + + if (options is None) or options.enable_attention: + self.fuse_multi_head_attention(options) + if progress_bar: + progress_bar.update(1) + + if (options is None) or options.enable_skip_layer_norm: + self.fuse_skip_layer_norm() + if progress_bar: + progress_bar.update(1) + + self.fuse_shape() + if progress_bar: + progress_bar.update(1) + + # Remove reshape nodes that having same shape of input and output based on symbolic shape inference. + self.utils.remove_useless_reshape_nodes() + if progress_bar: + progress_bar.update(1) + + if (options is None) or options.enable_bias_skip_layer_norm: + # Fuse SkipLayerNormalization and Add Bias before it. + self.fuse_add_bias_skip_layer_norm() + if progress_bar: + progress_bar.update(1) + + if options is not None and options.enable_gelu_approximation: + self.gelu_approximation() + if progress_bar: + progress_bar.update(1) + + self.postprocess() + if progress_bar: + progress_bar.update(1) + + logger.info(f"opset version: {self.get_opset_version()}") + + def get_fused_operator_statistics(self): + """ + Returns node count of fused operators. + """ + op_count = {} + ops = [ + "MultiHeadAttention", + "LayerNormalization", + "SkipLayerNormalization", + ] + + for op in ops: + nodes = self.get_nodes_by_op_type(op) + op_count[op] = len(nodes) + + logger.info(f"Optimized operators:{op_count}") + return op_count diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/onnx_model_t5.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/onnx_model_t5.py new file mode 100644 index 0000000000000000000000000000000000000000..0f98f85617cc0b8434c2f304c8cab1717b2e273a --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/onnx_model_t5.py @@ -0,0 +1,985 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +# -------------------------------------------------------------------------- +import logging + +import numpy as np +from fusion_attention import AttentionMask, FusionAttention +from fusion_base import Fusion +from fusion_simplified_layernorm import FusionSimplifiedLayerNormalization, FusionSkipSimplifiedLayerNormalization +from fusion_utils import NumpyHelper +from onnx import NodeProto, TensorProto, helper +from onnx_model import OnnxModel +from onnx_model_bert import BertOnnxModel + +logger = logging.getLogger(__name__) + + +class FusionT5Attention(FusionAttention): + """ + Fuse T5 Attention subgraph into one Attention node. + """ + + def __init__( + self, + model: OnnxModel, + hidden_size: int, + num_heads: int, + attention_mask: AttentionMask, + ): + super().__init__( + model, + hidden_size, + num_heads, + attention_mask, + use_multi_head_attention=False, + search_op_types=["Softmax"], + ) + self.static_kv = 1 + + def make_attention_node( + self, + mask_index: str | None, + q_matmul: NodeProto, + k_matmul: NodeProto, + v_matmul: NodeProto, + num_heads: int, + hidden_size: int, + input: str, + output: str, + attn_bias: str | None, + scale: float, + ) -> NodeProto | None: + """Create an Attention node. + Args: + mask_index (str): mask input + q_matmul (NodeProto): MatMul node in fully connection for Q + k_matmul (NodeProto): MatMul node in fully connection for K + v_matmul (NodeProto): MatMul node in fully connection for V + num_heads (int): number of attention heads. If a model is pruned, it is the number of heads after pruning. + hidden_size (int): hidden dimension. If a model is pruned, it is the hidden dimension after pruning. + input (str): input name + output (str): output name + Returns: + Union[NodeProto, None]: the node created or None if failed. + """ + assert num_heads > 0 + + if hidden_size > 0 and (hidden_size % num_heads) != 0: + logger.debug(f"input hidden size {hidden_size} is not a multiple of num of heads {num_heads}") + return None + + q_weight = self.model.get_initializer(q_matmul.input[1]) + k_weight = self.model.get_initializer(k_matmul.input[1]) + v_weight = self.model.get_initializer(v_matmul.input[1]) + + if q_weight is None or k_weight is None or v_weight is None: + matmul = q_matmul if q_weight is None else k_matmul if k_weight is None else v_matmul + print( + f"{matmul.input[1]} is not an initializer. " + "Please set do_constant_folding=True in torch.onnx.export to unblock attention fusion" + ) + return None + + qw = NumpyHelper.to_array(q_weight) + kw = NumpyHelper.to_array(k_weight) + vw = NumpyHelper.to_array(v_weight) + + # assert q and k have same shape as expected + assert qw.shape == kw.shape + + qw_in_size = qw.shape[0] + kw_in_size = kw.shape[0] + vw_in_size = vw.shape[0] + + assert qw_in_size == kw_in_size == vw_in_size + + if hidden_size > 0 and hidden_size != qw_in_size: + logger.warning( + f"Input hidden size ({hidden_size}) is not same as weight matrix dimension of q,k,v ({qw_in_size}). " + "Please provide a correct input hidden size or pass in 0" + ) + + qw_out_size = np.prod(qw.shape[1:]) + qkv_weight = np.stack((qw, kw, vw), axis=1) + qkv_weight_dim = 3 * qw_out_size + + attention_node_name = self.model.create_node_name("Attention") + + weight = helper.make_tensor( + name=attention_node_name + "_qkv_weight", + data_type=TensorProto.FLOAT, + dims=[qw_in_size, qkv_weight_dim], + vals=qkv_weight.tobytes(), + raw=True, + ) + + self.model.add_initializer(weight, self.this_graph_name) + + attention_inputs = [ + input, + attention_node_name + "_qkv_weight", + "", + ] + if mask_index: + attention_inputs.append(mask_index) + else: + attention_inputs.append("") + + if attn_bias: + attention_inputs.append("") # no past + attention_inputs.append(attn_bias) + + while attention_inputs and attention_inputs[-1] == "": + attention_inputs.pop() + + attention_node = helper.make_node( + "Attention", + inputs=attention_inputs, + outputs=[output], + name=attention_node_name, + ) + attention_node.domain = "com.microsoft" + attention_node.attribute.extend([helper.make_attribute("num_heads", num_heads)]) + + if scale is not None: + attention_node.attribute.extend([helper.make_attribute("scale", scale)]) + + if self.mask_filter_value is not None: + attention_node.attribute.extend([helper.make_attribute("mask_filter_value", float(self.mask_filter_value))]) + + return attention_node + + def create_mha_node( + self, + query: str, + key: str, + value: str, + mask_index: str | None, + attn_bias: str | None, + past_key: str | None, + past_value: str | None, + output: str, + present_key: str | None, + present_value: str | None, + num_heads: int, + hidden_size: int, + ) -> NodeProto | None: + assert num_heads > 0 and hidden_size > 0 and query and key and value + + if (hidden_size % num_heads) != 0: + logger.debug(f"input hidden size {hidden_size} is not a multiple of num of heads {num_heads}") + return None + + attention_node_name = self.model.create_node_name("MultiHeadAttention") + attention_inputs = [ + query, + key, + value, + "", # bias + ] + + if mask_index: + attention_inputs.append(mask_index) + else: + attention_inputs.append("") + + if attn_bias: + attention_inputs.append(attn_bias) + else: + attention_inputs.append("") + + if past_key: + assert past_value + attention_inputs.append(past_key) + attention_inputs.append(past_value) + + while attention_inputs and attention_inputs[-1] == "": + attention_inputs.pop() + + attention_outputs = [output] + if present_key: + assert present_value + attention_outputs.append(present_key) + attention_outputs.append(present_value) + + print(f"{attention_inputs=}, {attention_outputs=}, {attention_node_name=}") + attention_node = helper.make_node( + "MultiHeadAttention", + inputs=attention_inputs, + outputs=attention_outputs, + name=attention_node_name, + ) + + attention_node.domain = "com.microsoft" + attention_node.attribute.extend([helper.make_attribute("num_heads", num_heads)]) + attention_node.attribute.extend([helper.make_attribute("scale", 1.0)]) + if self.mask_filter_value is not None: + attention_node.attribute.extend([helper.make_attribute("mask_filter_value", float(self.mask_filter_value))]) + + self.increase_counter("MultiHeadAttention") + return attention_node + + def fuse(self, node, input_name_to_nodes, output_name_to_node): + if self.fuse_t5_encoder(node, input_name_to_nodes, output_name_to_node): + return + + self.fuse_t5_decoder(node, input_name_to_nodes, output_name_to_node) + + def fuse_t5_encoder(self, softmax_node, input_name_to_nodes, output_name_to_node): + assert softmax_node.op_type == "Softmax" + qkv_nodes = self.model.match_child_path( + softmax_node, + ["MatMul", "Transpose", "Reshape"], + edges=[(0, 0), (0, 0), (0, 0)], + input_name_to_nodes=input_name_to_nodes, + ) + if qkv_nodes is None: + return False + matmul_qkv, _, reshape_qkv = qkv_nodes + + qkv_shape_nodes = self.model.match_parent_path( + reshape_qkv, + ["Concat", "Unsqueeze", "Gather", "Shape"], + [1, 0, 0, 0], + output_name_to_node, + ) + if qkv_shape_nodes is None: + return False + input_shape_node = qkv_shape_nodes[-1] + + v_nodes = self.model.match_parent_path( + matmul_qkv, + ["Transpose", "Reshape", "MatMul"], + [1, 0, 0], + output_name_to_node, + ) + if v_nodes is None: + return False + _, reshape_v, matmul_v = v_nodes + # todo: check reshape_v parent nodes + + qk_nodes = self.model.match_parent_path( + matmul_qkv, + ["Softmax", "Add", "MatMul"], + [0, 0, 0], + output_name_to_node, + ) + if qk_nodes is None: + return False + _, add_qk, matmul_qk = qk_nodes + + mask_nodes = self.model.match_parent_path( + add_qk, + ["Add", "Mul", "Sub", "Cast", "Unsqueeze", "Unsqueeze"], + [1, 1, 0, 1, 0, 0], + output_name_to_node, + ) + + is_pattern_for_one_graph_input = mask_nodes is None + if mask_nodes is not None: + mul_node = mask_nodes[1] + else: + # Pattern for SD3 and Flux. + mask_nodes = self.model.match_parent_path( + add_qk, + ["Add", "Slice", "Mul", "Sub", "Unsqueeze", "Unsqueeze"], + [1, 1, 0, 0, 1, 0], + output_name_to_node, + ) + + # If the model is not optimized by ORT, there might be an additional Cast node. + if mask_nodes is None: + mask_nodes = self.model.match_parent_path( + add_qk, + ["Add", "Slice", "Mul", "Sub", "Cast", "Unsqueeze", "Unsqueeze"], + [1, 1, 0, 0, 1, 0, 0], + output_name_to_node, + ) + if mask_nodes is None: + return False + mul_node = mask_nodes[2] + + _, mul_val = self.model.get_constant_input(mul_node) + if mul_val is None: + return False + + if mul_val != -10000: + self.mask_filter_value = float(mul_val) + + # If the mask is derived from shape of input_ids, it means there is no padding mask. + mask_nodes_2 = self.model.match_parent_path( + mask_nodes[-1], + ["ConstantOfShape", "Concat", "Unsqueeze", "Gather", "Shape"], + [0, 0, 0, 0, 0], + output_name_to_node, + ) + mask_nodes_3 = self.model.match_parent_path( + mask_nodes[-1], + ["ConstantOfShape", "Concat", "Unsqueeze", "Gather", "Shape"], + [0, 0, 1, 0, 0], + output_name_to_node, + ) + if ( + mask_nodes_2 is not None + and any(input.name == mask_nodes_2[-1].input[0] for input in self.model.graph().input) + and mask_nodes_3 is not None + and mask_nodes_2[-1].input[0] == mask_nodes_3[-1].input[0] + and len(mask_nodes_2[1].input) == 2 + ): + mask_index = "" + else: + mask_index = self.attention_mask.process_mask(mask_nodes[-1].input[0]) + + res_pos_bias = None + rpb_nodes = self.model.match_parent_path( + add_qk, + ["Add", "RelativePositionBias"], + [1, 0], + ) + if rpb_nodes is None and is_pattern_for_one_graph_input: + # Pattern for SD3 and Flux. + rpb_nodes = self.model.match_parent_path( + add_qk, + ["Add", "Slice", "RelativePositionBias"], + [1, 0, 0], + ) + if rpb_nodes is None: + return False + + res_pos_bias = rpb_nodes[-1].output[0] + + k_nodes = self.model.match_parent_path( + matmul_qk, + ["Transpose", "Reshape", "MatMul"], + [1, 0, 0], + ) + if k_nodes is None: + return False + _, _, matmul_k = k_nodes + # todo: check reshape_k parent nodes + + q_nodes = self.model.match_parent_path( + matmul_qk, + ["Transpose", "Reshape", "MatMul"], + [0, 0, 0], + ) + if q_nodes is None: + return False + + _, reshape_q, matmul_q = q_nodes + # todo: check reshape_q parent nodes + + if matmul_q.input[0] != input_shape_node.input[0]: + return False + + q_num_heads, q_hidden_size = self.get_num_heads_and_hidden_size(reshape_q) + + new_node = self.make_attention_node( + mask_index, + matmul_q, + matmul_k, + matmul_v, + num_heads=q_num_heads, + hidden_size=q_hidden_size, + input=input_shape_node.input[0], + output=reshape_qkv.output[0], + attn_bias=res_pos_bias, + scale=1.0, + ) + if new_node is None: + return False + + self.nodes_to_add.append(new_node) + self.node_name_to_graph_name[new_node.name] = self.this_graph_name + + self.nodes_to_remove.append(reshape_qkv) + self.prune_graph = True + return True + + def fuse_t5_decoder(self, softmax_node, input_name_to_nodes, output_name_to_node): + assert softmax_node.op_type == "Softmax" + + qkv_nodes = self.model.match_child_path( + softmax_node, + ["MatMul", "Transpose", "Reshape"], + edges=[(0, 0), (0, 0), (0, 0)], + input_name_to_nodes=input_name_to_nodes, + ) + if qkv_nodes is None: + return + matmul_qkv, _transpose_qkv, reshape_qkv = qkv_nodes + + qkv_shape_nodes = self.model.match_parent_path( + reshape_qkv, + ["Concat", "Unsqueeze", "Gather", "Shape"], + [1, 0, 0, 0], + ) + if qkv_shape_nodes is None: + return + input_shape_node = qkv_shape_nodes[-1] + + value = None + past_value = None + present_value = None + v_nodes = self.model.match_parent_path( + matmul_qkv, + ["Concat", "Transpose", "Reshape", "MatMul"], + [1, 1, 0, 0], + ) + if v_nodes is None: + v_nodes = self.model.match_parent_path( + matmul_qkv, + ["Transpose", "Reshape", "MatMul"], + [1, 0, 0], + ) + if v_nodes is not None: + transpose_v, reshape_v, matmul_v = v_nodes + value = reshape_v.input[0] + present_value = transpose_v.output[0] + if "present_value" not in present_value: + return + if matmul_v.input[0] != input_shape_node.input[0]: + self.static_kv = 1 + else: + self.static_kv = 0 + else: + past_value = matmul_qkv.input[1] + if past_value in output_name_to_node: + return + if "past_value_cross" not in past_value: + return + self.static_kv = 1 + else: + concat_v, _, reshape_v, _ = v_nodes + past_value = concat_v.input[0] + if past_value in output_name_to_node: + return + if "past_value_self" not in past_value: + return + present_value = concat_v.output[0] + if "present_value_self" not in present_value: + return + value = reshape_v.input[0] + self.static_kv = 0 + + qk_nodes = self.model.match_parent_path( + matmul_qkv, + ["Softmax", "Add", "MatMul"], + [0, 0, 0], + ) + if qk_nodes is None: + return + _, add_qk, matmul_qk = qk_nodes + + mask_index = None + res_pos_bias = None + if self.static_kv == 1: + mask_nodes = self.model.match_parent_path( + add_qk, + ["Add", "Mul", "Sub", "Cast", "Unsqueeze", "Unsqueeze"], + [1, 1, 0, 1, 0, 0], + ) + if mask_nodes is not None: + mul_node = mask_nodes[1] + else: + mask_nodes = self.model.match_parent_path( + add_qk, + ["Add", "Slice", "Mul", "Sub", "Cast", "Unsqueeze", "Unsqueeze"], + [1, 1, 0, 0, 1, 0, 0], + ) + if mask_nodes is None: + return + mul_node = mask_nodes[2] + + _, mul_val = self.model.get_constant_input(mul_node) + if mul_val != -10000: + self.mask_filter_value = mul_val + + mask_index = self.attention_mask.process_mask(mask_nodes[-1].input[0]) + else: + matched_path_index, _, _ = self.model.match_parent_paths( + add_qk, + [ + (["Add", "Slice"], [1, 0]), + (["Add", "RelativePositionBias"], [1, 0]), + ], + output_name_to_node, + ) + if matched_path_index < 0: + logger.debug("Skip MultiHeadAttention fusion since attention bias pattern not matched") + return + + res_pos_bias = add_qk.input[1] + + key = None + past_key = None + present_key = None + if self.static_kv == 1: + k_nodes = self.model.match_parent_path( + matmul_qk, + ["Transpose", "Reshape", "MatMul"], + [1, 0, 0], + ) + if k_nodes is not None: + transpose_k, reshape_k, _ = k_nodes + key = reshape_k.input[0] + present_key_transpose_nodes = input_name_to_nodes[reshape_k.output[0]] + for present_key_transpose_node in present_key_transpose_nodes: + present_key_candidate = self.model.find_graph_output(present_key_transpose_node.output[0]) + if present_key_candidate is not None: + present_key = present_key_candidate.name + break + if present_key is None: + return + if "present_key_cross" not in present_key: + return + else: + k_nodes = self.model.match_parent_path( + matmul_qk, + ["Transpose"], + [1], + ) + if k_nodes is None: + return + transpose_k = k_nodes[0] + + past_key = transpose_k.input[0] + if past_key in output_name_to_node: + return + if "past_key_cross" not in past_key: + return + else: + idx, k_nodes, _ = self.model.match_parent_paths( + matmul_qk, + [ + (["Transpose", "Concat", "Reshape", "MatMul"], [1, 0, 1, 0]), + (["Transpose", "Concat", "Transpose", "Reshape", "MatMul"], [1, 0, 1, 0, 0]), + ], + output_name_to_node, + ) + past_key_transpose_node = None + present_key_transpose_nodes = None + if k_nodes is not None: + concat_k, reshape_k = k_nodes[1], k_nodes[-2] + key = reshape_k.input[0] + + if idx == 0: + past_key_transpose_node = output_name_to_node[concat_k.input[0]] + past_key = past_key_transpose_node.input[0] + else: + past_key = concat_k.input[0] + if past_key in output_name_to_node: + return + if "past_key_self" not in past_key: + return + + if idx == 0: + present_key_transpose_nodes = input_name_to_nodes[concat_k.output[0]] + for present_key_transpose_node in present_key_transpose_nodes: + present_key_candidate = self.model.find_graph_output(present_key_transpose_node.output[0]) + if present_key_candidate is not None: + present_key = present_key_candidate.name + break + else: + present_key = concat_k.output[0] + if present_key is None: + return + if "present_key_self" not in present_key: + return + else: + k_nodes = self.model.match_parent_path( + matmul_qk, + ["Transpose", "Reshape", "MatMul"], + [1, 0, 0], + ) + if k_nodes is None: + return + _, reshape_k, _ = k_nodes + key = reshape_k.input[0] + present_key_transpose_nodes = input_name_to_nodes[reshape_k.output[0]] + for present_key_transpose_node in present_key_transpose_nodes: + present_key_candidate = self.model.find_graph_output(present_key_transpose_node.output[0]) + if present_key_candidate is not None: + present_key = present_key_candidate.name + break + if present_key is None: + return + if "present_key_self" not in present_key: + return + + q_nodes = self.model.match_parent_path( + matmul_qk, + ["Transpose", "Reshape", "MatMul"], + [0, 0, 0], + ) + if q_nodes is None: + return + + transpose_q, reshape_q, matmul_q = q_nodes + + if matmul_q.input[0] != input_shape_node.input[0]: + return + + q_num_heads, q_hidden_size = self.get_num_heads_and_hidden_size(reshape_q) + + if self.static_kv == 1 and past_key is not None: + key = past_key + value = past_value + past_key = None + past_value = None + + if not (key and value and q_num_heads > 0 and q_hidden_size > 0): + return + + new_node = self.create_mha_node( + query=matmul_q.output[0], + key=key, + value=value, + mask_index=mask_index, + attn_bias=res_pos_bias, + past_key=past_key, + past_value=past_value, + output=reshape_qkv.output[0], + present_key=present_key, + present_value=present_value, + num_heads=q_num_heads, + hidden_size=q_hidden_size, + ) + + if new_node: + self.nodes_to_add.append(new_node) + self.node_name_to_graph_name[new_node.name] = self.this_graph_name + + # Since present_* is graph output, we need update the graph to avoid circular. + if present_key or present_value: + for graph_output in [present_key, present_value]: + if not (graph_output and self.model.find_graph_output(graph_output)): + print(f"{graph_output=} does not exist in graph output") + return + assert graph_output in output_name_to_node + output_name_to_node[graph_output].output[0] = graph_output + "_copy" + self.model.replace_input_of_all_nodes(graph_output, graph_output + "_copy") + + self.nodes_to_remove.append(reshape_qkv) + self.prune_graph = False + + +class FusionRelativePositionBiasBlock(Fusion): + def __init__(self, model: OnnxModel): + super().__init__(model, "RelativePositionBias", ["Softmax"]) + + def fuse(self, node, input_name_to_nodes, output_name_to_node): + compute_bias_nodes = self.model.match_parent_path( + node, + ["Add", "Add", "Slice", "Unsqueeze", "Transpose", "Gather", "Where"], + [0, 1, 0, 0, 0, 0, 1], + output_name_to_node, + ) + + if compute_bias_nodes is None: + compute_bias_nodes = self.model.match_parent_path( + node, + ["Add", "Add", "Slice", "Unsqueeze", "Transpose", "Gather", "Add", "Where"], + [0, 1, 0, 0, 0, 0, 1, 1], + output_name_to_node, + ) + if compute_bias_nodes is None: + return + + gather = compute_bias_nodes[5] + where = compute_bias_nodes[-1] + slice = compute_bias_nodes[2] + unsqueeze = compute_bias_nodes[3] + + # Current fusion will not remove the node until the graph is processed. + # This avoids to fuse it again when it is shared by multiple layers. + if unsqueeze in self.nodes_to_remove: + return + + compute_buckets_nodes = self.model.match_parent_path( + where, + ["Min", "ConstantOfShape", "Shape", "Add", "Cast", "Mul", "Div", "Log", "Div"], + [2, 1, 0, 0, 0, 0, 0, 0, 0], + output_name_to_node, + ) + if compute_buckets_nodes is None: + return + + # This value is to used to compute max_distance later. + log_max = self.model.get_constant_value(compute_buckets_nodes[-3].input[1]) + + div = compute_buckets_nodes[-1] + + range_nodes = self.model.match_parent_path( + div, + ["Cast", "Neg", "Min", "ConstantOfShape", "Shape", "Sub", "Unsqueeze", "Range"], + [0, 0, 0, 1, 0, 0, 0, 0], + output_name_to_node, + ) + + is_bidirectional = False + if range_nodes is None: + range_nodes = self.model.match_parent_path( + div, ["Cast", "Abs", "Sub", "Unsqueeze", "Range"], [0, 0, 0, 0, 0], output_name_to_node + ) + is_bidirectional = True + if range_nodes is None: + return + range_node = range_nodes[-1] + + # Double check that the constant relative to max_distance and relative_attention_num_buckets. + # Most t5 models use max_distance=128, so we hardcode it unitl we see a model with different value. + + # The log_max is the value of the following formula: + # math.log(max_distance / (relative_attention_num_buckets // (4 if is_bidirectional else 2))) + # See https://github.com/huggingface/transformers/blob/608e163b527eaee41e650ffb9eb4c422d2679902/src/transformers/models/t5/modeling_t5.py#L397. + # Here is the value based on max_distance=128 and relative_attention_num_buckets=32: + max_distance = int(np.round(np.exp(log_max) * (32 // (4 if is_bidirectional else 2)))) + if max_distance != 128: + logger.warning( + f"max_distance is {max_distance}, which is different from the default value 128. " + "Please double check the model configuration." + ) + + node_name = self.model.create_node_name( + "RelativePositionBias", name_prefix="RelPosBias_" + ("encoder" if is_bidirectional else "decoder") + ) + + table_weight_i = self.model.get_initializer(gather.input[0]) + if table_weight_i is None: + return + table_weight = NumpyHelper.to_array(table_weight_i) + table_weight_t = np.transpose(table_weight) + bias_table = helper.make_tensor( + name=node_name + "_bias_table_weight", + data_type=TensorProto.FLOAT, + dims=[np.shape(table_weight)[0], np.shape(table_weight)[1]], + vals=table_weight_t.tobytes(), + raw=True, + ) + self.model.add_initializer(bias_table, self.this_graph_name) + + # Relative position is like the following in encoder: + # seq_len + # | + # Range(0, *) + # / \ + # Unsqueeze(axes=0) Unsqueeze(axes=1) + # \ / + # Sub + # | + # Abs + # + # Relative position is like the following in decoder: + # past_seq_len seq_len + # \ / + # Add + # / \ + # Range(0, *) Range(0, *) + # \ / + # Sub + # Note that the graph will slice the attention bias to get last seq_len rows. + # + # In new version of transformers, the pattern of decoder is changed like the following + # + # total_seq_len Range(start=past_seq_len, end=total_seq_len) + # | | + # Range(0, *) Unsqueeze(axes=1) + # | | + # Unsqueeze(axes=0) Cast(to=int64) + # \ / + # Sub + # Currently, there is still Slice to get last seq_len rows so end result is same. + # But need to be careful that the shape of bias tensor is changed before Slice. + # + # RelativePositionBias operator requires query_length == key_length so we shall pass in total_seq_len. + # Here we get the end value of the Range node as length to pass to the RelativePositionBias node. + + # TODO: Optimization opportunity: change RelativePositionBias op to support query_length != key_length. + # only compute seq_len rows, then we can remove the Slice after the RelativePositionBias node. + inputs = [bias_table.name, range_node.input[1], range_node.input[1]] + + # Use a new tensor name since the shape might be different as mentioned above. + bias_output = node_name + "_rel_pos_bias" + slice.input[0] = bias_output + + rpb_node = helper.make_node( + "RelativePositionBias", + inputs=inputs, + outputs=[bias_output], + name=node_name, + ) + rpb_node.domain = "com.microsoft" + rpb_node.attribute.extend([helper.make_attribute("max_distance", max_distance)]) + rpb_node.attribute.extend([helper.make_attribute("is_bidirectional", is_bidirectional)]) + self.node_name_to_graph_name[rpb_node.name] = self.this_graph_name + self.nodes_to_add.append(rpb_node) + self.prune_graph = True + + +class T5OnnxModel(BertOnnxModel): + def __init__(self, model, num_heads: int = 0, hidden_size: int = 0): + super().__init__(model, num_heads, hidden_size) + self.attention_mask = AttentionMask(self) + + # When the model has only one input (input_ids), there is no padding mask. + if len(self.model.graph.input) == 1: + from fusion_options import AttentionMaskFormat # noqa: PLC0415 + + self.attention_mask.mask_format = AttentionMaskFormat.NoMask + + self.attention_fusion = FusionT5Attention(self, self.hidden_size, self.num_heads, self.attention_mask) + self.layer_norm_fusion = FusionSimplifiedLayerNormalization(self) + self.skip_layer_norm_fusion = FusionSkipSimplifiedLayerNormalization(self) + self.rpb_fusion = FusionRelativePositionBiasBlock(self) + + def fuse_attention(self): + self.attention_fusion.apply() + + def fuse_layer_norm(self): + self.layer_norm_fusion.apply() + + def fuse_skip_layer_norm(self, shape_infer=True): + self.skip_layer_norm_fusion.apply() + + def adjust_rel_pos_bis_length_input(self): + # For T5 encoder, it uses complex logic to compute the query and key length when there is only one graph input (input_ids) + # We can directly get the length from shape (the 2nd dimension) of input_ids. + for node in self.nodes(): + if node.op_type == "RelativePositionBias": + nodes = self.match_parent_path( + node, + [ + "Gather", + "Shape", + "Transpose", + "Reshape", + "Concat", + "Unsqueeze", + "Gather", + "Shape", + "SimplifiedLayerNormalization", + "Gather", + ], + [1, 0, 0, 0, 1, 0, 0, 0, 0, 0], + ) + # TODO: more validation on node attributes + if nodes is not None: + graph_input_names = [input.name for input in self.model.graph.input] + if nodes[-1].input[1] in graph_input_names: + node_name = self.create_node_name("Shape", name_prefix="Added_Shape_") + shape_node = helper.make_node( + "Shape", + inputs=[nodes[-1].input[1]], + outputs=[node_name + "_Output"], + name=node_name, + ) + + indices_1 = helper.make_tensor( + name="Constant_Index_1", + data_type=TensorProto.INT64, + dims=[1], # Shape of the tensor + vals=[1], # Tensor values + ) + self.add_initializer(indices_1) + + gather = helper.make_node( + "Gather", + inputs=[node_name + "_Output", "Constant_Index_1"], + outputs=[node_name + "_Output_Gather_1"], + name=self.create_node_name("Gather", name_prefix="Added_Gather_"), + axis=0, + ) + + self.add_node(shape_node) + self.add_node(gather) + node.input[1] = node_name + "_Output_Gather_1" + node.input[2] = node_name + "_Output_Gather_1" + + break + + # Remove get_extended_attention_mask() since it generates all zeros. + def remove_extended_mask_decoder_init(self): + nodes_to_remove = [] + for node in self.nodes(): + if node.op_type == "Add": + extended_mask_nodes = self.match_parent_path( + node, + [ + "Mul", + "Sub", + "Mul", + "Unsqueeze", + "Cast", + "LessOrEqual", + "Tile", + "Concat", + "Unsqueeze", + "Gather", + "Shape", + ], + [1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0], + ) + if extended_mask_nodes is None: + continue + + rpb_nodes = self.match_parent_path(node, ["RelativePositionBias"], [0]) + if rpb_nodes is None: + continue + + rpb_node = rpb_nodes[0] + rpb_node.output[0] = node.output[0] + + nodes_to_remove.extend(extended_mask_nodes) + nodes_to_remove.append(node) + self.remove_nodes(nodes_to_remove) + + def remove_extended_mask_decoder(self): + nodes_to_remove = [] + for node in self.nodes(): + if node.op_type == "Add": + extended_mask_nodes = self.match_parent_path( + node, + [ + "Mul", + "Sub", + "Mul", + "Unsqueeze", + "Concat", + "Cast", + "LessOrEqual", + "Tile", + "Concat", + "Unsqueeze", + "Gather", + "Shape", + ], + [1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0], + ) + if extended_mask_nodes is None: + continue + + rpb_nodes = self.match_parent_path(node, ["Slice", "RelativePositionBias"], [0, 0]) + if rpb_nodes is None: + continue + + rpb_node = rpb_nodes[0] + rpb_node.output[0] = node.output[0] + + nodes_to_remove.extend(extended_mask_nodes) + nodes_to_remove.append(node) + self.remove_nodes(nodes_to_remove) + + def preprocess(self): + self.adjust_reshape_and_expand() + self.rpb_fusion.apply() + + def postprocess(self): + # remove get_extended_attention_mask() since it generates all zeros. + self.remove_extended_mask_decoder_init() + self.remove_extended_mask_decoder() + self.adjust_rel_pos_bis_length_input() + + self.prune_graph() diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/onnx_model_tnlr.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/onnx_model_tnlr.py new file mode 100644 index 0000000000000000000000000000000000000000..6bf9c5f0db9b40aad21395e0922e98ce9656ae2a --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/onnx_model_tnlr.py @@ -0,0 +1,226 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +# -------------------------------------------------------------------------- +import logging + +from fusion_attention import AttentionMask, FusionAttention +from fusion_utils import NumpyHelper +from onnx import NodeProto, helper +from onnx_model import OnnxModel +from onnx_model_bert import BertOnnxModel + +logger = logging.getLogger(__name__) + + +class FusionTnlrAttention(FusionAttention): + """ + Fuse TNLR Attention subgraph into one Attention node. + TNLR Attention has extra addition after qk nodes and adopts [S, B, NH] as I/O shape. + """ + + def __init__( + self, + model: OnnxModel, + hidden_size: int, + num_heads: int, + attention_mask: AttentionMask, + ): + super().__init__(model, hidden_size, num_heads, attention_mask) + + def create_attention_node( + self, + mask_index: str, + matmul: NodeProto, + add: NodeProto, + num_heads: int, + hidden_size: int, + input: str, + output: str, + add_qk_str: str, + ) -> NodeProto | None: + assert num_heads > 0 + if hidden_size > 0 and (hidden_size % num_heads) != 0: + logger.debug(f"input hidden size {hidden_size} is not a multiple of num of heads {num_heads}") + return None + + weight = self.model.get_initializer(matmul.input[1]) + bias = self.model.get_initializer(add.input[1]) or self.model.get_initializer(add.input[0]) + + if weight is None or bias is None: + return None + + qkv_weight = NumpyHelper.to_array(weight) + qkv_bias = NumpyHelper.to_array(bias) + + attention_node_name = self.model.create_node_name("Attention") + + tensor_dtype = weight.data_type + np_type = helper.tensor_dtype_to_np_dtype(tensor_dtype) + weight = helper.make_tensor( + name=attention_node_name + "_qkv_weight", + data_type=tensor_dtype, + dims=[hidden_size, 3 * hidden_size], + vals=qkv_weight.astype(np_type).tobytes(), + raw=True, + ) + self.model.add_initializer(weight, self.this_graph_name) + + bias = helper.make_tensor( + name=attention_node_name + "_qkv_bias", + data_type=tensor_dtype, + dims=[3 * hidden_size], + vals=qkv_bias.astype(np_type).tobytes(), + raw=True, + ) + self.model.add_initializer(bias, self.this_graph_name) + + attention_inputs = [ + input, + attention_node_name + "_qkv_weight", + attention_node_name + "_qkv_bias", + ] + if mask_index is not None: + attention_inputs.append(mask_index) + else: + attention_inputs.append("") + + if add_qk_str is not None: + attention_inputs.append("") + attention_inputs.append(add_qk_str) + + attention_node = helper.make_node( + "Attention", + inputs=attention_inputs, + outputs=[output], + name=attention_node_name, + ) + attention_node.domain = "com.microsoft" + attention_node.attribute.extend([helper.make_attribute("num_heads", num_heads)]) + + return attention_node + + def fuse(self, normalize_node, input_name_to_nodes, output_name_to_node): + # Sometimes we can not fuse skiplayernormalization since the add before layernorm has an output that used by nodes outside skiplayernorm + # Conceptually we treat add before layernorm as skiplayernorm node since they share the same pattern + start_node = normalize_node + if normalize_node.op_type != "SkipLayerNormalization": + return + + # SkipLayerNormalization has two inputs, and one of them is the root input for attention. + qkv_nodes = self.model.match_parent_path( + start_node, + ["Where", "Add", "MatMul", "Reshape", "Transpose", "MatMul"], + [1, 1, 1, 0, 0, 0], + ) + if qkv_nodes is not None: + (_, _, matmul_below, reshape_qkv, transpose_qkv, matmul_qkv) = qkv_nodes + else: + return + + other_inputs = [] + for _i, input in enumerate(start_node.input): + if input not in output_name_to_node: + continue + + if input == qkv_nodes[0].output[0]: + continue + other_inputs.append(input) + if len(other_inputs) != 1: + return + + root_input = other_inputs[0] + + v_nodes = self.model.match_parent_path( + matmul_qkv, + ["Transpose", "Reshape", "Slice", "Add", "MatMul"], + [1, 0, 0, 0, 1], + ) + if v_nodes is None: + return + (_, _, _, add, matmul) = v_nodes + + upper_nodes = self.model.match_parent_path(matmul, ["Transpose"], [0]) + transpose = upper_nodes[0] + + qk_nodes = self.model.match_parent_path(matmul_qkv, ["Softmax", "Add", "MatMul"], [0, 0, 0]) + if qk_nodes is None: + return + (_, add_qk, matmul_qk) = qk_nodes + + q_nodes = self.model.match_parent_path( + matmul_qk, + ["Mul", "Transpose", "Reshape", "Slice", "Add", "MatMul"], + [0, 0, 0, 0, 0, 1], + ) + if q_nodes is None: + return + add = q_nodes[-2] + matmul = q_nodes[-1] + + k_nodes = self.model.match_parent_path( + matmul_qk, + ["Transpose", "Reshape", "Slice", "Add", "MatMul"], + [1, 0, 0, 0, 1], + ) + if k_nodes is None: + return + add = k_nodes[-2] + matmul = k_nodes[-1] + + relative_position_bias_nodes = self.model.match_parent_path(add_qk, ["Reshape", "Where"], [1, 0]) + if relative_position_bias_nodes is None: + return + + if matmul.input[0] == root_input: + mask_index = None + attention_last_node = reshape_qkv + # number of heads are same for all the paths, hence to create attention node, we pass the q_num_heads + # the input_hidden_size represents the input hidden size, this is used as needed but hidden sizes for Q, K are extracted appropriately + new_node = self.create_attention_node( + mask_index, + matmul, + add, + self.num_heads, + self.hidden_size, + root_input, + attention_last_node.output[0], + relative_position_bias_nodes[0].input[0], + ) + if new_node is None: + return + + self.nodes_to_add.append(new_node) + self.node_name_to_graph_name[new_node.name] = self.this_graph_name + + # Add a transpose node after the attention node + back_transpose = helper.make_node( + "Transpose", + ["back_transpose_in_" + new_node.name], + [new_node.output[0]], + "back_transpose_" + new_node.name, + perm=[1, 0, 2], + ) + self.model.add_node(back_transpose, self.this_graph_name) + new_node.input[0] = transpose.input[0] + new_node.output[0] = "back_transpose_in_" + new_node.name + + self.nodes_to_remove.extend([attention_last_node, transpose_qkv, matmul_qkv]) + self.nodes_to_remove.extend(qk_nodes) + self.nodes_to_remove.extend(q_nodes) + self.nodes_to_remove.extend(k_nodes) + self.nodes_to_remove.extend(v_nodes) + + # Use prune graph to remove mask nodes since they are shared by all attention nodes. + # self.nodes_to_remove.extend(mask_nodes) + self.prune_graph = True + + +class TnlrOnnxModel(BertOnnxModel): + def __init__(self, model, num_heads, hidden_size): + super().__init__(model, num_heads, hidden_size) + self.attention_mask = AttentionMask(self) + self.attention_fusion = FusionTnlrAttention(self, self.hidden_size, self.num_heads, self.attention_mask) + + def fuse_attention(self): + self.attention_fusion.apply() diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/onnx_model_unet.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/onnx_model_unet.py new file mode 100644 index 0000000000000000000000000000000000000000..db390fa8f2bf0e04f5d384387cc54292a49e08c3 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/onnx_model_unet.py @@ -0,0 +1,258 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +# -------------------------------------------------------------------------- + +import logging + +from fusion_attention_unet import FusionAttentionUnet +from fusion_bias_add import FusionBiasAdd +from fusion_biassplitgelu import FusionBiasSplitGelu +from fusion_group_norm import FusionGroupNorm +from fusion_nhwc_conv import FusionNhwcConv +from fusion_options import FusionOptions +from fusion_skip_group_norm import FusionSkipGroupNorm +from fusion_transpose import FusionInsertTranspose, FusionTranspose +from import_utils import is_installed +from onnx import ModelProto +from onnx_model import OnnxModel +from onnx_model_bert import BertOnnxModel + +logger = logging.getLogger(__name__) + + +class UnetOnnxModel(BertOnnxModel): + def __init__(self, model: ModelProto, num_heads: int = 0, hidden_size: int = 0): + """Initialize UNet ONNX Model. + + Args: + model (ModelProto): the ONNX model + num_heads (int, optional): number of attention heads. Defaults to 0 (detect the parameter automatically). + hidden_size (int, optional): hidden dimension. Defaults to 0 (detect the parameter automatically). + """ + assert (num_heads == 0 and hidden_size == 0) or (num_heads > 0 and hidden_size % num_heads == 0) + + super().__init__(model, num_heads=num_heads, hidden_size=hidden_size) + + def preprocess(self): + self.remove_useless_div() + + def postprocess(self): + self.prune_graph() + self.remove_unused_constant() + + def remove_useless_div(self): + """Remove Div by 1""" + div_nodes = [node for node in self.nodes() if node.op_type == "Div"] + + nodes_to_remove = [] + for div in div_nodes: + if self.find_constant_input(div, 1.0) == 1: + nodes_to_remove.append(div) + + for node in nodes_to_remove: + self.replace_input_of_all_nodes(node.output[0], node.input[0]) + + if nodes_to_remove: + self.remove_nodes(nodes_to_remove) + logger.info("Removed %d Div nodes", len(nodes_to_remove)) + + def convert_conv_to_nhwc(self): + # Transpose weights in offline might help since ORT does not apply constant-folding on Transpose nodes. + conv_to_nhwc_conv = FusionNhwcConv(self, update_weight=True) + conv_to_nhwc_conv.apply() + + def merge_adjacent_transpose(self): + fusion_transpose = FusionTranspose(self) + fusion_transpose.apply() + + remove_count = 0 + nodes = self.get_nodes_by_op_type("Transpose") + for node in nodes: + permutation = OnnxModel.get_node_attribute(node, "perm") + assert isinstance(permutation, list) + if permutation != list(range(len(permutation))): + continue + assert not ( + self.find_graph_output(node.output[0]) + or self.find_graph_input(node.input[0]) + or self.find_graph_output(node.input[0]) + ) + + # Let all children nodes skip current Transpose node and link to its parent + # Note that we cannot update parent node output since parent node might have more than one children. + self.replace_input_of_all_nodes(node.output[0], node.input[0]) + + self.remove_node(node) + remove_count += 1 + + total = len(fusion_transpose.nodes_to_remove) + remove_count + if total: + logger.info("Removed %d Transpose nodes", total) + + def fuse_multi_head_attention(self, options: FusionOptions | None = None): + # Self Attention + enable_packed_qkv = (options is None) or options.enable_packed_qkv + self_attention_fusion = FusionAttentionUnet( + self, + self.hidden_size, + self.num_heads, + is_cross_attention=False, + enable_packed_qkv=enable_packed_qkv, + enable_packed_kv=False, + ) + self_attention_fusion.apply() + + # Cross Attention + enable_packed_kv = (options is None) or options.enable_packed_kv + cross_attention_fusion = FusionAttentionUnet( + self, + self.hidden_size, + self.num_heads, + is_cross_attention=True, + enable_packed_qkv=False, + enable_packed_kv=enable_packed_kv, + ) + cross_attention_fusion.apply() + + def fuse_bias_add(self): + fusion = FusionBiasAdd(self) + fusion.apply() + + def optimize(self, options: FusionOptions | None = None): + if is_installed("tqdm"): + import tqdm # noqa: PLC0415 + from tqdm.contrib.logging import logging_redirect_tqdm # noqa: PLC0415 + + with logging_redirect_tqdm(): + steps = 18 + progress_bar = tqdm.tqdm(range(steps), initial=0, desc="fusion") + self._optimize(options, progress_bar) + else: + logger.info("tqdm is not installed. Run optimization without progress bar") + self._optimize(options, None) + + def _optimize(self, options: FusionOptions | None = None, progress_bar=None): + if (options is not None) and not options.enable_shape_inference: + self.disable_shape_inference() + + self.utils.remove_identity_nodes() + if progress_bar: + progress_bar.update(1) + + # Remove cast nodes that having same data type of input and output based on symbolic shape inference. + self.utils.remove_useless_cast_nodes() + if progress_bar: + progress_bar.update(1) + + if (options is None) or options.enable_layer_norm: + self.fuse_layer_norm() + if progress_bar: + progress_bar.update(1) + + if (options is None) or options.enable_gelu: + self.fuse_gelu() + if progress_bar: + progress_bar.update(1) + + self.preprocess() + if progress_bar: + progress_bar.update(1) + + self.fuse_reshape() + if progress_bar: + progress_bar.update(1) + + if (options is None) or options.enable_group_norm: + channels_last = (options is None) or options.group_norm_channels_last + group_norm_fusion = FusionGroupNorm(self, channels_last) + group_norm_fusion.apply() + + insert_transpose_fusion = FusionInsertTranspose(self) + insert_transpose_fusion.apply() + if progress_bar: + progress_bar.update(1) + + if (options is None) or options.enable_bias_splitgelu: + bias_split_gelu_fusion = FusionBiasSplitGelu(self) + bias_split_gelu_fusion.apply() + if progress_bar: + progress_bar.update(1) + + if (options is None) or options.enable_attention: + # self.save_model_to_file("before_mha.onnx") + self.fuse_multi_head_attention(options) + if progress_bar: + progress_bar.update(1) + + if (options is None) or options.enable_skip_layer_norm: + self.fuse_skip_layer_norm() + if progress_bar: + progress_bar.update(1) + + self.fuse_shape() + if progress_bar: + progress_bar.update(1) + + # Remove reshape nodes that having same shape of input and output based on symbolic shape inference. + self.utils.remove_useless_reshape_nodes() + if progress_bar: + progress_bar.update(1) + + if (options is None) or options.enable_skip_group_norm: + skip_group_norm_fusion = FusionSkipGroupNorm(self) + skip_group_norm_fusion.apply() + if progress_bar: + progress_bar.update(1) + + if (options is None) or options.enable_bias_skip_layer_norm: + # Fuse SkipLayerNormalization and Add Bias before it. + self.fuse_add_bias_skip_layer_norm() + if progress_bar: + progress_bar.update(1) + + if options is not None and options.enable_gelu_approximation: + self.gelu_approximation() + if progress_bar: + progress_bar.update(1) + + if options is None or options.enable_nhwc_conv: + self.convert_conv_to_nhwc() + self.merge_adjacent_transpose() + if progress_bar: + progress_bar.update(1) + + if options is not None and options.enable_bias_add: + self.fuse_bias_add() + if progress_bar: + progress_bar.update(1) + + self.postprocess() + if progress_bar: + progress_bar.update(1) + + logger.info(f"opset version: {self.get_opset_version()}") + + def get_fused_operator_statistics(self): + """ + Returns node count of fused operators. + """ + op_count = {} + ops = [ + "Attention", + "MultiHeadAttention", + "LayerNormalization", + "SkipLayerNormalization", + "BiasSplitGelu", + "GroupNorm", + "SkipGroupNorm", + "NhwcConv", + "BiasAdd", + ] + + for op in ops: + nodes = self.get_nodes_by_op_type(op) + op_count[op] = len(nodes) + + logger.info(f"Optimized operators:{op_count}") + return op_count diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/onnx_model_vae.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/onnx_model_vae.py new file mode 100644 index 0000000000000000000000000000000000000000..1ee1e8c55f2ea343974b7c012d5124b445d898e3 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/onnx_model_vae.py @@ -0,0 +1,42 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +# -------------------------------------------------------------------------- + +from logging import getLogger + +from fusion_attention_vae import FusionAttentionVae +from fusion_options import FusionOptions +from onnx import ModelProto +from onnx_model_unet import UnetOnnxModel + +logger = getLogger(__name__) + + +class VaeOnnxModel(UnetOnnxModel): + def __init__(self, model: ModelProto, num_heads: int = 0, hidden_size: int = 0): + assert (num_heads == 0 and hidden_size == 0) or (num_heads > 0 and hidden_size % num_heads == 0) + super().__init__(model, num_heads=num_heads, hidden_size=hidden_size) + + def fuse_multi_head_attention(self, options: FusionOptions | None = None): + # Self Attention + self_attention_fusion = FusionAttentionVae(self, self.hidden_size, self.num_heads) + self_attention_fusion.apply() + + def get_fused_operator_statistics(self): + """ + Returns node count of fused operators. + """ + op_count = {} + ops = [ + "Attention", + "GroupNorm", + "SkipGroupNorm", + "NhwcConv", + ] + for op in ops: + nodes = self.get_nodes_by_op_type(op) + op_count[op] = len(nodes) + + logger.info(f"Optimized operators:{op_count}") + return op_count diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/onnx_utils.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/onnx_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..838b8cf3ba3c38b1049094404b9369cbcb28618f --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/onnx_utils.py @@ -0,0 +1,55 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +# -------------------------------------------------------------------------- +from fusion_utils import NumpyHelper +from onnx import ModelProto, TensorProto +from onnx.external_data_helper import set_external_data +from onnx_model import OnnxModel + +from onnxruntime import OrtValue + + +def extract_raw_data_from_model(model: ModelProto): + """ + Extract external data from model and return the external data as a list of tuples (name, value). + Note this function does not handle external data that is not loaded into the model as raw data. + + Args: + model (ModelProto): the model proto to extract external data from. + Returns: + (external_names, external_values): a tuple of two lists of external data names and values. + """ + external_data = [] + onnx_model = OnnxModel(model) + for graph in onnx_model.graphs(): + for initializer in graph.initializer: + name = initializer.name + + if initializer.HasField("raw_data"): + numpy_tensor = NumpyHelper.to_array(initializer) + ort_value = OrtValue.ortvalue_from_numpy(numpy_tensor) + external_data.append((name, ort_value)) + # mimic set_external_data + set_external_data(initializer, location="foo.bin") + initializer.name = name + initializer.ClearField("raw_data") + + return zip(*external_data, strict=False) + + +def has_external_data(model: ModelProto): + """ + Check if the model has external data. + + Args: + model (ModelProto): the model proto to check for external data. + Returns: + bool: True if the model has external data, False otherwise. + """ + onnx_model = OnnxModel(model) + for graph in onnx_model.graphs(): + for initializer in graph.initializer: + if initializer.HasField("data_location") and initializer.data_location == TensorProto.EXTERNAL: + return True + return False diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/optimizer.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/optimizer.py new file mode 100644 index 0000000000000000000000000000000000000000..4a22a32e55b7663f5442e9c22f8545e4f85ece70 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/optimizer.py @@ -0,0 +1,621 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +# -------------------------------------------------------------------------- + +# Convert Bert ONNX model converted from TensorFlow or exported from PyTorch to use Attention, Gelu, +# SkipLayerNormalization and EmbedLayerNormalization ops to optimize +# performance on NVidia GPU and CPU. +# +# For Bert model exported from PyTorch, OnnxRuntime has bert model optimization support internally. +# You can use the option --use_onnxruntime to check optimizations from OnnxRuntime. +# For Bert model file like name.onnx, optimized model for GPU or CPU from OnnxRuntime will output as +# name_ort_gpu.onnx or name_ort_cpu.onnx in the same directory. +# +# This script is retained for experiment purpose. Useful scenarios like the following: +# (1) Change model from fp32 to fp16 for mixed precision inference in GPU with Tensor Core. +# (2) Change input data type from int64 to int32. +# (3) Some model cannot be handled by OnnxRuntime, and you can modify this script to get optimized model. + +import argparse +import logging +import os +import tempfile +from pathlib import Path + +from fusion_options import FusionOptions +from onnx import ModelProto, load_model +from onnx_model import OnnxModel +from onnx_model_bart import BartOnnxModel +from onnx_model_bert import BertOnnxModel +from onnx_model_bert_keras import BertOnnxModelKeras +from onnx_model_bert_tf import BertOnnxModelTF +from onnx_model_clip import ClipOnnxModel +from onnx_model_conformer import ConformerOnnxModel +from onnx_model_gpt2 import Gpt2OnnxModel +from onnx_model_mmdit import MmditOnnxModel +from onnx_model_phi import PhiOnnxModel +from onnx_model_sam2 import Sam2OnnxModel +from onnx_model_t5 import T5OnnxModel +from onnx_model_tnlr import TnlrOnnxModel +from onnx_model_unet import UnetOnnxModel +from onnx_model_vae import VaeOnnxModel +from onnx_utils import extract_raw_data_from_model, has_external_data + +import onnxruntime + +logger = logging.getLogger(__name__) + +# Map model type to tuple: optimizer class, export tools (pytorch, tf2onnx, keras2onnx), and default opt_level +MODEL_TYPES = { + "bart": (BartOnnxModel, "pytorch", 1), + "bert": (BertOnnxModel, "pytorch", 1), + "bert_tf": (BertOnnxModelTF, "tf2onnx", 0), + "bert_keras": (BertOnnxModelKeras, "keras2onnx", 0), + "clip": (ClipOnnxModel, "pytorch", 1), # Clip in Stable Diffusion + "conformer": (ConformerOnnxModel, "pytorch", 1), + "gpt2": (Gpt2OnnxModel, "pytorch", 1), + "gpt2_tf": (Gpt2OnnxModel, "tf2onnx", 0), # might add a class for GPT2OnnxModel for TF later. + "gpt_neox": (BertOnnxModel, "pytorch", 0), # GPT-NeoX + "phi": (PhiOnnxModel, "pytorch", 0), + "qwen3": (Gpt2OnnxModel, "pytorch", 0), # Qwen3 (decoder-only with RoPE, GQA, RMSNorm) + "sam2": (Sam2OnnxModel, "pytorch", 1), + "swin": (BertOnnxModel, "pytorch", 1), + "tnlr": (TnlrOnnxModel, "pytorch", 1), + "t5": (T5OnnxModel, "pytorch", 2), + "unet": (UnetOnnxModel, "pytorch", 1), # UNet in Stable Diffusion + "vae": (VaeOnnxModel, "pytorch", 1), # UAE in Stable Diffusion + "vit": (BertOnnxModel, "pytorch", 1), + "mmdit": (MmditOnnxModel, "pytorch", 1), +} + + +def optimize_by_onnxruntime( + onnx_model: str | ModelProto | None = None, + use_gpu: bool = False, + optimized_model_path: str | None = None, + opt_level: int | None = 99, + disabled_optimizers: list[str] = [], # noqa: B006 + verbose: bool = False, + save_as_external_data: bool = False, + external_data_filename: str = "", + external_data_file_threshold: int = 1024, + *, + provider: str | None = None, + **deprecated_kwargs, +) -> str: + """ + Use onnxruntime to optimize model. + + Args: + onnx_model (str | ModelProto): the path of input onnx model or ModelProto. + use_gpu (bool): whether the optimized model is targeted to run in GPU. + optimized_model_path (str or None): the path of optimized model. + opt_level (int): graph optimization level. + disabled_optimizers (List[str]): a list of names of disabled optimizers + save_as_external_data (bool): whether to save external data outside of ONNX model + external_data_filename (str): name of external data file. If not provided, name is automatically created from ONNX model. + external_data_file_threshold (int): threshold to decide whether to save tensor in ONNX model or in external data file + provider (str or None): execution provider to use if use_gpu + Returns: + optimized_model_path (str): the path of optimized model + """ + assert opt_level in [1, 2, 99] + from torch import version as torch_version # noqa: PLC0415 + + if onnx_model is None: + onnx_model = deprecated_kwargs.pop("onnx_model_path", None) + assert onnx_model is not None + + if ( + use_gpu + and provider is None + and set(onnxruntime.get_available_providers()).isdisjoint( + ["CUDAExecutionProvider", "MIGraphXExecutionProvider"] + ) + ): + logger.error("There is no gpu for onnxruntime to do optimization.") + return onnx_model + + model = ( + OnnxModel(load_model(onnx_model, load_external_data=False)) + if isinstance(onnx_model, str) + else OnnxModel(onnx_model) + ) + if model.use_float16() and not use_gpu: + logger.warning( + "This model uses float16 in the graph, use_gpu=False might cause extra Cast nodes. " + "Most operators have no float16 implementation in CPU, so Cast nodes are added to compute them in float32. " + "If the model is intended to use in GPU, please set use_gpu=True. " + "Otherwise, consider exporting onnx in float32 and optional int8 quantization for better performance. " + ) + + sess_options = onnxruntime.SessionOptions() + if opt_level == 1: + sess_options.graph_optimization_level = onnxruntime.GraphOptimizationLevel.ORT_ENABLE_BASIC + elif opt_level == 2: + sess_options.graph_optimization_level = onnxruntime.GraphOptimizationLevel.ORT_ENABLE_EXTENDED + elif opt_level == 3: + sess_options.graph_optimization_level = onnxruntime.GraphOptimizationLevel.ORT_ENABLE_LAYOUT + else: + sess_options.graph_optimization_level = onnxruntime.GraphOptimizationLevel.ORT_ENABLE_ALL + + if optimized_model_path is None: + if isinstance(onnx_model, str): + path_prefix = str(Path(onnx_model).with_suffix("")) # remove .onnx suffix + else: + path_prefix = "optimized_model" + optimized_model_path = "{}_o{}_{}.onnx".format(path_prefix, opt_level, "gpu" if use_gpu else "cpu") + + sess_options.optimized_model_filepath = optimized_model_path + if save_as_external_data: + if len(external_data_filename) == 0: + # Set external data filename to model_name.onnx.data + external_data_filename = os.path.basename(optimized_model_path) + ".data" + sess_options.add_session_config_entry( + "session.optimized_model_external_initializers_file_name", external_data_filename + ) + sess_options.add_session_config_entry( + "session.optimized_model_external_initializers_min_size_in_bytes", str(external_data_file_threshold) + ) + + if verbose: + print("Using onnxruntime to optimize model - Debug level Set to verbose") + sess_options.log_severity_level = 0 + + kwargs = {} + if disabled_optimizers: + kwargs["disabled_optimizers"] = disabled_optimizers + + if not use_gpu: + providers = ["CPUExecutionProvider"] + elif provider is not None: + if provider == "dml": + providers = ["DmlExecutionProvider"] + elif provider == "migraphx": + providers = ["MIGraphXExecutionProvider"] + elif provider == "cuda": + providers = ["CUDAExecutionProvider"] + elif provider == "tensorrt": + providers = ["TensorrtExecutionProvider", "CUDAExecutionProvider"] + else: + providers = ["CUDAExecutionProvider"] + + providers.append("CPUExecutionProvider") + else: + providers = [] + + if torch_version.hip: + providers.append("MIGraphXExecutionProvider") + else: + providers.append("CUDAExecutionProvider") + + # For large model, extract external data from model and add to session options + if isinstance(onnx_model, ModelProto): + if has_external_data(onnx_model): + raise ValueError( + "ModelProto has external data not loaded into memory, ORT cannot create session. " + "Please load external data before calling this function. " + "See https://onnx.ai/onnx/repo-docs/ExternalData.html for more information." + ) + external_names, external_values = extract_raw_data_from_model(onnx_model) + sess_options.add_external_initializers(list(external_names), list(external_values)) + + # Inference session is only used to optimize the model. + onnx_model = onnx_model.SerializeToString() if isinstance(onnx_model, ModelProto) else onnx_model + onnxruntime.InferenceSession(onnx_model, sess_options, providers=providers, **kwargs) + + assert os.path.exists(optimized_model_path) and os.path.isfile(optimized_model_path) + logger.debug("Save optimized model by onnxruntime to %s", optimized_model_path) + return optimized_model_path + + +def optimize_by_fusion( + model: ModelProto, + model_type: str = "bert", + num_heads: int = 0, + hidden_size: int = 0, + optimization_options: FusionOptions | None = None, +) -> OnnxModel: + """Optimize Model by graph fusion logic. + + Note that ONNXRuntime graph optimizations (like constant folding) will not be applied. So it is better to enable + constant folding during exporting ONNX model, or run optimize_by_onnxruntime on the model first like optimize_model. + + For BERT model, num_heads and hidden_size are optional. For other model types, you need to specify these parameters. + + Args: + model (ModelProto): model object + model_type (str, optional): model type - like bert, bert_tf, bert_keras or gpt2. Defaults to 'bert'. + num_heads (int, optional): number of attention heads. Defaults to 0. + 0 allows detect the parameter from graph automatically. + hidden_size (int, optional): hidden size. Defaults to 0. + 0 allows detect the parameter from graph automatically. + optimization_options (FusionOptions, optional): optimization options that turn on/off some fusions. + Defaults to None. + + Returns: + object of an optimizer class. + """ + if model_type not in ["bert", "t5", "swin", "unet", "vae", "clip", "sam2", "mmdit"] and ( + num_heads == 0 or hidden_size == 0 + ): + logger.warning(f"Please specify parameters of num_heads and hidden_size for model_type {model_type}") + + if model_type not in MODEL_TYPES: + logger.warning(f"Unsupported model type: {model_type} for graph fusion, directly return model.") + return OnnxModel(model) + + (optimizer_class, producer, _) = MODEL_TYPES[model_type] + + if model.producer_name and producer != model.producer_name: + logger.warning( + f'Model producer not matched: Expected "{producer}", Got "{model.producer_name}".' + "Please specify correct --model_type parameter." + ) + + if optimization_options is None: + optimization_options = FusionOptions(model_type) + + optimizer = optimizer_class(model, num_heads, hidden_size) + + optimizer.optimize(optimization_options) + + optimizer.topological_sort() + + optimizer.model.producer_name = "onnxruntime.transformers" + from onnxruntime import __version__ as onnxruntime_version # noqa: PLC0415 + + optimizer.model.producer_version = onnxruntime_version + + return optimizer + + +def optimize_model( + input: str | ModelProto, + model_type: str = "bert", + num_heads: int = 0, + hidden_size: int = 0, + optimization_options: FusionOptions | None = None, + opt_level: int | None = None, + use_gpu: bool = False, + only_onnxruntime: bool = False, + verbose: bool = False, + *, + provider: str | None = None, +) -> OnnxModel: + """Optimize Model by OnnxRuntime and/or python fusion logic. + + ONNX Runtime has graph optimizations (https://onnxruntime.ai/docs/performance/model-optimizations/graph-optimizations.html). + However, the coverage is limited. We also have graph fusions that implemented in Python to improve the coverage. + They can combined: ONNX Runtime will run first when opt_level > 0, then graph fusions in Python will be applied. + + To use ONNX Runtime only and no Python fusion logic, use only_onnxruntime flag and a positive opt_level like + optimize_model(input, opt_level=1, use_gpu=False, only_onnxruntime=True) + + When opt_level is None, we will choose default optimization level according to model type. + + When opt_level is 0 and only_onnxruntime is False, only python fusion logic is used and onnxruntime is disabled. + + When opt_level > 1, use_gpu shall set properly + since the optimized graph might contain operators for GPU or CPU only. + + If your model is intended for GPU inference only (especially float16 or mixed precision model), it is recommended to + set use_gpu to be True, otherwise the model is not optimized for GPU inference. + + For BERT model, num_heads and hidden_size are optional. For other model types, you need specify these parameters. + + Args: + input (str | ModelProto): input model path or ModelProto. + model_type (str, optional): model type - like bert, bert_tf, bert_keras or gpt2. Defaults to 'bert'. + num_heads (int, optional): number of attention heads. Defaults to 0. + 0 allows detect the parameter from graph automatically. + hidden_size (int, optional): hidden size. Defaults to 0. + 0 allows detect the parameter from graph automatically. + optimization_options (FusionOptions, optional): optimization options that turn on/off some fusions. + Defaults to None. + opt_level (int, optional): onnxruntime graph optimization level (0, 1, 2 or 99) or None. Defaults to None. + When the value is None, default value (1 for bert and gpt2, 0 for other model types) will be used. + When the level > 0, onnxruntime will be used to optimize model first. + use_gpu (bool, optional): use gpu or not for onnxruntime. Defaults to False. + only_onnxruntime (bool, optional): only use onnxruntime to optimize model, and no python fusion. + Defaults to False. + provider (str, optional): execution provider to use if use_gpu. Defaults to None. + + Returns: + object of an optimizer class. + """ + assert opt_level is None or opt_level in [0, 1, 2, 99] + + if model_type not in MODEL_TYPES: + logger.warning(f"Unsupported model type: {model_type} for optimization, directly return model.") + return OnnxModel(load_model(input)) if isinstance(input, str) else OnnxModel(input) + + (optimizer_class, _, default_opt_level) = MODEL_TYPES[model_type] + + if opt_level is None: + opt_level = default_opt_level + + # Disable constant sharing to avoid model proto str mismatch in test. Ideally the optimizer should not + # affect other fusions. We can update the expected model proto once the ConstantSharing optimizer logic becomes + # stable. + disabled_optimizers = ["ConstantSharing"] + temp_model_path = None + temp_dir = tempfile.TemporaryDirectory() + optimized_model_name = "model_o{}_{}.onnx".format(opt_level, "gpu" if use_gpu else "cpu") + optimized_model_path = os.path.join(temp_dir.name, optimized_model_name) + + # Auto detect if input model has external data + has_external_data_file = False + original_model = load_model(input, load_external_data=False) if isinstance(input, str) else input + if has_external_data(original_model): + has_external_data_file = True + del original_model + + if opt_level > 1: + # Disable some optimizers that might cause failure in symbolic shape inference or attention fusion. + disabled_optimizers += ( + [] + if only_onnxruntime + else [ + "MatMulScaleFusion", + "MatMulAddFusion", + "MatmulTransposeFusion", + "GemmActivationFusion", + "BiasSoftmaxFusion", + ] + ) + temp_model_path = optimize_by_onnxruntime( + input, + use_gpu=use_gpu, + provider=provider, + optimized_model_path=optimized_model_path, + opt_level=opt_level, + disabled_optimizers=disabled_optimizers, + verbose=verbose, + save_as_external_data=has_external_data_file, + ) + elif opt_level == 1: + # basic optimizations (like constant folding and cast elimination) are not specified to execution provider. + # Note that use_gpu=False might cause extra Cast nodes for float16 model since most operators does not support float16 in CPU. + # Sometime, use_gpu=True might cause extra memory copy nodes when some operators are supported only in CPU. + # We might need remove GPU memory copy nodes as preprocess of optimize_by_fusion if they cause no matching in fusion. + temp_model_path = optimize_by_onnxruntime( + input, + use_gpu=use_gpu, + provider=provider, + optimized_model_path=optimized_model_path, + opt_level=1, + disabled_optimizers=disabled_optimizers, + verbose=verbose, + save_as_external_data=has_external_data_file, + ) + + if only_onnxruntime and not temp_model_path: + logger.warning("Please specify a positive value for opt_level when only_onnxruntime is True") + + if temp_model_path is not None: + model = load_model(temp_model_path) + elif isinstance(input, str): + model = load_model(input) + else: + model = input + + if only_onnxruntime: + optimizer = optimizer_class(model, num_heads, hidden_size) + else: + optimizer = optimize_by_fusion(model, model_type, num_heads, hidden_size, optimization_options) + + # remove the temporary directory + temp_dir.cleanup() + + return optimizer + + +def get_fusion_statistics(optimized_model_path: str) -> dict[str, int]: + """ + Get counter of fused operators in optimized model. + + Args: + optimized_model_path (str): the path of onnx model. + + Returns: + A dictionary with operator type as key, and count as value + """ + model = load_model(optimized_model_path, format=None, load_external_data=True) + optimizer = BertOnnxModel(model) + return optimizer.get_fused_operator_statistics() + + +def _parse_arguments(): + parser = argparse.ArgumentParser( + description="Graph optimization tool for ONNX Runtime." + "It transforms ONNX graph to use optimized operators for Transformer models." + ) + parser.add_argument("--input", required=True, type=str, help="input onnx model path") + + parser.add_argument("--output", required=True, type=str, help="optimized onnx model path") + + parser.add_argument( + "--model_type", + required=False, + type=str.lower, + default="bert", + choices=list(MODEL_TYPES.keys()), + help="Model type selected in the list: " + ", ".join(MODEL_TYPES.keys()), + ) + + parser.add_argument( + "--num_heads", + required=False, + type=int, + default=0, + help="number of attention heads like 12 for bert-base and 16 for bert-large. " + "Default is 0 to detect automatically for BERT." + "For other model type, this parameter need specify correctly.", + ) + + parser.add_argument( + "--hidden_size", + required=False, + type=int, + default=0, + help="hidden size like 768 for bert-base and 1024 for bert-large. " + "Default is 0 to detect automatically for BERT. " + "For other model type, this parameter need specify correctly.", + ) + + parser.add_argument( + "--input_int32", + required=False, + action="store_true", + help="Use int32 (instead of int64) inputs. " + "It could avoid unnecessary data cast when EmbedLayerNormalization is fused for BERT.", + ) + parser.set_defaults(input_int32=False) + + parser.add_argument( + "--float16", + required=False, + action="store_true", + help="Convert all weights and nodes in float32 to float16. " + "It has potential loss in precision compared to mixed precision conversion.", + ) + parser.set_defaults(float16=False) + + FusionOptions.add_arguments(parser) + + parser.add_argument("--verbose", required=False, action="store_true", help="show debug information.") + parser.set_defaults(verbose=False) + + parser.add_argument( + "--use_gpu", + required=False, + action="store_true", + help="Use GPU for inference. Set this flag if your model is intended for GPU when opt_level > 1.", + ) + parser.set_defaults(use_gpu=False) + + parser.add_argument( + "--provider", + required=False, + type=str, + default=None, + help="Execution provider to use if use_gpu", + ) + + parser.add_argument( + "--only_onnxruntime", + required=False, + action="store_true", + help="optimized by onnxruntime only, and no graph fusion in Python", + ) + parser.set_defaults(only_onnxruntime=False) + + parser.add_argument( + "--opt_level", + required=False, + type=int, + choices=[0, 1, 2, 3, 99], + default=None, + help="onnxruntime optimization level. 0 will disable onnxruntime graph optimization. " + "The recommended value is 1. When opt_level > 1 is used, optimized model for GPU might not run in CPU. " + "Level 2, Level 3 and 99 are intended for --only_onnxruntime.", + ) + + parser.add_argument( + "--use_external_data_format", + required=False, + action="store_true", + help="use external data format to store large model (>2GB)", + ) + parser.set_defaults(use_external_data_format=False) + + parser.add_argument( + "--disable_symbolic_shape_infer", + required=False, + action="store_true", + help="disable symbolic shape inference", + ) + parser.set_defaults(disable_symbolic_shape_infer=False) + + parser.add_argument( + "--convert_to_packing_mode", + required=False, + action="store_true", + help="convert the model to packing mode. Only available for BERT like model", + ) + parser.set_defaults(convert_to_packing_mode=False) + + parser.add_argument( + "--convert_attribute", + required=False, + action="store_true", + help="convert attributes when using a rewritten ONNX model (e.g. Dynamo-exported model from ONNX Script)", + ) + parser.set_defaults(convert_attribute=False) + + args = parser.parse_args() + + return args + + +def _setup_logger(verbose): + if verbose: + logging.basicConfig( + format="[%(filename)s:%(lineno)s - %(funcName)20s()] %(message)s", level=logging.DEBUG, force=True + ) + else: + logging.basicConfig(format="%(funcName)20s: %(message)s", level=logging.INFO, force=True) + + +def main(): + args = _parse_arguments() + + _setup_logger(args.verbose) + + logger.debug(f"arguments:{args}") + + if os.path.realpath(args.input) == os.path.realpath(args.output): + logger.warning("Specified the same input and output path. Note that this may overwrite the original model") + + optimization_options = FusionOptions.parse(args) + + optimizer = optimize_model( + args.input, + args.model_type, + args.num_heads, + args.hidden_size, + opt_level=args.opt_level, + optimization_options=optimization_options, + use_gpu=args.use_gpu, + provider=args.provider, + only_onnxruntime=args.only_onnxruntime, + ) + + if args.float16: + optimizer.convert_float_to_float16(keep_io_types=True) + + if args.input_int32: + optimizer.change_graph_inputs_to_int32() + + # Print the operator statistics might help end user. + optimizer.get_operator_statistics() + + fused_op_count = optimizer.get_fused_operator_statistics() + if "bert" in args.model_type and optimizer.is_fully_optimized(fused_op_count): + logger.info("The model has been fully optimized.") + else: + logger.info("The model has been optimized.") + + if args.convert_to_packing_mode: + if args.model_type == "bert": + optimizer.convert_to_packing_mode(not args.disable_symbolic_shape_infer) + else: + logger.warning("Packing mode only supports BERT like models") + + optimizer.save_model_to_file(args.output, args.use_external_data_format, convert_attribute=args.convert_attribute) + + +if __name__ == "__main__": + main() diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/past_helper.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/past_helper.py new file mode 100644 index 0000000000000000000000000000000000000000..61d2f5db63a46dbffc2383abbb530c6060f974b6 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/past_helper.py @@ -0,0 +1,149 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +import logging + +import torch + +logger = logging.getLogger(__name__) + + +class PastKeyValuesHelper: + """Helper functions to process past key values for encoder-decoder model""" + + @staticmethod + def get_past_names(num_layers, present: bool = False): + past_self_names = [] + past_cross_names = [] + for i in range(num_layers): + past_self_names.extend( + [f"present_key_self_{i}", f"present_value_self_{i}"] + if present + else [f"past_key_self_{i}", f"past_value_self_{i}"] + ) + past_cross_names.extend( + [f"present_key_cross_{i}", f"present_value_cross_{i}"] + if present + else [f"past_key_cross_{i}", f"past_value_cross_{i}"] + ) + return past_self_names + past_cross_names + + @staticmethod + def group_by_self_or_cross(present_key_values): + """Split present state from grouped by layer to grouped by self/cross attention. + Before: (past_key_self_0, past_value_self_0, past_key_cross_0, past_value_cross_0), (past_key_self_1, past_value_self_1, past_key_cross_1, past_value_cross_1), ... + After: (past_key_self_0, past_value_self_0, past_key_self_1, past_value_self_1, ...), (past_key_cross_0, past_value_cross_0, past_key_cross_1, past_value_cross_1, ...) + + """ + present_self = [] + present_cross = [] + for _i, present_layer_i in enumerate(present_key_values): + assert len(present_layer_i) == 4, f"Expected to have four items. Got {len(present_layer_i)}" + ( + present_key_self, + present_value_self, + present_key_cross, + present_value_cross, + ) = present_layer_i + present_self.extend([present_key_self, present_value_self]) + present_cross.extend([present_key_cross, present_value_cross]) + return present_self, present_cross + + @staticmethod + def group_by_layer(past, num_layers): + """Reorder past state from grouped by self/cross attention to grouped by layer. + Before: past_key_self_0, past_value_self_0, past_key_self_1, past_value_self_1, ..., past_key_cross_0, past_value_cross_0, past_key_cross_1, past_value_cross_1, ... + After: (past_key_self_0, past_value_self_0, past_key_cross_0, past_value_cross_0), (past_key_self_1, past_value_self_1, past_key_cross_1, past_value_cross_1), + """ + assert len(past) == 4 * num_layers + return tuple( + [ + past[2 * i], + past[2 * i + 1], + past[2 * num_layers + 2 * i], + past[2 * num_layers + 2 * i + 1], + ] + for i in range(num_layers) + ) + + @staticmethod + def back_group_by_layer(past_key_values: tuple[tuple[torch.Tensor]]): + """Categorize present_key_values from self and cross attention to layer by layer. + + Reorder past state from grouped by self/cross attention to grouped by layer. + Before: past_key_self_0, past_value_self_0, past_key_self_1, past_value_self_1, ..., + past_key_cross_0, past_value_cross_0, past_key_cross_1, past_value_cross_1, ... + After: (past_key_self_0, past_value_self_0, past_key_cross_0, past_value_cross_0), + (past_key_self_1, past_value_self_1, past_key_cross_1, past_value_cross_1), + + Args: + present_key_values: From past_key_values of a model (group by self and cross attention) + + Returns: + past_tuples: present key and values grouped by layer. + """ + past_tuples = () + half_idx = len(past_key_values) // 2 + for i in range(len(past_key_values) // 4): + idx = 2 * i + past_tuples += ( + ( + past_key_values[idx], + past_key_values[idx + 1], + past_key_values[half_idx + idx], + past_key_values[half_idx + idx + 1], + ), + ) + return past_tuples + + @staticmethod + def group_by_self_and_cross(present_key_values: tuple[torch.Tensor], concat: bool = False): + """Categorize present_key_values into self and cross attention. + + Split present state from grouped by layer to grouped by self/cross attention. + Before: (past_key_self_0, past_value_self_0, past_key_cross_0, past_value_cross_0), + (past_key_self_1, past_value_self_1, past_key_cross_1, past_value_cross_1), ... + After: (past_key_self_0, past_value_self_0, past_key_self_1, past_value_self_1, ...), + (past_key_cross_0, past_value_cross_0, past_key_cross_1, past_value_cross_1, ...) + + Args: + present_key_values: From past_key_values of a model (group by layer) + concat: If concat self attention with cross attention key/value to return + + Returns: + present_self (Tuple[torch.Tensor]): present key and values from self attention + present_cross (Tuple[torch.Tensor]): present key and values from cross attention + """ + present_self: list[torch.Tensor] = [] + present_cross: list[torch.Tensor] = [] + for _, present_layer_i in enumerate(present_key_values): + assert len(present_layer_i) == 4, f"Expected to have four items. Got {len(present_layer_i)}" + present_key_self, present_value_self, present_key_cross, present_value_cross = present_layer_i + present_self.extend([present_key_self, present_value_self]) + present_cross.extend([present_key_cross, present_value_cross]) + if concat: + return present_self + present_cross + else: + return present_self, present_cross + + @staticmethod + def get_input_names(past_key_values: tuple[tuple[torch.Tensor]], encoder=True): + """Process input names of model wrapper. + + Args: + past_key_values: Consider `self` and `cross` past_key_values + + Returns: + names (List[string]): input names + """ + names = [] + num_layers = len(past_key_values) // 4 if encoder else len(past_key_values) + prefix = "past_" if not encoder else "present_" + for i in range(num_layers): + names.extend([prefix + s for s in [f"key_self_{i}", f"value_self_{i}"]]) + for i in range(num_layers): + names.extend([prefix + s for s in [f"key_cross_{i}", f"value_cross_{i}"]]) + return names diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/profile_result_processor.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/profile_result_processor.py new file mode 100644 index 0000000000000000000000000000000000000000..d52f069f8fa7c34629c93cc347a1339d4c9fc611 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/profile_result_processor.py @@ -0,0 +1,358 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +# -------------------------------------------------------------------------- + +"""This profiler result processor print out the kernel time spent on each Node of the model. +Example of importing profile result file from onnxruntime_perf_test: + python profile_result_processor.py --input profile_2021-10-25_12-02-41.json +""" + +import argparse +import json + +_NODES_TYPE_CONTAINING_SUBGRAPH = frozenset(("Scan", "Loop", "If")) + + +def parse_arguments(argv=None): + parser = argparse.ArgumentParser() + + parser.add_argument( + "-i", + "--input", + required=False, + type=str, + help="Set the input file for reading the profile results", + ) + + parser.add_argument( + "--threshold", + required=False, + type=float, + default=0.01, + help="Threshold of run time ratio among all nodes. Nodes with larger ratio will show in top expensive nodes.", + ) + + parser.add_argument( + "--provider", + required=False, + type=str, + default="cuda", + help="Execution provider to use", + ) + + parser.add_argument( + "--kernel_time_only", + required=False, + action="store_true", + help="Only include the kernel time and no fence time", + ) + + parser.set_defaults(kernel_time_only=False) + + parser.add_argument("-v", "--verbose", required=False, action="store_true") + parser.set_defaults(verbose=False) + + return parser.parse_args(argv) + + +def load_profile_json(profile_file): + print(f"loading profile output {profile_file} ...") + + with open(profile_file) as opened_file: + sess_time = json.load(opened_file) + + assert isinstance(sess_time, list) + return sess_time + + +def parse_kernel_results(sess_time, threshold=0): + """Parse profile data and output nodes in two sections - nodes in the original order, and top expensive nodes. + + Args: + sess_time (List[Dict]): profile data + threshold (int, optional): Minimum ratio of duration among all. Defaults to 0. + + Returns: + List[str]: lines of string for output. + """ + kernel_name_to_op_name = {} + kernel_time = {} + kernel_freq = {} + total = 0 + session_init = False + for item in sess_time: + # Skip all MemcpyHostToDevice before session_initialization + if item["cat"] == "Session" and item["name"] == "session_initialization": + session_init = True + if not session_init: + continue + + if item["cat"] == "Kernel" and "dur" in item and "args" in item and "op_name" in item["args"]: + kernel_name = item["name"] + + op_name = item["args"]["op_name"] + if op_name in _NODES_TYPE_CONTAINING_SUBGRAPH: + continue + + # Handle MemcpyHostToDevice and MemcpyDeviceToHost here + if not op_name: + op_name = f"({kernel_name})" + + if kernel_name in kernel_time: + kernel_time[kernel_name] += item["dur"] + kernel_freq[kernel_name] += 1 + else: + kernel_time[kernel_name] = item["dur"] + kernel_freq[kernel_name] = 1 + kernel_name_to_op_name[kernel_name] = op_name + + total += item["dur"] + + if not kernel_time: + return ["No kernel record found!"] + + # Output items with run time ratio > thresholds, and sorted by duration in the descending order. + lines = [] + lines.append(f"\nTop expensive kernels with Time% >= {threshold * 100:.2f}:") + lines.append("-" * 64) + lines.append("Total(μs)\tTime%\tCalls\tAvg(μs)\tKernel") + for kernel_name, duration in sorted(kernel_time.items(), key=lambda x: x[1], reverse=True): + ratio = duration / total + if ratio < threshold: + continue + + calls = kernel_freq[kernel_name] + avg_time = duration / float(calls) + lines.append(f"{duration:10d}\t{ratio * 100.0:5.2f}\t{calls:5d}\t{avg_time:8.1f}\t{kernel_name}") + + # Group by operator + op_time = {} + for kernel_name, op_name in kernel_name_to_op_name.items(): + duration = kernel_time[kernel_name] + if op_name in op_time: + op_time[op_name] += duration + else: + op_time[op_name] = duration + + lines.append("\nGroup kernel time by operator:") + lines.append("-" * 64) + lines.append("Total(μs)\tTime%\tOperator") + for op_name, duration in sorted(op_time.items(), key=lambda x: x[1], reverse=True): + ratio = duration / total + lines.append(f"{duration:10d}\t{ratio * 100.0:5.2f}\t{op_name}") + + return lines + + +def parse_node_results(sess_time, kernel_time_only=False, threshold=0): + """Parse profile data and output nodes in two sections - nodes in the original order, and top expensive nodes. + + Args: + sess_time (List[Dict]): profile data + kernel_time_only (bool, optional): Only include items for kernel time. Defaults to False. + threshold (int, optional): Minimum ratio of duration among all. Defaults to 0. + + Returns: + List[str]: lines of string for output. + """ + node_name_list = [] + node_time = {} + node_freq = {} + node_provider = {} + total = 0 + for item in sess_time: + if item["cat"] == "Node" and "dur" in item and "args" in item and "op_name" in item["args"]: + node_name = ( + item["name"].replace("_kernel_time", "").replace("_fence_before", "").replace("_fence_after", "") + ) + + if "provider" in item["args"]: + if item["args"]["provider"] == "CPUExecutionProvider": + device = "CPU" + elif item["args"]["provider"] == "CUDAExecutionProvider": + device = "CUDA" + elif item["args"]["provider"] == "DmlExecutionProvider": + device = "DML" + + if node_name not in node_provider: + node_provider[node_name] = device + else: + assert node_provider[node_name] == device + elif kernel_time_only: + continue + + op_name = item["args"]["op_name"] + if op_name in _NODES_TYPE_CONTAINING_SUBGRAPH: + continue + + if node_name in node_time: + node_time[node_name] += item["dur"] + node_freq[node_name] += 1 + else: + node_time[node_name] = item["dur"] + node_freq[node_name] = 1 + node_name_list.append(node_name) + + total += item["dur"] + + # Output items in the original order. + lines = [ + "\nNodes in the original order:", + "-" * 64, + "Total(μs)\tTime%\tAcc %\tAvg(μs)\tCalls\tProvider\tNode", + ] + before_percentage = 0.0 + for node_name in node_name_list: + duration = node_time[node_name] + calls = node_freq[node_name] + avg_time = duration / float(calls) + percentage = (duration / total) * 100.0 + provider = node_provider.get(node_name, "") + before_percentage += percentage + lines.append( + f"{duration:10d}\t{percentage:5.2f}\t{before_percentage:5.2f}\t{avg_time:8.1f}\t{calls:5d}\t{provider:8s}\t{node_name}" + ) + + # Output items with run time ratio > thresholds, and sorted by duration in the descending order. + lines.append(f"\nTop expensive nodes with Time% >= {threshold * 100:.2f}:") + lines.append("-" * 64) + lines.append("Total(μs)\tTime%\tAvg(μs)\tCalls\tProvider\tNode") + for node_name, duration in sorted(node_time.items(), key=lambda x: x[1], reverse=True): + ratio = duration / total + if ratio < threshold: + continue + + calls = node_freq[node_name] + avg_time = duration / float(calls) + percentage = (duration / total) * 100.0 + provider = node_provider.get(node_name, "") + lines.append(f"{duration:10d}\t{percentage:5.2f}\t{avg_time:8.1f}\t{calls:5d}\t{provider:8s}\t{node_name}") + + return lines + + +def group_node_results(sess_time): + """Group results by operator name. + + Args: + sess_time (List[Dict]): profile data + + Returns: + List[str]: lines of string for output. + """ + op_kernel_time = {} + op_kernel_records = {} + total_kernel_time = 0 + + provider_op_kernel_time = {} + provider_op_kernel_records = {} + provider_kernel_time = {} + + op_fence_time = {} + total_fence_time = 0 + + provider_counter = {} + for item in sess_time: + if item["cat"] == "Node" and "dur" in item and "args" in item and "op_name" in item["args"]: + op_name = item["args"]["op_name"] + + # TODO: shall we have a separated group for nodes with subgraph? + if op_name in _NODES_TYPE_CONTAINING_SUBGRAPH: + continue + + if "provider" not in item["args"]: + if "fence" in item["name"]: + if op_name in op_fence_time: + op_fence_time[op_name] += item["dur"] + else: + op_fence_time[op_name] = item["dur"] + total_fence_time += item["dur"] + continue + + provider = item["args"].get("provider", "") + if provider in provider_counter: + provider_counter[provider] += 1 + else: + provider_counter[provider] = 1 + + key = f"{provider}:{op_name}" + if key in provider_op_kernel_time: + provider_op_kernel_time[key] += item["dur"] + provider_op_kernel_records[key] += 1 + else: + provider_op_kernel_time[key] = item["dur"] + provider_op_kernel_records[key] = 1 + + if provider in provider_kernel_time: + provider_kernel_time[provider] += item["dur"] + else: + provider_kernel_time[provider] = item["dur"] + + if op_name in op_kernel_time: + op_kernel_time[op_name] += item["dur"] + op_kernel_records[op_name] += 1 + else: + op_kernel_time[op_name] = item["dur"] + op_kernel_records[op_name] = 1 + + total_kernel_time += item["dur"] + + lines = ["", "Grouped by operator"] + lines.append("-" * 64) + lines.append("Total(μs)\tTime%\tKernel(μs)\tKernel%\tCalls\tAvgKernel(μs)\tFence(μs)\tOperator") + for op_name, kernel_time in sorted(op_kernel_time.items(), key=lambda x: x[1], reverse=True): + fence_time = op_fence_time.get(op_name, 0) + kernel_time_ratio = kernel_time / total_kernel_time + total_time = kernel_time + fence_time + time_ratio = total_time / (total_kernel_time + total_fence_time) + kernel_calls = op_kernel_records[op_name] + avg_kernel_time = kernel_time / kernel_calls + lines.append( + f"{total_time:10d}\t{time_ratio * 100.0:5.2f}\t{kernel_time:11d}\t{kernel_time_ratio * 100.0:5.2f}\t{kernel_calls:5d}\t{avg_kernel_time:14.1f}\t{fence_time:10d}\t{op_name}" + ) + + lines += ["", "Grouped by provider + operator"] + lines.append("-" * 64) + lines.append("Kernel(μs)\tProvider%\tCalls\tAvgKernel(μs)\tProvider\tOperator") + for key, kernel_time in sorted(provider_op_kernel_time.items(), key=lambda x: x[1], reverse=True): + parts = key.split(":") + provider = parts[0] + op_name = parts[1] + short_ep = provider.replace("ExecutionProvider", "") + calls = provider_op_kernel_records[key] + avg_kernel_time = kernel_time / calls + provider_time_ratio = kernel_time / provider_kernel_time[provider] + lines.append( + f"{kernel_time:10d}\t{provider_time_ratio * 100.0:9.2f}\t{calls:5d}\t{avg_kernel_time:14.1f}\t{short_ep:8s}\t{op_name}" + ) + + return lines + + +def process_results(profile_file, args): + profile_records = load_profile_json(profile_file) + + lines = parse_kernel_results(profile_records, args.threshold) + + lines += parse_node_results(profile_records, args.kernel_time_only, args.threshold) + + lines += group_node_results(profile_records) + + return lines + + +if __name__ == "__main__": + arguments = parse_arguments() + print("Arguments", arguments) + + from benchmark_helper import setup_logger + + setup_logger(arguments.verbose) + + profile_file = arguments.input + + results = process_results(profile_file, arguments) + + for line in results: + print(line) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/profiler.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/profiler.py new file mode 100644 index 0000000000000000000000000000000000000000..7079f0b004ba844fab30ae13b410e481479a8d46 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/profiler.py @@ -0,0 +1,434 @@ +import argparse +import os + +import numpy +import psutil +from onnx import TensorProto + +""" +This profiler tool could run a transformer model and print out the kernel time spent on each Node of the model. +Example of profiling of longformer model: + python profiler.py --model longformer-base-4096_fp32.onnx --batch_size 1 --sequence_length 4096 --global_length 8 --samples 1000 --thread_num 8 --dummy_inputs longformer --use_gpu +Example of importing profile result file from onnxruntime_perf_test: + python profiler.py --input profile_2021-10-25_12-02-41.json +""" + + +def parse_arguments(argv=None): + parser = argparse.ArgumentParser() + + parser.add_argument( + "-i", + "--input", + required=False, + type=str, + help="Set the input file for reading the profile results", + ) + + parser.add_argument( + "-m", + "--model", + required=False, + type=str, + help="onnx model path to run profiling. Required when --input is not specified.", + ) + + parser.add_argument( + "-b", + "--batch_size", + required=False, + type=int, + default=1, + help="batch size of input", + ) + + parser.add_argument( + "-s", + "--sequence_length", + required=False, + type=int, + default=32, + help="sequence length of input", + ) + + parser.add_argument( + "--past_sequence_length", + required=False, + type=int, + default=1, + help="past sequence length for gpt2", + ) + + parser.add_argument( + "--global_length", + required=False, + type=int, + default=1, + help="number of global tokens for longformer", + ) + + parser.add_argument( + "--samples", + required=False, + type=int, + default=1000, + help="number of samples to test. Set it large enough to reduce the variance of performance result.", + ) + + parser.add_argument( + "--threshold", + required=False, + type=float, + default=0.01, + help="Threshold of run time ratio among all nodes. Nodes with larger ratio will show in top expensive nodes.", + ) + + parser.add_argument( + "--thread_num", + required=False, + type=int, + default=-1, + help="number of threads to use", + ) + + parser.add_argument( + "--input_ids_name", + required=False, + type=str, + default=None, + help="input name for input IDs, for bert", + ) + parser.add_argument( + "--segment_ids_name", + required=False, + type=str, + default=None, + help="input name for segment IDs, for bert", + ) + parser.add_argument( + "--input_mask_name", + required=False, + type=str, + default=None, + help="input name for attention mask, for bert", + ) + + parser.add_argument( + "--dummy_inputs", + required=False, + default="default", + choices=["bert", "gpt2", "longformer", "default"], + help="Type of model inputs. The default will create dummy inputs with ones.", + ) + + parser.add_argument("-g", "--use_gpu", required=False, action="store_true", help="use GPU") + parser.set_defaults(use_gpu=False) + + parser.add_argument( + "--provider", + required=False, + type=str, + default="cuda", + help="Execution provider to use", + ) + + parser.add_argument( + "--basic_optimization", + required=False, + action="store_true", + help="Enable only basic graph optimizations. By default, all optimizations are enabled in OnnxRuntime", + ) + parser.set_defaults(basic_optimization=False) + + parser.add_argument( + "--kernel_time_only", + required=False, + action="store_true", + help="Only include the kernel time and no fence time", + ) + parser.set_defaults(kernel_time_only=False) + + parser.add_argument("-v", "--verbose", required=False, action="store_true") + parser.set_defaults(verbose=False) + + return parser.parse_args(argv) + + +def run_profile(onnx_model_path, use_gpu, provider, basic_optimization, thread_num, all_inputs): + from benchmark_helper import create_onnxruntime_session # noqa: PLC0415 + + session = create_onnxruntime_session( + onnx_model_path, + use_gpu, + provider, + enable_all_optimization=not basic_optimization, + num_threads=thread_num, + enable_profiling=True, + ) + + for inputs in all_inputs: + _ = session.run(None, inputs) + + profile_file = session.end_profiling() + return profile_file + + +def get_dim_from_type_proto(dim): + return getattr(dim, dim.WhichOneof("value")) if type(dim.WhichOneof("value")) == str else None # noqa: E721 + + +def get_shape_from_type_proto(type_proto): + return [get_dim_from_type_proto(d) for d in type_proto.tensor_type.shape.dim] + + +def create_dummy_inputs(onnx_model, batch_size, sequence_length, samples): + """Create dummy inputs for ONNX model. + + Args: + onnx_model (OnnxModel): ONNX model + batch_size (int): batch size + sequence_length (int): sequence length + samples (int): number of samples + + Returns: + List[Dict]: list of inputs + """ + dummy_inputs = {} + for graph_input in onnx_model.get_graph_inputs_excluding_initializers(): + shape = get_shape_from_type_proto(graph_input.type) + symbol_dims = [] + for i, dim in enumerate(shape): + if isinstance(dim, str): + symbol_dims.append(i) + + # allowed symbolic dimensions: batch_size and sequence_length + if len(symbol_dims) > 2: + return None + if len(symbol_dims) > 0: + shape[symbol_dims[0]] = batch_size + if len(symbol_dims) > 1: + shape[symbol_dims[1]] = sequence_length + + elem_type = graph_input.type.tensor_type.elem_type + assert elem_type in [TensorProto.FLOAT, TensorProto.INT32, TensorProto.INT64] + data_type = ( + numpy.float32 + if elem_type == TensorProto.FLOAT + else (numpy.int64 if elem_type == TensorProto.INT64 else numpy.int32) + ) + data = numpy.ones(shape, dtype=data_type) + dummy_inputs[graph_input.name] = data + + all_inputs = [dummy_inputs for _ in range(samples)] + return all_inputs + + +def create_bert_inputs( + onnx_model, + batch_size, + sequence_length, + samples, + input_ids_name=None, + segment_ids_name=None, + input_mask_name=None, +): + """Create dummy inputs for BERT model. + + Args: + onnx_model (OnnxModel): ONNX model + batch_size (int): batch size + sequence_length (int): sequence length + samples (int): number of samples + input_ids_name (str, optional): Name of graph input for input IDs. Defaults to None. + segment_ids_name (str, optional): Name of graph input for segment IDs. Defaults to None. + input_mask_name (str, optional): Name of graph input for attention mask. Defaults to None. + + Returns: + List[Dict]: list of inputs + """ + from bert_test_data import find_bert_inputs, generate_test_data # noqa: PLC0415 + + input_ids, segment_ids, input_mask = find_bert_inputs(onnx_model, input_ids_name, segment_ids_name, input_mask_name) + all_inputs = generate_test_data( + batch_size, + sequence_length, + test_cases=samples, + seed=123, + verbose=False, + input_ids=input_ids, + segment_ids=segment_ids, + input_mask=input_mask, + random_mask_length=False, + ) + + return all_inputs + + +def create_gpt2_inputs(onnx_model, batch_size, sequence_length, past_sequence_length, samples): + """Create dummy inputs for GPT-2 model. + + Args: + onnx_model (OnnxModel): ONNX model + batch_size (int): batch size + sequence_length (int): sequence length + past_sequence_length (int): past sequence length + samples (int): number of samples + + Raises: + RuntimeError: symbolic is not supported. Use the tool convert_to_onnx.py to export ONNX model instead. + + Returns: + List[Dict]: list of inputs + """ + # The symbolic names shall be same as those used in Gpt2Helper.export_onnx(...) function. + symbols = { + "batch_size": batch_size, + "seq_len": sequence_length, + "past_seq_len": past_sequence_length, + "total_seq_len": sequence_length + past_sequence_length, + } + + dummy_inputs = {} + for graph_input in onnx_model.get_graph_inputs_excluding_initializers(): + shape = get_shape_from_type_proto(graph_input.type) + for i, dim in enumerate(shape): + if isinstance(dim, str): + if dim not in symbols: + raise RuntimeError(f"symbol is not supported: {dim}") + else: + shape[i] = symbols[dim] + + elem_type = graph_input.type.tensor_type.elem_type + assert elem_type in [TensorProto.FLOAT, TensorProto.INT32, TensorProto.INT64] + data_type = ( + numpy.float32 + if elem_type == TensorProto.FLOAT + else (numpy.int64 if elem_type == TensorProto.INT64 else numpy.int32) + ) + data = numpy.ones(shape, dtype=data_type) + dummy_inputs[graph_input.name] = data + + all_inputs = [dummy_inputs for _ in range(samples)] + return all_inputs + + +def create_longformer_inputs(onnx_model, batch_size, sequence_length, global_length, samples): + """Create dummy inputs for Longformer model. + + Args: + onnx_model (OnnxModel): ONNX model + batch_size (int): batch size + sequence_length (int): sequence length + global_length (int): number of global tokens + samples (int): number of samples + + Raises: + RuntimeError: symbolic is not supported. Use the tool convert_longformer_to_onnx.py to export ONNX model instead. + + Returns: + List[Dict]: list of inputs + """ + symbols = {"batch_size": batch_size, "sequence_length": sequence_length} + + dummy_inputs = {} + for graph_input in onnx_model.get_graph_inputs_excluding_initializers(): + shape = get_shape_from_type_proto(graph_input.type) + for i, dim in enumerate(shape): + if isinstance(dim, str): + if dim not in symbols: + raise RuntimeError(f"symbol is not supported: {dim}") + else: + shape[i] = symbols[dim] + + elem_type = graph_input.type.tensor_type.elem_type + assert elem_type in [TensorProto.FLOAT, TensorProto.INT32, TensorProto.INT64] + data_type = ( + numpy.float32 + if elem_type == TensorProto.FLOAT + else (numpy.int64 if elem_type == TensorProto.INT64 else numpy.int32) + ) + + if "global" in graph_input.name: + data = numpy.zeros(shape, dtype=data_type) + data[:, :global_length] = 1 + else: + data = numpy.ones(shape, dtype=data_type) + dummy_inputs[graph_input.name] = data + + all_inputs = [dummy_inputs for _ in range(samples)] + return all_inputs + + +def run(args): + num_threads = args.thread_num if args.thread_num > 0 else psutil.cpu_count(logical=False) + + # Set OMP environment variable before importing onnxruntime. Needed for cpu only, and no impact for onnxruntime-gpu package. + if "OMP_NUM_THREADS" not in os.environ: + os.environ["OMP_NUM_THREADS"] = str(num_threads) + + from onnx import load # noqa: PLC0415 + from onnx_model import OnnxModel # noqa: PLC0415 + + onnx_model = OnnxModel(load(args.model)) + + all_inputs = None + if args.dummy_inputs == "bert": + all_inputs = create_bert_inputs( + onnx_model, + args.batch_size, + args.sequence_length, + args.samples, + args.input_ids_name, + args.segment_ids_name, + args.input_mask_name, + ) + elif args.dummy_inputs == "gpt2": + all_inputs = create_gpt2_inputs( + onnx_model, + args.batch_size, + args.sequence_length, + args.past_sequence_length, + args.samples, + ) + elif args.dummy_inputs == "longformer": + all_inputs = create_longformer_inputs( + onnx_model, + args.batch_size, + args.sequence_length, + args.global_length, + args.samples, + ) + else: # default + all_inputs = create_dummy_inputs(onnx_model, args.batch_size, args.sequence_length, args.samples) + + profile_file = run_profile( + args.model, + args.use_gpu, + args.provider, + args.basic_optimization, + args.thread_num, + all_inputs, + ) + + return profile_file + + +if __name__ == "__main__": + arguments = parse_arguments() + print("Arguments", arguments) + + from benchmark_helper import setup_logger + + setup_logger(arguments.verbose) + + if not arguments.input: + assert arguments.model, "requires either --model to run profiling or --input to read profiling results" + profile_file = run(arguments) + else: + profile_file = arguments.input + from profile_result_processor import process_results + + results = process_results(profile_file, arguments) + + for line in results: + print(line) diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/quantize_helper.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/quantize_helper.py new file mode 100644 index 0000000000000000000000000000000000000000..a77018acec8922964e7ecf32615a5db7bfac7990 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/quantize_helper.py @@ -0,0 +1,76 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +import logging +import os + +import onnx +import torch +from transformers.modeling_utils import Conv1D + +logger = logging.getLogger(__name__) + + +def _conv1d_to_linear(module): + in_size, out_size = module.weight.shape + linear = torch.nn.Linear(in_size, out_size) + linear.weight.data = module.weight.data.T.contiguous() + linear.bias.data = module.bias.data + return linear + + +def conv1d_to_linear(model): + """in-place + This is for Dynamic Quantization, as Conv1D is not recognized by PyTorch, convert it to nn.Linear + """ + logger.debug("replace Conv1D with Linear") + for name in list(model._modules): + module = model._modules[name] + if isinstance(module, Conv1D): + linear = _conv1d_to_linear(module) + model._modules[name] = linear + else: + conv1d_to_linear(module) + + +def _get_size_of_pytorch_model(model): + torch.save(model.state_dict(), "temp.p") + size = os.path.getsize("temp.p") / (1024 * 1024) + os.remove("temp.p") + return size + + +class QuantizeHelper: + @staticmethod + def quantize_torch_model(model, dtype=torch.qint8): + """ + Usage: model = quantize_model(model) + + TODO: mix of in-place and return, but results are different + """ + conv1d_to_linear(model) + quantized_model = torch.quantization.quantize_dynamic(model, {torch.nn.Linear}, dtype=dtype) + logger.info(f"Size of full precision Torch model(MB):{_get_size_of_pytorch_model(model)}") + logger.info(f"Size of quantized Torch model(MB):{_get_size_of_pytorch_model(quantized_model)}") + return quantized_model + + @staticmethod + def quantize_onnx_model(onnx_model_path, quantized_model_path, use_external_data_format=False): + from pathlib import Path # noqa: PLC0415 + + from onnxruntime.quantization import quantize_dynamic # noqa: PLC0415 + + Path(quantized_model_path).parent.mkdir(parents=True, exist_ok=True) + logger.info(f"Size of full precision ONNX model(MB):{os.path.getsize(onnx_model_path) / (1024 * 1024)}") + quantize_dynamic( + onnx_model_path, + quantized_model_path, + use_external_data_format=use_external_data_format, + extra_options={"DefaultTensorType": onnx.TensorProto.FLOAT}, + ) + logger.info(f"quantized model saved to:{quantized_model_path}") + # TODO: inlcude external data in total model size. + logger.info(f"Size of quantized ONNX model(MB):{os.path.getsize(quantized_model_path) / (1024 * 1024)}") diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/shape_infer_helper.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/shape_infer_helper.py new file mode 100644 index 0000000000000000000000000000000000000000..6643d8b26dab40bd6dd0fec80a113df10ed7e303 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/shape_infer_helper.py @@ -0,0 +1,121 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +# -------------------------------------------------------------------------- + +import logging +import os +import sys + +# In ORT Package the symbolic_shape_infer.py is in ../tools +file_path = os.path.dirname(__file__) +if os.path.exists(os.path.join(file_path, "../tools/symbolic_shape_infer.py")): + sys.path.append(os.path.join(file_path, "../tools")) +else: + sys.path.append(os.path.join(file_path, "..")) + +from symbolic_shape_infer import SymbolicShapeInference, get_shape_from_type_proto, sympy # noqa: E402 + +logger = logging.getLogger(__name__) + + +class SymbolicShapeInferenceHelper(SymbolicShapeInference): + def __init__(self, model, verbose=0, int_max=2**31 - 1, auto_merge=True, guess_output_rank=False): + super().__init__(int_max, auto_merge, guess_output_rank, verbose) + self.model_ = model + self.all_shapes_inferred_: bool = False + self.is_inferred_: bool = False + self.dynamic_axis_mapping_: dict[str, int] = {} + + def infer(self, dynamic_axis_mapping: dict[str, int], max_runs: int = 200): + """Run shape inference, and try replace dynamic axis from string to integer when mapping is provided. + + Args: + dynamic_axis_mapping (_type_): a dictionary with name of dynamic axis as key, like {"batch_size" : 4} + max_runs (int, optional): limit maximum number of runs to avoid infinite loop. Defaults to 200. + + Returns: + bool: whether all shapes has been inferred or not. + """ + assert dynamic_axis_mapping is not None + + if self.is_inferred_ and self.dynamic_axis_mapping_ == dynamic_axis_mapping: + return self.all_shapes_inferred_ + + self.dynamic_axis_mapping_ = dynamic_axis_mapping + + self._preprocess(self.model_) + + count = 0 + while self.run_: + logger.debug(f"shape infer run {count}") + self.all_shapes_inferred_ = self._infer_impl() + count += 1 + if max_runs > 0 and count >= max_runs: + break + + self.is_inferred_ = True + return self.all_shapes_inferred_ + + def _get_sympy_shape(self, node, idx): + """Override it to ensure shape inference by giving the actual value of dynamic axis.""" + sympy_shape = [] + + shape = self._get_shape(node, idx) + if shape: + for dim in shape: + if isinstance(dim, str): + if dim in self.dynamic_axis_mapping_: + sympy_shape.append(self.dynamic_axis_mapping_[dim]) + elif dim in self.symbolic_dims_: + sympy_shape.append(self.symbolic_dims_[dim]) + else: + sympy_shape.append(sympy.Symbol(dim, integer=True)) + else: + assert dim is not None + sympy_shape.append(dim) + return sympy_shape + + def get_edge_shape(self, edge): + """Get shape of an edge. + + Args: + edge (str): name of edge + + Returns: + Optional[List[int]]: the shape, or None if shape is unknown + """ + assert self.all_shapes_inferred_ + if edge not in self.known_vi_: + print("Cannot retrieve the shape of " + str(edge)) + return None + + type_proto = self.known_vi_[edge].type + shape = get_shape_from_type_proto(type_proto) + + if shape is not None: + for i, dim in enumerate(shape): + if isinstance(dim, str) and dim in self.dynamic_axis_mapping_: + shape[i] = self.dynamic_axis_mapping_[dim] + + return shape + + def compare_shape(self, edge, edge_other): + """Compare shape of two edges. + + Args: + edge (str): name of edge + edge_other (str): name of another edge + + Raises: + Exception: At least one shape is missed for edges to compare + + Returns: + bool: whether the shape is same or not + """ + assert self.all_shapes_inferred_ + shape = self.get_edge_shape(edge) + shape_other = self.get_edge_shape(edge_other) + if shape is None or shape_other is None: + raise Exception("At least one shape is missed for edges to compare") + return shape == shape_other diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/shape_optimizer.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/shape_optimizer.py new file mode 100644 index 0000000000000000000000000000000000000000..c3c4db68d31c874861a3422b04140d9d7e1b9cd5 --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/shape_optimizer.py @@ -0,0 +1,400 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +# -------------------------------------------------------------------------- + +# This tool is not used directly in bert optimization. It could assist developing the optimization script on the following scenarios: +# (1) It could simplify graph by removing many sub-graphs related to reshape. +# (2) It could reduce extra inputs and outputs to fit other tools. The script compare_bert_results.py or bert_perf_test.py requires 3 inputs. + +import argparse +import logging +import os +import re # noqa: F401 +import sys +import tempfile +from collections import deque # noqa: F401 +from datetime import datetime +from pathlib import Path # noqa: F401 + +import numpy as np +import onnx +from onnx import ModelProto, TensorProto, numpy_helper +from onnx_model import OnnxModel + +import onnxruntime + +logger = logging.getLogger(__name__) + +CONSTANT_SHAPE_NAME_PREFIX = "constant_shape_opt__" +RESHAPE_INPUT_SHAPE_PREFIX = "reshape_input_shape__" + + +class BertOnnxModelShapeOptimizer(OnnxModel): + """ + This optimizer will replace Shape output or the shape input of Reshape node by initializer. Currently, it requires + model inputs to have static shape. + """ + + def __init__(self, onnx_model): + super().__init__(onnx_model.model) + + def add_shape_initializer(self, shape): + """ + Add an initializer for constant shape. + """ + shape_value = np.asarray(shape, dtype=np.int64) + constant_shape_name = self.create_node_name("Constant", CONSTANT_SHAPE_NAME_PREFIX) + tensor = onnx.helper.make_tensor( + name=constant_shape_name, + data_type=TensorProto.INT64, + dims=shape_value.shape, + vals=shape_value, + ) + self.add_initializer(tensor) + return tensor + + def get_shape_outputs(self): + """ + Returns a list of output names of all Shape nodes. + """ + input_name_to_nodes = self.input_name_to_nodes() + + outputs = [] + for node in self.model.graph.node: + if node.op_type == "Shape": + if node.output[0] in input_name_to_nodes: + outputs.append(node.output[0]) + + return outputs + + def get_reshape_shape_inputs(self): + """ + Returns a list of shape input names of Reshape nodes. + """ + self.output_name_to_node() + + shape_inputs = [] + for node in self.model.graph.node: + if node.op_type == "Reshape": + shape_inputs.append(node.input[1]) + + return shape_inputs + + def add_shape_for_reshape_input(self): + """ + For each Reshape node, create a Shape node for its first input. + Returns the output names of these Shape nodes. + """ + output_names = [] + nodes_to_add = [] + for node in self.model.graph.node: + if node.op_type == "Reshape": + input = node.input[0] + output_name = self.create_node_name("Reshape_Input", RESHAPE_INPUT_SHAPE_PREFIX) + shape_node = onnx.helper.make_node("Shape", inputs=[input], outputs=[output_name]) + nodes_to_add.append(shape_node) + output_names.append(output_name) + + self.add_nodes(nodes_to_add) + return output_names + + def add_extra_graph_output(self, extra_outputs): + """ + Add a list of output names to graph output. + """ + names_to_evaluate = [] + output_names = [output.name for output in self.model.graph.output] + for name in extra_outputs: + if self.get_initializer(name) is not None: # already a constant + continue + names_to_evaluate.append(name) + + if name not in output_names: + output_info = onnx.helper.ValueInfoProto() + output_info.name = name + self.model.graph.output.extend([output_info]) + output_names.append(name) + + return names_to_evaluate + + # Update input and output shape to be static + def use_static_input(self, inputs, batch_size=1, max_seq_len=128): + """ + Update the model to use static axes instead of dynamic axes for graph inputs. + """ + for input in self.model.graph.input: + if input.name in inputs: + dim_proto = input.type.tensor_type.shape.dim[0] + dim_proto.dim_value = batch_size + dim_proto = input.type.tensor_type.shape.dim[1] + if dim_proto.HasField("dim_param"): + dim_proto.dim_value = max_seq_len + elif dim_proto.HasField("dim_value") and dim_proto.dim_value != max_seq_len: + raise ValueError( + f"Unable to set dimension value to {max_seq_len} for axis {1} of {input.name}. Contradicts existing dimension value {dim_proto.dim_value}." + ) + + def create_dummy_inputs( + self, + input_ids, + segment_ids, + input_mask, + batch_size, + sequence_length, + elem_type, + dictionary_size=8, + ): + """ + Create dummy data for model inputs. If the model has more than 3 inputs, please update this function accordingly before running the tool. + """ + assert elem_type in [1, 6, 7] # only int32, int64 and float32 are supported. + + # Create dummy inputs + input_1 = np.random.randint(dictionary_size, size=(batch_size, sequence_length), dtype=np.int32) + input_2 = np.ones((batch_size, sequence_length), dtype=np.int32) + input_3 = np.zeros((batch_size, sequence_length), dtype=np.int32) + + # Here we assume that 3 inputs have same data type + if elem_type == 1: # float32 + input_1 = np.float32(input_1) + input_2 = np.float32(input_2) + input_3 = np.float32(input_3) + elif elem_type == 7: # int64 + input_1 = np.int64(input_1) + input_2 = np.int64(input_2) + input_3 = np.int64(input_3) + + inputs = {input_ids: input_1, input_mask: input_2, segment_ids: input_3} + return inputs + + def shape_optimization( + self, + temp_model_path, + input_ids, + segment_ids, + input_mask, + output_names, + batch_size, + sequence_length, + enable_shape_opt, + enable_reshape_opt, + verbose, + ): + self.bert_inputs = [input_ids, segment_ids, input_mask] + + extra_outputs = [] + if enable_shape_opt: + extra_outputs.extend(self.get_shape_outputs()) + + if enable_reshape_opt: + reshape_shape_inputs = self.get_reshape_shape_inputs() + reshape_input_shapes = self.add_shape_for_reshape_input() + extra_outputs.extend(reshape_shape_inputs) + extra_outputs.extend(reshape_input_shapes) + + if len(extra_outputs) == 0: + return + + names_to_evaluate = self.add_extra_graph_output(extra_outputs) + + # This tool does not support dynamic axes right now. + self.use_static_input(self.bert_inputs, batch_size, sequence_length) + + with open(temp_model_path, "wb") as out: + out.write(self.model.SerializeToString()) + sess_options = onnxruntime.SessionOptions() + sess_options.graph_optimization_level = onnxruntime.GraphOptimizationLevel.ORT_DISABLE_ALL + session = onnxruntime.InferenceSession( + temp_model_path, + sess_options, + providers=["CUDAExecutionProvider", "CPUExecutionProvider"], + ) + + elem_type = 7 + for input in self.model.graph.input: + if input.name == input_ids: + elem_type = input.type.tensor_type.elem_type + inputs = self.create_dummy_inputs(input_ids, segment_ids, input_mask, batch_size, sequence_length, elem_type) + + outputs = session.run(names_to_evaluate, inputs) + shapes = {} + for i, name in enumerate(names_to_evaluate): + shapes[name] = outputs[i] + + logger.debug(f"shapes={shapes}") + + if enable_reshape_opt: + for i, shape_input in enumerate(reshape_shape_inputs): + input_shape = reshape_input_shapes[i] + self.update_target_shape(shapes, shape_input, input_shape, verbose) + + for name, shape in shapes.items(): + tensor = self.add_shape_initializer(shape) + self.replace_input_of_all_nodes(name, tensor.name) + + # Remove extra outputs, and prune all nodes not linked to output. + self.prune_graph(output_names) + + def update_target_shape(self, shapes, shape_input, input_shape, verbose): + """ + Update the target shape to use 0 to represent that dimension value does not change. + For example, shape of source data is (2, 5, 8) and target shape is (2, 5, 4, 2), the target shape will be updated to (0, 0, 4, 2). + """ + if shape_input in shapes: + target_shape = shapes[shape_input] + else: + initializer = self.get_initializer(shape_input) + assert initializer is not None + target_shape = numpy_helper.to_array(initializer) + + if input_shape in shapes: + source_shape = shapes[input_shape] + else: + initializer = self.get_initializer(input_shape) + assert initializer is not None + source_shape = numpy_helper.to_array(initializer) + + new_target_shape = [] + for i, dim_value in enumerate(target_shape): + if i < len(source_shape) and source_shape[i] == dim_value: + new_target_shape.append(0) + else: + new_target_shape.append(dim_value) + shapes[shape_input] = new_target_shape + + logger.debug(f"source_shape={source_shape}, target_shape={target_shape}, new_target_shape={new_target_shape}") + + def validate_input(self, input: str): + if not self.find_graph_input(input): + valid_names = [input.name for input in self.model.graph.input] + raise Exception(f"Input {input} does not exist in the graph inputs: {valid_names}") + + def validate_outputs(self, output_names: list[str]): + valid_names = [output.name for output in self.model.graph.output] + for name in output_names: + if name not in valid_names: + raise Exception(f"Output {name} does not exist in the graph outputs: {valid_names}") + + def optimize( + self, + output_path: str, + input_ids: str, + segment_ids: str, + input_mask: str, + enable_shape_opt: bool, + enable_reshape_opt: bool, + output_names: list[str] | None = None, + batch_size=1, + sequence_length=128, + verbose=False, + ): + # Skip if shape optimization has been done before. + for tensor in self.model.graph.initializer: + if tensor.name.startswith(CONSTANT_SHAPE_NAME_PREFIX): + logger.info("Skip shape optimization since it has been done before") + return + + self.validate_input(input_ids) + self.validate_input(segment_ids) + self.validate_input(input_mask) + + if output_names is not None: + self.validate_outputs(output_names) + self.prune_graph(output_names) + + remaining_outputs = [output.name for output in self.model.graph.output] + + if enable_shape_opt or enable_reshape_opt: + if len(self.get_graph_inputs_excluding_initializers()) != 3: + logger.info("Skip shape optimization since graph input number is not 3") + return + + with tempfile.TemporaryDirectory() as temp_dir: + temp_file_name = "temp_{}.onnx".format(datetime.now().strftime("%m_%d-%H_%M_%S")) + dir = "." if verbose else temp_dir + temp_file = os.path.join(dir, temp_file_name) + self.shape_optimization( + temp_file, + input_ids, + segment_ids, + input_mask, + remaining_outputs, + batch_size, + sequence_length, + enable_shape_opt, + enable_reshape_opt, + verbose, + ) + logger.debug(f"Temp model with additional outputs: {temp_file}") + logger.warning( + f"Shape optimization is done. The optimized model might only work for input with batch_size={batch_size} sequence_length={sequence_length}" + ) + + if output_path is not None: + with open(output_path, "wb") as out: + out.write(self.model.SerializeToString()) + + +def parse_arguments(): + parser = argparse.ArgumentParser() + parser.add_argument("--input", required=True, type=str) + parser.add_argument("--output", required=True, type=str) + parser.add_argument("--input_ids", required=True, type=str) + parser.add_argument("--segment_ids", required=True, type=str) + parser.add_argument("--input_mask", required=True, type=str) + parser.add_argument("--output_names", required=False, type=str, default=None) + parser.add_argument("--batch_size", required=False, type=int, default=1) + parser.add_argument("--sequence_length", required=False, type=int, default=128) + parser.add_argument("--enable_shape_opt", required=False, action="store_true") + parser.set_defaults(enable_shape_opt=False) + parser.add_argument("--enable_reshape_opt", required=False, action="store_true") + parser.set_defaults(enable_reshape_opt=False) + parser.add_argument("--verbose", required=False, action="store_true") + parser.set_defaults(verbose=False) + args = parser.parse_args() + return args + + +def setup_logging(verbose): + log_handler = logging.StreamHandler(sys.stdout) + if verbose: + log_handler.setFormatter(logging.Formatter("[%(filename)s:%(lineno)s - %(funcName)20s()] %(message)s")) + logging_level = logging.DEBUG + else: + log_handler.setFormatter(logging.Formatter("%(filename)20s: %(message)s")) + logging_level = logging.INFO + log_handler.setLevel(logging_level) + logger.addHandler(log_handler) + logger.setLevel(logging_level) + + +def main(): + args = parse_arguments() + setup_logging(args.verbose) + + output_names = None if args.output_names is None else args.output_names.split(";") + + model = ModelProto() + with open(args.input, "rb") as input_file: + model.ParseFromString(input_file.read()) + onnx_model = OnnxModel(model) + + optimizer = BertOnnxModelShapeOptimizer(onnx_model) + + optimizer.optimize( + args.output, + args.input_ids, + args.segment_ids, + args.input_mask, + args.enable_shape_opt, + args.enable_reshape_opt, + output_names, + args.batch_size, + args.sequence_length, + args.verbose, + ) + + +if __name__ == "__main__": + main() diff --git a/python/user_packages/Python313/site-packages/onnxruntime/transformers/torch_onnx_export_helper.py b/python/user_packages/Python313/site-packages/onnxruntime/transformers/torch_onnx_export_helper.py new file mode 100644 index 0000000000000000000000000000000000000000..f79bab72bfbf98e2fe081f7ca295aa8db70b345a --- /dev/null +++ b/python/user_packages/Python313/site-packages/onnxruntime/transformers/torch_onnx_export_helper.py @@ -0,0 +1,75 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +# -------------------------------------------------------------------------- + +import torch +from torch._C._onnx import OperatorExportTypes + +TrainingMode = torch.onnx.TrainingMode +from packaging.version import Version # noqa: E402 + + +def torch_onnx_export( + model, + args, + f, + export_params=True, + verbose=False, + training=TrainingMode.EVAL, + input_names=None, + output_names=None, + operator_export_type=OperatorExportTypes.ONNX, + opset_version=None, + _retain_param_name=None, + do_constant_folding=True, + example_outputs=None, + strip_doc_string=None, + dynamic_axes=None, + keep_initializers_as_inputs=None, + custom_opsets=None, + enable_onnx_checker=None, + use_external_data_format=None, + export_modules_as_functions=False, +): + if Version(torch.__version__) >= Version("1.11.0"): + torch.onnx.export( + model=model, + args=args, + f=f, + export_params=export_params, + verbose=verbose, + training=training, + input_names=input_names, + output_names=output_names, + operator_export_type=operator_export_type, + opset_version=opset_version, + do_constant_folding=do_constant_folding, + dynamic_axes=dynamic_axes, + keep_initializers_as_inputs=keep_initializers_as_inputs, + custom_opsets=custom_opsets, + export_modules_as_functions=export_modules_as_functions, + dynamo=False, + ) + else: + torch.onnx.export( + model=model, + args=args, + f=f, + export_params=export_params, + verbose=verbose, + training=training, + input_names=input_names, + output_names=output_names, + operator_export_type=operator_export_type, + opset_version=opset_version, + _retain_param_name=_retain_param_name, + do_constant_folding=do_constant_folding, + example_outputs=example_outputs, + strip_doc_string=strip_doc_string, + dynamic_axes=dynamic_axes, + keep_initializers_as_inputs=keep_initializers_as_inputs, + custom_opsets=custom_opsets, + enable_onnx_checker=enable_onnx_checker, + use_external_data_format=use_external_data_format, + ) diff --git a/qt/6.8.1/msvc2022_64/lib/Qt6SvgWidgets.lib b/qt/6.8.1/msvc2022_64/lib/Qt6SvgWidgets.lib new file mode 100644 index 0000000000000000000000000000000000000000..37c1dbd9958f378394d907824370fa17ed53e83a Binary files /dev/null and b/qt/6.8.1/msvc2022_64/lib/Qt6SvgWidgets.lib differ diff --git a/qt/6.8.1/msvc2022_64/lib/Qt6SvgWidgets.prl b/qt/6.8.1/msvc2022_64/lib/Qt6SvgWidgets.prl new file mode 100644 index 0000000000000000000000000000000000000000..9f01d3c1d76bc760774167d66fe243be48a72bcb --- /dev/null +++ b/qt/6.8.1/msvc2022_64/lib/Qt6SvgWidgets.prl @@ -0,0 +1,3 @@ +QMAKE_PRL_TARGET = Qt6SvgWidgets.lib +QMAKE_PRL_CONFIG = shared +QMAKE_PRL_VERSION = 6.8.1 diff --git a/qt/6.8.1/msvc2022_64/lib/Qt6SvgWidgetsd.lib b/qt/6.8.1/msvc2022_64/lib/Qt6SvgWidgetsd.lib new file mode 100644 index 0000000000000000000000000000000000000000..4c96f2eb53876d495c465ac2e0d42fd55a9d6011 Binary files /dev/null and b/qt/6.8.1/msvc2022_64/lib/Qt6SvgWidgetsd.lib differ diff --git a/qt/6.8.1/msvc2022_64/lib/Qt6SvgWidgetsd.prl b/qt/6.8.1/msvc2022_64/lib/Qt6SvgWidgetsd.prl new file mode 100644 index 0000000000000000000000000000000000000000..530199db13b3dbb7ba5742b19455214c07710c8c --- /dev/null +++ b/qt/6.8.1/msvc2022_64/lib/Qt6SvgWidgetsd.prl @@ -0,0 +1,3 @@ +QMAKE_PRL_TARGET = Qt6SvgWidgetsd.lib +QMAKE_PRL_CONFIG = shared +QMAKE_PRL_VERSION = 6.8.1 diff --git a/qt/6.8.1/msvc2022_64/lib/Qt6Test.prl b/qt/6.8.1/msvc2022_64/lib/Qt6Test.prl new file mode 100644 index 0000000000000000000000000000000000000000..3ab00c855ad0369561980af0219e96b6731e5331 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/lib/Qt6Test.prl @@ -0,0 +1,3 @@ +QMAKE_PRL_TARGET = Qt6Test.lib +QMAKE_PRL_CONFIG = shared +QMAKE_PRL_VERSION = 6.8.1 diff --git a/qt/6.8.1/msvc2022_64/lib/Qt6Testd.prl b/qt/6.8.1/msvc2022_64/lib/Qt6Testd.prl new file mode 100644 index 0000000000000000000000000000000000000000..21af849277970d5825dc952c5d870dd0b93d081e --- /dev/null +++ b/qt/6.8.1/msvc2022_64/lib/Qt6Testd.prl @@ -0,0 +1,3 @@ +QMAKE_PRL_TARGET = Qt6Testd.lib +QMAKE_PRL_CONFIG = shared +QMAKE_PRL_VERSION = 6.8.1 diff --git a/qt/6.8.1/msvc2022_64/lib/Qt6UiTools.lib b/qt/6.8.1/msvc2022_64/lib/Qt6UiTools.lib new file mode 100644 index 0000000000000000000000000000000000000000..85abcfb918bd910d54361af9c6c287a25864e227 Binary files /dev/null and b/qt/6.8.1/msvc2022_64/lib/Qt6UiTools.lib differ diff --git a/qt/6.8.1/msvc2022_64/lib/Qt6UiTools.prl b/qt/6.8.1/msvc2022_64/lib/Qt6UiTools.prl new file mode 100644 index 0000000000000000000000000000000000000000..8c0caca33fee5bcf8448f1dfcb79c74a6bbe83e4 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/lib/Qt6UiTools.prl @@ -0,0 +1,3 @@ +QMAKE_PRL_TARGET = Qt6UiTools.lib +QMAKE_PRL_CONFIG = shared +QMAKE_PRL_VERSION = 6.8.1 diff --git a/qt/6.8.1/msvc2022_64/lib/Qt6UiToolsd.lib b/qt/6.8.1/msvc2022_64/lib/Qt6UiToolsd.lib new file mode 100644 index 0000000000000000000000000000000000000000..d1cf9ccb9876b694864650e46e6c2abe69883d6d Binary files /dev/null and b/qt/6.8.1/msvc2022_64/lib/Qt6UiToolsd.lib differ diff --git a/qt/6.8.1/msvc2022_64/lib/Qt6UiToolsd.prl b/qt/6.8.1/msvc2022_64/lib/Qt6UiToolsd.prl new file mode 100644 index 0000000000000000000000000000000000000000..51875300c831a10636d514d78d4149e6225ea796 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/lib/Qt6UiToolsd.prl @@ -0,0 +1,3 @@ +QMAKE_PRL_TARGET = Qt6UiToolsd.lib +QMAKE_PRL_CONFIG = shared +QMAKE_PRL_VERSION = 6.8.1 diff --git a/qt/6.8.1/msvc2022_64/lib/Qt6Widgets.prl b/qt/6.8.1/msvc2022_64/lib/Qt6Widgets.prl new file mode 100644 index 0000000000000000000000000000000000000000..59483e6e67b041260e4c28762366a9de7875fcc5 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/lib/Qt6Widgets.prl @@ -0,0 +1,3 @@ +QMAKE_PRL_TARGET = Qt6Widgets.lib +QMAKE_PRL_CONFIG = shared +QMAKE_PRL_VERSION = 6.8.1 diff --git a/qt/6.8.1/msvc2022_64/lib/Qt6Widgetsd.prl b/qt/6.8.1/msvc2022_64/lib/Qt6Widgetsd.prl new file mode 100644 index 0000000000000000000000000000000000000000..f0a18a08460ab4a825ccb8bff4c22bf30212ec4b --- /dev/null +++ b/qt/6.8.1/msvc2022_64/lib/Qt6Widgetsd.prl @@ -0,0 +1,3 @@ +QMAKE_PRL_TARGET = Qt6Widgetsd.lib +QMAKE_PRL_CONFIG = shared +QMAKE_PRL_VERSION = 6.8.1 diff --git a/qt/6.8.1/msvc2022_64/lib/Qt6Xml.prl b/qt/6.8.1/msvc2022_64/lib/Qt6Xml.prl new file mode 100644 index 0000000000000000000000000000000000000000..2eea82ff6f18784a1745137079d912bfca88566e --- /dev/null +++ b/qt/6.8.1/msvc2022_64/lib/Qt6Xml.prl @@ -0,0 +1,3 @@ +QMAKE_PRL_TARGET = Qt6Xml.lib +QMAKE_PRL_CONFIG = shared +QMAKE_PRL_VERSION = 6.8.1 diff --git a/qt/6.8.1/msvc2022_64/lib/Qt6Xmld.prl b/qt/6.8.1/msvc2022_64/lib/Qt6Xmld.prl new file mode 100644 index 0000000000000000000000000000000000000000..43c7e5c1c29a8b3e6f926c5fb0cf8bd3f5d86d95 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/lib/Qt6Xmld.prl @@ -0,0 +1,3 @@ +QMAKE_PRL_TARGET = Qt6Xmld.lib +QMAKE_PRL_CONFIG = shared +QMAKE_PRL_VERSION = 6.8.1 diff --git a/qt/6.8.1/msvc2022_64/metatypes/qt6concurrent_metatypes.json b/qt/6.8.1/msvc2022_64/metatypes/qt6concurrent_metatypes.json new file mode 100644 index 0000000000000000000000000000000000000000..0d4f101c7a37a4c875e6999bee1a287fdb733380 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/metatypes/qt6concurrent_metatypes.json @@ -0,0 +1,2 @@ +[ +] diff --git a/qt/6.8.1/msvc2022_64/metatypes/qt6core_metatypes.json b/qt/6.8.1/msvc2022_64/metatypes/qt6core_metatypes.json new file mode 100644 index 0000000000000000000000000000000000000000..fe50f5e9329ef68f9aeb91325f253811a7f70a50 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/metatypes/qt6core_metatypes.json @@ -0,0 +1,9418 @@ +[ + { + "classes": [ + { + "className": "Qt", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "GlobalColor", + "values": [ + "color0", + "color1", + "black", + "white", + "darkGray", + "gray", + "lightGray", + "red", + "green", + "blue", + "cyan", + "magenta", + "yellow", + "darkRed", + "darkGreen", + "darkBlue", + "darkCyan", + "darkMagenta", + "darkYellow", + "transparent" + ] + }, + { + "isClass": true, + "isFlag": false, + "name": "ColorScheme", + "values": [ + "Unknown", + "Light", + "Dark" + ] + }, + { + "alias": "MouseButton", + "isClass": false, + "isFlag": true, + "name": "MouseButtons", + "values": [ + "NoButton", + "LeftButton", + "RightButton", + "MiddleButton", + "BackButton", + "XButton1", + "ExtraButton1", + "ForwardButton", + "XButton2", + "ExtraButton2", + "TaskButton", + "ExtraButton3", + "ExtraButton4", + "ExtraButton5", + "ExtraButton6", + "ExtraButton7", + "ExtraButton8", + "ExtraButton9", + "ExtraButton10", + "ExtraButton11", + "ExtraButton12", + "ExtraButton13", + "ExtraButton14", + "ExtraButton15", + "ExtraButton16", + "ExtraButton17", + "ExtraButton18", + "ExtraButton19", + "ExtraButton20", + "ExtraButton21", + "ExtraButton22", + "ExtraButton23", + "ExtraButton24", + "AllButtons", + "MaxMouseButton", + "MouseButtonMask" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "Orientation", + "values": [ + "Horizontal", + "Vertical" + ] + }, + { + "alias": "Orientation", + "isClass": false, + "isFlag": true, + "name": "Orientations", + "values": [ + "Horizontal", + "Vertical" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "FocusPolicy", + "values": [ + "NoFocus", + "TabFocus", + "ClickFocus", + "StrongFocus", + "WheelFocus" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "TabFocusBehavior", + "values": [ + "NoTabFocus", + "TabFocusTextControls", + "TabFocusListControls", + "TabFocusAllControls" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "SortOrder", + "values": [ + "AscendingOrder", + "DescendingOrder" + ] + }, + { + "alias": "SplitBehaviorFlags", + "isClass": false, + "isFlag": true, + "name": "SplitBehavior", + "values": [ + "KeepEmptyParts", + "SkipEmptyParts" + ] + }, + { + "alias": "AlignmentFlag", + "isClass": false, + "isFlag": true, + "name": "Alignment", + "values": [ + "AlignLeft", + "AlignLeading", + "AlignRight", + "AlignTrailing", + "AlignHCenter", + "AlignJustify", + "AlignAbsolute", + "AlignHorizontal_Mask", + "AlignTop", + "AlignBottom", + "AlignVCenter", + "AlignBaseline", + "AlignVertical_Mask", + "AlignCenter" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "TextFlag", + "values": [ + "TextSingleLine", + "TextDontClip", + "TextExpandTabs", + "TextShowMnemonic", + "TextWordWrap", + "TextWrapAnywhere", + "TextDontPrint", + "TextIncludeTrailingSpaces", + "TextHideMnemonic", + "TextJustificationForced", + "TextForceLeftToRight", + "TextForceRightToLeft", + "TextLongestVariant" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "TextElideMode", + "values": [ + "ElideLeft", + "ElideRight", + "ElideMiddle", + "ElideNone" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "WindowType", + "values": [ + "Widget", + "Window", + "Dialog", + "Sheet", + "Drawer", + "Popup", + "Tool", + "ToolTip", + "SplashScreen", + "Desktop", + "SubWindow", + "ForeignWindow", + "CoverWindow", + "WindowType_Mask", + "MSWindowsFixedSizeDialogHint", + "MSWindowsOwnDC", + "BypassWindowManagerHint", + "X11BypassWindowManagerHint", + "FramelessWindowHint", + "WindowTitleHint", + "WindowSystemMenuHint", + "WindowMinimizeButtonHint", + "WindowMaximizeButtonHint", + "WindowMinMaxButtonsHint", + "WindowContextHelpButtonHint", + "WindowShadeButtonHint", + "WindowStaysOnTopHint", + "WindowTransparentForInput", + "WindowOverridesSystemGestures", + "WindowDoesNotAcceptFocus", + "MaximizeUsingFullscreenGeometryHint", + "CustomizeWindowHint", + "WindowStaysOnBottomHint", + "WindowCloseButtonHint", + "MacWindowToolBarButtonHint", + "BypassGraphicsProxyWidget", + "NoDropShadowWindowHint", + "WindowFullscreenButtonHint" + ] + }, + { + "alias": "WindowType", + "isClass": false, + "isFlag": true, + "name": "WindowFlags", + "values": [ + "Widget", + "Window", + "Dialog", + "Sheet", + "Drawer", + "Popup", + "Tool", + "ToolTip", + "SplashScreen", + "Desktop", + "SubWindow", + "ForeignWindow", + "CoverWindow", + "WindowType_Mask", + "MSWindowsFixedSizeDialogHint", + "MSWindowsOwnDC", + "BypassWindowManagerHint", + "X11BypassWindowManagerHint", + "FramelessWindowHint", + "WindowTitleHint", + "WindowSystemMenuHint", + "WindowMinimizeButtonHint", + "WindowMaximizeButtonHint", + "WindowMinMaxButtonsHint", + "WindowContextHelpButtonHint", + "WindowShadeButtonHint", + "WindowStaysOnTopHint", + "WindowTransparentForInput", + "WindowOverridesSystemGestures", + "WindowDoesNotAcceptFocus", + "MaximizeUsingFullscreenGeometryHint", + "CustomizeWindowHint", + "WindowStaysOnBottomHint", + "WindowCloseButtonHint", + "MacWindowToolBarButtonHint", + "BypassGraphicsProxyWidget", + "NoDropShadowWindowHint", + "WindowFullscreenButtonHint" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "WindowState", + "values": [ + "WindowNoState", + "WindowMinimized", + "WindowMaximized", + "WindowFullScreen", + "WindowActive" + ] + }, + { + "alias": "WindowState", + "isClass": false, + "isFlag": true, + "name": "WindowStates", + "values": [ + "WindowNoState", + "WindowMinimized", + "WindowMaximized", + "WindowFullScreen", + "WindowActive" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "ApplicationState", + "values": [ + "ApplicationSuspended", + "ApplicationHidden", + "ApplicationInactive", + "ApplicationActive" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "ScreenOrientation", + "values": [ + "PrimaryOrientation", + "PortraitOrientation", + "LandscapeOrientation", + "InvertedPortraitOrientation", + "InvertedLandscapeOrientation" + ] + }, + { + "alias": "ScreenOrientation", + "isClass": false, + "isFlag": true, + "name": "ScreenOrientations", + "values": [ + "PrimaryOrientation", + "PortraitOrientation", + "LandscapeOrientation", + "InvertedPortraitOrientation", + "InvertedLandscapeOrientation" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "WidgetAttribute", + "values": [ + "WA_Disabled", + "WA_UnderMouse", + "WA_MouseTracking", + "WA_OpaquePaintEvent", + "WA_StaticContents", + "WA_LaidOut", + "WA_PaintOnScreen", + "WA_NoSystemBackground", + "WA_UpdatesDisabled", + "WA_Mapped", + "WA_InputMethodEnabled", + "WA_WState_Visible", + "WA_WState_Hidden", + "WA_ForceDisabled", + "WA_KeyCompression", + "WA_PendingMoveEvent", + "WA_PendingResizeEvent", + "WA_SetPalette", + "WA_SetFont", + "WA_SetCursor", + "WA_NoChildEventsFromChildren", + "WA_WindowModified", + "WA_Resized", + "WA_Moved", + "WA_PendingUpdate", + "WA_InvalidSize", + "WA_CustomWhatsThis", + "WA_LayoutOnEntireRect", + "WA_OutsideWSRange", + "WA_GrabbedShortcut", + "WA_TransparentForMouseEvents", + "WA_PaintUnclipped", + "WA_SetWindowIcon", + "WA_NoMouseReplay", + "WA_DeleteOnClose", + "WA_RightToLeft", + "WA_SetLayoutDirection", + "WA_NoChildEventsForParent", + "WA_ForceUpdatesDisabled", + "WA_WState_Created", + "WA_WState_CompressKeys", + "WA_WState_InPaintEvent", + "WA_WState_Reparented", + "WA_WState_ConfigPending", + "WA_WState_Polished", + "WA_WState_OwnSizePolicy", + "WA_WState_ExplicitShowHide", + "WA_ShowModal", + "WA_MouseNoMask", + "WA_NoMousePropagation", + "WA_Hover", + "WA_InputMethodTransparent", + "WA_QuitOnClose", + "WA_KeyboardFocusChange", + "WA_AcceptDrops", + "WA_DropSiteRegistered", + "WA_WindowPropagation", + "WA_NoX11EventCompression", + "WA_TintedBackground", + "WA_X11OpenGLOverlay", + "WA_AlwaysShowToolTips", + "WA_MacOpaqueSizeGrip", + "WA_SetStyle", + "WA_SetLocale", + "WA_MacShowFocusRect", + "WA_MacNormalSize", + "WA_MacSmallSize", + "WA_MacMiniSize", + "WA_LayoutUsesWidgetRect", + "WA_StyledBackground", + "WA_CanHostQMdiSubWindowTitleBar", + "WA_MacAlwaysShowToolWindow", + "WA_StyleSheet", + "WA_ShowWithoutActivating", + "WA_X11BypassTransientForHint", + "WA_NativeWindow", + "WA_DontCreateNativeAncestors", + "WA_DontShowOnScreen", + "WA_X11NetWmWindowTypeDesktop", + "WA_X11NetWmWindowTypeDock", + "WA_X11NetWmWindowTypeToolBar", + "WA_X11NetWmWindowTypeMenu", + "WA_X11NetWmWindowTypeUtility", + "WA_X11NetWmWindowTypeSplash", + "WA_X11NetWmWindowTypeDialog", + "WA_X11NetWmWindowTypeDropDownMenu", + "WA_X11NetWmWindowTypePopupMenu", + "WA_X11NetWmWindowTypeToolTip", + "WA_X11NetWmWindowTypeNotification", + "WA_X11NetWmWindowTypeCombo", + "WA_X11NetWmWindowTypeDND", + "WA_SetWindowModality", + "WA_WState_WindowOpacitySet", + "WA_TranslucentBackground", + "WA_AcceptTouchEvents", + "WA_WState_AcceptedTouchBeginEvent", + "WA_TouchPadAcceptSingleTouchEvents", + "WA_X11DoNotAcceptFocus", + "WA_AlwaysStackOnTop", + "WA_TabletTracking", + "WA_ContentsMarginsRespectsSafeArea", + "WA_StyleSheetTarget", + "WA_AttributeCount" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "ApplicationAttribute", + "values": [ + "AA_QtQuickUseDefaultSizePolicy", + "AA_DontShowIconsInMenus", + "AA_NativeWindows", + "AA_DontCreateNativeWidgetSiblings", + "AA_PluginApplication", + "AA_DontUseNativeMenuBar", + "AA_MacDontSwapCtrlAndMeta", + "AA_Use96Dpi", + "AA_DisableNativeVirtualKeyboard", + "AA_DontUseNativeMenuWindows", + "AA_SynthesizeTouchForUnhandledMouseEvents", + "AA_SynthesizeMouseForUnhandledTouchEvents", + "AA_UseHighDpiPixmaps", + "AA_ForceRasterWidgets", + "AA_UseDesktopOpenGL", + "AA_UseOpenGLES", + "AA_UseSoftwareOpenGL", + "AA_ShareOpenGLContexts", + "AA_SetPalette", + "AA_EnableHighDpiScaling", + "AA_DisableHighDpiScaling", + "AA_UseStyleSheetPropagationInWidgetStyles", + "AA_DontUseNativeDialogs", + "AA_SynthesizeMouseForUnhandledTabletEvents", + "AA_CompressHighFrequencyEvents", + "AA_DontCheckOpenGLContextThreadAffinity", + "AA_DisableShaderDiskCache", + "AA_DontShowShortcutsInContextMenus", + "AA_CompressTabletEvents", + "AA_DisableSessionManager", + "AA_AttributeCount" + ] + }, + { + "alias": "ImageConversionFlag", + "isClass": false, + "isFlag": true, + "name": "ImageConversionFlags", + "values": [ + "ColorMode_Mask", + "AutoColor", + "ColorOnly", + "MonoOnly", + "AlphaDither_Mask", + "ThresholdAlphaDither", + "OrderedAlphaDither", + "DiffuseAlphaDither", + "NoAlpha", + "Dither_Mask", + "DiffuseDither", + "OrderedDither", + "ThresholdDither", + "DitherMode_Mask", + "AutoDither", + "PreferDither", + "AvoidDither", + "NoOpaqueDetection", + "NoFormatConversion" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "BGMode", + "values": [ + "TransparentMode", + "OpaqueMode" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "Key", + "values": [ + "Key_Space", + "Key_Any", + "Key_Exclam", + "Key_QuoteDbl", + "Key_NumberSign", + "Key_Dollar", + "Key_Percent", + "Key_Ampersand", + "Key_Apostrophe", + "Key_ParenLeft", + "Key_ParenRight", + "Key_Asterisk", + "Key_Plus", + "Key_Comma", + "Key_Minus", + "Key_Period", + "Key_Slash", + "Key_0", + "Key_1", + "Key_2", + "Key_3", + "Key_4", + "Key_5", + "Key_6", + "Key_7", + "Key_8", + "Key_9", + "Key_Colon", + "Key_Semicolon", + "Key_Less", + "Key_Equal", + "Key_Greater", + "Key_Question", + "Key_At", + "Key_A", + "Key_B", + "Key_C", + "Key_D", + "Key_E", + "Key_F", + "Key_G", + "Key_H", + "Key_I", + "Key_J", + "Key_K", + "Key_L", + "Key_M", + "Key_N", + "Key_O", + "Key_P", + "Key_Q", + "Key_R", + "Key_S", + "Key_T", + "Key_U", + "Key_V", + "Key_W", + "Key_X", + "Key_Y", + "Key_Z", + "Key_BracketLeft", + "Key_Backslash", + "Key_BracketRight", + "Key_AsciiCircum", + "Key_Underscore", + "Key_QuoteLeft", + "Key_BraceLeft", + "Key_Bar", + "Key_BraceRight", + "Key_AsciiTilde", + "Key_nobreakspace", + "Key_exclamdown", + "Key_cent", + "Key_sterling", + "Key_currency", + "Key_yen", + "Key_brokenbar", + "Key_section", + "Key_diaeresis", + "Key_copyright", + "Key_ordfeminine", + "Key_guillemotleft", + "Key_notsign", + "Key_hyphen", + "Key_registered", + "Key_macron", + "Key_degree", + "Key_plusminus", + "Key_twosuperior", + "Key_threesuperior", + "Key_acute", + "Key_micro", + "Key_mu", + "Key_paragraph", + "Key_periodcentered", + "Key_cedilla", + "Key_onesuperior", + "Key_masculine", + "Key_guillemotright", + "Key_onequarter", + "Key_onehalf", + "Key_threequarters", + "Key_questiondown", + "Key_Agrave", + "Key_Aacute", + "Key_Acircumflex", + "Key_Atilde", + "Key_Adiaeresis", + "Key_Aring", + "Key_AE", + "Key_Ccedilla", + "Key_Egrave", + "Key_Eacute", + "Key_Ecircumflex", + "Key_Ediaeresis", + "Key_Igrave", + "Key_Iacute", + "Key_Icircumflex", + "Key_Idiaeresis", + "Key_ETH", + "Key_Ntilde", + "Key_Ograve", + "Key_Oacute", + "Key_Ocircumflex", + "Key_Otilde", + "Key_Odiaeresis", + "Key_multiply", + "Key_Ooblique", + "Key_Ugrave", + "Key_Uacute", + "Key_Ucircumflex", + "Key_Udiaeresis", + "Key_Yacute", + "Key_THORN", + "Key_ssharp", + "Key_division", + "Key_ydiaeresis", + "Key_Escape", + "Key_Tab", + "Key_Backtab", + "Key_Backspace", + "Key_Return", + "Key_Enter", + "Key_Insert", + "Key_Delete", + "Key_Pause", + "Key_Print", + "Key_SysReq", + "Key_Clear", + "Key_Home", + "Key_End", + "Key_Left", + "Key_Up", + "Key_Right", + "Key_Down", + "Key_PageUp", + "Key_PageDown", + "Key_Shift", + "Key_Control", + "Key_Meta", + "Key_Alt", + "Key_CapsLock", + "Key_NumLock", + "Key_ScrollLock", + "Key_F1", + "Key_F2", + "Key_F3", + "Key_F4", + "Key_F5", + "Key_F6", + "Key_F7", + "Key_F8", + "Key_F9", + "Key_F10", + "Key_F11", + "Key_F12", + "Key_F13", + "Key_F14", + "Key_F15", + "Key_F16", + "Key_F17", + "Key_F18", + "Key_F19", + "Key_F20", + "Key_F21", + "Key_F22", + "Key_F23", + "Key_F24", + "Key_F25", + "Key_F26", + "Key_F27", + "Key_F28", + "Key_F29", + "Key_F30", + "Key_F31", + "Key_F32", + "Key_F33", + "Key_F34", + "Key_F35", + "Key_Super_L", + "Key_Super_R", + "Key_Menu", + "Key_Hyper_L", + "Key_Hyper_R", + "Key_Help", + "Key_Direction_L", + "Key_Direction_R", + "Key_AltGr", + "Key_Multi_key", + "Key_Codeinput", + "Key_SingleCandidate", + "Key_MultipleCandidate", + "Key_PreviousCandidate", + "Key_Mode_switch", + "Key_Kanji", + "Key_Muhenkan", + "Key_Henkan", + "Key_Romaji", + "Key_Hiragana", + "Key_Katakana", + "Key_Hiragana_Katakana", + "Key_Zenkaku", + "Key_Hankaku", + "Key_Zenkaku_Hankaku", + "Key_Touroku", + "Key_Massyo", + "Key_Kana_Lock", + "Key_Kana_Shift", + "Key_Eisu_Shift", + "Key_Eisu_toggle", + "Key_Hangul", + "Key_Hangul_Start", + "Key_Hangul_End", + "Key_Hangul_Hanja", + "Key_Hangul_Jamo", + "Key_Hangul_Romaja", + "Key_Hangul_Jeonja", + "Key_Hangul_Banja", + "Key_Hangul_PreHanja", + "Key_Hangul_PostHanja", + "Key_Hangul_Special", + "Key_Dead_Grave", + "Key_Dead_Acute", + "Key_Dead_Circumflex", + "Key_Dead_Tilde", + "Key_Dead_Macron", + "Key_Dead_Breve", + "Key_Dead_Abovedot", + "Key_Dead_Diaeresis", + "Key_Dead_Abovering", + "Key_Dead_Doubleacute", + "Key_Dead_Caron", + "Key_Dead_Cedilla", + "Key_Dead_Ogonek", + "Key_Dead_Iota", + "Key_Dead_Voiced_Sound", + "Key_Dead_Semivoiced_Sound", + "Key_Dead_Belowdot", + "Key_Dead_Hook", + "Key_Dead_Horn", + "Key_Dead_Stroke", + "Key_Dead_Abovecomma", + "Key_Dead_Abovereversedcomma", + "Key_Dead_Doublegrave", + "Key_Dead_Belowring", + "Key_Dead_Belowmacron", + "Key_Dead_Belowcircumflex", + "Key_Dead_Belowtilde", + "Key_Dead_Belowbreve", + "Key_Dead_Belowdiaeresis", + "Key_Dead_Invertedbreve", + "Key_Dead_Belowcomma", + "Key_Dead_Currency", + "Key_Dead_a", + "Key_Dead_A", + "Key_Dead_e", + "Key_Dead_E", + "Key_Dead_i", + "Key_Dead_I", + "Key_Dead_o", + "Key_Dead_O", + "Key_Dead_u", + "Key_Dead_U", + "Key_Dead_Small_Schwa", + "Key_Dead_Capital_Schwa", + "Key_Dead_Greek", + "Key_Dead_Lowline", + "Key_Dead_Aboveverticalline", + "Key_Dead_Belowverticalline", + "Key_Dead_Longsolidusoverlay", + "Key_Back", + "Key_Forward", + "Key_Stop", + "Key_Refresh", + "Key_VolumeDown", + "Key_VolumeMute", + "Key_VolumeUp", + "Key_BassBoost", + "Key_BassUp", + "Key_BassDown", + "Key_TrebleUp", + "Key_TrebleDown", + "Key_MediaPlay", + "Key_MediaStop", + "Key_MediaPrevious", + "Key_MediaNext", + "Key_MediaRecord", + "Key_MediaPause", + "Key_MediaTogglePlayPause", + "Key_HomePage", + "Key_Favorites", + "Key_Search", + "Key_Standby", + "Key_OpenUrl", + "Key_LaunchMail", + "Key_LaunchMedia", + "Key_Launch0", + "Key_Launch1", + "Key_Launch2", + "Key_Launch3", + "Key_Launch4", + "Key_Launch5", + "Key_Launch6", + "Key_Launch7", + "Key_Launch8", + "Key_Launch9", + "Key_LaunchA", + "Key_LaunchB", + "Key_LaunchC", + "Key_LaunchD", + "Key_LaunchE", + "Key_LaunchF", + "Key_MonBrightnessUp", + "Key_MonBrightnessDown", + "Key_KeyboardLightOnOff", + "Key_KeyboardBrightnessUp", + "Key_KeyboardBrightnessDown", + "Key_PowerOff", + "Key_WakeUp", + "Key_Eject", + "Key_ScreenSaver", + "Key_WWW", + "Key_Memo", + "Key_LightBulb", + "Key_Shop", + "Key_History", + "Key_AddFavorite", + "Key_HotLinks", + "Key_BrightnessAdjust", + "Key_Finance", + "Key_Community", + "Key_AudioRewind", + "Key_BackForward", + "Key_ApplicationLeft", + "Key_ApplicationRight", + "Key_Book", + "Key_CD", + "Key_Calculator", + "Key_ToDoList", + "Key_ClearGrab", + "Key_Close", + "Key_Copy", + "Key_Cut", + "Key_Display", + "Key_DOS", + "Key_Documents", + "Key_Excel", + "Key_Explorer", + "Key_Game", + "Key_Go", + "Key_iTouch", + "Key_LogOff", + "Key_Market", + "Key_Meeting", + "Key_MenuKB", + "Key_MenuPB", + "Key_MySites", + "Key_News", + "Key_OfficeHome", + "Key_Option", + "Key_Paste", + "Key_Phone", + "Key_Calendar", + "Key_Reply", + "Key_Reload", + "Key_RotateWindows", + "Key_RotationPB", + "Key_RotationKB", + "Key_Save", + "Key_Send", + "Key_Spell", + "Key_SplitScreen", + "Key_Support", + "Key_TaskPane", + "Key_Terminal", + "Key_Tools", + "Key_Travel", + "Key_Video", + "Key_Word", + "Key_Xfer", + "Key_ZoomIn", + "Key_ZoomOut", + "Key_Away", + "Key_Messenger", + "Key_WebCam", + "Key_MailForward", + "Key_Pictures", + "Key_Music", + "Key_Battery", + "Key_Bluetooth", + "Key_WLAN", + "Key_UWB", + "Key_AudioForward", + "Key_AudioRepeat", + "Key_AudioRandomPlay", + "Key_Subtitle", + "Key_AudioCycleTrack", + "Key_Time", + "Key_Hibernate", + "Key_View", + "Key_TopMenu", + "Key_PowerDown", + "Key_Suspend", + "Key_ContrastAdjust", + "Key_LaunchG", + "Key_LaunchH", + "Key_TouchpadToggle", + "Key_TouchpadOn", + "Key_TouchpadOff", + "Key_MicMute", + "Key_Red", + "Key_Green", + "Key_Yellow", + "Key_Blue", + "Key_ChannelUp", + "Key_ChannelDown", + "Key_Guide", + "Key_Info", + "Key_Settings", + "Key_MicVolumeUp", + "Key_MicVolumeDown", + "Key_New", + "Key_Open", + "Key_Find", + "Key_Undo", + "Key_Redo", + "Key_MediaLast", + "Key_Select", + "Key_Yes", + "Key_No", + "Key_Cancel", + "Key_Printer", + "Key_Execute", + "Key_Sleep", + "Key_Play", + "Key_Zoom", + "Key_Exit", + "Key_Context1", + "Key_Context2", + "Key_Context3", + "Key_Context4", + "Key_Call", + "Key_Hangup", + "Key_Flip", + "Key_ToggleCallHangup", + "Key_VoiceDial", + "Key_LastNumberRedial", + "Key_Camera", + "Key_CameraFocus", + "Key_unknown" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "KeyboardModifier", + "values": [ + "NoModifier", + "ShiftModifier", + "ControlModifier", + "AltModifier", + "MetaModifier", + "KeypadModifier", + "GroupSwitchModifier", + "KeyboardModifierMask" + ] + }, + { + "alias": "KeyboardModifier", + "isClass": false, + "isFlag": true, + "name": "KeyboardModifiers", + "values": [ + "NoModifier", + "ShiftModifier", + "ControlModifier", + "AltModifier", + "MetaModifier", + "KeypadModifier", + "GroupSwitchModifier", + "KeyboardModifierMask" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "Modifier", + "values": [ + "META", + "SHIFT", + "CTRL", + "ALT", + "MODIFIER_MASK" + ] + }, + { + "alias": "Modifier", + "isClass": false, + "isFlag": true, + "name": "Modifiers", + "values": [ + "META", + "SHIFT", + "CTRL", + "ALT", + "MODIFIER_MASK" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "ArrowType", + "values": [ + "NoArrow", + "UpArrow", + "DownArrow", + "LeftArrow", + "RightArrow" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "PenStyle", + "values": [ + "NoPen", + "SolidLine", + "DashLine", + "DotLine", + "DashDotLine", + "DashDotDotLine", + "CustomDashLine" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "PenCapStyle", + "values": [ + "FlatCap", + "SquareCap", + "RoundCap", + "MPenCapStyle" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "PenJoinStyle", + "values": [ + "MiterJoin", + "BevelJoin", + "RoundJoin", + "SvgMiterJoin", + "MPenJoinStyle" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "BrushStyle", + "values": [ + "NoBrush", + "SolidPattern", + "Dense1Pattern", + "Dense2Pattern", + "Dense3Pattern", + "Dense4Pattern", + "Dense5Pattern", + "Dense6Pattern", + "Dense7Pattern", + "HorPattern", + "VerPattern", + "CrossPattern", + "BDiagPattern", + "FDiagPattern", + "DiagCrossPattern", + "LinearGradientPattern", + "RadialGradientPattern", + "ConicalGradientPattern", + "TexturePattern" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "SizeMode", + "values": [ + "AbsoluteSize", + "RelativeSize" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "CursorShape", + "values": [ + "ArrowCursor", + "UpArrowCursor", + "CrossCursor", + "WaitCursor", + "IBeamCursor", + "SizeVerCursor", + "SizeHorCursor", + "SizeBDiagCursor", + "SizeFDiagCursor", + "SizeAllCursor", + "BlankCursor", + "SplitVCursor", + "SplitHCursor", + "PointingHandCursor", + "ForbiddenCursor", + "WhatsThisCursor", + "BusyCursor", + "OpenHandCursor", + "ClosedHandCursor", + "DragCopyCursor", + "DragMoveCursor", + "DragLinkCursor", + "LastCursor", + "BitmapCursor", + "CustomCursor" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "TextFormat", + "values": [ + "PlainText", + "RichText", + "AutoText", + "MarkdownText" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "AspectRatioMode", + "values": [ + "IgnoreAspectRatio", + "KeepAspectRatio", + "KeepAspectRatioByExpanding" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "DockWidgetArea", + "values": [ + "LeftDockWidgetArea", + "RightDockWidgetArea", + "TopDockWidgetArea", + "BottomDockWidgetArea", + "DockWidgetArea_Mask", + "AllDockWidgetAreas", + "NoDockWidgetArea" + ] + }, + { + "alias": "DockWidgetArea", + "isClass": false, + "isFlag": true, + "name": "DockWidgetAreas", + "values": [ + "LeftDockWidgetArea", + "RightDockWidgetArea", + "TopDockWidgetArea", + "BottomDockWidgetArea", + "DockWidgetArea_Mask", + "AllDockWidgetAreas", + "NoDockWidgetArea" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "ToolBarArea", + "values": [ + "LeftToolBarArea", + "RightToolBarArea", + "TopToolBarArea", + "BottomToolBarArea", + "ToolBarArea_Mask", + "AllToolBarAreas", + "NoToolBarArea" + ] + }, + { + "alias": "ToolBarArea", + "isClass": false, + "isFlag": true, + "name": "ToolBarAreas", + "values": [ + "LeftToolBarArea", + "RightToolBarArea", + "TopToolBarArea", + "BottomToolBarArea", + "ToolBarArea_Mask", + "AllToolBarAreas", + "NoToolBarArea" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "DateFormat", + "values": [ + "TextDate", + "ISODate", + "RFC2822Date", + "ISODateWithMs" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "TimeSpec", + "values": [ + "LocalTime", + "UTC", + "OffsetFromUTC", + "TimeZone" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "DayOfWeek", + "values": [ + "Monday", + "Tuesday", + "Wednesday", + "Thursday", + "Friday", + "Saturday", + "Sunday" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "ScrollBarPolicy", + "values": [ + "ScrollBarAsNeeded", + "ScrollBarAlwaysOff", + "ScrollBarAlwaysOn" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "CaseSensitivity", + "values": [ + "CaseInsensitive", + "CaseSensitive" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "Corner", + "values": [ + "TopLeftCorner", + "TopRightCorner", + "BottomLeftCorner", + "BottomRightCorner" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "Edge", + "values": [ + "TopEdge", + "LeftEdge", + "RightEdge", + "BottomEdge" + ] + }, + { + "alias": "Edge", + "isClass": false, + "isFlag": true, + "name": "Edges", + "values": [ + "TopEdge", + "LeftEdge", + "RightEdge", + "BottomEdge" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "ConnectionType", + "values": [ + "AutoConnection", + "DirectConnection", + "QueuedConnection", + "BlockingQueuedConnection", + "UniqueConnection", + "SingleShotConnection" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "ShortcutContext", + "values": [ + "WidgetShortcut", + "WindowShortcut", + "ApplicationShortcut", + "WidgetWithChildrenShortcut" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "FillRule", + "values": [ + "OddEvenFill", + "WindingFill" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "MaskMode", + "values": [ + "MaskInColor", + "MaskOutColor" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "ClipOperation", + "values": [ + "NoClip", + "ReplaceClip", + "IntersectClip" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "ItemSelectionMode", + "values": [ + "ContainsItemShape", + "IntersectsItemShape", + "ContainsItemBoundingRect", + "IntersectsItemBoundingRect" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "ItemSelectionOperation", + "values": [ + "ReplaceSelection", + "AddToSelection" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "TransformationMode", + "values": [ + "FastTransformation", + "SmoothTransformation" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "Axis", + "values": [ + "XAxis", + "YAxis", + "ZAxis" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "FocusReason", + "values": [ + "MouseFocusReason", + "TabFocusReason", + "BacktabFocusReason", + "ActiveWindowFocusReason", + "PopupFocusReason", + "ShortcutFocusReason", + "MenuBarFocusReason", + "OtherFocusReason", + "NoFocusReason" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "ContextMenuPolicy", + "values": [ + "NoContextMenu", + "DefaultContextMenu", + "ActionsContextMenu", + "CustomContextMenu", + "PreventContextMenu" + ] + }, + { + "isClass": true, + "isFlag": false, + "name": "ContextMenuTrigger", + "values": [ + "Press", + "Release" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "InputMethodQuery", + "values": [ + "ImEnabled", + "ImCursorRectangle", + "ImFont", + "ImCursorPosition", + "ImSurroundingText", + "ImCurrentSelection", + "ImMaximumTextLength", + "ImAnchorPosition", + "ImHints", + "ImPreferredLanguage", + "ImAbsolutePosition", + "ImTextBeforeCursor", + "ImTextAfterCursor", + "ImEnterKeyType", + "ImAnchorRectangle", + "ImInputItemClipRectangle", + "ImReadOnly", + "ImPlatformData", + "ImQueryInput", + "ImQueryAll" + ] + }, + { + "alias": "InputMethodQuery", + "isClass": false, + "isFlag": true, + "name": "InputMethodQueries", + "values": [ + "ImEnabled", + "ImCursorRectangle", + "ImFont", + "ImCursorPosition", + "ImSurroundingText", + "ImCurrentSelection", + "ImMaximumTextLength", + "ImAnchorPosition", + "ImHints", + "ImPreferredLanguage", + "ImAbsolutePosition", + "ImTextBeforeCursor", + "ImTextAfterCursor", + "ImEnterKeyType", + "ImAnchorRectangle", + "ImInputItemClipRectangle", + "ImReadOnly", + "ImPlatformData", + "ImQueryInput", + "ImQueryAll" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "InputMethodHint", + "values": [ + "ImhNone", + "ImhHiddenText", + "ImhSensitiveData", + "ImhNoAutoUppercase", + "ImhPreferNumbers", + "ImhPreferUppercase", + "ImhPreferLowercase", + "ImhNoPredictiveText", + "ImhDate", + "ImhTime", + "ImhPreferLatin", + "ImhMultiLine", + "ImhNoEditMenu", + "ImhNoTextHandles", + "ImhDigitsOnly", + "ImhFormattedNumbersOnly", + "ImhUppercaseOnly", + "ImhLowercaseOnly", + "ImhDialableCharactersOnly", + "ImhEmailCharactersOnly", + "ImhUrlCharactersOnly", + "ImhLatinOnly", + "ImhExclusiveInputMask" + ] + }, + { + "alias": "InputMethodHint", + "isClass": false, + "isFlag": true, + "name": "InputMethodHints", + "values": [ + "ImhNone", + "ImhHiddenText", + "ImhSensitiveData", + "ImhNoAutoUppercase", + "ImhPreferNumbers", + "ImhPreferUppercase", + "ImhPreferLowercase", + "ImhNoPredictiveText", + "ImhDate", + "ImhTime", + "ImhPreferLatin", + "ImhMultiLine", + "ImhNoEditMenu", + "ImhNoTextHandles", + "ImhDigitsOnly", + "ImhFormattedNumbersOnly", + "ImhUppercaseOnly", + "ImhLowercaseOnly", + "ImhDialableCharactersOnly", + "ImhEmailCharactersOnly", + "ImhUrlCharactersOnly", + "ImhLatinOnly", + "ImhExclusiveInputMask" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "EnterKeyType", + "values": [ + "EnterKeyDefault", + "EnterKeyReturn", + "EnterKeyDone", + "EnterKeyGo", + "EnterKeySend", + "EnterKeySearch", + "EnterKeyNext", + "EnterKeyPrevious" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "ToolButtonStyle", + "values": [ + "ToolButtonIconOnly", + "ToolButtonTextOnly", + "ToolButtonTextBesideIcon", + "ToolButtonTextUnderIcon", + "ToolButtonFollowStyle" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "LayoutDirection", + "values": [ + "LeftToRight", + "RightToLeft", + "LayoutDirectionAuto" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "DropAction", + "values": [ + "CopyAction", + "MoveAction", + "LinkAction", + "ActionMask", + "TargetMoveAction", + "IgnoreAction" + ] + }, + { + "alias": "DropAction", + "isClass": false, + "isFlag": true, + "name": "DropActions", + "values": [ + "CopyAction", + "MoveAction", + "LinkAction", + "ActionMask", + "TargetMoveAction", + "IgnoreAction" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "CheckState", + "values": [ + "Unchecked", + "PartiallyChecked", + "Checked" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "ItemDataRole", + "values": [ + "DisplayRole", + "DecorationRole", + "EditRole", + "ToolTipRole", + "StatusTipRole", + "WhatsThisRole", + "FontRole", + "TextAlignmentRole", + "BackgroundRole", + "ForegroundRole", + "CheckStateRole", + "AccessibleTextRole", + "AccessibleDescriptionRole", + "SizeHintRole", + "InitialSortOrderRole", + "DisplayPropertyRole", + "DecorationPropertyRole", + "ToolTipPropertyRole", + "StatusTipPropertyRole", + "WhatsThisPropertyRole", + "UserRole" + ] + }, + { + "alias": "ItemFlag", + "isClass": false, + "isFlag": true, + "name": "ItemFlags", + "values": [ + "NoItemFlags", + "ItemIsSelectable", + "ItemIsEditable", + "ItemIsDragEnabled", + "ItemIsDropEnabled", + "ItemIsUserCheckable", + "ItemIsEnabled", + "ItemIsAutoTristate", + "ItemNeverHasChildren", + "ItemIsUserTristate" + ] + }, + { + "alias": "MatchFlag", + "isClass": false, + "isFlag": true, + "name": "MatchFlags", + "values": [ + "MatchExactly", + "MatchContains", + "MatchStartsWith", + "MatchEndsWith", + "MatchRegularExpression", + "MatchWildcard", + "MatchFixedString", + "MatchTypeMask", + "MatchCaseSensitive", + "MatchWrap", + "MatchRecursive" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "WindowModality", + "values": [ + "NonModal", + "WindowModal", + "ApplicationModal" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "TextInteractionFlag", + "values": [ + "NoTextInteraction", + "TextSelectableByMouse", + "TextSelectableByKeyboard", + "LinksAccessibleByMouse", + "LinksAccessibleByKeyboard", + "TextEditable", + "TextEditorInteraction", + "TextBrowserInteraction" + ] + }, + { + "alias": "TextInteractionFlag", + "isClass": false, + "isFlag": true, + "name": "TextInteractionFlags", + "values": [ + "NoTextInteraction", + "TextSelectableByMouse", + "TextSelectableByKeyboard", + "LinksAccessibleByMouse", + "LinksAccessibleByKeyboard", + "TextEditable", + "TextEditorInteraction", + "TextBrowserInteraction" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "SizeHint", + "values": [ + "MinimumSize", + "PreferredSize", + "MaximumSize", + "MinimumDescent", + "NSizeHints" + ] + }, + { + "alias": "TouchPointState", + "isClass": false, + "isFlag": true, + "name": "TouchPointStates", + "values": [ + "TouchPointUnknownState", + "TouchPointPressed", + "TouchPointMoved", + "TouchPointStationary", + "TouchPointReleased" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "GestureState", + "values": [ + "NoGesture", + "GestureStarted", + "GestureUpdated", + "GestureFinished", + "GestureCanceled" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "GestureType", + "values": [ + "TapGesture", + "TapAndHoldGesture", + "PanGesture", + "PinchGesture", + "SwipeGesture", + "CustomGesture", + "LastGestureType" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "NativeGestureType", + "values": [ + "BeginNativeGesture", + "EndNativeGesture", + "PanNativeGesture", + "ZoomNativeGesture", + "SmartZoomNativeGesture", + "RotateNativeGesture", + "SwipeNativeGesture" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "CursorMoveStyle", + "values": [ + "LogicalMoveStyle", + "VisualMoveStyle" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "TimerType", + "values": [ + "PreciseTimer", + "CoarseTimer", + "VeryCoarseTimer" + ] + }, + { + "isClass": true, + "isFlag": false, + "name": "TimerId", + "values": [ + "Invalid" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "ScrollPhase", + "values": [ + "NoScrollPhase", + "ScrollBegin", + "ScrollUpdate", + "ScrollEnd", + "ScrollMomentum" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "MouseEventSource", + "values": [ + "MouseEventNotSynthesized", + "MouseEventSynthesizedBySystem", + "MouseEventSynthesizedByQt", + "MouseEventSynthesizedByApplication" + ] + }, + { + "alias": "MouseEventFlag", + "isClass": false, + "isFlag": true, + "name": "MouseEventFlags", + "values": [ + "NoMouseEventFlag", + "MouseEventCreatedDoubleClick", + "MouseEventFlagMask" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "ChecksumType", + "values": [ + "ChecksumIso3309", + "ChecksumItuV41" + ] + }, + { + "isClass": true, + "isFlag": false, + "name": "HighDpiScaleFactorRoundingPolicy", + "values": [ + "Unset", + "Round", + "Ceil", + "Floor", + "RoundPreferFloor", + "PassThrough" + ] + }, + { + "isClass": true, + "isFlag": false, + "name": "PermissionStatus", + "values": [ + "Undetermined", + "Granted", + "Denied" + ] + } + ], + "lineNumber": 25, + "namespace": true, + "qualifiedClassName": "Qt" + } + ], + "inputFile": "qnamespace.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QAbstractAnimation", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "Direction", + "values": [ + "Forward", + "Backward" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "State", + "values": [ + "Stopped", + "Paused", + "Running" + ] + } + ], + "lineNumber": 19, + "object": true, + "properties": [ + { + "bindable": "bindableState", + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "state", + "notify": "stateChanged", + "read": "state", + "required": false, + "scriptable": true, + "stored": true, + "type": "State", + "user": false + }, + { + "bindable": "bindableLoopCount", + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "loopCount", + "read": "loopCount", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setLoopCount" + }, + { + "bindable": "bindableCurrentTime", + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "currentTime", + "read": "currentTime", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setCurrentTime" + }, + { + "bindable": "bindableCurrentLoop", + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "currentLoop", + "notify": "currentLoopChanged", + "read": "currentLoop", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "bindable": "bindableDirection", + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "direction", + "notify": "directionChanged", + "read": "direction", + "required": false, + "scriptable": true, + "stored": true, + "type": "Direction", + "user": false, + "write": "setDirection" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "duration", + "read": "duration", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + } + ], + "qualifiedClassName": "QAbstractAnimation", + "signals": [ + { + "access": "public", + "index": 0, + "name": "finished", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "newState", + "type": "QAbstractAnimation::State" + }, + { + "name": "oldState", + "type": "QAbstractAnimation::State" + } + ], + "index": 1, + "name": "stateChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "currentLoop", + "type": "int" + } + ], + "index": 2, + "name": "currentLoopChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QAbstractAnimation::Direction" + } + ], + "index": 3, + "name": "directionChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "policy", + "type": "QAbstractAnimation::DeletionPolicy" + } + ], + "index": 4, + "name": "start", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "isCloned": true, + "name": "start", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "pause", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "resume", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "bool" + } + ], + "index": 8, + "name": "setPaused", + "returnType": "void" + }, + { + "access": "public", + "index": 9, + "name": "stop", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "msecs", + "type": "int" + } + ], + "index": 10, + "name": "setCurrentTime", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "className": "QAnimationDriver", + "lineNumber": 106, + "object": true, + "qualifiedClassName": "QAnimationDriver", + "signals": [ + { + "access": "public", + "index": 0, + "name": "started", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "stopped", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qabstractanimation.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QDefaultAnimationDriver", + "lineNumber": 81, + "object": true, + "qualifiedClassName": "QDefaultAnimationDriver", + "slots": [ + { + "access": "private", + "index": 0, + "name": "startTimer", + "returnType": "void" + }, + { + "access": "private", + "index": 1, + "name": "stopTimer", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QAnimationDriver" + } + ] + }, + { + "className": "QAbstractAnimationTimer", + "lineNumber": 110, + "object": true, + "qualifiedClassName": "QAbstractAnimationTimer", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "className": "QUnifiedTimer", + "lineNumber": 126, + "object": true, + "qualifiedClassName": "QUnifiedTimer", + "slots": [ + { + "access": "private", + "index": 0, + "name": "startTimers", + "returnType": "void" + }, + { + "access": "private", + "index": 1, + "name": "stopTimer", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "className": "QAnimationTimer", + "lineNumber": 219, + "object": true, + "qualifiedClassName": "QAnimationTimer", + "slots": [ + { + "access": "private", + "index": 0, + "name": "startAnimations", + "returnType": "void" + }, + { + "access": "private", + "index": 1, + "name": "stopTimer", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QAbstractAnimationTimer" + } + ] + } + ], + "inputFile": "qabstractanimation_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QAbstractEventDispatcher", + "lineNumber": 16, + "object": true, + "qualifiedClassName": "QAbstractEventDispatcher", + "signals": [ + { + "access": "public", + "index": 0, + "name": "aboutToBlock", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "awake", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "className": "QAbstractEventDispatcherV2", + "lineNumber": 96, + "object": true, + "qualifiedClassName": "QAbstractEventDispatcherV2", + "superClasses": [ + { + "access": "public", + "name": "QAbstractEventDispatcher" + } + ] + } + ], + "inputFile": "qabstracteventdispatcher.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QAbstractItemModel", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "LayoutChangeHint", + "values": [ + "NoLayoutChangeHint", + "VerticalSortHint", + "HorizontalSortHint" + ] + }, + { + "isClass": true, + "isFlag": false, + "name": "CheckIndexOption", + "values": [ + "NoOption", + "IndexIsValid", + "DoNotUseParent", + "ParentIsInvalid" + ] + } + ], + "lineNumber": 258, + "methods": [ + { + "access": "public", + "arguments": [ + { + "name": "row", + "type": "int" + }, + { + "name": "column", + "type": "int" + }, + { + "name": "parent", + "type": "QModelIndex" + } + ], + "index": 26, + "name": "hasIndex", + "returnType": "bool" + }, + { + "access": "public", + "arguments": [ + { + "name": "row", + "type": "int" + }, + { + "name": "column", + "type": "int" + } + ], + "index": 27, + "isCloned": true, + "name": "hasIndex", + "returnType": "bool" + }, + { + "access": "public", + "arguments": [ + { + "name": "row", + "type": "int" + }, + { + "name": "column", + "type": "int" + }, + { + "name": "parent", + "type": "QModelIndex" + } + ], + "index": 28, + "name": "index", + "returnType": "QModelIndex" + }, + { + "access": "public", + "arguments": [ + { + "name": "row", + "type": "int" + }, + { + "name": "column", + "type": "int" + } + ], + "index": 29, + "isCloned": true, + "name": "index", + "returnType": "QModelIndex" + }, + { + "access": "public", + "arguments": [ + { + "name": "child", + "type": "QModelIndex" + } + ], + "index": 30, + "name": "parent", + "returnType": "QModelIndex" + }, + { + "access": "public", + "arguments": [ + { + "name": "row", + "type": "int" + }, + { + "name": "column", + "type": "int" + }, + { + "name": "idx", + "type": "QModelIndex" + } + ], + "index": 31, + "name": "sibling", + "returnType": "QModelIndex" + }, + { + "access": "public", + "arguments": [ + { + "name": "parent", + "type": "QModelIndex" + } + ], + "index": 32, + "name": "rowCount", + "returnType": "int" + }, + { + "access": "public", + "index": 33, + "isCloned": true, + "name": "rowCount", + "returnType": "int" + }, + { + "access": "public", + "arguments": [ + { + "name": "parent", + "type": "QModelIndex" + } + ], + "index": 34, + "name": "columnCount", + "returnType": "int" + }, + { + "access": "public", + "index": 35, + "isCloned": true, + "name": "columnCount", + "returnType": "int" + }, + { + "access": "public", + "arguments": [ + { + "name": "parent", + "type": "QModelIndex" + } + ], + "index": 36, + "name": "hasChildren", + "returnType": "bool" + }, + { + "access": "public", + "index": 37, + "isCloned": true, + "name": "hasChildren", + "returnType": "bool" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "QModelIndex" + }, + { + "name": "role", + "type": "int" + } + ], + "index": 38, + "name": "data", + "returnType": "QVariant" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "QModelIndex" + } + ], + "index": 39, + "isCloned": true, + "name": "data", + "returnType": "QVariant" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "QModelIndex" + }, + { + "name": "value", + "type": "QVariant" + }, + { + "name": "role", + "type": "int" + } + ], + "index": 40, + "name": "setData", + "returnType": "bool" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "QModelIndex" + }, + { + "name": "value", + "type": "QVariant" + } + ], + "index": 41, + "isCloned": true, + "name": "setData", + "returnType": "bool" + }, + { + "access": "public", + "arguments": [ + { + "name": "section", + "type": "int" + }, + { + "name": "orientation", + "type": "Qt::Orientation" + }, + { + "name": "role", + "type": "int" + } + ], + "index": 42, + "name": "headerData", + "returnType": "QVariant" + }, + { + "access": "public", + "arguments": [ + { + "name": "section", + "type": "int" + }, + { + "name": "orientation", + "type": "Qt::Orientation" + } + ], + "index": 43, + "isCloned": true, + "name": "headerData", + "returnType": "QVariant" + }, + { + "access": "public", + "arguments": [ + { + "name": "row", + "type": "int" + }, + { + "name": "count", + "type": "int" + }, + { + "name": "parent", + "type": "QModelIndex" + } + ], + "index": 44, + "name": "insertRows", + "returnType": "bool", + "revision": 1540 + }, + { + "access": "public", + "arguments": [ + { + "name": "row", + "type": "int" + }, + { + "name": "count", + "type": "int" + } + ], + "index": 45, + "isCloned": true, + "name": "insertRows", + "returnType": "bool", + "revision": 1540 + }, + { + "access": "public", + "arguments": [ + { + "name": "column", + "type": "int" + }, + { + "name": "count", + "type": "int" + }, + { + "name": "parent", + "type": "QModelIndex" + } + ], + "index": 46, + "name": "insertColumns", + "returnType": "bool", + "revision": 1540 + }, + { + "access": "public", + "arguments": [ + { + "name": "column", + "type": "int" + }, + { + "name": "count", + "type": "int" + } + ], + "index": 47, + "isCloned": true, + "name": "insertColumns", + "returnType": "bool", + "revision": 1540 + }, + { + "access": "public", + "arguments": [ + { + "name": "row", + "type": "int" + }, + { + "name": "count", + "type": "int" + }, + { + "name": "parent", + "type": "QModelIndex" + } + ], + "index": 48, + "name": "removeRows", + "returnType": "bool", + "revision": 1540 + }, + { + "access": "public", + "arguments": [ + { + "name": "row", + "type": "int" + }, + { + "name": "count", + "type": "int" + } + ], + "index": 49, + "isCloned": true, + "name": "removeRows", + "returnType": "bool", + "revision": 1540 + }, + { + "access": "public", + "arguments": [ + { + "name": "column", + "type": "int" + }, + { + "name": "count", + "type": "int" + }, + { + "name": "parent", + "type": "QModelIndex" + } + ], + "index": 50, + "name": "removeColumns", + "returnType": "bool", + "revision": 1540 + }, + { + "access": "public", + "arguments": [ + { + "name": "column", + "type": "int" + }, + { + "name": "count", + "type": "int" + } + ], + "index": 51, + "isCloned": true, + "name": "removeColumns", + "returnType": "bool", + "revision": 1540 + }, + { + "access": "public", + "arguments": [ + { + "name": "sourceParent", + "type": "QModelIndex" + }, + { + "name": "sourceRow", + "type": "int" + }, + { + "name": "count", + "type": "int" + }, + { + "name": "destinationParent", + "type": "QModelIndex" + }, + { + "name": "destinationChild", + "type": "int" + } + ], + "index": 52, + "name": "moveRows", + "returnType": "bool", + "revision": 1540 + }, + { + "access": "public", + "arguments": [ + { + "name": "sourceParent", + "type": "QModelIndex" + }, + { + "name": "sourceColumn", + "type": "int" + }, + { + "name": "count", + "type": "int" + }, + { + "name": "destinationParent", + "type": "QModelIndex" + }, + { + "name": "destinationChild", + "type": "int" + } + ], + "index": 53, + "name": "moveColumns", + "returnType": "bool", + "revision": 1540 + }, + { + "access": "public", + "arguments": [ + { + "name": "row", + "type": "int" + }, + { + "name": "parent", + "type": "QModelIndex" + } + ], + "index": 54, + "name": "insertRow", + "returnType": "bool", + "revision": 1540 + }, + { + "access": "public", + "arguments": [ + { + "name": "row", + "type": "int" + } + ], + "index": 55, + "isCloned": true, + "name": "insertRow", + "returnType": "bool", + "revision": 1540 + }, + { + "access": "public", + "arguments": [ + { + "name": "column", + "type": "int" + }, + { + "name": "parent", + "type": "QModelIndex" + } + ], + "index": 56, + "name": "insertColumn", + "returnType": "bool", + "revision": 1540 + }, + { + "access": "public", + "arguments": [ + { + "name": "column", + "type": "int" + } + ], + "index": 57, + "isCloned": true, + "name": "insertColumn", + "returnType": "bool", + "revision": 1540 + }, + { + "access": "public", + "arguments": [ + { + "name": "row", + "type": "int" + }, + { + "name": "parent", + "type": "QModelIndex" + } + ], + "index": 58, + "name": "removeRow", + "returnType": "bool", + "revision": 1540 + }, + { + "access": "public", + "arguments": [ + { + "name": "row", + "type": "int" + } + ], + "index": 59, + "isCloned": true, + "name": "removeRow", + "returnType": "bool", + "revision": 1540 + }, + { + "access": "public", + "arguments": [ + { + "name": "column", + "type": "int" + }, + { + "name": "parent", + "type": "QModelIndex" + } + ], + "index": 60, + "name": "removeColumn", + "returnType": "bool", + "revision": 1540 + }, + { + "access": "public", + "arguments": [ + { + "name": "column", + "type": "int" + } + ], + "index": 61, + "isCloned": true, + "name": "removeColumn", + "returnType": "bool", + "revision": 1540 + }, + { + "access": "public", + "arguments": [ + { + "name": "sourceParent", + "type": "QModelIndex" + }, + { + "name": "sourceRow", + "type": "int" + }, + { + "name": "destinationParent", + "type": "QModelIndex" + }, + { + "name": "destinationChild", + "type": "int" + } + ], + "index": 62, + "name": "moveRow", + "returnType": "bool", + "revision": 1540 + }, + { + "access": "public", + "arguments": [ + { + "name": "sourceParent", + "type": "QModelIndex" + }, + { + "name": "sourceColumn", + "type": "int" + }, + { + "name": "destinationParent", + "type": "QModelIndex" + }, + { + "name": "destinationChild", + "type": "int" + } + ], + "index": 63, + "name": "moveColumn", + "returnType": "bool", + "revision": 1540 + }, + { + "access": "public", + "arguments": [ + { + "name": "parent", + "type": "QModelIndex" + } + ], + "index": 64, + "name": "fetchMore", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "parent", + "type": "QModelIndex" + } + ], + "index": 65, + "name": "canFetchMore", + "returnType": "bool" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "QModelIndex" + } + ], + "index": 66, + "name": "flags", + "returnType": "Qt::ItemFlags" + }, + { + "access": "public", + "arguments": [ + { + "name": "column", + "type": "int" + }, + { + "name": "order", + "type": "Qt::SortOrder" + } + ], + "index": 67, + "name": "sort", + "returnType": "void", + "revision": 1540 + }, + { + "access": "public", + "arguments": [ + { + "name": "column", + "type": "int" + } + ], + "index": 68, + "isCloned": true, + "name": "sort", + "returnType": "void", + "revision": 1540 + }, + { + "access": "public", + "arguments": [ + { + "name": "start", + "type": "QModelIndex" + }, + { + "name": "role", + "type": "int" + }, + { + "name": "value", + "type": "QVariant" + }, + { + "name": "hits", + "type": "int" + }, + { + "name": "flags", + "type": "Qt::MatchFlags" + } + ], + "index": 69, + "name": "match", + "returnType": "QModelIndexList" + }, + { + "access": "public", + "arguments": [ + { + "name": "start", + "type": "QModelIndex" + }, + { + "name": "role", + "type": "int" + }, + { + "name": "value", + "type": "QVariant" + }, + { + "name": "hits", + "type": "int" + } + ], + "index": 70, + "isCloned": true, + "name": "match", + "returnType": "QModelIndexList" + }, + { + "access": "public", + "arguments": [ + { + "name": "start", + "type": "QModelIndex" + }, + { + "name": "role", + "type": "int" + }, + { + "name": "value", + "type": "QVariant" + } + ], + "index": 71, + "isCloned": true, + "name": "match", + "returnType": "QModelIndexList" + } + ], + "object": true, + "qualifiedClassName": "QAbstractItemModel", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "topLeft", + "type": "QModelIndex" + }, + { + "name": "bottomRight", + "type": "QModelIndex" + }, + { + "name": "roles", + "type": "QList" + } + ], + "index": 0, + "name": "dataChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "topLeft", + "type": "QModelIndex" + }, + { + "name": "bottomRight", + "type": "QModelIndex" + } + ], + "index": 1, + "isCloned": true, + "name": "dataChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "orientation", + "type": "Qt::Orientation" + }, + { + "name": "first", + "type": "int" + }, + { + "name": "last", + "type": "int" + } + ], + "index": 2, + "name": "headerDataChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "parents", + "type": "QList" + }, + { + "name": "hint", + "type": "QAbstractItemModel::LayoutChangeHint" + } + ], + "index": 3, + "name": "layoutChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "parents", + "type": "QList" + } + ], + "index": 4, + "isCloned": true, + "name": "layoutChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "isCloned": true, + "name": "layoutChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "parents", + "type": "QList" + }, + { + "name": "hint", + "type": "QAbstractItemModel::LayoutChangeHint" + } + ], + "index": 6, + "name": "layoutAboutToBeChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "parents", + "type": "QList" + } + ], + "index": 7, + "isCloned": true, + "name": "layoutAboutToBeChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 8, + "isCloned": true, + "name": "layoutAboutToBeChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "parent", + "type": "QModelIndex" + }, + { + "name": "first", + "type": "int" + }, + { + "name": "last", + "type": "int" + } + ], + "index": 9, + "name": "rowsAboutToBeInserted", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "parent", + "type": "QModelIndex" + }, + { + "name": "first", + "type": "int" + }, + { + "name": "last", + "type": "int" + } + ], + "index": 10, + "name": "rowsInserted", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "parent", + "type": "QModelIndex" + }, + { + "name": "first", + "type": "int" + }, + { + "name": "last", + "type": "int" + } + ], + "index": 11, + "name": "rowsAboutToBeRemoved", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "parent", + "type": "QModelIndex" + }, + { + "name": "first", + "type": "int" + }, + { + "name": "last", + "type": "int" + } + ], + "index": 12, + "name": "rowsRemoved", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "parent", + "type": "QModelIndex" + }, + { + "name": "first", + "type": "int" + }, + { + "name": "last", + "type": "int" + } + ], + "index": 13, + "name": "columnsAboutToBeInserted", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "parent", + "type": "QModelIndex" + }, + { + "name": "first", + "type": "int" + }, + { + "name": "last", + "type": "int" + } + ], + "index": 14, + "name": "columnsInserted", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "parent", + "type": "QModelIndex" + }, + { + "name": "first", + "type": "int" + }, + { + "name": "last", + "type": "int" + } + ], + "index": 15, + "name": "columnsAboutToBeRemoved", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "parent", + "type": "QModelIndex" + }, + { + "name": "first", + "type": "int" + }, + { + "name": "last", + "type": "int" + } + ], + "index": 16, + "name": "columnsRemoved", + "returnType": "void" + }, + { + "access": "public", + "index": 17, + "name": "modelAboutToBeReset", + "returnType": "void" + }, + { + "access": "public", + "index": 18, + "name": "modelReset", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "sourceParent", + "type": "QModelIndex" + }, + { + "name": "sourceStart", + "type": "int" + }, + { + "name": "sourceEnd", + "type": "int" + }, + { + "name": "destinationParent", + "type": "QModelIndex" + }, + { + "name": "destinationRow", + "type": "int" + } + ], + "index": 19, + "name": "rowsAboutToBeMoved", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "sourceParent", + "type": "QModelIndex" + }, + { + "name": "sourceStart", + "type": "int" + }, + { + "name": "sourceEnd", + "type": "int" + }, + { + "name": "destinationParent", + "type": "QModelIndex" + }, + { + "name": "destinationRow", + "type": "int" + } + ], + "index": 20, + "name": "rowsMoved", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "sourceParent", + "type": "QModelIndex" + }, + { + "name": "sourceStart", + "type": "int" + }, + { + "name": "sourceEnd", + "type": "int" + }, + { + "name": "destinationParent", + "type": "QModelIndex" + }, + { + "name": "destinationColumn", + "type": "int" + } + ], + "index": 21, + "name": "columnsAboutToBeMoved", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "sourceParent", + "type": "QModelIndex" + }, + { + "name": "sourceStart", + "type": "int" + }, + { + "name": "sourceEnd", + "type": "int" + }, + { + "name": "destinationParent", + "type": "QModelIndex" + }, + { + "name": "destinationColumn", + "type": "int" + } + ], + "index": 22, + "name": "columnsMoved", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "index": 23, + "name": "submit", + "returnType": "bool" + }, + { + "access": "public", + "index": 24, + "name": "revert", + "returnType": "void" + }, + { + "access": "protected", + "index": 25, + "name": "resetInternalData", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "className": "QAbstractTableModel", + "lineNumber": 450, + "object": true, + "qualifiedClassName": "QAbstractTableModel", + "superClasses": [ + { + "access": "public", + "name": "QAbstractItemModel" + } + ] + }, + { + "className": "QAbstractListModel", + "lineNumber": 476, + "object": true, + "qualifiedClassName": "QAbstractListModel", + "superClasses": [ + { + "access": "public", + "name": "QAbstractItemModel" + } + ] + } + ], + "inputFile": "qabstractitemmodel.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QAbstractProxyModel", + "lineNumber": 16, + "methods": [ + { + "access": "public", + "arguments": [ + { + "name": "proxyIndex", + "type": "QModelIndex" + } + ], + "index": 8, + "name": "mapToSource", + "returnType": "QModelIndex" + }, + { + "access": "public", + "arguments": [ + { + "name": "sourceIndex", + "type": "QModelIndex" + } + ], + "index": 9, + "name": "mapFromSource", + "returnType": "QModelIndex" + }, + { + "access": "public", + "arguments": [ + { + "name": "selection", + "type": "QItemSelection" + } + ], + "index": 10, + "name": "mapSelectionToSource", + "returnType": "QItemSelection" + }, + { + "access": "public", + "arguments": [ + { + "name": "selection", + "type": "QItemSelection" + } + ], + "index": 11, + "name": "mapSelectionFromSource", + "returnType": "QItemSelection" + } + ], + "object": true, + "properties": [ + { + "bindable": "bindableSourceModel", + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "sourceModel", + "notify": "sourceModelChanged", + "read": "sourceModel", + "required": false, + "scriptable": true, + "stored": true, + "type": "QAbstractItemModel*", + "user": false, + "write": "setSourceModel" + } + ], + "qualifiedClassName": "QAbstractProxyModel", + "signals": [ + { + "access": "public", + "index": 0, + "name": "sourceModelChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "private", + "index": 1, + "name": "_q_sourceModelDestroyed", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "type": "QModelIndex" + }, + { + "type": "int" + }, + { + "type": "int" + } + ], + "index": 2, + "name": "_q_sourceModelRowsAboutToBeInserted", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "type": "QModelIndex" + }, + { + "type": "int" + }, + { + "type": "int" + } + ], + "index": 3, + "name": "_q_sourceModelRowsInserted", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "type": "QModelIndex" + }, + { + "type": "int" + }, + { + "type": "int" + } + ], + "index": 4, + "name": "_q_sourceModelRowsRemoved", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "type": "QModelIndex" + }, + { + "type": "int" + }, + { + "type": "int" + } + ], + "index": 5, + "name": "_q_sourceModelColumnsAboutToBeInserted", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "type": "QModelIndex" + }, + { + "type": "int" + }, + { + "type": "int" + } + ], + "index": 6, + "name": "_q_sourceModelColumnsInserted", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "type": "QModelIndex" + }, + { + "type": "int" + }, + { + "type": "int" + } + ], + "index": 7, + "name": "_q_sourceModelColumnsRemoved", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QAbstractItemModel" + } + ] + } + ], + "inputFile": "qabstractproxymodel.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QAnimationGroup", + "lineNumber": 14, + "object": true, + "qualifiedClassName": "QAnimationGroup", + "superClasses": [ + { + "access": "public", + "name": "QAbstractAnimation" + } + ] + } + ], + "inputFile": "qanimationgroup.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QBuffer", + "lineNumber": 15, + "object": true, + "qualifiedClassName": "QBuffer", + "slots": [ + { + "access": "private", + "index": 0, + "name": "_q_emitSignals", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QIODevice" + } + ] + } + ], + "inputFile": "qbuffer.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QCalendar", + "enums": [ + { + "isClass": true, + "isFlag": false, + "name": "System", + "values": [ + "Gregorian", + "Julian", + "Milankovic", + "Jalali", + "IslamicCivil", + "Last", + "User" + ] + } + ], + "gadget": true, + "lineNumber": 52, + "qualifiedClassName": "QCalendar" + } + ], + "inputFile": "qcalendar.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QCborError", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "Code", + "type": "int", + "values": [ + "UnknownError", + "AdvancePastEnd", + "InputOutputError", + "GarbageAtEnd", + "EndOfFile", + "UnexpectedBreak", + "UnknownType", + "IllegalType", + "IllegalNumber", + "IllegalSimpleType", + "InvalidUtf8String", + "DataTooLarge", + "NestingTooDeep", + "UnsupportedType", + "NoError" + ] + } + ], + "gadget": true, + "lineNumber": 62, + "qualifiedClassName": "QCborError" + } + ], + "inputFile": "qcborcommon.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QCborStreamReader", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "Type", + "type": "quint8", + "values": [ + "UnsignedInteger", + "NegativeInteger", + "ByteString", + "ByteArray", + "TextString", + "String", + "Array", + "Map", + "Tag", + "SimpleType", + "HalfFloat", + "Float16", + "Float", + "Double", + "Invalid" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "StringResultCode", + "values": [ + "EndOfString", + "Ok", + "Error" + ] + } + ], + "gadget": true, + "lineNumber": 27, + "qualifiedClassName": "QCborStreamReader" + } + ], + "inputFile": "qcborstreamreader.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QCborValue", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "Type", + "type": "int", + "values": [ + "Integer", + "ByteArray", + "String", + "Array", + "Map", + "Tag", + "SimpleType", + "False", + "True", + "Null", + "Undefined", + "Double", + "DateTime", + "Url", + "RegularExpression", + "Uuid", + "Invalid" + ] + } + ], + "gadget": true, + "lineNumber": 46, + "qualifiedClassName": "QCborValue" + } + ], + "inputFile": "qcborvalue.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QChronoTimer", + "lineNumber": 20, + "object": true, + "properties": [ + { + "bindable": "bindableSingleShot", + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "singleShot", + "read": "isSingleShot", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setSingleShot" + }, + { + "bindable": "bindableInterval", + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "interval", + "read": "interval", + "required": false, + "scriptable": true, + "stored": true, + "type": "std::chrono::nanoseconds", + "user": false, + "write": "setInterval" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "remainingTime", + "read": "remainingTime", + "required": false, + "scriptable": true, + "stored": true, + "type": "std::chrono::nanoseconds", + "user": false + }, + { + "bindable": "bindableTimerType", + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "timerType", + "read": "timerType", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::TimerType", + "user": false, + "write": "setTimerType" + }, + { + "bindable": "bindableActive", + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "active", + "read": "isActive", + "required": false, + "scriptable": true, + "stored": false, + "type": "bool", + "user": false + } + ], + "qualifiedClassName": "QChronoTimer", + "signals": [ + { + "access": "public", + "index": 0, + "name": "timeout", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "index": 1, + "name": "start", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "stop", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qchronotimer.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QConcatenateTablesProxyModel", + "lineNumber": 15, + "methods": [ + { + "access": "public", + "arguments": [ + { + "name": "sourceModel", + "type": "QAbstractItemModel*" + } + ], + "index": 0, + "name": "addSourceModel", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "sourceModel", + "type": "QAbstractItemModel*" + } + ], + "index": 1, + "name": "removeSourceModel", + "returnType": "void" + } + ], + "object": true, + "qualifiedClassName": "QConcatenateTablesProxyModel", + "superClasses": [ + { + "access": "public", + "name": "QAbstractItemModel" + } + ] + } + ], + "inputFile": "qconcatenatetablesproxymodel.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QCoreApplication", + "lineNumber": 44, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "applicationName", + "notify": "applicationNameChanged", + "read": "applicationName", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setApplicationName" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "applicationVersion", + "notify": "applicationVersionChanged", + "read": "applicationVersion", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setApplicationVersion" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "organizationName", + "notify": "organizationNameChanged", + "read": "organizationName", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setOrganizationName" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "organizationDomain", + "notify": "organizationDomainChanged", + "read": "organizationDomain", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setOrganizationDomain" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "quitLockEnabled", + "read": "isQuitLockEnabled", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setQuitLockEnabled" + } + ], + "qualifiedClassName": "QCoreApplication", + "signals": [ + { + "access": "public", + "index": 0, + "name": "aboutToQuit", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "organizationNameChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "organizationDomainChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "applicationNameChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "applicationVersionChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "index": 5, + "name": "quit", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "retcode", + "type": "int" + } + ], + "index": 6, + "name": "exit", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "isCloned": true, + "name": "exit", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qcoreapplication.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QEvent", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "Type", + "values": [ + "None", + "Timer", + "MouseButtonPress", + "MouseButtonRelease", + "MouseButtonDblClick", + "MouseMove", + "KeyPress", + "KeyRelease", + "FocusIn", + "FocusOut", + "FocusAboutToChange", + "Enter", + "Leave", + "Paint", + "Move", + "Resize", + "Create", + "Destroy", + "Show", + "Hide", + "Close", + "Quit", + "ParentChange", + "ParentAboutToChange", + "ThreadChange", + "WindowActivate", + "WindowDeactivate", + "ShowToParent", + "HideToParent", + "Wheel", + "WindowTitleChange", + "WindowIconChange", + "ApplicationWindowIconChange", + "ApplicationFontChange", + "ApplicationLayoutDirectionChange", + "ApplicationPaletteChange", + "PaletteChange", + "Clipboard", + "Speech", + "MetaCall", + "SockAct", + "WinEventAct", + "DeferredDelete", + "DragEnter", + "DragMove", + "DragLeave", + "Drop", + "DragResponse", + "ChildAdded", + "ChildPolished", + "ChildRemoved", + "ShowWindowRequest", + "PolishRequest", + "Polish", + "LayoutRequest", + "UpdateRequest", + "UpdateLater", + "EmbeddingControl", + "ActivateControl", + "DeactivateControl", + "ContextMenu", + "InputMethod", + "TabletMove", + "LocaleChange", + "LanguageChange", + "LayoutDirectionChange", + "Style", + "TabletPress", + "TabletRelease", + "OkRequest", + "HelpRequest", + "IconDrag", + "FontChange", + "EnabledChange", + "ActivationChange", + "StyleChange", + "IconTextChange", + "ModifiedChange", + "MouseTrackingChange", + "WindowBlocked", + "WindowUnblocked", + "WindowStateChange", + "ReadOnlyChange", + "ToolTip", + "WhatsThis", + "StatusTip", + "ActionChanged", + "ActionAdded", + "ActionRemoved", + "FileOpen", + "Shortcut", + "ShortcutOverride", + "WhatsThisClicked", + "ToolBarChange", + "ApplicationActivate", + "ApplicationActivated", + "ApplicationDeactivate", + "ApplicationDeactivated", + "QueryWhatsThis", + "EnterWhatsThisMode", + "LeaveWhatsThisMode", + "ZOrderChange", + "HoverEnter", + "HoverLeave", + "HoverMove", + "AcceptDropsChange", + "ZeroTimerEvent", + "GraphicsSceneMouseMove", + "GraphicsSceneMousePress", + "GraphicsSceneMouseRelease", + "GraphicsSceneMouseDoubleClick", + "GraphicsSceneContextMenu", + "GraphicsSceneHoverEnter", + "GraphicsSceneHoverMove", + "GraphicsSceneHoverLeave", + "GraphicsSceneHelp", + "GraphicsSceneDragEnter", + "GraphicsSceneDragMove", + "GraphicsSceneDragLeave", + "GraphicsSceneDrop", + "GraphicsSceneWheel", + "GraphicsSceneLeave", + "KeyboardLayoutChange", + "DynamicPropertyChange", + "TabletEnterProximity", + "TabletLeaveProximity", + "NonClientAreaMouseMove", + "NonClientAreaMouseButtonPress", + "NonClientAreaMouseButtonRelease", + "NonClientAreaMouseButtonDblClick", + "MacSizeChange", + "ContentsRectChange", + "MacGLWindowChange", + "FutureCallOut", + "GraphicsSceneResize", + "GraphicsSceneMove", + "CursorChange", + "ToolTipChange", + "NetworkReplyUpdated", + "GrabMouse", + "UngrabMouse", + "GrabKeyboard", + "UngrabKeyboard", + "StateMachineSignal", + "StateMachineWrapped", + "TouchBegin", + "TouchUpdate", + "TouchEnd", + "NativeGesture", + "RequestSoftwareInputPanel", + "CloseSoftwareInputPanel", + "WinIdChange", + "Gesture", + "GestureOverride", + "ScrollPrepare", + "Scroll", + "Expose", + "InputMethodQuery", + "OrientationChange", + "TouchCancel", + "ThemeChange", + "SockClose", + "PlatformPanel", + "StyleAnimationUpdate", + "ApplicationStateChange", + "WindowChangeInternal", + "ScreenChangeInternal", + "PlatformSurface", + "Pointer", + "TabletTrackingChange", + "WindowAboutToChangeInternal", + "DevicePixelRatioChange", + "ChildWindowAdded", + "ChildWindowRemoved", + "ParentWindowAboutToChange", + "ParentWindowChange", + "User", + "MaxUser" + ] + } + ], + "gadget": true, + "lineNumber": 44, + "qualifiedClassName": "QEvent" + } + ], + "inputFile": "qcoreevent.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QCryptographicHash", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "Algorithm", + "values": [ + "Md4", + "Md5", + "Sha1", + "Sha224", + "Sha256", + "Sha384", + "Sha512", + "Keccak_224", + "Keccak_256", + "Keccak_384", + "Keccak_512", + "RealSha3_224", + "RealSha3_256", + "RealSha3_384", + "RealSha3_512", + "Sha3_224", + "Sha3_256", + "Sha3_384", + "Sha3_512", + "Blake2b_160", + "Blake2b_256", + "Blake2b_384", + "Blake2b_512", + "Blake2s_128", + "Blake2s_160", + "Blake2s_224", + "Blake2s_256", + "NumAlgorithms" + ] + } + ], + "gadget": true, + "lineNumber": 19, + "qualifiedClassName": "QCryptographicHash" + } + ], + "inputFile": "qcryptographichash.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QEasingCurve", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "Type", + "values": [ + "Linear", + "InQuad", + "OutQuad", + "InOutQuad", + "OutInQuad", + "InCubic", + "OutCubic", + "InOutCubic", + "OutInCubic", + "InQuart", + "OutQuart", + "InOutQuart", + "OutInQuart", + "InQuint", + "OutQuint", + "InOutQuint", + "OutInQuint", + "InSine", + "OutSine", + "InOutSine", + "OutInSine", + "InExpo", + "OutExpo", + "InOutExpo", + "OutInExpo", + "InCirc", + "OutCirc", + "InOutCirc", + "OutInCirc", + "InElastic", + "OutElastic", + "InOutElastic", + "OutInElastic", + "InBack", + "OutBack", + "InOutBack", + "OutInBack", + "InBounce", + "OutBounce", + "InOutBounce", + "OutInBounce", + "InCurve", + "OutCurve", + "SineCurve", + "CosineCurve", + "BezierSpline", + "TCBSpline", + "Custom", + "NCurveTypes" + ] + } + ], + "gadget": true, + "lineNumber": 19, + "qualifiedClassName": "QEasingCurve" + } + ], + "inputFile": "qeasingcurve.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QEventDispatcherWin32", + "lineNumber": 32, + "object": true, + "qualifiedClassName": "QEventDispatcherWin32", + "superClasses": [ + { + "access": "public", + "name": "QAbstractEventDispatcher" + } + ] + } + ], + "inputFile": "qeventdispatcher_win_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QEventLoop", + "enums": [ + { + "alias": "ProcessEventsFlag", + "isClass": false, + "isFlag": true, + "name": "ProcessEventsFlags", + "values": [ + "AllEvents", + "ExcludeUserInputEvents", + "ExcludeSocketNotifiers", + "WaitForMoreEvents", + "X11ExcludeTimers", + "EventLoopExec", + "DialogExec", + "ApplicationExec" + ] + } + ], + "lineNumber": 15, + "object": true, + "qualifiedClassName": "QEventLoop", + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "returnCode", + "type": "int" + } + ], + "index": 0, + "name": "exit", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "isCloned": true, + "name": "exit", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "quit", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qeventloop.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QFactoryLoader", + "lineNumber": 61, + "object": true, + "qualifiedClassName": "QFactoryLoader", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qfactoryloader_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QFile", + "lineNumber": 92, + "object": true, + "qualifiedClassName": "QFile", + "superClasses": [ + { + "access": "public", + "name": "QFileDevice" + } + ] + } + ], + "inputFile": "qfile.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QFileDevice", + "lineNumber": 31, + "object": true, + "qualifiedClassName": "QFileDevice", + "superClasses": [ + { + "access": "public", + "name": "QIODevice" + } + ] + } + ], + "inputFile": "qfiledevice.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QFileSelector", + "lineNumber": 13, + "object": true, + "qualifiedClassName": "QFileSelector", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qfileselector.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QFileSystemWatcher", + "lineNumber": 16, + "object": true, + "qualifiedClassName": "QFileSystemWatcher", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "path", + "type": "QString" + } + ], + "index": 0, + "name": "fileChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "path", + "type": "QString" + } + ], + "index": 1, + "name": "directoryChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qfilesystemwatcher.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QFileSystemWatcherEngine", + "lineNumber": 29, + "object": true, + "qualifiedClassName": "QFileSystemWatcherEngine", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "path", + "type": "QString" + }, + { + "name": "removed", + "type": "bool" + } + ], + "index": 0, + "name": "fileChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "path", + "type": "QString" + }, + { + "name": "removed", + "type": "bool" + } + ], + "index": 1, + "name": "directoryChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qfilesystemwatcher_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QPollingFileSystemWatcherEngine", + "lineNumber": 30, + "object": true, + "qualifiedClassName": "QPollingFileSystemWatcherEngine", + "superClasses": [ + { + "access": "public", + "name": "QFileSystemWatcherEngine" + } + ] + } + ], + "inputFile": "qfilesystemwatcher_polling_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QWindowsFileSystemWatcherEngine", + "lineNumber": 37, + "object": true, + "qualifiedClassName": "QWindowsFileSystemWatcherEngine", + "signals": [ + { + "access": "public", + "arguments": [ + { + "type": "QString" + } + ], + "index": 0, + "name": "driveLockForRemoval", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QString" + } + ], + "index": 1, + "name": "driveLockForRemovalFailed", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QString" + } + ], + "index": 2, + "name": "driveRemoved", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QFileSystemWatcherEngine" + } + ] + }, + { + "className": "QWindowsFileSystemWatcherEngineThread", + "lineNumber": 112, + "object": true, + "qualifiedClassName": "QWindowsFileSystemWatcherEngineThread", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "path", + "type": "QString" + }, + { + "name": "removed", + "type": "bool" + } + ], + "index": 0, + "name": "fileChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "path", + "type": "QString" + }, + { + "name": "removed", + "type": "bool" + } + ], + "index": 1, + "name": "directoryChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QThread" + } + ] + } + ], + "inputFile": "qfilesystemwatcher_win_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QFutureWatcherBase", + "lineNumber": 18, + "object": true, + "qualifiedClassName": "QFutureWatcherBase", + "signals": [ + { + "access": "public", + "index": 0, + "name": "started", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "finished", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "canceled", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "paused", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "suspending", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "suspended", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "resumed", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "resultIndex", + "type": "int" + } + ], + "index": 7, + "name": "resultReadyAt", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "beginIndex", + "type": "int" + }, + { + "name": "endIndex", + "type": "int" + } + ], + "index": 8, + "name": "resultsReadyAt", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "minimum", + "type": "int" + }, + { + "name": "maximum", + "type": "int" + } + ], + "index": 9, + "name": "progressRangeChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "progressValue", + "type": "int" + } + ], + "index": 10, + "name": "progressValueChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "progressText", + "type": "QString" + } + ], + "index": 11, + "name": "progressTextChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "index": 12, + "name": "cancel", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "suspend", + "type": "bool" + } + ], + "index": 13, + "name": "setSuspended", + "returnType": "void" + }, + { + "access": "public", + "index": 14, + "name": "suspend", + "returnType": "void" + }, + { + "access": "public", + "index": 15, + "name": "resume", + "returnType": "void" + }, + { + "access": "public", + "index": 16, + "name": "toggleSuspended", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "paused", + "type": "bool" + } + ], + "index": 17, + "name": "setPaused", + "returnType": "void" + }, + { + "access": "public", + "index": 18, + "name": "pause", + "returnType": "void" + }, + { + "access": "public", + "index": 19, + "name": "togglePaused", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qfuturewatcher.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QIdentityProxyModel", + "lineNumber": 17, + "object": true, + "qualifiedClassName": "QIdentityProxyModel", + "superClasses": [ + { + "access": "public", + "name": "QAbstractProxyModel" + } + ] + } + ], + "inputFile": "qidentityproxymodel.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QIODevice", + "lineNumber": 27, + "object": true, + "qualifiedClassName": "QIODevice", + "signals": [ + { + "access": "public", + "index": 0, + "name": "readyRead", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "channel", + "type": "int" + } + ], + "index": 1, + "name": "channelReadyRead", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "bytes", + "type": "qint64" + } + ], + "index": 2, + "name": "bytesWritten", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "channel", + "type": "int" + }, + { + "name": "bytes", + "type": "qint64" + } + ], + "index": 3, + "name": "channelBytesWritten", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "aboutToClose", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "readChannelFinished", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QIODeviceBase" + } + ] + } + ], + "inputFile": "qiodevice.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QItemSelectionModel", + "enums": [ + { + "alias": "SelectionFlag", + "isClass": false, + "isFlag": true, + "name": "SelectionFlags", + "values": [ + "NoUpdate", + "Clear", + "Select", + "Deselect", + "Toggle", + "Current", + "Rows", + "Columns", + "SelectCurrent", + "ToggleCurrent", + "ClearAndSelect" + ] + } + ], + "lineNumber": 90, + "methods": [ + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "QModelIndex" + } + ], + "index": 12, + "name": "isSelected", + "returnType": "bool" + }, + { + "access": "public", + "arguments": [ + { + "name": "row", + "type": "int" + }, + { + "name": "parent", + "type": "QModelIndex" + } + ], + "index": 13, + "name": "isRowSelected", + "returnType": "bool" + }, + { + "access": "public", + "arguments": [ + { + "name": "row", + "type": "int" + } + ], + "index": 14, + "isCloned": true, + "name": "isRowSelected", + "returnType": "bool" + }, + { + "access": "public", + "arguments": [ + { + "name": "column", + "type": "int" + }, + { + "name": "parent", + "type": "QModelIndex" + } + ], + "index": 15, + "name": "isColumnSelected", + "returnType": "bool" + }, + { + "access": "public", + "arguments": [ + { + "name": "column", + "type": "int" + } + ], + "index": 16, + "isCloned": true, + "name": "isColumnSelected", + "returnType": "bool" + }, + { + "access": "public", + "arguments": [ + { + "name": "row", + "type": "int" + }, + { + "name": "parent", + "type": "QModelIndex" + } + ], + "index": 17, + "name": "rowIntersectsSelection", + "returnType": "bool" + }, + { + "access": "public", + "arguments": [ + { + "name": "row", + "type": "int" + } + ], + "index": 18, + "isCloned": true, + "name": "rowIntersectsSelection", + "returnType": "bool" + }, + { + "access": "public", + "arguments": [ + { + "name": "column", + "type": "int" + }, + { + "name": "parent", + "type": "QModelIndex" + } + ], + "index": 19, + "name": "columnIntersectsSelection", + "returnType": "bool" + }, + { + "access": "public", + "arguments": [ + { + "name": "column", + "type": "int" + } + ], + "index": 20, + "isCloned": true, + "name": "columnIntersectsSelection", + "returnType": "bool" + }, + { + "access": "public", + "arguments": [ + { + "name": "column", + "type": "int" + } + ], + "index": 21, + "name": "selectedRows", + "returnType": "QModelIndexList" + }, + { + "access": "public", + "index": 22, + "isCloned": true, + "name": "selectedRows", + "returnType": "QModelIndexList" + }, + { + "access": "public", + "arguments": [ + { + "name": "row", + "type": "int" + } + ], + "index": 23, + "name": "selectedColumns", + "returnType": "QModelIndexList" + }, + { + "access": "public", + "index": 24, + "isCloned": true, + "name": "selectedColumns", + "returnType": "QModelIndexList" + } + ], + "object": true, + "properties": [ + { + "bindable": "bindableModel", + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "model", + "notify": "modelChanged", + "read": "model", + "required": false, + "scriptable": true, + "stored": true, + "type": "QAbstractItemModel*", + "user": false, + "write": "setModel" + }, + { + "constant": false, + "designable": false, + "final": false, + "index": 1, + "name": "hasSelection", + "notify": "selectionChanged", + "read": "hasSelection", + "required": false, + "scriptable": true, + "stored": false, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": false, + "final": false, + "index": 2, + "name": "currentIndex", + "notify": "currentChanged", + "read": "currentIndex", + "required": false, + "scriptable": true, + "stored": false, + "type": "QModelIndex", + "user": false + }, + { + "constant": false, + "designable": false, + "final": false, + "index": 3, + "name": "selection", + "notify": "selectionChanged", + "read": "selection", + "required": false, + "scriptable": true, + "stored": false, + "type": "QItemSelection", + "user": false + }, + { + "constant": false, + "designable": false, + "final": false, + "index": 4, + "name": "selectedIndexes", + "notify": "selectionChanged", + "read": "selectedIndexes", + "required": false, + "scriptable": true, + "stored": false, + "type": "QModelIndexList", + "user": false + } + ], + "qualifiedClassName": "QItemSelectionModel", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "selected", + "type": "QItemSelection" + }, + { + "name": "deselected", + "type": "QItemSelection" + } + ], + "index": 0, + "name": "selectionChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "current", + "type": "QModelIndex" + }, + { + "name": "previous", + "type": "QModelIndex" + } + ], + "index": 1, + "name": "currentChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "current", + "type": "QModelIndex" + }, + { + "name": "previous", + "type": "QModelIndex" + } + ], + "index": 2, + "name": "currentRowChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "current", + "type": "QModelIndex" + }, + { + "name": "previous", + "type": "QModelIndex" + } + ], + "index": 3, + "name": "currentColumnChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "model", + "type": "QAbstractItemModel*" + } + ], + "index": 4, + "name": "modelChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "QModelIndex" + }, + { + "name": "command", + "type": "QItemSelectionModel::SelectionFlags" + } + ], + "index": 5, + "name": "setCurrentIndex", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "QModelIndex" + }, + { + "name": "command", + "type": "QItemSelectionModel::SelectionFlags" + } + ], + "index": 6, + "name": "select", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "selection", + "type": "QItemSelection" + }, + { + "name": "command", + "type": "QItemSelectionModel::SelectionFlags" + } + ], + "index": 7, + "name": "select", + "returnType": "void" + }, + { + "access": "public", + "index": 8, + "name": "clear", + "returnType": "void" + }, + { + "access": "public", + "index": 9, + "name": "reset", + "returnType": "void" + }, + { + "access": "public", + "index": 10, + "name": "clearSelection", + "returnType": "void" + }, + { + "access": "public", + "index": 11, + "name": "clearCurrentIndex", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qitemselectionmodel.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QLibrary", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "LoadHint", + "values": [ + "ResolveAllSymbolsHint", + "ExportExternalSymbolsHint", + "LoadArchiveMemberHint", + "PreventUnloadHint", + "DeepBindHint" + ] + }, + { + "alias": "LoadHint", + "isClass": false, + "isFlag": true, + "name": "LoadHints", + "values": [ + "ResolveAllSymbolsHint", + "ExportExternalSymbolsHint", + "LoadArchiveMemberHint", + "PreventUnloadHint", + "DeepBindHint" + ] + } + ], + "lineNumber": 16, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "fileName", + "read": "fileName", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setFileName" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "loadHints", + "read": "loadHints", + "required": false, + "scriptable": true, + "stored": true, + "type": "LoadHints", + "user": false, + "write": "setLoadHints" + } + ], + "qualifiedClassName": "QLibrary", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qlibrary.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QLocale", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "Language", + "type": "ushort", + "values": [ + "AnyLanguage", + "C", + "Abkhazian", + "Afar", + "Afrikaans", + "Aghem", + "Akan", + "Akkadian", + "Akoose", + "Albanian", + "AmericanSignLanguage", + "Amharic", + "AncientEgyptian", + "AncientGreek", + "Arabic", + "Aragonese", + "Aramaic", + "Armenian", + "Assamese", + "Asturian", + "Asu", + "Atsam", + "Avaric", + "Avestan", + "Aymara", + "Azerbaijani", + "Bafia", + "Balinese", + "Bambara", + "Bamun", + "Bangla", + "Basaa", + "Bashkir", + "Basque", + "BatakToba", + "Belarusian", + "Bemba", + "Bena", + "Bhojpuri", + "Bislama", + "Blin", + "Bodo", + "Bosnian", + "Breton", + "Buginese", + "Bulgarian", + "Burmese", + "Cantonese", + "Catalan", + "Cebuano", + "CentralAtlasTamazight", + "CentralKurdish", + "Chakma", + "Chamorro", + "Chechen", + "Cherokee", + "Chickasaw", + "Chiga", + "Chinese", + "Church", + "Chuvash", + "Colognian", + "Coptic", + "Cornish", + "Corsican", + "Cree", + "Croatian", + "Czech", + "Danish", + "Divehi", + "Dogri", + "Duala", + "Dutch", + "Dzongkha", + "Embu", + "English", + "Erzya", + "Esperanto", + "Estonian", + "Ewe", + "Ewondo", + "Faroese", + "Fijian", + "Filipino", + "Finnish", + "French", + "Friulian", + "Fulah", + "Gaelic", + "Ga", + "Galician", + "Ganda", + "Geez", + "Georgian", + "German", + "Gothic", + "Greek", + "Guarani", + "Gujarati", + "Gusii", + "Haitian", + "Hausa", + "Hawaiian", + "Hebrew", + "Herero", + "Hindi", + "HiriMotu", + "Hungarian", + "Icelandic", + "Ido", + "Igbo", + "InariSami", + "Indonesian", + "Ingush", + "Interlingua", + "Interlingue", + "Inuktitut", + "Inupiaq", + "Irish", + "Italian", + "Japanese", + "Javanese", + "Jju", + "JolaFonyi", + "Kabuverdianu", + "Kabyle", + "Kako", + "Kalaallisut", + "Kalenjin", + "Kamba", + "Kannada", + "Kanuri", + "Kashmiri", + "Kazakh", + "Kenyang", + "Khmer", + "Kiche", + "Kikuyu", + "Kinyarwanda", + "Komi", + "Kongo", + "Konkani", + "Korean", + "Koro", + "KoyraboroSenni", + "KoyraChiini", + "Kpelle", + "Kuanyama", + "Kurdish", + "Kwasio", + "Kyrgyz", + "Lakota", + "Langi", + "Lao", + "Latin", + "Latvian", + "Lezghian", + "Limburgish", + "Lingala", + "LiteraryChinese", + "Lithuanian", + "Lojban", + "LowerSorbian", + "LowGerman", + "LubaKatanga", + "LuleSami", + "Luo", + "Luxembourgish", + "Luyia", + "Macedonian", + "Machame", + "Maithili", + "MakhuwaMeetto", + "Makonde", + "Malagasy", + "Malayalam", + "Malay", + "Maltese", + "Mandingo", + "Manipuri", + "Manx", + "Maori", + "Mapuche", + "Marathi", + "Marshallese", + "Masai", + "Mazanderani", + "Mende", + "Meru", + "Meta", + "Mohawk", + "Mongolian", + "Morisyen", + "Mundang", + "Muscogee", + "Nama", + "NauruLanguage", + "Navajo", + "Ndonga", + "Nepali", + "Newari", + "Ngiemboon", + "Ngomba", + "NigerianPidgin", + "Nko", + "NorthernLuri", + "NorthernSami", + "NorthernSotho", + "NorthNdebele", + "NorwegianBokmal", + "NorwegianNynorsk", + "Nuer", + "Nyanja", + "Nyankole", + "Occitan", + "Odia", + "Ojibwa", + "OldIrish", + "OldNorse", + "OldPersian", + "Oromo", + "Osage", + "Ossetic", + "Pahlavi", + "Palauan", + "Pali", + "Papiamento", + "Pashto", + "Persian", + "Phoenician", + "Polish", + "Portuguese", + "Prussian", + "Punjabi", + "Quechua", + "Romanian", + "Romansh", + "Rombo", + "Rundi", + "Russian", + "Rwa", + "Saho", + "Sakha", + "Samburu", + "Samoan", + "Sango", + "Sangu", + "Sanskrit", + "Santali", + "Sardinian", + "Saurashtra", + "Sena", + "Serbian", + "Shambala", + "Shona", + "SichuanYi", + "Sicilian", + "Sidamo", + "Silesian", + "Sindhi", + "Sinhala", + "SkoltSami", + "Slovak", + "Slovenian", + "Soga", + "Somali", + "SouthernKurdish", + "SouthernSami", + "SouthernSotho", + "SouthNdebele", + "Spanish", + "StandardMoroccanTamazight", + "Sundanese", + "Swahili", + "Swati", + "Swedish", + "SwissGerman", + "Syriac", + "Tachelhit", + "Tahitian", + "TaiDam", + "Taita", + "Tajik", + "Tamil", + "Taroko", + "Tasawaq", + "Tatar", + "Telugu", + "Teso", + "Thai", + "Tibetan", + "Tigre", + "Tigrinya", + "TokelauLanguage", + "TokPisin", + "Tongan", + "Tsonga", + "Tswana", + "Turkish", + "Turkmen", + "TuvaluLanguage", + "Tyap", + "Ugaritic", + "Ukrainian", + "UpperSorbian", + "Urdu", + "Uyghur", + "Uzbek", + "Vai", + "Venda", + "Vietnamese", + "Volapuk", + "Vunjo", + "Walloon", + "Walser", + "Warlpiri", + "Welsh", + "WesternBalochi", + "WesternFrisian", + "Wolaytta", + "Wolof", + "Xhosa", + "Yangben", + "Yiddish", + "Yoruba", + "Zarma", + "Zhuang", + "Zulu", + "Kaingang", + "Nheengatu", + "Haryanvi", + "NorthernFrisian", + "Rajasthani", + "Moksha", + "TokiPona", + "Pijin", + "Obolo", + "Baluchi", + "Ligurian", + "Rohingya", + "Torwali", + "Anii", + "Kangri", + "Venetian", + "Kuvi", + "Afan", + "Bengali", + "Bhutani", + "Byelorussian", + "Cambodian", + "CentralMoroccoTamazight", + "Chewa", + "Frisian", + "Greenlandic", + "Inupiak", + "Kirghiz", + "Kurundi", + "Kwanyama", + "Navaho", + "Oriya", + "RhaetoRomance", + "Uighur", + "Uigur", + "Walamo", + "LastLanguage" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "Script", + "type": "ushort", + "values": [ + "AnyScript", + "AdlamScript", + "AhomScript", + "AnatolianHieroglyphsScript", + "ArabicScript", + "ArmenianScript", + "AvestanScript", + "BalineseScript", + "BamumScript", + "BanglaScript", + "BassaVahScript", + "BatakScript", + "BhaiksukiScript", + "BopomofoScript", + "BrahmiScript", + "BrailleScript", + "BugineseScript", + "BuhidScript", + "CanadianAboriginalScript", + "CarianScript", + "CaucasianAlbanianScript", + "ChakmaScript", + "ChamScript", + "CherokeeScript", + "CopticScript", + "CuneiformScript", + "CypriotScript", + "CyrillicScript", + "DeseretScript", + "DevanagariScript", + "DuployanScript", + "EgyptianHieroglyphsScript", + "ElbasanScript", + "EthiopicScript", + "FraserScript", + "GeorgianScript", + "GlagoliticScript", + "GothicScript", + "GranthaScript", + "GreekScript", + "GujaratiScript", + "GurmukhiScript", + "HangulScript", + "HanScript", + "HanunooScript", + "HanWithBopomofoScript", + "HatranScript", + "HebrewScript", + "HiraganaScript", + "ImperialAramaicScript", + "InscriptionalPahlaviScript", + "InscriptionalParthianScript", + "JamoScript", + "JapaneseScript", + "JavaneseScript", + "KaithiScript", + "KannadaScript", + "KatakanaScript", + "KayahLiScript", + "KharoshthiScript", + "KhmerScript", + "KhojkiScript", + "KhudawadiScript", + "KoreanScript", + "LannaScript", + "LaoScript", + "LatinScript", + "LepchaScript", + "LimbuScript", + "LinearAScript", + "LinearBScript", + "LycianScript", + "LydianScript", + "MahajaniScript", + "MalayalamScript", + "MandaeanScript", + "ManichaeanScript", + "MarchenScript", + "MeiteiMayekScript", + "MendeScript", + "MeroiticCursiveScript", + "MeroiticScript", + "ModiScript", + "MongolianScript", + "MroScript", + "MultaniScript", + "MyanmarScript", + "NabataeanScript", + "NewaScript", + "NewTaiLueScript", + "NkoScript", + "OdiaScript", + "OghamScript", + "OlChikiScript", + "OldHungarianScript", + "OldItalicScript", + "OldNorthArabianScript", + "OldPermicScript", + "OldPersianScript", + "OldSouthArabianScript", + "OrkhonScript", + "OsageScript", + "OsmanyaScript", + "PahawhHmongScript", + "PalmyreneScript", + "PauCinHauScript", + "PhagsPaScript", + "PhoenicianScript", + "PollardPhoneticScript", + "PsalterPahlaviScript", + "RejangScript", + "RunicScript", + "SamaritanScript", + "SaurashtraScript", + "SharadaScript", + "ShavianScript", + "SiddhamScript", + "SignWritingScript", + "SimplifiedHanScript", + "SinhalaScript", + "SoraSompengScript", + "SundaneseScript", + "SylotiNagriScript", + "SyriacScript", + "TagalogScript", + "TagbanwaScript", + "TaiLeScript", + "TaiVietScript", + "TakriScript", + "TamilScript", + "TangutScript", + "TeluguScript", + "ThaanaScript", + "ThaiScript", + "TibetanScript", + "TifinaghScript", + "TirhutaScript", + "TraditionalHanScript", + "UgariticScript", + "VaiScript", + "VarangKshitiScript", + "YiScript", + "HanifiScript", + "BengaliScript", + "MendeKikakuiScript", + "OriyaScript", + "SimplifiedChineseScript", + "TraditionalChineseScript", + "LastScript" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "Country", + "type": "ushort", + "values": [ + "AnyTerritory", + "Afghanistan", + "AlandIslands", + "Albania", + "Algeria", + "AmericanSamoa", + "Andorra", + "Angola", + "Anguilla", + "Antarctica", + "AntiguaAndBarbuda", + "Argentina", + "Armenia", + "Aruba", + "AscensionIsland", + "Australia", + "Austria", + "Azerbaijan", + "Bahamas", + "Bahrain", + "Bangladesh", + "Barbados", + "Belarus", + "Belgium", + "Belize", + "Benin", + "Bermuda", + "Bhutan", + "Bolivia", + "BosniaAndHerzegovina", + "Botswana", + "BouvetIsland", + "Brazil", + "BritishIndianOceanTerritory", + "BritishVirginIslands", + "Brunei", + "Bulgaria", + "BurkinaFaso", + "Burundi", + "Cambodia", + "Cameroon", + "Canada", + "CanaryIslands", + "CapeVerde", + "CaribbeanNetherlands", + "CaymanIslands", + "CentralAfricanRepublic", + "CeutaAndMelilla", + "Chad", + "Chile", + "China", + "ChristmasIsland", + "ClippertonIsland", + "CocosIslands", + "Colombia", + "Comoros", + "CongoBrazzaville", + "CongoKinshasa", + "CookIslands", + "CostaRica", + "Croatia", + "Cuba", + "Curacao", + "Cyprus", + "Czechia", + "Denmark", + "DiegoGarcia", + "Djibouti", + "Dominica", + "DominicanRepublic", + "Ecuador", + "Egypt", + "ElSalvador", + "EquatorialGuinea", + "Eritrea", + "Estonia", + "Eswatini", + "Ethiopia", + "Europe", + "EuropeanUnion", + "FalklandIslands", + "FaroeIslands", + "Fiji", + "Finland", + "France", + "FrenchGuiana", + "FrenchPolynesia", + "FrenchSouthernTerritories", + "Gabon", + "Gambia", + "Georgia", + "Germany", + "Ghana", + "Gibraltar", + "Greece", + "Greenland", + "Grenada", + "Guadeloupe", + "Guam", + "Guatemala", + "Guernsey", + "GuineaBissau", + "Guinea", + "Guyana", + "Haiti", + "HeardAndMcDonaldIslands", + "Honduras", + "HongKong", + "Hungary", + "Iceland", + "India", + "Indonesia", + "Iran", + "Iraq", + "Ireland", + "IsleOfMan", + "Israel", + "Italy", + "IvoryCoast", + "Jamaica", + "Japan", + "Jersey", + "Jordan", + "Kazakhstan", + "Kenya", + "Kiribati", + "Kosovo", + "Kuwait", + "Kyrgyzstan", + "Laos", + "LatinAmerica", + "Latvia", + "Lebanon", + "Lesotho", + "Liberia", + "Libya", + "Liechtenstein", + "Lithuania", + "Luxembourg", + "Macao", + "Macedonia", + "Madagascar", + "Malawi", + "Malaysia", + "Maldives", + "Mali", + "Malta", + "MarshallIslands", + "Martinique", + "Mauritania", + "Mauritius", + "Mayotte", + "Mexico", + "Micronesia", + "Moldova", + "Monaco", + "Mongolia", + "Montenegro", + "Montserrat", + "Morocco", + "Mozambique", + "Myanmar", + "Namibia", + "NauruTerritory", + "Nepal", + "Netherlands", + "NewCaledonia", + "NewZealand", + "Nicaragua", + "Nigeria", + "Niger", + "Niue", + "NorfolkIsland", + "NorthernMarianaIslands", + "NorthKorea", + "Norway", + "Oman", + "OutlyingOceania", + "Pakistan", + "Palau", + "PalestinianTerritories", + "Panama", + "PapuaNewGuinea", + "Paraguay", + "Peru", + "Philippines", + "Pitcairn", + "Poland", + "Portugal", + "PuertoRico", + "Qatar", + "Reunion", + "Romania", + "Russia", + "Rwanda", + "SaintBarthelemy", + "SaintHelena", + "SaintKittsAndNevis", + "SaintLucia", + "SaintMartin", + "SaintPierreAndMiquelon", + "SaintVincentAndGrenadines", + "Samoa", + "SanMarino", + "SaoTomeAndPrincipe", + "SaudiArabia", + "Senegal", + "Serbia", + "Seychelles", + "SierraLeone", + "Singapore", + "SintMaarten", + "Slovakia", + "Slovenia", + "SolomonIslands", + "Somalia", + "SouthAfrica", + "SouthGeorgiaAndSouthSandwichIslands", + "SouthKorea", + "SouthSudan", + "Spain", + "SriLanka", + "Sudan", + "Suriname", + "SvalbardAndJanMayen", + "Sweden", + "Switzerland", + "Syria", + "Taiwan", + "Tajikistan", + "Tanzania", + "Thailand", + "TimorLeste", + "Togo", + "TokelauTerritory", + "Tonga", + "TrinidadAndTobago", + "TristanDaCunha", + "Tunisia", + "Turkey", + "Turkmenistan", + "TurksAndCaicosIslands", + "TuvaluTerritory", + "Uganda", + "Ukraine", + "UnitedArabEmirates", + "UnitedKingdom", + "UnitedStatesOutlyingIslands", + "UnitedStates", + "UnitedStatesVirginIslands", + "Uruguay", + "Uzbekistan", + "Vanuatu", + "VaticanCity", + "Venezuela", + "Vietnam", + "WallisAndFutuna", + "WesternSahara", + "World", + "Yemen", + "Zambia", + "Zimbabwe", + "AnyCountry", + "Bonaire", + "BosniaAndHerzegowina", + "CuraSao", + "CzechRepublic", + "DemocraticRepublicOfCongo", + "DemocraticRepublicOfKorea", + "EastTimor", + "LatinAmericaAndTheCaribbean", + "Macau", + "NauruCountry", + "PeoplesRepublicOfCongo", + "RepublicOfKorea", + "RussianFederation", + "SaintVincentAndTheGrenadines", + "SouthGeorgiaAndTheSouthSandwichIslands", + "SvalbardAndJanMayenIslands", + "Swaziland", + "SyrianArabRepublic", + "TokelauCountry", + "TuvaluCountry", + "UnitedStatesMinorOutlyingIslands", + "VaticanCityState", + "WallisAndFutunaIslands", + "LastTerritory", + "LastCountry" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "MeasurementSystem", + "values": [ + "MetricSystem", + "ImperialUSSystem", + "ImperialUKSystem", + "ImperialSystem" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "FormatType", + "values": [ + "LongFormat", + "ShortFormat", + "NarrowFormat" + ] + }, + { + "alias": "NumberOption", + "isClass": false, + "isFlag": true, + "name": "NumberOptions", + "values": [ + "DefaultNumberOptions", + "OmitGroupSeparator", + "RejectGroupSeparator", + "OmitLeadingZeroInExponent", + "RejectLeadingZeroInExponent", + "IncludeTrailingZeroesAfterDot", + "RejectTrailingZeroesAfterDot" + ] + }, + { + "isClass": true, + "isFlag": false, + "name": "TagSeparator", + "type": "char", + "values": [ + "Dash", + "Underscore" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "CurrencySymbolFormat", + "values": [ + "CurrencyIsoCode", + "CurrencySymbol", + "CurrencyDisplayName" + ] + }, + { + "alias": "DataSizeFormat", + "isClass": false, + "isFlag": true, + "name": "DataSizeFormats", + "values": [ + "DataSizeBase1000", + "DataSizeSIQuantifiers", + "DataSizeIecFormat", + "DataSizeTraditionalFormat", + "DataSizeSIFormat" + ] + }, + { + "alias": "LanguageCodeType", + "isClass": false, + "isFlag": true, + "name": "LanguageCodeTypes", + "values": [ + "ISO639Part1", + "ISO639Part2B", + "ISO639Part2T", + "ISO639Part3", + "LegacyLanguageCode", + "ISO639Part2", + "ISO639Alpha2", + "ISO639Alpha3", + "ISO639", + "AnyLanguageCode" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "QuotationStyle", + "values": [ + "StandardQuotation", + "AlternateQuotation" + ] + } + ], + "gadget": true, + "lineNumber": 28, + "qualifiedClassName": "QLocale" + } + ], + "inputFile": "qlocale.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QMimeData", + "lineNumber": 15, + "object": true, + "qualifiedClassName": "QMimeData", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qmimedata.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QMimeType", + "gadget": true, + "lineNumber": 24, + "methods": [ + { + "access": "public", + "arguments": [ + { + "name": "mimeTypeName", + "type": "QString" + } + ], + "index": 0, + "name": "inherits", + "returnType": "bool" + } + ], + "properties": [ + { + "constant": true, + "designable": true, + "final": false, + "index": 0, + "name": "valid", + "read": "isValid", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 1, + "name": "isDefault", + "read": "isDefault", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 2, + "name": "name", + "read": "name", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 3, + "name": "comment", + "read": "comment", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 4, + "name": "genericIconName", + "read": "genericIconName", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 5, + "name": "iconName", + "read": "iconName", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 6, + "name": "globPatterns", + "read": "globPatterns", + "required": false, + "scriptable": true, + "stored": true, + "type": "QStringList", + "user": false + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 7, + "name": "parentMimeTypes", + "read": "parentMimeTypes", + "required": false, + "scriptable": true, + "stored": true, + "type": "QStringList", + "user": false + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 8, + "name": "allAncestors", + "read": "allAncestors", + "required": false, + "scriptable": true, + "stored": true, + "type": "QStringList", + "user": false + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 9, + "name": "aliases", + "read": "aliases", + "required": false, + "scriptable": true, + "stored": true, + "type": "QStringList", + "user": false + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 10, + "name": "suffixes", + "read": "suffixes", + "required": false, + "scriptable": true, + "stored": true, + "type": "QStringList", + "user": false + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 11, + "name": "preferredSuffix", + "read": "preferredSuffix", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 12, + "name": "filterString", + "read": "filterString", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + } + ], + "qualifiedClassName": "QMimeType" + } + ], + "inputFile": "qmimetype.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QNonContiguousByteDevice", + "lineNumber": 28, + "object": true, + "qualifiedClassName": "QNonContiguousByteDevice", + "signals": [ + { + "access": "public", + "index": 0, + "name": "readyRead", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "current", + "type": "qint64" + }, + { + "name": "total", + "type": "qint64" + } + ], + "index": 1, + "name": "readProgress", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "className": "QNonContiguousByteDeviceByteArrayImpl", + "lineNumber": 67, + "object": true, + "qualifiedClassName": "QNonContiguousByteDeviceByteArrayImpl", + "superClasses": [ + { + "access": "public", + "name": "QNonContiguousByteDevice" + } + ] + }, + { + "className": "QNonContiguousByteDeviceRingBufferImpl", + "lineNumber": 85, + "object": true, + "qualifiedClassName": "QNonContiguousByteDeviceRingBufferImpl", + "superClasses": [ + { + "access": "public", + "name": "QNonContiguousByteDevice" + } + ] + }, + { + "className": "QNonContiguousByteDeviceIoDeviceImpl", + "lineNumber": 103, + "object": true, + "qualifiedClassName": "QNonContiguousByteDeviceIoDeviceImpl", + "superClasses": [ + { + "access": "public", + "name": "QNonContiguousByteDevice" + } + ] + }, + { + "className": "QNonContiguousByteDeviceBufferImpl", + "lineNumber": 127, + "object": true, + "qualifiedClassName": "QNonContiguousByteDeviceBufferImpl", + "superClasses": [ + { + "access": "public", + "name": "QNonContiguousByteDevice" + } + ] + }, + { + "className": "QByteDeviceWrappingIoDevice", + "lineNumber": 145, + "object": true, + "qualifiedClassName": "QByteDeviceWrappingIoDevice", + "superClasses": [ + { + "access": "public", + "name": "QIODevice" + } + ] + } + ], + "inputFile": "qnoncontiguousbytedevice_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QObjectCleanupHandler", + "lineNumber": 11, + "object": true, + "qualifiedClassName": "QObjectCleanupHandler", + "slots": [ + { + "access": "private", + "arguments": [ + { + "type": "QObject*" + } + ], + "index": 0, + "name": "objectDestroyed", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qobjectcleanuphandler.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QParallelAnimationGroup", + "lineNumber": 14, + "object": true, + "qualifiedClassName": "QParallelAnimationGroup", + "slots": [ + { + "access": "private", + "index": 0, + "name": "_q_uncontrolledAnimationFinished", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QAnimationGroup" + } + ] + } + ], + "inputFile": "qparallelanimationgroup.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QPauseAnimation", + "lineNumber": 15, + "object": true, + "properties": [ + { + "bindable": "bindableDuration", + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "duration", + "read": "duration", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setDuration" + } + ], + "qualifiedClassName": "QPauseAnimation", + "superClasses": [ + { + "access": "public", + "name": "QAbstractAnimation" + } + ] + } + ], + "inputFile": "qpauseanimation.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QLocationPermission", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "Accuracy", + "type": "quint8", + "values": [ + "Approximate", + "Precise" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "Availability", + "type": "quint8", + "values": [ + "WhenInUse", + "Always" + ] + } + ], + "gadget": true, + "lineNumber": 98, + "qualifiedClassName": "QLocationPermission" + }, + { + "className": "QCalendarPermission", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "AccessMode", + "type": "quint8", + "values": [ + "ReadOnly", + "ReadWrite" + ] + } + ], + "gadget": true, + "lineNumber": 131, + "qualifiedClassName": "QCalendarPermission" + }, + { + "className": "QContactsPermission", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "AccessMode", + "type": "quint8", + "values": [ + "ReadOnly", + "ReadWrite" + ] + } + ], + "gadget": true, + "lineNumber": 154, + "qualifiedClassName": "QContactsPermission" + }, + { + "className": "QBluetoothPermission", + "enums": [ + { + "alias": "CommunicationMode", + "isClass": false, + "isFlag": true, + "name": "CommunicationModes", + "type": "quint8", + "values": [ + "Access", + "Advertise", + "Default" + ] + } + ], + "gadget": true, + "lineNumber": 177, + "qualifiedClassName": "QBluetoothPermission" + } + ], + "inputFile": "qpermissions.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QPluginLoader", + "lineNumber": 20, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "fileName", + "read": "fileName", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setFileName" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "loadHints", + "read": "loadHints", + "required": false, + "scriptable": true, + "stored": true, + "type": "QLibrary::LoadHints", + "user": false, + "write": "setLoadHints" + } + ], + "qualifiedClassName": "QPluginLoader", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qpluginloader.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QProcess", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "ProcessError", + "values": [ + "FailedToStart", + "Crashed", + "Timedout", + "ReadError", + "WriteError", + "UnknownError" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "ProcessState", + "values": [ + "NotRunning", + "Starting", + "Running" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "ProcessChannel", + "values": [ + "StandardOutput", + "StandardError" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "ProcessChannelMode", + "values": [ + "SeparateChannels", + "MergedChannels", + "ForwardedChannels", + "ForwardedOutputChannel", + "ForwardedErrorChannel" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "InputChannelMode", + "values": [ + "ManagedInputChannel", + "ForwardedInputChannel" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "ExitStatus", + "values": [ + "NormalExit", + "CrashExit" + ] + } + ], + "lineNumber": 81, + "object": true, + "qualifiedClassName": "QProcess", + "signals": [ + { + "access": "public", + "index": 0, + "name": "started", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "exitCode", + "type": "int" + }, + { + "name": "exitStatus", + "type": "QProcess::ExitStatus" + } + ], + "index": 1, + "name": "finished", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "exitCode", + "type": "int" + } + ], + "index": 2, + "isCloned": true, + "name": "finished", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "error", + "type": "QProcess::ProcessError" + } + ], + "index": 3, + "name": "errorOccurred", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "state", + "type": "QProcess::ProcessState" + } + ], + "index": 4, + "name": "stateChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "readyReadStandardOutput", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "readyReadStandardError", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "index": 7, + "name": "terminate", + "returnType": "void" + }, + { + "access": "public", + "index": 8, + "name": "kill", + "returnType": "void" + }, + { + "access": "private", + "index": 9, + "name": "_q_canReadStandardOutput", + "returnType": "bool" + }, + { + "access": "private", + "index": 10, + "name": "_q_canReadStandardError", + "returnType": "bool" + }, + { + "access": "private", + "index": 11, + "name": "_q_startupNotification", + "returnType": "bool" + }, + { + "access": "private", + "index": 12, + "name": "_q_processDied", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QIODevice" + } + ] + } + ], + "inputFile": "qprocess.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QPropertyAnimation", + "lineNumber": 14, + "object": true, + "properties": [ + { + "bindable": "bindablePropertyName", + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "propertyName", + "read": "propertyName", + "required": false, + "scriptable": true, + "stored": true, + "type": "QByteArray", + "user": false, + "write": "setPropertyName" + }, + { + "bindable": "bindableTargetObject", + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "targetObject", + "read": "targetObject", + "required": false, + "scriptable": true, + "stored": true, + "type": "QObject*", + "user": false, + "write": "setTargetObject" + } + ], + "qualifiedClassName": "QPropertyAnimation", + "superClasses": [ + { + "access": "public", + "name": "QVariantAnimation" + } + ] + } + ], + "inputFile": "qpropertyanimation.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QSaveFile", + "lineNumber": 23, + "object": true, + "qualifiedClassName": "QSaveFile", + "superClasses": [ + { + "access": "public", + "name": "QFileDevice" + } + ] + } + ], + "inputFile": "qsavefile.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QSequentialAnimationGroup", + "lineNumber": 16, + "object": true, + "properties": [ + { + "bindable": "bindableCurrentAnimation", + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "currentAnimation", + "notify": "currentAnimationChanged", + "read": "currentAnimation", + "required": false, + "scriptable": true, + "stored": true, + "type": "QAbstractAnimation*", + "user": false + } + ], + "qualifiedClassName": "QSequentialAnimationGroup", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "current", + "type": "QAbstractAnimation*" + } + ], + "index": 0, + "name": "currentAnimationChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "private", + "index": 1, + "name": "_q_uncontrolledAnimationFinished", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QAnimationGroup" + } + ] + } + ], + "inputFile": "qsequentialanimationgroup.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QSettings", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "Status", + "values": [ + "NoError", + "AccessError", + "FormatError" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "Format", + "values": [ + "NativeFormat", + "IniFormat", + "Registry32Format", + "Registry64Format", + "InvalidFormat", + "CustomFormat1", + "CustomFormat2", + "CustomFormat3", + "CustomFormat4", + "CustomFormat5", + "CustomFormat6", + "CustomFormat7", + "CustomFormat8", + "CustomFormat9", + "CustomFormat10", + "CustomFormat11", + "CustomFormat12", + "CustomFormat13", + "CustomFormat14", + "CustomFormat15", + "CustomFormat16" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "Scope", + "values": [ + "UserScope", + "SystemScope" + ] + } + ], + "lineNumber": 26, + "object": true, + "qualifiedClassName": "QSettings", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qsettings.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QSharedMemory", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "AccessMode", + "values": [ + "ReadOnly", + "ReadWrite" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "SharedMemoryError", + "values": [ + "NoError", + "PermissionDenied", + "InvalidSize", + "KeyError", + "AlreadyExists", + "NotFound", + "LockError", + "OutOfResources", + "UnknownError" + ] + } + ], + "lineNumber": 22, + "object": true, + "qualifiedClassName": "QSharedMemory", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qsharedmemory.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QSignalMapper", + "lineNumber": 13, + "object": true, + "qualifiedClassName": "QSignalMapper", + "signals": [ + { + "access": "public", + "arguments": [ + { + "type": "int" + } + ], + "index": 0, + "name": "mappedInt", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QString" + } + ], + "index": 1, + "name": "mappedString", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QObject*" + } + ], + "index": 2, + "name": "mappedObject", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "index": 3, + "name": "map", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "sender", + "type": "QObject*" + } + ], + "index": 4, + "name": "map", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qsignalmapper.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QSingleShotTimer", + "lineNumber": 29, + "object": true, + "qualifiedClassName": "QSingleShotTimer", + "signals": [ + { + "access": "public", + "index": 0, + "name": "timeout", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qsingleshottimer_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QSocketNotifier", + "lineNumber": 13, + "object": true, + "qualifiedClassName": "QSocketNotifier", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "socket", + "type": "QSocketDescriptor" + }, + { + "name": "activationEvent", + "type": "QSocketNotifier::Type" + } + ], + "index": 0, + "name": "activated", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "socket", + "type": "QSocketDescriptor" + } + ], + "index": 1, + "isCloned": true, + "name": "activated", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "socket", + "type": "int" + } + ], + "index": 2, + "name": "activated", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "type": "bool" + } + ], + "index": 3, + "name": "setEnabled", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qsocketnotifier.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QSortFilterProxyModel", + "lineNumber": 20, + "object": true, + "properties": [ + { + "bindable": "bindableFilterRegularExpression", + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "filterRegularExpression", + "read": "filterRegularExpression", + "required": false, + "scriptable": true, + "stored": true, + "type": "QRegularExpression", + "user": false, + "write": "setFilterRegularExpression" + }, + { + "bindable": "bindableFilterKeyColumn", + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "filterKeyColumn", + "read": "filterKeyColumn", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setFilterKeyColumn" + }, + { + "bindable": "bindableDynamicSortFilter", + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "dynamicSortFilter", + "read": "dynamicSortFilter", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setDynamicSortFilter" + }, + { + "bindable": "bindableFilterCaseSensitivity", + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "filterCaseSensitivity", + "notify": "filterCaseSensitivityChanged", + "read": "filterCaseSensitivity", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::CaseSensitivity", + "user": false, + "write": "setFilterCaseSensitivity" + }, + { + "bindable": "bindableSortCaseSensitivity", + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "sortCaseSensitivity", + "notify": "sortCaseSensitivityChanged", + "read": "sortCaseSensitivity", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::CaseSensitivity", + "user": false, + "write": "setSortCaseSensitivity" + }, + { + "bindable": "bindableIsSortLocaleAware", + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "isSortLocaleAware", + "notify": "sortLocaleAwareChanged", + "read": "isSortLocaleAware", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setSortLocaleAware" + }, + { + "bindable": "bindableSortRole", + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "sortRole", + "notify": "sortRoleChanged", + "read": "sortRole", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setSortRole" + }, + { + "bindable": "bindableFilterRole", + "constant": false, + "designable": true, + "final": false, + "index": 7, + "name": "filterRole", + "notify": "filterRoleChanged", + "read": "filterRole", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setFilterRole" + }, + { + "bindable": "bindableRecursiveFilteringEnabled", + "constant": false, + "designable": true, + "final": false, + "index": 8, + "name": "recursiveFilteringEnabled", + "notify": "recursiveFilteringEnabledChanged", + "read": "isRecursiveFilteringEnabled", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setRecursiveFilteringEnabled" + }, + { + "bindable": "bindableAutoAcceptChildRows", + "constant": false, + "designable": true, + "final": false, + "index": 9, + "name": "autoAcceptChildRows", + "notify": "autoAcceptChildRowsChanged", + "read": "autoAcceptChildRows", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setAutoAcceptChildRows" + } + ], + "qualifiedClassName": "QSortFilterProxyModel", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "dynamicSortFilter", + "type": "bool" + } + ], + "index": 0, + "name": "dynamicSortFilterChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "filterCaseSensitivity", + "type": "Qt::CaseSensitivity" + } + ], + "index": 1, + "name": "filterCaseSensitivityChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "sortCaseSensitivity", + "type": "Qt::CaseSensitivity" + } + ], + "index": 2, + "name": "sortCaseSensitivityChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "sortLocaleAware", + "type": "bool" + } + ], + "index": 3, + "name": "sortLocaleAwareChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "sortRole", + "type": "int" + } + ], + "index": 4, + "name": "sortRoleChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "filterRole", + "type": "int" + } + ], + "index": 5, + "name": "filterRoleChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "recursiveFilteringEnabled", + "type": "bool" + } + ], + "index": 6, + "name": "recursiveFilteringEnabledChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "autoAcceptChildRows", + "type": "bool" + } + ], + "index": 7, + "name": "autoAcceptChildRowsChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "pattern", + "type": "QString" + } + ], + "index": 8, + "name": "setFilterRegularExpression", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "regularExpression", + "type": "QRegularExpression" + } + ], + "index": 9, + "name": "setFilterRegularExpression", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "pattern", + "type": "QString" + } + ], + "index": 10, + "name": "setFilterWildcard", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "pattern", + "type": "QString" + } + ], + "index": 11, + "name": "setFilterFixedString", + "returnType": "void" + }, + { + "access": "public", + "index": 12, + "name": "invalidate", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QAbstractProxyModel" + } + ] + } + ], + "inputFile": "qsortfilterproxymodel.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QStandardPaths", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "StandardLocation", + "values": [ + "DesktopLocation", + "DocumentsLocation", + "FontsLocation", + "ApplicationsLocation", + "MusicLocation", + "MoviesLocation", + "PicturesLocation", + "TempLocation", + "HomeLocation", + "AppLocalDataLocation", + "CacheLocation", + "GenericDataLocation", + "RuntimeLocation", + "ConfigLocation", + "DownloadLocation", + "GenericCacheLocation", + "GenericConfigLocation", + "AppDataLocation", + "AppConfigLocation", + "PublicShareLocation", + "TemplatesLocation", + "StateLocation", + "GenericStateLocation" + ] + }, + { + "alias": "LocateOption", + "isClass": false, + "isFlag": true, + "name": "LocateOptions", + "values": [ + "LocateFile", + "LocateDirectory" + ] + } + ], + "gadget": true, + "lineNumber": 15, + "qualifiedClassName": "QStandardPaths" + } + ], + "inputFile": "qstandardpaths.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QStringListModel", + "lineNumber": 14, + "object": true, + "qualifiedClassName": "QStringListModel", + "superClasses": [ + { + "access": "public", + "name": "QAbstractListModel" + } + ] + } + ], + "inputFile": "qstringlistmodel.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QSystemSemaphore", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "AccessMode", + "values": [ + "Open", + "Create" + ] + } + ], + "gadget": true, + "lineNumber": 18, + "qualifiedClassName": "QSystemSemaphore" + } + ], + "inputFile": "qsystemsemaphore.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QTemporaryFile", + "lineNumber": 22, + "object": true, + "qualifiedClassName": "QTemporaryFile", + "superClasses": [ + { + "access": "public", + "name": "QFile" + } + ] + } + ], + "inputFile": "qtemporaryfile.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QDeviceClosedNotifier", + "lineNumber": 28, + "object": true, + "qualifiedClassName": "QDeviceClosedNotifier", + "slots": [ + { + "access": "public", + "index": 0, + "name": "flushStream", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qtextstream_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QThread", + "lineNumber": 27, + "object": true, + "qualifiedClassName": "QThread", + "signals": [ + { + "access": "public", + "index": 0, + "name": "started", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "finished", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "type": "Priority" + } + ], + "index": 2, + "name": "start", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "isCloned": true, + "name": "start", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "terminate", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "retcode", + "type": "int" + } + ], + "index": 5, + "name": "exit", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "isCloned": true, + "name": "exit", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "quit", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qthread.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QThreadPool", + "lineNumber": 21, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "expiryTimeout", + "read": "expiryTimeout", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setExpiryTimeout" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "maxThreadCount", + "read": "maxThreadCount", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setMaxThreadCount" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "activeThreadCount", + "read": "activeThreadCount", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "stackSize", + "read": "stackSize", + "required": false, + "scriptable": true, + "stored": true, + "type": "uint", + "user": false, + "write": "setStackSize" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "threadPriority", + "read": "threadPriority", + "required": false, + "scriptable": true, + "stored": true, + "type": "QThread::Priority", + "user": false, + "write": "setThreadPriority" + } + ], + "qualifiedClassName": "QThreadPool", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qthreadpool.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QTimeLine", + "lineNumber": 18, + "object": true, + "properties": [ + { + "bindable": "bindableDuration", + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "duration", + "read": "duration", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setDuration" + }, + { + "bindable": "bindableUpdateInterval", + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "updateInterval", + "read": "updateInterval", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setUpdateInterval" + }, + { + "bindable": "bindableCurrentTime", + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "currentTime", + "read": "currentTime", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setCurrentTime" + }, + { + "bindable": "bindableDirection", + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "direction", + "read": "direction", + "required": false, + "scriptable": true, + "stored": true, + "type": "Direction", + "user": false, + "write": "setDirection" + }, + { + "bindable": "bindableLoopCount", + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "loopCount", + "read": "loopCount", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setLoopCount" + }, + { + "bindable": "bindableEasingCurve", + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "easingCurve", + "read": "easingCurve", + "required": false, + "scriptable": true, + "stored": true, + "type": "QEasingCurve", + "user": false, + "write": "setEasingCurve" + } + ], + "qualifiedClassName": "QTimeLine", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "x", + "type": "qreal" + } + ], + "index": 0, + "name": "valueChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "int" + } + ], + "index": 1, + "name": "frameChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "newState", + "type": "QTimeLine::State" + } + ], + "index": 2, + "name": "stateChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "finished", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "index": 4, + "name": "start", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "resume", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "stop", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "paused", + "type": "bool" + } + ], + "index": 7, + "name": "setPaused", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "msec", + "type": "int" + } + ], + "index": 8, + "name": "setCurrentTime", + "returnType": "void" + }, + { + "access": "public", + "index": 9, + "name": "toggleDirection", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qtimeline.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QTimer", + "lineNumber": 19, + "object": true, + "properties": [ + { + "bindable": "bindableSingleShot", + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "singleShot", + "read": "isSingleShot", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setSingleShot" + }, + { + "bindable": "bindableInterval", + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "interval", + "read": "interval", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setInterval" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "remainingTime", + "read": "remainingTime", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "bindable": "bindableTimerType", + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "timerType", + "read": "timerType", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::TimerType", + "user": false, + "write": "setTimerType" + }, + { + "bindable": "bindableActive", + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "active", + "read": "isActive", + "required": false, + "scriptable": true, + "stored": false, + "type": "bool", + "user": false + } + ], + "qualifiedClassName": "QTimer", + "signals": [ + { + "access": "public", + "index": 0, + "name": "timeout", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "msec", + "type": "int" + } + ], + "index": 1, + "name": "start", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "start", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "stop", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qtimer.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QNativeIpcKey", + "enums": [ + { + "isClass": true, + "isFlag": false, + "name": "Type", + "type": "quint16", + "values": [ + "SystemV", + "PosixRealtime", + "Windows" + ] + } + ], + "gadget": true, + "lineNumber": 17, + "qualifiedClassName": "QNativeIpcKey" + } + ], + "inputFile": "qtipccommon.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QTranslator", + "lineNumber": 18, + "object": true, + "qualifiedClassName": "QTranslator", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qtranslator.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QTransposeProxyModel", + "lineNumber": 16, + "object": true, + "qualifiedClassName": "QTransposeProxyModel", + "superClasses": [ + { + "access": "public", + "name": "QAbstractProxyModel" + } + ] + } + ], + "inputFile": "qtransposeproxymodel.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QVariantAnimation", + "lineNumber": 18, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "startValue", + "read": "startValue", + "required": false, + "scriptable": true, + "stored": true, + "type": "QVariant", + "user": false, + "write": "setStartValue" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "endValue", + "read": "endValue", + "required": false, + "scriptable": true, + "stored": true, + "type": "QVariant", + "user": false, + "write": "setEndValue" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "currentValue", + "notify": "valueChanged", + "read": "currentValue", + "required": false, + "scriptable": true, + "stored": true, + "type": "QVariant", + "user": false + }, + { + "bindable": "bindableDuration", + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "duration", + "read": "duration", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setDuration" + }, + { + "bindable": "bindableEasingCurve", + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "easingCurve", + "read": "easingCurve", + "required": false, + "scriptable": true, + "stored": true, + "type": "QEasingCurve", + "user": false, + "write": "setEasingCurve" + } + ], + "qualifiedClassName": "QVariantAnimation", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "value", + "type": "QVariant" + } + ], + "index": 0, + "name": "valueChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QAbstractAnimation" + } + ] + } + ], + "inputFile": "qvariantanimation.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QWindowsPipeReader", + "lineNumber": 27, + "object": true, + "qualifiedClassName": "QWindowsPipeReader", + "signals": [ + { + "access": "public", + "arguments": [ + { + "type": "ulong" + }, + { + "type": "QString" + } + ], + "index": 0, + "name": "winError", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "readyRead", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "pipeClosed", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qwindowspipereader_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QWindowsPipeWriter", + "lineNumber": 27, + "object": true, + "qualifiedClassName": "QWindowsPipeWriter", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "bytes", + "type": "qint64" + } + ], + "index": 0, + "name": "bytesWritten", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "writeFailed", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qwindowspipewriter_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QWinEventNotifier", + "lineNumber": 14, + "object": true, + "qualifiedClassName": "QWinEventNotifier", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "hEvent", + "type": "HANDLE" + } + ], + "index": 0, + "name": "activated", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "enable", + "type": "bool" + } + ], + "index": 1, + "name": "setEnabled", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qwineventnotifier.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QEmptyItemModel", + "lineNumber": 693, + "object": true, + "qualifiedClassName": "QEmptyItemModel", + "superClasses": [ + { + "access": "public", + "name": "QAbstractItemModel" + } + ] + } + ], + "inputFile": "qabstractitemmodel.cpp", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QWindowsRemovableDriveListener", + "lineNumber": 57, + "object": true, + "qualifiedClassName": "QWindowsRemovableDriveListener", + "signals": [ + { + "access": "public", + "index": 0, + "name": "driveAdded", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "driveRemoved", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QString" + } + ], + "index": 2, + "name": "driveRemoved", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QString" + } + ], + "index": 3, + "name": "driveLockForRemoval", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QString" + } + ], + "index": 4, + "name": "driveLockForRemovalFailed", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QAbstractNativeEventFilter" + } + ] + } + ], + "inputFile": "qfilesystemwatcher_win.cpp", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QObjectContinuationWrapper", + "lineNumber": 43, + "object": true, + "qualifiedClassName": "QObjectContinuationWrapper", + "signals": [ + { + "access": "public", + "index": 0, + "name": "run", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qfutureinterface.cpp", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QThreadPoolThread", + "lineNumber": 23, + "object": true, + "qualifiedClassName": "QThreadPoolThread", + "superClasses": [ + { + "access": "public", + "name": "QThread" + } + ] + } + ], + "inputFile": "qthreadpool.cpp", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QObject", + "constructors": [ + { + "access": "public", + "arguments": [ + { + "name": "parent", + "type": "QObject*" + } + ], + "index": 0, + "name": "QObject", + "returnType": "" + }, + { + "access": "public", + "index": 1, + "isCloned": true, + "name": "QObject", + "returnType": "" + } + ], + "lineNumber": 102, + "object": true, + "properties": [ + { + "bindable": "bindableObjectName", + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "objectName", + "notify": "objectNameChanged", + "read": "objectName", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setObjectName" + } + ], + "qualifiedClassName": "QObject", + "signals": [ + { + "access": "public", + "arguments": [ + { + "type": "QObject*" + } + ], + "index": 0, + "name": "destroyed", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "isCloned": true, + "name": "destroyed", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "objectName", + "type": "QString" + } + ], + "index": 2, + "name": "objectNameChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "index": 3, + "name": "deleteLater", + "returnType": "void" + } + ] + } + ], + "inputFile": "qobject.h", + "outputRevision": 68 + } +] diff --git a/qt/6.8.1/msvc2022_64/metatypes/qt6dbus_metatypes.json b/qt/6.8.1/msvc2022_64/metatypes/qt6dbus_metatypes.json new file mode 100644 index 0000000000000000000000000000000000000000..37c164b91e6044b2f2c93f6a86103c6bfd36a54c --- /dev/null +++ b/qt/6.8.1/msvc2022_64/metatypes/qt6dbus_metatypes.json @@ -0,0 +1,1069 @@ +[ + { + "classes": [ + { + "className": "QDBusAbstractAdaptor", + "lineNumber": 16, + "object": true, + "qualifiedClassName": "QDBusAbstractAdaptor", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qdbusabstractadaptor.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QDBusAdaptorConnector", + "lineNumber": 56, + "object": true, + "qualifiedClassName": "QDBusAdaptorConnector", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "obj", + "type": "QObject*" + }, + { + "name": "metaObject", + "type": "const QMetaObject*" + }, + { + "name": "sid", + "type": "int" + }, + { + "name": "args", + "type": "QVariantList" + } + ], + "index": 0, + "name": "relaySignal", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "index": 1, + "name": "relaySlot", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "polish", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qdbusabstractadaptor_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QDBusAbstractInterface", + "lineNumber": 42, + "object": true, + "qualifiedClassName": "QDBusAbstractInterface", + "slots": [ + { + "access": "private", + "arguments": [ + { + "type": "QString" + }, + { + "type": "QString" + }, + { + "type": "QString" + } + ], + "index": 0, + "name": "_q_serviceOwnerChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QDBusAbstractInterfaceBase" + } + ] + } + ], + "inputFile": "qdbusabstractinterface.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QDBusConnection", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "BusType", + "values": [ + "SessionBus", + "SystemBus", + "ActivationBus" + ] + }, + { + "alias": "RegisterOption", + "isClass": false, + "isFlag": true, + "name": "RegisterOptions", + "values": [ + "ExportAdaptors", + "ExportScriptableSlots", + "ExportScriptableSignals", + "ExportScriptableProperties", + "ExportScriptableInvokables", + "ExportScriptableContents", + "ExportNonScriptableSlots", + "ExportNonScriptableSignals", + "ExportNonScriptableProperties", + "ExportNonScriptableInvokables", + "ExportNonScriptableContents", + "ExportAllSlots", + "ExportAllSignals", + "ExportAllProperties", + "ExportAllInvokables", + "ExportAllContents", + "ExportAllSignal", + "ExportChildObjects" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "UnregisterMode", + "values": [ + "UnregisterNode", + "UnregisterTree" + ] + } + ], + "gadget": true, + "lineNumber": 41, + "qualifiedClassName": "QDBusConnection" + } + ], + "inputFile": "qdbusconnection.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QDBusConnectionPrivate", + "lineNumber": 74, + "object": true, + "qualifiedClassName": "QDBusConnectionPrivate", + "signals": [ + { + "access": "public", + "index": 0, + "name": "dispatchStatusChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "msg", + "type": "QDBusMessage" + } + ], + "index": 1, + "name": "spyHooksFinished", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "pcall", + "type": "QDBusPendingCallPrivate*" + }, + { + "name": "msg", + "type": "void*" + }, + { + "name": "timeout", + "type": "int" + } + ], + "index": 2, + "name": "messageNeedsSending", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "pcall", + "type": "QDBusPendingCallPrivate*" + }, + { + "name": "msg", + "type": "void*" + } + ], + "index": 3, + "isCloned": true, + "name": "messageNeedsSending", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "name", + "type": "QString" + }, + { + "name": "oldOwner", + "type": "QString" + }, + { + "name": "newOwner", + "type": "QString" + } + ], + "index": 4, + "name": "serviceOwnerChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "error", + "type": "QDBusError" + }, + { + "name": "message", + "type": "QDBusMessage" + } + ], + "index": 5, + "name": "callWithCallbackFailed", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "enable", + "type": "bool" + } + ], + "index": 6, + "name": "setDispatchEnabled", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "doDispatch", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "qintptr" + } + ], + "index": 8, + "name": "socketRead", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "qintptr" + } + ], + "index": 9, + "name": "socketWrite", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "o", + "type": "QObject*" + } + ], + "index": 10, + "name": "objectDestroyed", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "obj", + "type": "QObject*" + }, + { + "type": "const QMetaObject*" + }, + { + "name": "signalId", + "type": "int" + }, + { + "name": "args", + "type": "QVariantList" + } + ], + "index": 11, + "name": "relaySignal", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "name", + "type": "QString" + }, + { + "name": "oldOwner", + "type": "QString" + }, + { + "name": "newOwner", + "type": "QString" + } + ], + "index": 12, + "name": "serviceOwnerChangedNoLock", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "serviceName", + "type": "QString" + } + ], + "index": 13, + "name": "registerServiceNoLock", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "serviceName", + "type": "QString" + } + ], + "index": 14, + "name": "unregisterServiceNoLock", + "returnType": "void" + }, + { + "access": "private", + "index": 15, + "name": "handleDBusDisconnection", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qdbusconnection_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QDBusConnectionInterface", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "ServiceQueueOptions", + "values": [ + "DontQueueService", + "QueueService", + "ReplaceExistingService" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "ServiceReplacementOptions", + "values": [ + "DontAllowReplacement", + "AllowReplacement" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "RegisterServiceReply", + "values": [ + "ServiceNotRegistered", + "ServiceRegistered", + "ServiceQueued" + ] + } + ], + "lineNumber": 25, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "registeredServiceNames", + "read": "registeredServiceNames", + "required": false, + "scriptable": true, + "stored": true, + "type": "QDBusReply", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "activatableServiceNames", + "read": "activatableServiceNames", + "required": false, + "scriptable": true, + "stored": true, + "type": "QDBusReply", + "user": false + } + ], + "qualifiedClassName": "QDBusConnectionInterface", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "service", + "type": "QString" + } + ], + "index": 0, + "name": "serviceRegistered", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "service", + "type": "QString" + } + ], + "index": 1, + "name": "serviceUnregistered", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "name", + "type": "QString" + }, + { + "name": "oldOwner", + "type": "QString" + }, + { + "name": "newOwner", + "type": "QString" + } + ], + "index": 2, + "name": "serviceOwnerChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "error", + "type": "QDBusError" + }, + { + "name": "call", + "type": "QDBusMessage" + } + ], + "index": 3, + "name": "callWithCallbackFailed", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QString" + } + ], + "index": 4, + "name": "NameAcquired", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QString" + } + ], + "index": 5, + "name": "NameLost", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QString" + }, + { + "type": "QString" + }, + { + "type": "QString" + } + ], + "index": 6, + "name": "NameOwnerChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "index": 7, + "name": "registeredServiceNames", + "returnType": "QDBusReply" + }, + { + "access": "public", + "index": 8, + "name": "activatableServiceNames", + "returnType": "QDBusReply" + }, + { + "access": "public", + "arguments": [ + { + "name": "serviceName", + "type": "QString" + } + ], + "index": 9, + "name": "isServiceRegistered", + "returnType": "QDBusReply" + }, + { + "access": "public", + "arguments": [ + { + "name": "name", + "type": "QString" + } + ], + "index": 10, + "name": "serviceOwner", + "returnType": "QDBusReply" + }, + { + "access": "public", + "arguments": [ + { + "name": "serviceName", + "type": "QString" + } + ], + "index": 11, + "name": "unregisterService", + "returnType": "QDBusReply" + }, + { + "access": "public", + "arguments": [ + { + "name": "serviceName", + "type": "QString" + }, + { + "name": "qoption", + "type": "ServiceQueueOptions" + }, + { + "name": "roption", + "type": "ServiceReplacementOptions" + } + ], + "index": 12, + "name": "registerService", + "returnType": "QDBusReply" + }, + { + "access": "public", + "arguments": [ + { + "name": "serviceName", + "type": "QString" + }, + { + "name": "qoption", + "type": "ServiceQueueOptions" + } + ], + "index": 13, + "isCloned": true, + "name": "registerService", + "returnType": "QDBusReply" + }, + { + "access": "public", + "arguments": [ + { + "name": "serviceName", + "type": "QString" + } + ], + "index": 14, + "isCloned": true, + "name": "registerService", + "returnType": "QDBusReply" + }, + { + "access": "public", + "arguments": [ + { + "name": "serviceName", + "type": "QString" + } + ], + "index": 15, + "name": "servicePid", + "returnType": "QDBusReply" + }, + { + "access": "public", + "arguments": [ + { + "name": "serviceName", + "type": "QString" + } + ], + "index": 16, + "name": "serviceUid", + "returnType": "QDBusReply" + }, + { + "access": "public", + "arguments": [ + { + "name": "name", + "type": "QString" + } + ], + "index": 17, + "name": "startService", + "returnType": "QDBusReply" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QDBusAbstractInterface" + } + ] + } + ], + "inputFile": "qdbusconnectioninterface.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QDBusConnectionManager", + "lineNumber": 30, + "object": true, + "qualifiedClassName": "QDBusConnectionManager", + "superClasses": [ + { + "access": "public", + "name": "QDaemonThread" + } + ] + } + ], + "inputFile": "qdbusconnectionmanager_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QDBusError", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "ErrorType", + "values": [ + "NoError", + "Other", + "Failed", + "NoMemory", + "ServiceUnknown", + "NoReply", + "BadAddress", + "NotSupported", + "LimitsExceeded", + "AccessDenied", + "NoServer", + "Timeout", + "NoNetwork", + "AddressInUse", + "Disconnected", + "InvalidArgs", + "UnknownMethod", + "TimedOut", + "InvalidSignature", + "UnknownInterface", + "UnknownObject", + "UnknownProperty", + "PropertyReadOnly", + "InternalError", + "InvalidService", + "InvalidObjectPath", + "InvalidInterface", + "InvalidMember", + "LastErrorType" + ] + } + ], + "gadget": true, + "lineNumber": 20, + "qualifiedClassName": "QDBusError" + } + ], + "inputFile": "qdbuserror.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QDBusPendingCallWatcher", + "lineNumber": 60, + "object": true, + "qualifiedClassName": "QDBusPendingCallWatcher", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "self", + "type": "QDBusPendingCallWatcher*" + } + ], + "index": 0, + "name": "finished", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "isCloned": true, + "name": "finished", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QDBusPendingCall" + } + ] + } + ], + "inputFile": "qdbuspendingcall.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QDBusPendingCallWatcherHelper", + "lineNumber": 76, + "object": true, + "qualifiedClassName": "QDBusPendingCallWatcherHelper", + "signals": [ + { + "access": "public", + "index": 0, + "name": "finished", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "msg", + "type": "QDBusMessage" + } + ], + "index": 1, + "name": "reply", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "error", + "type": "QDBusError" + }, + { + "name": "msg", + "type": "QDBusMessage" + } + ], + "index": 2, + "name": "error", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qdbuspendingcall_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QDBusServer", + "lineNumber": 20, + "object": true, + "qualifiedClassName": "QDBusServer", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "connection", + "type": "QDBusConnection" + } + ], + "index": 0, + "name": "newConnection", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qdbusserver.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QDBusServiceWatcher", + "enums": [ + { + "alias": "WatchModeFlag", + "isClass": false, + "isFlag": true, + "name": "WatchMode", + "values": [ + "WatchForRegistration", + "WatchForUnregistration", + "WatchForOwnerChange" + ] + } + ], + "lineNumber": 22, + "object": true, + "properties": [ + { + "bindable": "bindableWatchedServices", + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "watchedServices", + "read": "watchedServices", + "required": false, + "scriptable": true, + "stored": true, + "type": "QStringList", + "user": false, + "write": "setWatchedServices" + }, + { + "bindable": "bindableWatchMode", + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "watchMode", + "read": "watchMode", + "required": false, + "scriptable": true, + "stored": true, + "type": "WatchMode", + "user": false, + "write": "setWatchMode" + } + ], + "qualifiedClassName": "QDBusServiceWatcher", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "service", + "type": "QString" + } + ], + "index": 0, + "name": "serviceRegistered", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "service", + "type": "QString" + } + ], + "index": 1, + "name": "serviceUnregistered", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "service", + "type": "QString" + }, + { + "name": "oldOwner", + "type": "QString" + }, + { + "name": "newOwner", + "type": "QString" + } + ], + "index": 2, + "name": "serviceOwnerChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "private", + "arguments": [ + { + "type": "QString" + }, + { + "type": "QString" + }, + { + "type": "QString" + } + ], + "index": 3, + "name": "_q_serviceOwnerChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qdbusservicewatcher.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QDBusVirtualObject", + "lineNumber": 19, + "object": true, + "qualifiedClassName": "QDBusVirtualObject", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qdbusvirtualobject.h", + "outputRevision": 68 + } +] diff --git a/qt/6.8.1/msvc2022_64/metatypes/qt6designer_metatypes.json b/qt/6.8.1/msvc2022_64/metatypes/qt6designer_metatypes.json new file mode 100644 index 0000000000000000000000000000000000000000..328d4e1e0355bece3b4eddc743b0eee0de5c6028 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/metatypes/qt6designer_metatypes.json @@ -0,0 +1,7772 @@ +[ + { + "classes": [ + { + "className": "QtColorButton", + "lineNumber": 22, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "backgroundCheckered", + "read": "isBackgroundCheckered", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setBackgroundCheckered" + } + ], + "qualifiedClassName": "QtColorButton", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "color", + "type": "QColor" + } + ], + "index": 0, + "name": "colorChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "color", + "type": "QColor" + } + ], + "index": 1, + "name": "setColor", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QToolButton" + } + ] + } + ], + "inputFile": "qtcolorbutton_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QtColorLine", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "ColorComponent", + "values": [ + "Red", + "Green", + "Blue", + "Hue", + "Saturation", + "Value", + "Alpha" + ] + } + ], + "lineNumber": 22, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "color", + "read": "color", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false, + "write": "setColor" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "indicatorSpace", + "read": "indicatorSpace", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setIndicatorSpace" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "indicatorSize", + "read": "indicatorSize", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setIndicatorSize" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "flip", + "read": "flip", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setFlip" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "backgroundCheckered", + "read": "isBackgroundCheckered", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setBackgroundCheckered" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "colorComponent", + "read": "colorComponent", + "required": false, + "scriptable": true, + "stored": true, + "type": "ColorComponent", + "user": false, + "write": "setColorComponent" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "orientation", + "read": "orientation", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::Orientation", + "user": false, + "write": "setOrientation" + } + ], + "qualifiedClassName": "QtColorLine", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "color", + "type": "QColor" + } + ], + "index": 0, + "name": "colorChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "color", + "type": "QColor" + } + ], + "index": 1, + "name": "setColor", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + } + ], + "inputFile": "qtcolorline_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QtGradientDialog", + "lineNumber": 22, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "gradient", + "read": "gradient", + "required": false, + "scriptable": true, + "stored": true, + "type": "QGradient", + "user": false, + "write": "setGradient" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "backgroundCheckered", + "read": "isBackgroundCheckered", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setBackgroundCheckered" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "detailsVisible", + "read": "detailsVisible", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setDetailsVisible" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "detailsButtonVisible", + "read": "isDetailsButtonVisible", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setDetailsButtonVisible" + } + ], + "qualifiedClassName": "QtGradientDialog", + "superClasses": [ + { + "access": "public", + "name": "QDialog" + } + ] + } + ], + "inputFile": "qtgradientdialog_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QtGradientEditor", + "lineNumber": 22, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "gradient", + "read": "gradient", + "required": false, + "scriptable": true, + "stored": true, + "type": "QGradient", + "user": false, + "write": "setGradient" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "backgroundCheckered", + "read": "isBackgroundCheckered", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setBackgroundCheckered" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "detailsVisible", + "read": "detailsVisible", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setDetailsVisible" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "detailsButtonVisible", + "read": "isDetailsButtonVisible", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setDetailsButtonVisible" + } + ], + "qualifiedClassName": "QtGradientEditor", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "gradient", + "type": "QGradient" + } + ], + "index": 0, + "name": "gradientChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "details", + "type": "bool" + }, + { + "name": "extenstionWidthHint", + "type": "int" + } + ], + "index": 1, + "name": "aboutToShowDetails", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + } + ], + "inputFile": "qtgradienteditor_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QtGradientManager", + "lineNumber": 31, + "object": true, + "qualifiedClassName": "QtGradientManager", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "id", + "type": "QString" + }, + { + "name": "gradient", + "type": "QGradient" + } + ], + "index": 0, + "name": "gradientAdded", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "id", + "type": "QString" + }, + { + "name": "newId", + "type": "QString" + } + ], + "index": 1, + "name": "gradientRenamed", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "id", + "type": "QString" + }, + { + "name": "newGradient", + "type": "QGradient" + } + ], + "index": 2, + "name": "gradientChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "id", + "type": "QString" + } + ], + "index": 3, + "name": "gradientRemoved", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "id", + "type": "QString" + }, + { + "name": "gradient", + "type": "QGradient" + } + ], + "index": 4, + "name": "addGradient", + "returnType": "QString" + }, + { + "access": "public", + "arguments": [ + { + "name": "id", + "type": "QString" + }, + { + "name": "newId", + "type": "QString" + } + ], + "index": 5, + "name": "renameGradient", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "id", + "type": "QString" + }, + { + "name": "newGradient", + "type": "QGradient" + } + ], + "index": 6, + "name": "changeGradient", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "id", + "type": "QString" + } + ], + "index": 7, + "name": "removeGradient", + "returnType": "void" + }, + { + "access": "public", + "index": 8, + "name": "clear", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qtgradientmanager_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QtGradientStopsController", + "lineNumber": 26, + "object": true, + "qualifiedClassName": "QtGradientStopsController", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "stops", + "type": "QGradientStops" + } + ], + "index": 0, + "name": "gradientStopsChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qtgradientstopscontroller_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QtGradientStopsModel", + "lineNumber": 43, + "object": true, + "qualifiedClassName": "QtGradientStopsModel", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "stop", + "type": "QtGradientStop*" + } + ], + "index": 0, + "name": "stopAdded", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "stop", + "type": "QtGradientStop*" + } + ], + "index": 1, + "name": "stopRemoved", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "stop", + "type": "QtGradientStop*" + }, + { + "name": "newPos", + "type": "qreal" + } + ], + "index": 2, + "name": "stopMoved", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "stop1", + "type": "QtGradientStop*" + }, + { + "name": "stop2", + "type": "QtGradientStop*" + } + ], + "index": 3, + "name": "stopsSwapped", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "stop", + "type": "QtGradientStop*" + }, + { + "name": "newColor", + "type": "QColor" + } + ], + "index": 4, + "name": "stopChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "stop", + "type": "QtGradientStop*" + }, + { + "name": "selected", + "type": "bool" + } + ], + "index": 5, + "name": "stopSelected", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "stop", + "type": "QtGradientStop*" + } + ], + "index": 6, + "name": "currentStopChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qtgradientstopsmodel_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QtGradientStopsWidget", + "lineNumber": 25, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "backgroundCheckered", + "read": "isBackgroundCheckered", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setBackgroundCheckered" + } + ], + "qualifiedClassName": "QtGradientStopsWidget", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "zoom", + "type": "double" + } + ], + "index": 0, + "name": "zoomChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QAbstractScrollArea" + } + ] + } + ], + "inputFile": "qtgradientstopswidget_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QtGradientView", + "lineNumber": 28, + "object": true, + "qualifiedClassName": "QtGradientView", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "id", + "type": "QString" + } + ], + "index": 0, + "name": "currentGradientChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "id", + "type": "QString" + } + ], + "index": 1, + "name": "gradientActivated", + "returnType": "void" + } + ], + "slots": [ + { + "access": "private", + "arguments": [ + { + "name": "id", + "type": "QString" + }, + { + "name": "gradient", + "type": "QGradient" + } + ], + "index": 2, + "name": "slotGradientAdded", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "id", + "type": "QString" + }, + { + "name": "newId", + "type": "QString" + } + ], + "index": 3, + "name": "slotGradientRenamed", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "id", + "type": "QString" + }, + { + "name": "newGradient", + "type": "QGradient" + } + ], + "index": 4, + "name": "slotGradientChanged", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "id", + "type": "QString" + } + ], + "index": 5, + "name": "slotGradientRemoved", + "returnType": "void" + }, + { + "access": "private", + "index": 6, + "name": "slotNewGradient", + "returnType": "void" + }, + { + "access": "private", + "index": 7, + "name": "slotEditGradient", + "returnType": "void" + }, + { + "access": "private", + "index": 8, + "name": "slotRemoveGradient", + "returnType": "void" + }, + { + "access": "private", + "index": 9, + "name": "slotRenameGradient", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "item", + "type": "QListWidgetItem*" + } + ], + "index": 10, + "name": "slotRenameGradientItem", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "item", + "type": "QListWidgetItem*" + } + ], + "index": 11, + "name": "slotCurrentItemChanged", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "item", + "type": "QListWidgetItem*" + } + ], + "index": 12, + "name": "slotGradientActivated", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + } + ], + "inputFile": "qtgradientview_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QtGradientViewDialog", + "lineNumber": 26, + "object": true, + "qualifiedClassName": "QtGradientViewDialog", + "slots": [ + { + "access": "private", + "arguments": [ + { + "name": "id", + "type": "QString" + } + ], + "index": 0, + "name": "slotGradientSelected", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "id", + "type": "QString" + } + ], + "index": 1, + "name": "slotGradientActivated", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QDialog" + } + ] + } + ], + "inputFile": "qtgradientviewdialog_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QtGradientWidget", + "lineNumber": 22, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "backgroundCheckered", + "read": "isBackgroundCheckered", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setBackgroundCheckered" + } + ], + "qualifiedClassName": "QtGradientWidget", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "point", + "type": "QPointF" + } + ], + "index": 0, + "name": "startLinearChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "point", + "type": "QPointF" + } + ], + "index": 1, + "name": "endLinearChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "point", + "type": "QPointF" + } + ], + "index": 2, + "name": "centralRadialChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "point", + "type": "QPointF" + } + ], + "index": 3, + "name": "focalRadialChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "radius", + "type": "qreal" + } + ], + "index": 4, + "name": "radiusRadialChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "point", + "type": "QPointF" + } + ], + "index": 5, + "name": "centralConicalChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "angle", + "type": "qreal" + } + ], + "index": 6, + "name": "angleConicalChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "stops", + "type": "QGradientStops" + } + ], + "index": 7, + "name": "setGradientStops", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + } + ], + "inputFile": "qtgradientwidget_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "DeviceSkin", + "lineNumber": 79, + "object": true, + "qualifiedClassName": "DeviceSkin", + "signals": [ + { + "access": "public", + "index": 0, + "name": "popupMenu", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "code", + "type": "int" + }, + { + "name": "text", + "type": "QString" + }, + { + "name": "autorep", + "type": "bool" + } + ], + "index": 1, + "name": "skinKeyPressEvent", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "code", + "type": "int" + }, + { + "name": "text", + "type": "QString" + }, + { + "name": "autorep", + "type": "bool" + } + ], + "index": 2, + "name": "skinKeyReleaseEvent", + "returnType": "void" + } + ], + "slots": [ + { + "access": "protected", + "index": 3, + "name": "skinKeyRepeat", + "returnType": "void" + }, + { + "access": "protected", + "index": 4, + "name": "moveParent", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + } + ], + "inputFile": "deviceskin_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "ActionEditor", + "lineNumber": 41, + "object": true, + "qualifiedClassName": "qdesigner_internal::ActionEditor", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "item", + "type": "QAction*" + }, + { + "name": "column", + "type": "int" + } + ], + "index": 0, + "name": "itemActivated", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "menu", + "type": "QMenu*" + }, + { + "name": "item", + "type": "QAction*" + } + ], + "index": 1, + "name": "contextMenuRequested", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "filter", + "type": "QString" + } + ], + "index": 2, + "name": "setFilter", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "mainContainerChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "clearSelection", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "a", + "type": "QAction*" + } + ], + "index": 5, + "name": "selectAction", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "item", + "type": "QAction*" + } + ], + "index": 6, + "name": "slotCurrentItemChanged", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "selected", + "type": "QItemSelection" + }, + { + "name": "deselected", + "type": "QItemSelection" + } + ], + "index": 7, + "name": "slotSelectionChanged", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "item", + "type": "QAction*" + }, + { + "name": "column", + "type": "int" + } + ], + "index": 8, + "name": "editAction", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "item", + "type": "QAction*" + } + ], + "index": 9, + "isCloned": true, + "name": "editAction", + "returnType": "void" + }, + { + "access": "private", + "index": 10, + "name": "editCurrentAction", + "returnType": "void" + }, + { + "access": "private", + "index": 11, + "name": "navigateToSlotCurrentAction", + "returnType": "void" + }, + { + "access": "private", + "index": 12, + "name": "slotActionChanged", + "returnType": "void" + }, + { + "access": "private", + "index": 13, + "name": "slotNewAction", + "returnType": "void" + }, + { + "access": "private", + "index": 14, + "name": "slotDelete", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "path", + "type": "QString" + }, + { + "name": "action", + "type": "QAction*" + } + ], + "index": 15, + "name": "resourceImageDropped", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "type": "QContextMenuEvent*" + }, + { + "type": "QAction*" + } + ], + "index": 16, + "name": "slotContextMenuRequested", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "a", + "type": "QAction*" + } + ], + "index": 17, + "name": "slotViewMode", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "w", + "type": "QWidget*" + } + ], + "index": 18, + "name": "slotSelectAssociatedWidget", + "returnType": "void" + }, + { + "access": "private", + "index": 19, + "name": "slotCopy", + "returnType": "void" + }, + { + "access": "private", + "index": 20, + "name": "slotCut", + "returnType": "void" + }, + { + "access": "private", + "index": 21, + "name": "slotPaste", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QDesignerActionEditorInterface" + } + ] + } + ], + "inputFile": "actioneditor_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "ActionModel", + "lineNumber": 38, + "object": true, + "qualifiedClassName": "qdesigner_internal::ActionModel", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "path", + "type": "QString" + }, + { + "name": "action", + "type": "QAction*" + } + ], + "index": 0, + "name": "resourceImageDropped", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QStandardItemModel" + } + ] + }, + { + "className": "ActionTreeView", + "lineNumber": 90, + "object": true, + "qualifiedClassName": "qdesigner_internal::ActionTreeView", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "event", + "type": "QContextMenuEvent*" + }, + { + "type": "QAction*" + } + ], + "index": 0, + "name": "actionContextMenuRequested", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "action", + "type": "QAction*" + } + ], + "index": 1, + "name": "currentActionChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "action", + "type": "QAction*" + }, + { + "name": "column", + "type": "int" + } + ], + "index": 2, + "name": "actionActivated", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "text", + "type": "QString" + } + ], + "index": 3, + "name": "filter", + "returnType": "void" + }, + { + "access": "protected", + "arguments": [ + { + "name": "current", + "type": "QModelIndex" + }, + { + "name": "previous", + "type": "QModelIndex" + } + ], + "index": 4, + "name": "currentChanged", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "type": "QModelIndex" + } + ], + "index": 5, + "name": "slotActivated", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QTreeView" + } + ] + }, + { + "className": "ActionListView", + "lineNumber": 124, + "object": true, + "qualifiedClassName": "qdesigner_internal::ActionListView", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "event", + "type": "QContextMenuEvent*" + }, + { + "type": "QAction*" + } + ], + "index": 0, + "name": "actionContextMenuRequested", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "action", + "type": "QAction*" + } + ], + "index": 1, + "name": "currentActionChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "action", + "type": "QAction*" + } + ], + "index": 2, + "name": "actionActivated", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "text", + "type": "QString" + } + ], + "index": 3, + "name": "filter", + "returnType": "void" + }, + { + "access": "protected", + "arguments": [ + { + "name": "current", + "type": "QModelIndex" + }, + { + "name": "previous", + "type": "QModelIndex" + } + ], + "index": 4, + "name": "currentChanged", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "type": "QModelIndex" + } + ], + "index": 5, + "name": "slotActivated", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QListView" + } + ] + }, + { + "className": "ActionView", + "lineNumber": 161, + "object": true, + "qualifiedClassName": "qdesigner_internal::ActionView", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "event", + "type": "QContextMenuEvent*" + }, + { + "type": "QAction*" + } + ], + "index": 0, + "name": "contextMenuRequested", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "action", + "type": "QAction*" + } + ], + "index": 1, + "name": "currentChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "action", + "type": "QAction*" + }, + { + "name": "column", + "type": "int" + } + ], + "index": 2, + "name": "activated", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "selected", + "type": "QItemSelection" + }, + { + "name": "deselected", + "type": "QItemSelection" + } + ], + "index": 3, + "name": "selectionChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "data", + "type": "QString" + }, + { + "name": "action", + "type": "QAction*" + } + ], + "index": 4, + "name": "resourceImageDropped", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "text", + "type": "QString" + } + ], + "index": 5, + "name": "filter", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "selectAll", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "clearSelection", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "a", + "type": "QAction*" + } + ], + "index": 8, + "name": "selectAction", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "action", + "type": "QAction*" + } + ], + "index": 9, + "name": "slotCurrentChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QStackedWidget" + } + ] + }, + { + "className": "ActionRepositoryMimeData", + "lineNumber": 208, + "object": true, + "qualifiedClassName": "qdesigner_internal::ActionRepositoryMimeData", + "superClasses": [ + { + "access": "public", + "name": "QMimeData" + } + ] + } + ], + "inputFile": "actionrepository_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "CodeDialog", + "lineNumber": 30, + "object": true, + "qualifiedClassName": "qdesigner_internal::CodeDialog", + "slots": [ + { + "access": "private", + "index": 0, + "name": "slotSaveAs", + "returnType": "void" + }, + { + "access": "private", + "index": 1, + "name": "copyAll", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QDialog" + } + ] + } + ], + "inputFile": "codedialog_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "ConnectionEdit", + "lineNumber": 127, + "object": true, + "qualifiedClassName": "qdesigner_internal::ConnectionEdit", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "idx", + "type": "int" + } + ], + "index": 0, + "name": "aboutToAddConnection", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "con", + "type": "qdesigner_internal::Connection*" + } + ], + "index": 1, + "name": "connectionAdded", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "con", + "type": "qdesigner_internal::Connection*" + } + ], + "index": 2, + "name": "aboutToRemoveConnection", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "idx", + "type": "int" + } + ], + "index": 3, + "name": "connectionRemoved", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "con", + "type": "qdesigner_internal::Connection*" + } + ], + "index": 4, + "name": "connectionSelected", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "wgt", + "type": "QWidget*" + } + ], + "index": 5, + "name": "widgetActivated", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "con", + "type": "qdesigner_internal::Connection*" + } + ], + "index": 6, + "name": "connectionChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "index": 7, + "name": "selectNone", + "returnType": "void" + }, + { + "access": "public", + "index": 8, + "name": "selectAll", + "returnType": "void" + }, + { + "access": "public", + "index": 9, + "name": "deleteSelected", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "background", + "type": "QWidget*" + } + ], + "index": 10, + "name": "setBackground", + "returnType": "void" + }, + { + "access": "public", + "index": 11, + "name": "updateBackground", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "w", + "type": "QWidget*" + } + ], + "index": 12, + "name": "widgetRemoved", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "o", + "type": "QObject*" + } + ], + "index": 13, + "name": "objectRemoved", + "returnType": "void" + }, + { + "access": "public", + "index": 14, + "name": "updateLines", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "enable", + "type": "bool" + } + ], + "index": 15, + "name": "enableUpdateBackground", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWidget" + }, + { + "access": "public", + "name": "CETypes" + } + ] + } + ], + "inputFile": "connectionedit_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "CssHighlighter", + "lineNumber": 37, + "object": true, + "qualifiedClassName": "qdesigner_internal::CssHighlighter", + "superClasses": [ + { + "access": "public", + "name": "QSyntaxHighlighter" + } + ] + } + ], + "inputFile": "csshighlighter_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "FormLayoutMenu", + "lineNumber": 34, + "object": true, + "qualifiedClassName": "qdesigner_internal::FormLayoutMenu", + "slots": [ + { + "access": "private", + "index": 0, + "name": "slotAddRow", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "formlayoutmenu_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "FormWindowBase", + "lineNumber": 42, + "object": true, + "qualifiedClassName": "qdesigner_internal::FormWindowBase", + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "resourceSet", + "type": "QtResourceSet*" + }, + { + "name": "resourceSetChanged", + "type": "bool" + } + ], + "index": 0, + "name": "resourceSetActivated", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "w", + "type": "QWidget*" + } + ], + "index": 1, + "name": "triggerDefaultAction", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "object", + "type": "QObject*" + } + ], + "index": 2, + "name": "sheetDestroyed", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QDesignerFormWindowInterface" + } + ] + } + ], + "inputFile": "formwindowbase_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "GridPanel", + "lineNumber": 32, + "object": true, + "qualifiedClassName": "qdesigner_internal::GridPanel", + "slots": [ + { + "access": "private", + "index": 0, + "name": "reset", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + } + ], + "inputFile": "gridpanel_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "HtmlHighlighter", + "lineNumber": 27, + "object": true, + "qualifiedClassName": "qdesigner_internal::HtmlHighlighter", + "superClasses": [ + { + "access": "public", + "name": "QSyntaxHighlighter" + } + ] + } + ], + "inputFile": "htmlhighlighter_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "InvisibleWidget", + "lineNumber": 26, + "object": true, + "qualifiedClassName": "qdesigner_internal::InvisibleWidget", + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + } + ], + "inputFile": "invisible_widget_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "Layout", + "lineNumber": 35, + "object": true, + "qualifiedClassName": "qdesigner_internal::Layout", + "slots": [ + { + "access": "private", + "index": 0, + "name": "widgetDestroyed", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "layout_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "MetaDataBase", + "lineNumber": 63, + "object": true, + "qualifiedClassName": "qdesigner_internal::MetaDataBase", + "slots": [ + { + "access": "private", + "arguments": [ + { + "name": "object", + "type": "QObject*" + } + ], + "index": 0, + "name": "slotDestroyed", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QDesignerMetaDataBaseInterface" + } + ] + } + ], + "inputFile": "metadatabase_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "MorphMenu", + "lineNumber": 29, + "object": true, + "qualifiedClassName": "qdesigner_internal::MorphMenu", + "slots": [ + { + "access": "private", + "arguments": [ + { + "name": "newClassName", + "type": "QString" + } + ], + "index": 0, + "name": "slotMorph", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "morphmenu_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "NewActionDialog", + "lineNumber": 60, + "object": true, + "qualifiedClassName": "qdesigner_internal::NewActionDialog", + "slots": [ + { + "access": "public", + "index": 0, + "name": "focusName", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "focusText", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "focusTooltip", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "focusShortcut", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "focusCheckable", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "focusMenuRole", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "text", + "type": "QString" + } + ], + "index": 6, + "name": "onEditActionTextTextEdited", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "text", + "type": "QString" + } + ], + "index": 7, + "name": "onEditObjectNameTextEdited", + "returnType": "void" + }, + { + "access": "private", + "index": 8, + "name": "slotEditToolTip", + "returnType": "void" + }, + { + "access": "private", + "index": 9, + "name": "slotResetKeySequence", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QDialog" + } + ] + } + ], + "inputFile": "newactiondialog_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "NewFormWidget", + "lineNumber": 43, + "object": true, + "qualifiedClassName": "qdesigner_internal::NewFormWidget", + "slots": [ + { + "access": "private", + "arguments": [ + { + "name": "item", + "type": "QTreeWidgetItem*" + } + ], + "index": 0, + "name": "treeWidgetItemActivated", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "current", + "type": "QTreeWidgetItem*" + } + ], + "index": 1, + "name": "treeWidgetCurrentItemChanged", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "item", + "type": "QTreeWidgetItem*" + } + ], + "index": 2, + "name": "treeWidgetItemPressed", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "idx", + "type": "int" + } + ], + "index": 3, + "name": "slotDeviceProfileIndexChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QDesignerNewFormWidgetInterface" + } + ] + } + ], + "inputFile": "newformwidget_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "OrderDialog", + "lineNumber": 33, + "object": true, + "qualifiedClassName": "qdesigner_internal::OrderDialog", + "slots": [ + { + "access": "private", + "index": 0, + "name": "upButtonClicked", + "returnType": "void" + }, + { + "access": "private", + "index": 1, + "name": "downButtonClicked", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "row", + "type": "int" + } + ], + "index": 2, + "name": "pageListCurrentRowChanged", + "returnType": "void" + }, + { + "access": "private", + "index": 3, + "name": "slotEnableButtonsAfterDnD", + "returnType": "void" + }, + { + "access": "private", + "index": 4, + "name": "slotReset", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QDialog" + } + ] + } + ], + "inputFile": "orderdialog_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "PlainTextEditorDialog", + "lineNumber": 28, + "object": true, + "qualifiedClassName": "qdesigner_internal::PlainTextEditorDialog", + "superClasses": [ + { + "access": "public", + "name": "QDialog" + } + ] + } + ], + "inputFile": "plaintexteditor_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QDesignerPluginManager", + "lineNumber": 73, + "object": true, + "qualifiedClassName": "QDesignerPluginManager", + "slots": [ + { + "access": "public", + "index": 0, + "name": "syncSettings", + "returnType": "bool" + }, + { + "access": "public", + "index": 1, + "name": "ensureInitialized", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "pluginmanager_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "PreviewConfigurationWidget", + "lineNumber": 32, + "object": true, + "qualifiedClassName": "qdesigner_internal::PreviewConfigurationWidget", + "slots": [ + { + "access": "private", + "index": 0, + "name": "slotEditAppStyleSheet", + "returnType": "void" + }, + { + "access": "private", + "index": 1, + "name": "slotDeleteSkinEntry", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "type": "int" + } + ], + "index": 2, + "name": "slotSkinChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QGroupBox" + } + ] + } + ], + "inputFile": "previewconfigurationwidget_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "PreviewManager", + "lineNumber": 79, + "object": true, + "qualifiedClassName": "qdesigner_internal::PreviewManager", + "signals": [ + { + "access": "public", + "index": 0, + "name": "firstPreviewOpened", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "lastPreviewClosed", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "index": 2, + "name": "closeAllPreviews", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "type": "int" + } + ], + "index": 3, + "name": "slotZoomChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "previewmanager_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "PromotionModel", + "lineNumber": 30, + "object": true, + "qualifiedClassName": "qdesigner_internal::PromotionModel", + "signals": [ + { + "access": "public", + "arguments": [ + { + "type": "QDesignerWidgetDataBaseItemInterface*" + }, + { + "name": "includeFile", + "type": "QString" + } + ], + "index": 0, + "name": "includeFileChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QDesignerWidgetDataBaseItemInterface*" + }, + { + "name": "newName", + "type": "QString" + } + ], + "index": 1, + "name": "classNameChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "private", + "arguments": [ + { + "name": "item", + "type": "QStandardItem*" + } + ], + "index": 2, + "name": "slotItemChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QStandardItemModel" + } + ] + } + ], + "inputFile": "promotionmodel_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "PromotionTaskMenu", + "lineNumber": 37, + "object": true, + "qualifiedClassName": "qdesigner_internal::PromotionTaskMenu", + "slots": [ + { + "access": "private", + "arguments": [ + { + "name": "customClassName", + "type": "QString" + } + ], + "index": 0, + "name": "slotPromoteToCustomWidget", + "returnType": "void" + }, + { + "access": "private", + "index": 1, + "name": "slotDemoteFromCustomWidget", + "returnType": "void" + }, + { + "access": "private", + "index": 2, + "name": "slotEditPromotedWidgets", + "returnType": "void" + }, + { + "access": "private", + "index": 3, + "name": "slotEditPromoteTo", + "returnType": "void" + }, + { + "access": "private", + "index": 4, + "name": "slotEditSignalsSlots", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "promotiontaskmenu_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "PropertyLineEdit", + "lineNumber": 27, + "object": true, + "qualifiedClassName": "qdesigner_internal::PropertyLineEdit", + "slots": [ + { + "access": "private", + "index": 0, + "name": "insertNewLine", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QLineEdit" + } + ] + } + ], + "inputFile": "propertylineedit_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QDesignerMimeData", + "lineNumber": 65, + "object": true, + "qualifiedClassName": "qdesigner_internal::QDesignerMimeData", + "superClasses": [ + { + "access": "public", + "name": "QMimeData" + } + ] + } + ], + "inputFile": "qdesigner_dnditem_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QDesignerDockWidget", + "lineNumber": 28, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "dockWidgetArea", + "read": "dockWidgetArea", + "required": false, + "scriptable": true, + "stored": false, + "type": "Qt::DockWidgetArea", + "user": false, + "write": "setDockWidgetArea" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "docked", + "read": "docked", + "required": false, + "scriptable": true, + "stored": false, + "type": "bool", + "user": false, + "write": "setDocked" + } + ], + "qualifiedClassName": "QDesignerDockWidget", + "superClasses": [ + { + "access": "public", + "name": "QDockWidget" + } + ] + }, + { + "className": "QDockWidgetPropertySheet", + "lineNumber": 50, + "object": true, + "qualifiedClassName": "QDockWidgetPropertySheet", + "superClasses": [ + { + "access": "public", + "name": "QDesignerPropertySheet" + } + ] + } + ], + "inputFile": "qdesigner_dockwidget_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QDesignerFormWindowManager", + "lineNumber": 30, + "object": true, + "qualifiedClassName": "qdesigner_internal::QDesignerFormWindowManager", + "superClasses": [ + { + "access": "public", + "name": "QDesignerFormWindowManagerInterface" + } + ] + } + ], + "inputFile": "qdesigner_formwindowmanager_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QDesignerMemberSheet", + "interfaces": [ + [ + { + "className": "QDesignerMemberSheetExtension", + "id": "\"org.qt-project.Qt.Designer.MemberSheet\"" + } + ] + ], + "lineNumber": 28, + "object": true, + "qualifiedClassName": "QDesignerMemberSheet", + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QDesignerMemberSheetExtension" + } + ] + }, + { + "className": "QDesignerMemberSheetFactory", + "interfaces": [ + [ + { + "className": "QAbstractExtensionFactory", + "id": "\"org.qt-project.Qt.QAbstractExtensionFactory\"" + } + ] + ], + "lineNumber": 65, + "object": true, + "qualifiedClassName": "QDesignerMemberSheetFactory", + "superClasses": [ + { + "access": "public", + "name": "QExtensionFactory" + } + ] + } + ], + "inputFile": "qdesigner_membersheet_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QDesignerMenu", + "lineNumber": 44, + "object": true, + "qualifiedClassName": "QDesignerMenu", + "slots": [ + { + "access": "private", + "index": 0, + "name": "slotAddSeparator", + "returnType": "void" + }, + { + "access": "private", + "index": 1, + "name": "slotRemoveSelectedAction", + "returnType": "void" + }, + { + "access": "private", + "index": 2, + "name": "slotShowSubMenuNow", + "returnType": "void" + }, + { + "access": "private", + "index": 3, + "name": "slotDeactivateNow", + "returnType": "void" + }, + { + "access": "private", + "index": 4, + "name": "slotAdjustSizeNow", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QMenu" + } + ] + } + ], + "inputFile": "qdesigner_menu_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "SpecialMenuAction", + "lineNumber": 38, + "object": true, + "qualifiedClassName": "qdesigner_internal::SpecialMenuAction", + "superClasses": [ + { + "access": "public", + "name": "QAction" + } + ] + }, + { + "className": "QDesignerMenuBar", + "lineNumber": 48, + "object": true, + "qualifiedClassName": "QDesignerMenuBar", + "slots": [ + { + "access": "private", + "index": 0, + "name": "deleteMenu", + "returnType": "void" + }, + { + "access": "private", + "index": 1, + "name": "slotRemoveMenuBar", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QMenuBar" + } + ] + } + ], + "inputFile": "qdesigner_menubar_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QDesignerObjectInspector", + "lineNumber": 46, + "object": true, + "qualifiedClassName": "qdesigner_internal::QDesignerObjectInspector", + "slots": [ + { + "access": "public", + "index": 0, + "name": "mainContainerChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QDesignerObjectInspectorInterface" + } + ] + } + ], + "inputFile": "qdesigner_objectinspector_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "NewPromotedClassPanel", + "lineNumber": 42, + "object": true, + "qualifiedClassName": "qdesigner_internal::NewPromotedClassPanel", + "signals": [ + { + "access": "public", + "arguments": [ + { + "type": "PromotionParameters" + }, + { + "name": "ok", + "type": "bool*" + } + ], + "index": 0, + "name": "newPromotedClass", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "index": 1, + "name": "grabFocus", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QString" + } + ], + "index": 2, + "name": "chooseBaseClass", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "type": "QString" + } + ], + "index": 3, + "name": "slotNameChanged", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "type": "QString" + } + ], + "index": 4, + "name": "slotIncludeFileChanged", + "returnType": "void" + }, + { + "access": "private", + "index": 5, + "name": "slotAdd", + "returnType": "void" + }, + { + "access": "private", + "index": 6, + "name": "slotReset", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QGroupBox" + } + ] + }, + { + "className": "QDesignerPromotionDialog", + "lineNumber": 82, + "object": true, + "qualifiedClassName": "qdesigner_internal::QDesignerPromotionDialog", + "signals": [ + { + "access": "public", + "arguments": [ + { + "type": "QString" + } + ], + "index": 0, + "name": "selectedBaseClassChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "private", + "index": 1, + "name": "slotRemove", + "returnType": "void" + }, + { + "access": "private", + "index": 2, + "name": "slotAcceptPromoteTo", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "type": "QItemSelection" + }, + { + "type": "QItemSelection" + } + ], + "index": 3, + "name": "slotSelectionChanged", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "type": "PromotionParameters" + }, + { + "name": "ok", + "type": "bool*" + } + ], + "index": 4, + "name": "slotNewPromotedClass", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "type": "QDesignerWidgetDataBaseItemInterface*" + }, + { + "name": "includeFile", + "type": "QString" + } + ], + "index": 5, + "name": "slotIncludeFileChanged", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "type": "QDesignerWidgetDataBaseItemInterface*" + }, + { + "name": "newName", + "type": "QString" + } + ], + "index": 6, + "name": "slotClassNameChanged", + "returnType": "void" + }, + { + "access": "private", + "index": 7, + "name": "slotUpdateFromWidgetDatabase", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "type": "QPoint" + } + ], + "index": 8, + "name": "slotTreeViewContextMenu", + "returnType": "void" + }, + { + "access": "private", + "index": 9, + "name": "slotEditSignalsSlots", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QDialog" + } + ] + } + ], + "inputFile": "qdesigner_promotiondialog_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QDesignerPropertyEditor", + "lineNumber": 30, + "object": true, + "qualifiedClassName": "qdesigner_internal::QDesignerPropertyEditor", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "name", + "type": "QString" + }, + { + "name": "value", + "type": "QVariant" + }, + { + "name": "enableSubPropertyHandling", + "type": "bool" + } + ], + "index": 0, + "name": "propertyValueChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "name", + "type": "QString" + } + ], + "index": 1, + "name": "resetProperty", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "name", + "type": "QString" + }, + { + "name": "value", + "type": "QVariant" + } + ], + "index": 2, + "name": "addDynamicProperty", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "name", + "type": "QString" + } + ], + "index": 3, + "name": "removeDynamicProperty", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "editorOpened", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "editorClosed", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "index": 6, + "name": "updatePropertySheet", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "reloadResourceProperties", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "name", + "type": "QString" + }, + { + "name": "value", + "type": "QVariant" + } + ], + "index": 8, + "name": "slotPropertyChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QDesignerPropertyEditorInterface" + } + ] + } + ], + "inputFile": "qdesigner_propertyeditor_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QDesignerPropertySheet", + "interfaces": [ + [ + { + "className": "QDesignerPropertySheetExtension", + "id": "\"org.qt-project.Qt.Designer.PropertySheet\"" + } + ], + [ + { + "className": "QDesignerDynamicPropertySheetExtension", + "id": "\"org.qt-project.Qt.Designer.DynamicPropertySheet\"" + } + ] + ], + "lineNumber": 42, + "object": true, + "qualifiedClassName": "QDesignerPropertySheet", + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QDesignerPropertySheetExtension" + }, + { + "access": "public", + "name": "QDesignerDynamicPropertySheetExtension" + } + ] + }, + { + "className": "QDesignerAbstractPropertySheetFactory", + "interfaces": [ + [ + { + "className": "QAbstractExtensionFactory", + "id": "\"org.qt-project.Qt.QAbstractExtensionFactory\"" + } + ] + ], + "lineNumber": 173, + "object": true, + "qualifiedClassName": "QDesignerAbstractPropertySheetFactory", + "slots": [ + { + "access": "private", + "arguments": [ + { + "name": "object", + "type": "QObject*" + } + ], + "index": 0, + "name": "objectDestroyed", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QExtensionFactory" + } + ] + } + ], + "inputFile": "qdesigner_propertysheet_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QStackedWidgetPreviewEventFilter", + "lineNumber": 36, + "object": true, + "qualifiedClassName": "QStackedWidgetPreviewEventFilter", + "slots": [ + { + "access": "public", + "index": 0, + "name": "updateButtons", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "prevPage", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "nextPage", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "className": "QStackedWidgetEventFilter", + "lineNumber": 70, + "object": true, + "qualifiedClassName": "QStackedWidgetEventFilter", + "slots": [ + { + "access": "private", + "index": 0, + "name": "removeCurrentPage", + "returnType": "void" + }, + { + "access": "private", + "index": 1, + "name": "addPage", + "returnType": "void" + }, + { + "access": "private", + "index": 2, + "name": "addPageAfter", + "returnType": "void" + }, + { + "access": "private", + "index": 3, + "name": "changeOrder", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QStackedWidgetPreviewEventFilter" + } + ] + } + ], + "inputFile": "qdesigner_stackedbox_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QTabWidgetEventFilter", + "lineNumber": 38, + "object": true, + "qualifiedClassName": "QTabWidgetEventFilter", + "slots": [ + { + "access": "private", + "index": 0, + "name": "removeCurrentPage", + "returnType": "void" + }, + { + "access": "private", + "index": 1, + "name": "addPage", + "returnType": "void" + }, + { + "access": "private", + "index": 2, + "name": "addPageAfter", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qdesigner_tabwidget_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QDesignerTaskMenu", + "interfaces": [ + [ + { + "className": "QDesignerTaskMenuExtension", + "id": "\"org.qt-project.Qt.Designer.TaskMenu\"" + } + ] + ], + "lineNumber": 36, + "object": true, + "qualifiedClassName": "qdesigner_internal::QDesignerTaskMenu", + "slots": [ + { + "access": "private", + "index": 0, + "name": "changeObjectName", + "returnType": "void" + }, + { + "access": "private", + "index": 1, + "name": "changeToolTip", + "returnType": "void" + }, + { + "access": "private", + "index": 2, + "name": "changeWhatsThis", + "returnType": "void" + }, + { + "access": "private", + "index": 3, + "name": "changeStyleSheet", + "returnType": "void" + }, + { + "access": "private", + "index": 4, + "name": "createMenuBar", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "area", + "type": "Qt::ToolBarArea" + } + ], + "index": 5, + "name": "addToolBar", + "returnType": "void" + }, + { + "access": "private", + "index": 6, + "name": "createStatusBar", + "returnType": "void" + }, + { + "access": "private", + "index": 7, + "name": "removeStatusBar", + "returnType": "void" + }, + { + "access": "private", + "index": 8, + "name": "containerFakeMethods", + "returnType": "void" + }, + { + "access": "private", + "index": 9, + "name": "slotNavigateToSlot", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "a", + "type": "QAction*" + } + ], + "index": 10, + "name": "applySize", + "returnType": "void" + }, + { + "access": "private", + "index": 11, + "name": "slotLayoutAlignment", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QDesignerTaskMenuExtension" + } + ] + } + ], + "inputFile": "qdesigner_taskmenu_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "ToolBarEventFilter", + "lineNumber": 42, + "object": true, + "qualifiedClassName": "qdesigner_internal::ToolBarEventFilter", + "slots": [ + { + "access": "private", + "index": 0, + "name": "slotRemoveSelectedAction", + "returnType": "void" + }, + { + "access": "private", + "index": 1, + "name": "slotRemoveToolBar", + "returnType": "void" + }, + { + "access": "private", + "index": 2, + "name": "slotInsertSeparator", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qdesigner_toolbar_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QToolBoxHelper", + "lineNumber": 34, + "object": true, + "qualifiedClassName": "QToolBoxHelper", + "slots": [ + { + "access": "private", + "index": 0, + "name": "removeCurrentPage", + "returnType": "void" + }, + { + "access": "private", + "index": 1, + "name": "addPage", + "returnType": "void" + }, + { + "access": "private", + "index": 2, + "name": "addPageAfter", + "returnType": "void" + }, + { + "access": "private", + "index": 3, + "name": "changeOrder", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qdesigner_toolbox_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "DesignerPixmapCache", + "lineNumber": 296, + "object": true, + "qualifiedClassName": "qdesigner_internal::DesignerPixmapCache", + "signals": [ + { + "access": "public", + "index": 0, + "name": "reloaded", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "className": "DesignerIconCache", + "lineNumber": 310, + "object": true, + "qualifiedClassName": "qdesigner_internal::DesignerIconCache", + "signals": [ + { + "access": "public", + "index": 0, + "name": "reloaded", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qdesigner_utils_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QDesignerWidget", + "lineNumber": 30, + "object": true, + "qualifiedClassName": "QDesignerWidget", + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + }, + { + "className": "QDesignerDialog", + "lineNumber": 51, + "object": true, + "qualifiedClassName": "QDesignerDialog", + "superClasses": [ + { + "access": "public", + "name": "QDialog" + } + ] + }, + { + "className": "Line", + "lineNumber": 67, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "orientation", + "read": "orientation", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::Orientation", + "user": false, + "write": "setOrientation" + } + ], + "qualifiedClassName": "Line", + "superClasses": [ + { + "access": "public", + "name": "QFrame" + } + ] + } + ], + "inputFile": "qdesigner_widget_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QDesignerWidgetBox", + "lineNumber": 29, + "object": true, + "qualifiedClassName": "qdesigner_internal::QDesignerWidgetBox", + "superClasses": [ + { + "access": "public", + "name": "QDesignerWidgetBoxInterface" + } + ] + } + ], + "inputFile": "qdesigner_widgetbox_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QDesignerWidgetItem", + "lineNumber": 44, + "object": true, + "qualifiedClassName": "qdesigner_internal::QDesignerWidgetItem", + "slots": [ + { + "access": "private", + "index": 0, + "name": "layoutChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QWidgetItemV2" + } + ] + } + ], + "inputFile": "qdesigner_widgetitem_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QLayoutSupport", + "interfaces": [ + [ + { + "className": "QDesignerLayoutDecorationExtension", + "id": "\"org.qt-project.Qt.Designer.LayoutDecoration\"" + } + ] + ], + "lineNumber": 139, + "object": true, + "qualifiedClassName": "qdesigner_internal::QLayoutSupport", + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QDesignerLayoutDecorationExtension" + } + ] + }, + { + "className": "QLayoutWidget", + "lineNumber": 223, + "object": true, + "qualifiedClassName": "QLayoutWidget", + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + } + ], + "inputFile": "qlayout_widget_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "RichTextEditorDialog", + "lineNumber": 33, + "object": true, + "qualifiedClassName": "qdesigner_internal::RichTextEditorDialog", + "slots": [ + { + "access": "private", + "arguments": [ + { + "name": "newIndex", + "type": "int" + } + ], + "index": 0, + "name": "tabIndexChanged", + "returnType": "void" + }, + { + "access": "private", + "index": 1, + "name": "richTextChanged", + "returnType": "void" + }, + { + "access": "private", + "index": 2, + "name": "sourceChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QDialog" + } + ] + } + ], + "inputFile": "richtexteditor_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "SheetDelegate", + "lineNumber": 30, + "object": true, + "qualifiedClassName": "qdesigner_internal::SheetDelegate", + "superClasses": [ + { + "access": "public", + "name": "QItemDelegate" + } + ] + } + ], + "inputFile": "sheet_delegate_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "Spacer", + "lineNumber": 28, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "spacerName", + "read": "objectName", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setObjectName" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "orientation", + "read": "orientation", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::Orientation", + "user": false, + "write": "setOrientation" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "sizeType", + "read": "sizeType", + "required": false, + "scriptable": true, + "stored": true, + "type": "QSizePolicy::Policy", + "user": false, + "write": "setSizeType" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "sizeHint", + "read": "sizeHintProperty", + "required": false, + "scriptable": true, + "stored": true, + "type": "QSize", + "user": false, + "write": "setSizeHintProperty" + } + ], + "qualifiedClassName": "Spacer", + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + } + ], + "inputFile": "spacer_widget_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "StyleSheetEditor", + "lineNumber": 33, + "object": true, + "qualifiedClassName": "qdesigner_internal::StyleSheetEditor", + "superClasses": [ + { + "access": "public", + "name": "QTextEdit" + } + ] + }, + { + "className": "StyleSheetEditorDialog", + "lineNumber": 41, + "object": true, + "qualifiedClassName": "qdesigner_internal::StyleSheetEditorDialog", + "slots": [ + { + "access": "private", + "index": 0, + "name": "validateStyleSheet", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "pos", + "type": "QPoint" + } + ], + "index": 1, + "name": "slotContextMenuRequested", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "property", + "type": "QString" + } + ], + "index": 2, + "name": "slotAddResource", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "property", + "type": "QString" + } + ], + "index": 3, + "name": "slotAddGradient", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "property", + "type": "QString" + } + ], + "index": 4, + "name": "slotAddColor", + "returnType": "void" + }, + { + "access": "private", + "index": 5, + "name": "slotAddFont", + "returnType": "void" + }, + { + "access": "private", + "index": 6, + "name": "slotRequestHelp", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QDialog" + } + ] + }, + { + "className": "StyleSheetPropertyEditorDialog", + "lineNumber": 90, + "object": true, + "qualifiedClassName": "qdesigner_internal::StyleSheetPropertyEditorDialog", + "slots": [ + { + "access": "private", + "index": 0, + "name": "applyStyleSheet", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "fullyQualifiedName": "qdesigner_internal::StyleSheetEditorDialog", + "name": "StyleSheetEditorDialog" + } + ] + } + ], + "inputFile": "stylesheeteditor_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "TextPropertyEditor", + "lineNumber": 32, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "text", + "read": "text", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": true, + "write": "setText" + } + ], + "qualifiedClassName": "qdesigner_internal::TextPropertyEditor", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "text", + "type": "QString" + } + ], + "index": 0, + "name": "textChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "editingFinished", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "text", + "type": "QString" + } + ], + "index": 2, + "name": "setText", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "selectAll", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "clear", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "text", + "type": "QString" + } + ], + "index": 5, + "name": "slotTextChanged", + "returnType": "void" + }, + { + "access": "private", + "index": 6, + "name": "slotTextEdited", + "returnType": "void" + }, + { + "access": "private", + "index": 7, + "name": "slotEditingFinished", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + } + ], + "inputFile": "textpropertyeditor_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "WidgetDataBase", + "lineNumber": 123, + "object": true, + "qualifiedClassName": "qdesigner_internal::WidgetDataBase", + "slots": [ + { + "access": "public", + "index": 0, + "name": "loadPlugins", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QDesignerWidgetDataBaseInterface" + } + ] + } + ], + "inputFile": "widgetdatabase_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "WidgetFactory", + "lineNumber": 43, + "object": true, + "qualifiedClassName": "qdesigner_internal::WidgetFactory", + "slots": [ + { + "access": "public", + "index": 0, + "name": "loadPlugins", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "formWindow", + "type": "QDesignerFormWindowInterface*" + } + ], + "index": 1, + "name": "activeFormWindowChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "formWindow", + "type": "QDesignerFormWindowInterface*" + } + ], + "index": 2, + "name": "formWindowAdded", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QDesignerWidgetFactoryInterface" + } + ] + } + ], + "inputFile": "widgetfactory_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "ZoomMenu", + "lineNumber": 36, + "object": true, + "qualifiedClassName": "qdesigner_internal::ZoomMenu", + "signals": [ + { + "access": "public", + "arguments": [ + { + "type": "int" + } + ], + "index": 0, + "name": "zoomChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "percent", + "type": "int" + } + ], + "index": 1, + "name": "setZoom", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "type": "QAction*" + } + ], + "index": 2, + "name": "slotZoomMenu", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "className": "ZoomView", + "lineNumber": 66, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "zoom", + "read": "zoom", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setZoom" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "zoomContextMenuEnabled", + "read": "isZoomContextMenuEnabled", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setZoomContextMenuEnabled" + } + ], + "qualifiedClassName": "qdesigner_internal::ZoomView", + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "percent", + "type": "int" + } + ], + "index": 0, + "name": "setZoom", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "globalPos", + "type": "QPoint" + } + ], + "index": 1, + "name": "showContextMenu", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QGraphicsView" + } + ] + }, + { + "className": "ZoomWidget", + "lineNumber": 134, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "widgetZoomContextMenuEnabled", + "read": "isWidgetZoomContextMenuEnabled", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setWidgetZoomContextMenuEnabled" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "itemAcceptDrops", + "read": "itemAcceptDrops", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setItemAcceptDrops" + } + ], + "qualifiedClassName": "qdesigner_internal::ZoomWidget", + "slots": [ + { + "access": "public", + "index": 0, + "name": "dump", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "fullyQualifiedName": "qdesigner_internal::ZoomView", + "name": "ZoomView" + } + ] + } + ], + "inputFile": "zoomwidget_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QDesignerActionEditorInterface", + "lineNumber": 16, + "object": true, + "qualifiedClassName": "QDesignerActionEditorInterface", + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "formWindow", + "type": "QDesignerFormWindowInterface*" + } + ], + "index": 0, + "name": "setFormWindow", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + } + ], + "inputFile": "abstractactioneditor.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QDesignerFormEditorInterface", + "lineNumber": 39, + "object": true, + "qualifiedClassName": "QDesignerFormEditorInterface", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "abstractformeditor.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QDesignerFormWindowInterface", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "ResourceFileSaveMode", + "values": [ + "SaveAllResourceFiles", + "SaveOnlyUsedResourceFiles", + "DontSaveResourceFiles" + ] + } + ], + "lineNumber": 20, + "object": true, + "qualifiedClassName": "QDesignerFormWindowInterface", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "mainContainer", + "type": "QWidget*" + } + ], + "index": 0, + "name": "mainContainerChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "toolIndex", + "type": "int" + } + ], + "index": 1, + "name": "toolChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "fileName", + "type": "QString" + } + ], + "index": 2, + "name": "fileNameChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "f", + "type": "Feature" + } + ], + "index": 3, + "name": "featureChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "selectionChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "geometryChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "resourceFilesChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "widget", + "type": "QWidget*" + } + ], + "index": 7, + "name": "widgetManaged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "widget", + "type": "QWidget*" + } + ], + "index": 8, + "name": "widgetUnmanaged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "widget", + "type": "QWidget*" + } + ], + "index": 9, + "name": "aboutToUnmanageWidget", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "widget", + "type": "QWidget*" + } + ], + "index": 10, + "name": "activated", + "returnType": "void" + }, + { + "access": "public", + "index": 11, + "name": "changed", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "w", + "type": "QWidget*" + } + ], + "index": 12, + "name": "widgetRemoved", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "o", + "type": "QObject*" + } + ], + "index": 13, + "name": "objectRemoved", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "widget", + "type": "QWidget*" + } + ], + "index": 14, + "name": "manageWidget", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "widget", + "type": "QWidget*" + } + ], + "index": 15, + "name": "unmanageWidget", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "f", + "type": "Feature" + } + ], + "index": 16, + "name": "setFeatures", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "dirty", + "type": "bool" + } + ], + "index": 17, + "name": "setDirty", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "changePropertyDisplay", + "type": "bool" + } + ], + "index": 18, + "name": "clearSelection", + "returnType": "void" + }, + { + "access": "public", + "index": 19, + "isCloned": true, + "name": "clearSelection", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "w", + "type": "QWidget*" + }, + { + "name": "select", + "type": "bool" + } + ], + "index": 20, + "name": "selectWidget", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "w", + "type": "QWidget*" + } + ], + "index": 21, + "isCloned": true, + "name": "selectWidget", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "grid", + "type": "QPoint" + } + ], + "index": 22, + "name": "setGrid", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "fileName", + "type": "QString" + } + ], + "index": 23, + "name": "setFileName", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "contents", + "type": "QString" + } + ], + "index": 24, + "name": "setContents", + "returnType": "bool" + }, + { + "access": "public", + "index": 25, + "name": "editWidgets", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "paths", + "type": "QStringList" + }, + { + "name": "errorCount", + "type": "int*" + }, + { + "name": "errorMessages", + "type": "QString*" + } + ], + "index": 26, + "name": "activateResourceFilePaths", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "paths", + "type": "QStringList" + }, + { + "name": "errorCount", + "type": "int*" + } + ], + "index": 27, + "isCloned": true, + "name": "activateResourceFilePaths", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "paths", + "type": "QStringList" + } + ], + "index": 28, + "isCloned": true, + "name": "activateResourceFilePaths", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + } + ], + "inputFile": "abstractformwindow.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QDesignerFormWindowManagerInterface", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "Action", + "values": [ + "CutAction", + "CopyAction", + "PasteAction", + "DeleteAction", + "SelectAllAction", + "LowerAction", + "RaiseAction", + "UndoAction", + "RedoAction", + "HorizontalLayoutAction", + "VerticalLayoutAction", + "SplitHorizontalAction", + "SplitVerticalAction", + "GridLayoutAction", + "FormLayoutAction", + "BreakLayoutAction", + "AdjustSizeAction", + "SimplifyLayoutAction", + "DefaultPreviewAction", + "FormWindowSettingsDialogAction" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "ActionGroup", + "values": [ + "StyledPreviewActionGroup" + ] + } + ], + "lineNumber": 23, + "object": true, + "qualifiedClassName": "QDesignerFormWindowManagerInterface", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "formWindow", + "type": "QDesignerFormWindowInterface*" + } + ], + "index": 0, + "name": "formWindowAdded", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "formWindow", + "type": "QDesignerFormWindowInterface*" + } + ], + "index": 1, + "name": "formWindowRemoved", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "formWindow", + "type": "QDesignerFormWindowInterface*" + } + ], + "index": 2, + "name": "activeFormWindowChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "fw", + "type": "QDesignerFormWindowInterface*" + } + ], + "index": 3, + "name": "formWindowSettingsChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "formWindow", + "type": "QDesignerFormWindowInterface*" + } + ], + "index": 4, + "name": "addFormWindow", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "formWindow", + "type": "QDesignerFormWindowInterface*" + } + ], + "index": 5, + "name": "removeFormWindow", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "formWindow", + "type": "QDesignerFormWindowInterface*" + } + ], + "index": 6, + "name": "setActiveFormWindow", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "showPreview", + "returnType": "void" + }, + { + "access": "public", + "index": 8, + "name": "closeAllPreviews", + "returnType": "void" + }, + { + "access": "public", + "index": 9, + "name": "showPluginDialog", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "abstractformwindowmanager.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QDesignerFormWindowToolInterface", + "lineNumber": 19, + "object": true, + "qualifiedClassName": "QDesignerFormWindowToolInterface", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "abstractformwindowtool.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QDesignerIntegrationInterface", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "ResourceFileWatcherBehaviour", + "values": [ + "NoResourceFileWatcher", + "ReloadResourceFileSilently", + "PromptToReloadResourceFile" + ] + } + ], + "lineNumber": 27, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "headerSuffix", + "read": "headerSuffix", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setHeaderSuffix" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "headerLowercase", + "read": "isHeaderLowercase", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setHeaderLowercase" + } + ], + "qualifiedClassName": "QDesignerIntegrationInterface", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "formWindow", + "type": "QDesignerFormWindowInterface*" + }, + { + "name": "name", + "type": "QString" + }, + { + "name": "value", + "type": "QVariant" + } + ], + "index": 0, + "name": "propertyChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "formWindow", + "type": "QDesignerFormWindowInterface*" + }, + { + "name": "object", + "type": "QObject*" + }, + { + "name": "newName", + "type": "QString" + }, + { + "name": "oldName", + "type": "QString" + } + ], + "index": 1, + "name": "objectNameChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "manual", + "type": "QString" + }, + { + "name": "document", + "type": "QString" + } + ], + "index": 2, + "name": "helpRequested", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "objectName", + "type": "QString" + }, + { + "name": "signalSignature", + "type": "QString" + }, + { + "name": "parameterNames", + "type": "QStringList" + } + ], + "index": 3, + "name": "navigateToSlot", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "slotSignature", + "type": "QString" + } + ], + "index": 4, + "name": "navigateToSlot", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "f", + "type": "Feature" + } + ], + "index": 5, + "name": "setFeatures", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "name", + "type": "QString" + }, + { + "name": "value", + "type": "QVariant" + }, + { + "name": "enableSubPropertyHandling", + "type": "bool" + } + ], + "index": 6, + "name": "updateProperty", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "name", + "type": "QString" + }, + { + "name": "value", + "type": "QVariant" + } + ], + "index": 7, + "name": "updateProperty", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "name", + "type": "QString" + } + ], + "index": 8, + "name": "resetProperty", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "name", + "type": "QString" + }, + { + "name": "value", + "type": "QVariant" + } + ], + "index": 9, + "name": "addDynamicProperty", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "name", + "type": "QString" + } + ], + "index": 10, + "name": "removeDynamicProperty", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "formWindow", + "type": "QDesignerFormWindowInterface*" + } + ], + "index": 11, + "name": "updateActiveFormWindow", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "formWindow", + "type": "QDesignerFormWindowInterface*" + } + ], + "index": 12, + "name": "setupFormWindow", + "returnType": "void" + }, + { + "access": "public", + "index": 13, + "name": "updateSelection", + "returnType": "void" + }, + { + "access": "public", + "index": 14, + "name": "updateCustomWidgetPlugins", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "className": "QDesignerIntegration", + "lineNumber": 106, + "object": true, + "qualifiedClassName": "QDesignerIntegration", + "superClasses": [ + { + "access": "public", + "name": "QDesignerIntegrationInterface" + } + ] + } + ], + "inputFile": "abstractintegration.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QDesignerMetaDataBaseInterface", + "lineNumber": 39, + "object": true, + "qualifiedClassName": "QDesignerMetaDataBaseInterface", + "signals": [ + { + "access": "public", + "index": 0, + "name": "changed", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "abstractmetadatabase.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QDesignerNewFormWidgetInterface", + "lineNumber": 15, + "object": true, + "qualifiedClassName": "QDesignerNewFormWidgetInterface", + "signals": [ + { + "access": "public", + "index": 0, + "name": "templateActivated", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "templateSelected", + "type": "bool" + } + ], + "index": 1, + "name": "currentTemplateChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + } + ], + "inputFile": "abstractnewformwidget.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QDesignerObjectInspectorInterface", + "lineNumber": 16, + "object": true, + "qualifiedClassName": "QDesignerObjectInspectorInterface", + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "formWindow", + "type": "QDesignerFormWindowInterface*" + } + ], + "index": 0, + "name": "setFormWindow", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + } + ], + "inputFile": "abstractobjectinspector.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QDesignerPropertyEditorInterface", + "lineNumber": 17, + "object": true, + "qualifiedClassName": "QDesignerPropertyEditorInterface", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "name", + "type": "QString" + }, + { + "name": "value", + "type": "QVariant" + } + ], + "index": 0, + "name": "propertyChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "object", + "type": "QObject*" + } + ], + "index": 1, + "name": "setObject", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "name", + "type": "QString" + }, + { + "name": "value", + "type": "QVariant" + }, + { + "name": "changed", + "type": "bool" + } + ], + "index": 2, + "name": "setPropertyValue", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "name", + "type": "QString" + }, + { + "name": "value", + "type": "QVariant" + } + ], + "index": 3, + "isCloned": true, + "name": "setPropertyValue", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "readOnly", + "type": "bool" + } + ], + "index": 4, + "name": "setReadOnly", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + } + ], + "inputFile": "abstractpropertyeditor.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QDesignerResourceBrowserInterface", + "lineNumber": 15, + "object": true, + "qualifiedClassName": "QDesignerResourceBrowserInterface", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "filePath", + "type": "QString" + } + ], + "index": 0, + "name": "currentPathChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "filePath", + "type": "QString" + } + ], + "index": 1, + "name": "pathActivated", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + } + ], + "inputFile": "abstractresourcebrowser.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QDesignerWidgetBoxInterface", + "lineNumber": 21, + "object": true, + "qualifiedClassName": "QDesignerWidgetBoxInterface", + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + } + ], + "inputFile": "abstractwidgetbox.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QDesignerWidgetDataBaseInterface", + "lineNumber": 67, + "object": true, + "qualifiedClassName": "QDesignerWidgetDataBaseInterface", + "signals": [ + { + "access": "public", + "index": 0, + "name": "changed", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "abstractwidgetdatabase.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QDesignerWidgetFactoryInterface", + "lineNumber": 16, + "object": true, + "qualifiedClassName": "QDesignerWidgetFactoryInterface", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "abstractwidgetfactory.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QExtensionFactory", + "interfaces": [ + [ + { + "className": "QAbstractExtensionFactory", + "id": "\"org.qt-project.Qt.QAbstractExtensionFactory\"" + } + ] + ], + "lineNumber": 18, + "object": true, + "qualifiedClassName": "QExtensionFactory", + "slots": [ + { + "access": "private", + "arguments": [ + { + "name": "object", + "type": "QObject*" + } + ], + "index": 0, + "name": "objectDestroyed", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QAbstractExtensionFactory" + } + ] + } + ], + "inputFile": "default_extensionfactory.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QExtensionManager", + "interfaces": [ + [ + { + "className": "QAbstractExtensionManager", + "id": "\"org.qt-project.Qt.QAbstractExtensionManager\"" + } + ] + ], + "lineNumber": 15, + "object": true, + "qualifiedClassName": "QExtensionManager", + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QAbstractExtensionManager" + } + ] + } + ], + "inputFile": "qextensionmanager.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QAbstractFormBuilderGadget", + "lineNumber": 47, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "itemFlags", + "read": "fakeItemFlags", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::ItemFlags", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "checkState", + "read": "fakeCheckState", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::CheckState", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "textAlignment", + "read": "fakeAlignment", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::Alignment", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "orientation", + "read": "fakeOrientation", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::Orientation", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "sizeType", + "read": "fakeSizeType", + "required": false, + "scriptable": true, + "stored": true, + "type": "QSizePolicy::Policy", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "colorRole", + "read": "fakeColorRole", + "required": false, + "scriptable": true, + "stored": true, + "type": "QPalette::ColorRole", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "colorGroup", + "read": "fakeColorGroup", + "required": false, + "scriptable": true, + "stored": true, + "type": "QPalette::ColorGroup", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 7, + "name": "styleStrategy", + "read": "fakeStyleStrategy", + "required": false, + "scriptable": true, + "stored": true, + "type": "QFont::StyleStrategy", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 8, + "name": "hintingPreference", + "read": "fakeHintingPreference", + "required": false, + "scriptable": true, + "stored": true, + "type": "QFont::HintingPreference", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 9, + "name": "fontWeight", + "read": "fakeFontWeight", + "required": false, + "scriptable": true, + "stored": true, + "type": "QFont::Weight", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 10, + "name": "cursorShape", + "read": "fakeCursorShape", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::CursorShape", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 11, + "name": "brushStyle", + "read": "fakeBrushStyle", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::BrushStyle", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 12, + "name": "toolBarArea", + "read": "fakeToolBarArea", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::ToolBarArea", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 13, + "name": "gradientType", + "read": "fakeGradientType", + "required": false, + "scriptable": true, + "stored": true, + "type": "QGradient::Type", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 14, + "name": "gradientSpread", + "read": "fakeGradientSpread", + "required": false, + "scriptable": true, + "stored": true, + "type": "QGradient::Spread", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 15, + "name": "gradientCoordinate", + "read": "fakeGradientCoordinate", + "required": false, + "scriptable": true, + "stored": true, + "type": "QGradient::CoordinateMode", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 16, + "name": "language", + "read": "fakeLanguage", + "required": false, + "scriptable": true, + "stored": true, + "type": "QLocale::Language", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 17, + "name": "country", + "read": "fakeCountry", + "required": false, + "scriptable": true, + "stored": true, + "type": "QLocale::Country", + "user": false + } + ], + "qualifiedClassName": "QAbstractFormBuilderGadget", + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + } + ], + "inputFile": "properties_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QtBoolEdit", + "lineNumber": 68, + "object": true, + "qualifiedClassName": "QtBoolEdit", + "signals": [ + { + "access": "public", + "arguments": [ + { + "type": "bool" + } + ], + "index": 0, + "name": "toggled", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + } + ], + "inputFile": "qtpropertybrowserutils_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "AbstractFindWidget", + "lineNumber": 32, + "object": true, + "qualifiedClassName": "AbstractFindWidget", + "slots": [ + { + "access": "public", + "index": 0, + "name": "activate", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "deactivate", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "findNext", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "findPrevious", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "findCurrentText", + "returnType": "void" + }, + { + "access": "private", + "index": 5, + "name": "updateButtons", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + } + ], + "inputFile": "abstractfindwidget_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "ItemViewFindWidget", + "lineNumber": 26, + "object": true, + "qualifiedClassName": "ItemViewFindWidget", + "superClasses": [ + { + "access": "public", + "name": "AbstractFindWidget" + } + ] + } + ], + "inputFile": "itemviewfindwidget_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "TextEditFindWidget", + "lineNumber": 24, + "object": true, + "qualifiedClassName": "TextEditFindWidget", + "superClasses": [ + { + "access": "public", + "name": "AbstractFindWidget" + } + ] + } + ], + "inputFile": "texteditfindwidget_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "FormLayoutRowDialog", + "lineNumber": 61, + "object": true, + "qualifiedClassName": "qdesigner_internal::FormLayoutRowDialog", + "slots": [ + { + "access": "private", + "arguments": [ + { + "name": "text", + "type": "QString" + } + ], + "index": 0, + "name": "labelTextEdited", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "text", + "type": "QString" + } + ], + "index": 1, + "name": "labelNameEdited", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "text", + "type": "QString" + } + ], + "index": 2, + "name": "fieldNameEdited", + "returnType": "void" + }, + { + "access": "private", + "index": 3, + "name": "buddyClicked", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "type": "int" + } + ], + "index": 4, + "name": "fieldClassChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QDialog" + } + ] + } + ], + "inputFile": "formlayoutmenu.cpp", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "LanguageResourceDialog", + "lineNumber": 43, + "object": true, + "qualifiedClassName": "qdesigner_internal::LanguageResourceDialog", + "superClasses": [ + { + "access": "public", + "name": "QDialog" + } + ] + }, + { + "className": "IconSelector", + "lineNumber": 64, + "object": true, + "qualifiedClassName": "qdesigner_internal::IconSelector", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "icon", + "type": "PropertySheetIconValue" + } + ], + "index": 0, + "name": "iconChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + }, + { + "className": "IconThemeEditor", + "lineNumber": 95, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "theme", + "read": "theme", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setTheme" + } + ], + "qualifiedClassName": "qdesigner_internal::IconThemeEditor", + "signals": [ + { + "access": "public", + "arguments": [ + { + "type": "QString" + } + ], + "index": 0, + "name": "edited", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "index": 1, + "name": "reset", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + }, + { + "className": "IconThemeEnumEditor", + "lineNumber": 118, + "object": true, + "qualifiedClassName": "qdesigner_internal::IconThemeEnumEditor", + "signals": [ + { + "access": "public", + "arguments": [ + { + "type": "int" + } + ], + "index": 0, + "name": "edited", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "index": 1, + "name": "reset", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + } + ], + "inputFile": "iconselector_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "PluginDialog", + "lineNumber": 28, + "object": true, + "qualifiedClassName": "qdesigner_internal::PluginDialog", + "slots": [ + { + "access": "private", + "index": 0, + "name": "updateCustomWidgetPlugins", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "pos", + "type": "QPoint" + } + ], + "index": 1, + "name": "treeWidgetContextMenu", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QDialog" + } + ] + } + ], + "inputFile": "plugindialog_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QtResourceEditorDialog", + "lineNumber": 27, + "object": true, + "qualifiedClassName": "QtResourceEditorDialog", + "slots": [ + { + "access": "public", + "index": 0, + "name": "accept", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QDialog" + } + ] + } + ], + "inputFile": "qtresourceeditordialog_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QtResourceModel", + "lineNumber": 58, + "object": true, + "qualifiedClassName": "QtResourceModel", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "resourceSet", + "type": "QtResourceSet*" + }, + { + "name": "resourceSetChanged", + "type": "bool" + } + ], + "index": 0, + "name": "resourceSetActivated", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "path", + "type": "QString" + } + ], + "index": 1, + "name": "qrcFileModifiedExternally", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qtresourcemodel_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QtResourceView", + "lineNumber": 29, + "object": true, + "qualifiedClassName": "QtResourceView", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "resource", + "type": "QString" + } + ], + "index": 0, + "name": "resourceSelected", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "resource", + "type": "QString" + } + ], + "index": 1, + "name": "resourceActivated", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + }, + { + "className": "QtResourceViewDialog", + "lineNumber": 71, + "object": true, + "qualifiedClassName": "QtResourceViewDialog", + "superClasses": [ + { + "access": "public", + "name": "QDialog" + } + ] + } + ], + "inputFile": "qtresourceview_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "SelectSignalDialog", + "lineNumber": 30, + "object": true, + "qualifiedClassName": "qdesigner_internal::SelectSignalDialog", + "slots": [ + { + "access": "private", + "arguments": [ + { + "type": "QModelIndex" + }, + { + "type": "QModelIndex" + } + ], + "index": 0, + "name": "currentChanged", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "type": "QModelIndex" + } + ], + "index": 1, + "name": "activated", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QDialog" + } + ] + } + ], + "inputFile": "selectsignaldialog_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "SignatureModel", + "lineNumber": 48, + "object": true, + "qualifiedClassName": "qdesigner_internal::SignatureModel", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "signature", + "type": "QString" + }, + { + "name": "ok", + "type": "bool*" + } + ], + "index": 0, + "name": "checkSignature", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QStandardItemModel" + } + ] + }, + { + "className": "SignaturePanel", + "lineNumber": 61, + "object": true, + "qualifiedClassName": "qdesigner_internal::SignaturePanel", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "signature", + "type": "QString" + }, + { + "name": "ok", + "type": "bool*" + } + ], + "index": 0, + "name": "checkSignature", + "returnType": "void" + } + ], + "slots": [ + { + "access": "private", + "index": 1, + "name": "slotAdd", + "returnType": "void" + }, + { + "access": "private", + "index": 2, + "name": "slotRemove", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "type": "QItemSelection" + }, + { + "type": "QItemSelection" + } + ], + "index": 3, + "name": "slotSelectionChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "className": "SignalSlotDialog", + "lineNumber": 99, + "object": true, + "qualifiedClassName": "qdesigner_internal::SignalSlotDialog", + "slots": [ + { + "access": "private", + "arguments": [ + { + "name": "signature", + "type": "QString" + }, + { + "name": "ok", + "type": "bool*" + } + ], + "index": 0, + "name": "slotCheckSignature", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QDialog" + } + ] + } + ], + "inputFile": "signalslotdialog_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "PreviewDeviceSkin", + "lineNumber": 120, + "object": true, + "qualifiedClassName": "qdesigner_internal::PreviewDeviceSkin", + "slots": [ + { + "access": "private", + "arguments": [ + { + "name": "code", + "type": "int" + }, + { + "name": "text", + "type": "QString" + }, + { + "name": "autorep", + "type": "bool" + } + ], + "index": 0, + "name": "slotSkinKeyPressEvent", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "code", + "type": "int" + }, + { + "name": "text", + "type": "QString" + }, + { + "name": "autorep", + "type": "bool" + } + ], + "index": 1, + "name": "slotSkinKeyReleaseEvent", + "returnType": "void" + }, + { + "access": "private", + "index": 2, + "name": "slotPopupMenu", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "type": "QAction*" + } + ], + "index": 3, + "name": "slotDirection", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "DeviceSkin" + } + ] + }, + { + "className": "ZoomablePreviewDeviceSkin", + "lineNumber": 302, + "object": true, + "qualifiedClassName": "qdesigner_internal::ZoomablePreviewDeviceSkin", + "signals": [ + { + "access": "public", + "arguments": [ + { + "type": "int" + } + ], + "index": 0, + "name": "zoomPercentChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "type": "int" + } + ], + "index": 1, + "name": "setZoomPercent", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "fullyQualifiedName": "qdesigner_internal::PreviewDeviceSkin", + "name": "PreviewDeviceSkin" + } + ] + } + ], + "inputFile": "previewmanager.cpp", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "MyMimeData", + "lineNumber": 31, + "object": true, + "qualifiedClassName": "qdesigner_internal::MyMimeData", + "superClasses": [ + { + "access": "public", + "name": "QMimeData" + } + ] + } + ], + "inputFile": "qdesigner_tabwidget.cpp", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "LayoutAlignmentMenu", + "lineNumber": 124, + "object": true, + "qualifiedClassName": "qdesigner_internal::LayoutAlignmentMenu", + "signals": [ + { + "access": "public", + "index": 0, + "name": "changed", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qdesigner_taskmenu.cpp", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QtColorButtonPrivate", + "lineNumber": 14, + "object": true, + "qualifiedClassName": "QtColorButtonPrivate", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qtcolorbutton.cpp", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QtGradientDialogPrivate", + "lineNumber": 10, + "object": true, + "qualifiedClassName": "QtGradientDialogPrivate", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qtgradientdialog.cpp", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QtGradientEditorPrivate", + "lineNumber": 14, + "object": true, + "qualifiedClassName": "QtGradientEditorPrivate", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qtgradienteditor.cpp", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QtGradientStopsControllerPrivate", + "lineNumber": 14, + "object": true, + "qualifiedClassName": "QtGradientStopsControllerPrivate", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qtgradientstopscontroller.cpp", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QtGradientStopsWidgetPrivate", + "lineNumber": 19, + "object": true, + "qualifiedClassName": "QtGradientStopsWidgetPrivate", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qtgradientstopswidget.cpp", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QtQrcManager", + "lineNumber": 272, + "object": true, + "qualifiedClassName": "qdesigner_internal::QtQrcManager", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "qrcFile", + "type": "qdesigner_internal::QtQrcFile*" + } + ], + "index": 0, + "name": "qrcFileInserted", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "qrcFile", + "type": "qdesigner_internal::QtQrcFile*" + }, + { + "name": "oldBeforeQrcFile", + "type": "qdesigner_internal::QtQrcFile*" + } + ], + "index": 1, + "name": "qrcFileMoved", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "qrcFile", + "type": "qdesigner_internal::QtQrcFile*" + } + ], + "index": 2, + "name": "qrcFileRemoved", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "resourcePrefix", + "type": "qdesigner_internal::QtResourcePrefix*" + } + ], + "index": 3, + "name": "resourcePrefixInserted", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "resourcePrefix", + "type": "qdesigner_internal::QtResourcePrefix*" + }, + { + "name": "oldBeforeResourcePrefix", + "type": "qdesigner_internal::QtResourcePrefix*" + } + ], + "index": 4, + "name": "resourcePrefixMoved", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "resourcePrefix", + "type": "qdesigner_internal::QtResourcePrefix*" + }, + { + "name": "oldPrefix", + "type": "QString" + } + ], + "index": 5, + "name": "resourcePrefixChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "resourcePrefix", + "type": "qdesigner_internal::QtResourcePrefix*" + }, + { + "name": "oldLanguage", + "type": "QString" + } + ], + "index": 6, + "name": "resourceLanguageChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "resourcePrefix", + "type": "qdesigner_internal::QtResourcePrefix*" + } + ], + "index": 7, + "name": "resourcePrefixRemoved", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "resourceFile", + "type": "qdesigner_internal::QtResourceFile*" + } + ], + "index": 8, + "name": "resourceFileInserted", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "resourceFile", + "type": "qdesigner_internal::QtResourceFile*" + }, + { + "name": "oldBeforeResourceFile", + "type": "qdesigner_internal::QtResourceFile*" + } + ], + "index": 9, + "name": "resourceFileMoved", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "resourceFile", + "type": "qdesigner_internal::QtResourceFile*" + }, + { + "name": "oldAlias", + "type": "QString" + } + ], + "index": 10, + "name": "resourceAliasChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "resourceFile", + "type": "qdesigner_internal::QtResourceFile*" + } + ], + "index": 11, + "name": "resourceFileRemoved", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "path", + "type": "QString" + }, + { + "name": "beforeQrcFile", + "type": "qdesigner_internal::QtQrcFile*" + }, + { + "name": "newFile", + "type": "bool" + } + ], + "index": 12, + "name": "insertQrcFile", + "returnType": "QtQrcFile*" + }, + { + "access": "public", + "arguments": [ + { + "name": "path", + "type": "QString" + }, + { + "name": "beforeQrcFile", + "type": "qdesigner_internal::QtQrcFile*" + } + ], + "index": 13, + "isCloned": true, + "name": "insertQrcFile", + "returnType": "QtQrcFile*" + }, + { + "access": "public", + "arguments": [ + { + "name": "path", + "type": "QString" + } + ], + "index": 14, + "isCloned": true, + "name": "insertQrcFile", + "returnType": "QtQrcFile*" + }, + { + "access": "public", + "arguments": [ + { + "name": "qrcFile", + "type": "QtQrcFile*" + }, + { + "name": "beforeQrcFile", + "type": "qdesigner_internal::QtQrcFile*" + } + ], + "index": 15, + "name": "moveQrcFile", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "qrcFile", + "type": "qdesigner_internal::QtQrcFile*" + }, + { + "name": "initialState", + "type": "QtQrcFileData" + } + ], + "index": 16, + "name": "setInitialState", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "qrcFile", + "type": "qdesigner_internal::QtQrcFile*" + } + ], + "index": 17, + "name": "removeQrcFile", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "qrcFile", + "type": "qdesigner_internal::QtQrcFile*" + }, + { + "name": "prefix", + "type": "QString" + }, + { + "name": "language", + "type": "QString" + }, + { + "name": "beforeResourcePrefix", + "type": "QtResourcePrefix*" + } + ], + "index": 18, + "name": "insertResourcePrefix", + "returnType": "QtResourcePrefix*" + }, + { + "access": "public", + "arguments": [ + { + "name": "qrcFile", + "type": "qdesigner_internal::QtQrcFile*" + }, + { + "name": "prefix", + "type": "QString" + }, + { + "name": "language", + "type": "QString" + } + ], + "index": 19, + "isCloned": true, + "name": "insertResourcePrefix", + "returnType": "QtResourcePrefix*" + }, + { + "access": "public", + "arguments": [ + { + "name": "resourcePrefix", + "type": "qdesigner_internal::QtResourcePrefix*" + }, + { + "name": "beforeResourcePrefix", + "type": "QtResourcePrefix*" + } + ], + "index": 20, + "name": "moveResourcePrefix", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "resourcePrefix", + "type": "qdesigner_internal::QtResourcePrefix*" + }, + { + "name": "newPrefix", + "type": "QString" + } + ], + "index": 21, + "name": "changeResourcePrefix", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "resourcePrefix", + "type": "qdesigner_internal::QtResourcePrefix*" + }, + { + "name": "newLanguage", + "type": "QString" + } + ], + "index": 22, + "name": "changeResourceLanguage", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "resourcePrefix", + "type": "qdesigner_internal::QtResourcePrefix*" + } + ], + "index": 23, + "name": "removeResourcePrefix", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "resourcePrefix", + "type": "qdesigner_internal::QtResourcePrefix*" + }, + { + "name": "path", + "type": "QString" + }, + { + "name": "alias", + "type": "QString" + }, + { + "name": "beforeResourceFile", + "type": "qdesigner_internal::QtResourceFile*" + } + ], + "index": 24, + "name": "insertResourceFile", + "returnType": "QtResourceFile*" + }, + { + "access": "public", + "arguments": [ + { + "name": "resourcePrefix", + "type": "qdesigner_internal::QtResourcePrefix*" + }, + { + "name": "path", + "type": "QString" + }, + { + "name": "alias", + "type": "QString" + } + ], + "index": 25, + "isCloned": true, + "name": "insertResourceFile", + "returnType": "QtResourceFile*" + }, + { + "access": "public", + "arguments": [ + { + "name": "resourceFile", + "type": "qdesigner_internal::QtResourceFile*" + }, + { + "name": "beforeResourceFile", + "type": "qdesigner_internal::QtResourceFile*" + } + ], + "index": 26, + "name": "moveResourceFile", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "resourceFile", + "type": "qdesigner_internal::QtResourceFile*" + }, + { + "name": "newAlias", + "type": "QString" + } + ], + "index": 27, + "name": "changeResourceAlias", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "resourceFile", + "type": "qdesigner_internal::QtResourceFile*" + } + ], + "index": 28, + "name": "removeResourceFile", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qtresourceeditordialog.cpp", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "RichTextEditor", + "lineNumber": 139, + "object": true, + "qualifiedClassName": "qdesigner_internal::RichTextEditor", + "signals": [ + { + "access": "public", + "index": 0, + "name": "stateChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "bool" + } + ], + "index": 1, + "name": "simplifyRichTextChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "b", + "type": "bool" + } + ], + "index": 2, + "name": "setFontBold", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "double" + } + ], + "index": 3, + "name": "setFontPointSize", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "text", + "type": "QString" + } + ], + "index": 4, + "name": "setText", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "v", + "type": "bool" + } + ], + "index": 5, + "name": "setSimplifyRichText", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QTextEdit" + } + ] + }, + { + "className": "AddLinkDialog", + "lineNumber": 166, + "object": true, + "qualifiedClassName": "qdesigner_internal::AddLinkDialog", + "slots": [ + { + "access": "public", + "index": 0, + "name": "accept", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QDialog" + } + ] + }, + { + "className": "HtmlTextEdit", + "lineNumber": 228, + "object": true, + "qualifiedClassName": "qdesigner_internal::HtmlTextEdit", + "slots": [ + { + "access": "private", + "arguments": [ + { + "name": "action", + "type": "QAction*" + } + ], + "index": 0, + "name": "actionTriggered", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QTextEdit" + } + ] + }, + { + "className": "ColorAction", + "lineNumber": 280, + "object": true, + "qualifiedClassName": "qdesigner_internal::ColorAction", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "color", + "type": "QColor" + } + ], + "index": 0, + "name": "colorChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "private", + "index": 1, + "name": "chooseColor", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QAction" + } + ] + }, + { + "className": "RichTextEditorToolBar", + "lineNumber": 331, + "object": true, + "qualifiedClassName": "qdesigner_internal::RichTextEditorToolBar", + "slots": [ + { + "access": "public", + "index": 0, + "name": "updateActions", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "action", + "type": "QAction*" + } + ], + "index": 1, + "name": "alignmentActionTriggered", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "size", + "type": "QString" + } + ], + "index": 2, + "name": "sizeInputActivated", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "color", + "type": "QColor" + } + ], + "index": 3, + "name": "colorChanged", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "super", + "type": "bool" + } + ], + "index": 4, + "name": "setVAlignSuper", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "sub", + "type": "bool" + } + ], + "index": 5, + "name": "setVAlignSub", + "returnType": "void" + }, + { + "access": "private", + "index": 6, + "name": "insertLink", + "returnType": "void" + }, + { + "access": "private", + "index": 7, + "name": "insertImage", + "returnType": "void" + }, + { + "access": "private", + "index": 8, + "name": "layoutDirectionChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QToolBar" + } + ] + } + ], + "inputFile": "richtexteditor.cpp", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "WizardPageChangeWatcher", + "lineNumber": 169, + "object": true, + "qualifiedClassName": "qdesigner_internal::WizardPageChangeWatcher", + "slots": [ + { + "access": "public", + "index": 0, + "name": "pageChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "widgetfactory.cpp", + "outputRevision": 68 + } +] diff --git a/qt/6.8.1/msvc2022_64/metatypes/qt6designercomponentsprivate_metatypes.json b/qt/6.8.1/msvc2022_64/metatypes/qt6designercomponentsprivate_metatypes.json new file mode 100644 index 0000000000000000000000000000000000000000..92711ec7f2a9a1dfc93794ca4c95d7658bc54b02 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/metatypes/qt6designercomponentsprivate_metatypes.json @@ -0,0 +1,7978 @@ +[ + { + "classes": [ + { + "className": "QtColorButton", + "lineNumber": 22, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "backgroundCheckered", + "read": "isBackgroundCheckered", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setBackgroundCheckered" + } + ], + "qualifiedClassName": "QtColorButton", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "color", + "type": "QColor" + } + ], + "index": 0, + "name": "colorChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "color", + "type": "QColor" + } + ], + "index": 1, + "name": "setColor", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QToolButton" + } + ] + } + ], + "inputFile": "qtcolorbutton_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "BuddyEditor", + "lineNumber": 21, + "object": true, + "qualifiedClassName": "qdesigner_internal::BuddyEditor", + "slots": [ + { + "access": "public", + "index": 0, + "name": "updateBackground", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "w", + "type": "QWidget*" + } + ], + "index": 1, + "name": "widgetRemoved", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "autoBuddy", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "fullyQualifiedName": "qdesigner_internal::ConnectionEdit", + "name": "ConnectionEdit" + } + ] + } + ], + "inputFile": "buddyeditor.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "BuddyEditorPlugin", + "interfaces": [ + [ + { + "className": "QDesignerFormEditorPluginInterface", + "id": "\"org.qt-project.Qt.Designer.QDesignerFormEditorPluginInterface\"" + } + ] + ], + "lineNumber": 23, + "object": true, + "qualifiedClassName": "qdesigner_internal::BuddyEditorPlugin", + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "formWindow", + "type": "QDesignerFormWindowInterface*" + } + ], + "index": 0, + "name": "activeFormWindowChanged", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "formWindow", + "type": "QDesignerFormWindowInterface*" + } + ], + "index": 1, + "name": "addFormWindow", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "formWindow", + "type": "QDesignerFormWindowInterface*" + } + ], + "index": 2, + "name": "removeFormWindow", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QDesignerFormEditorPluginInterface" + } + ] + } + ], + "inputFile": "buddyeditor_plugin.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "BuddyEditorTool", + "lineNumber": 23, + "object": true, + "qualifiedClassName": "qdesigner_internal::BuddyEditorTool", + "superClasses": [ + { + "access": "public", + "name": "QDesignerFormWindowToolInterface" + } + ] + } + ], + "inputFile": "buddyeditor_tool.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "ButtonGroupMenu", + "lineNumber": 24, + "object": true, + "qualifiedClassName": "qdesigner_internal::ButtonGroupMenu", + "slots": [ + { + "access": "private", + "index": 0, + "name": "selectGroup", + "returnType": "void" + }, + { + "access": "private", + "index": 1, + "name": "breakGroup", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "className": "ButtonGroupTaskMenu", + "interfaces": [ + [ + { + "className": "QDesignerTaskMenuExtension", + "id": "\"org.qt-project.Qt.Designer.TaskMenu\"" + } + ] + ], + "lineNumber": 53, + "object": true, + "qualifiedClassName": "qdesigner_internal::ButtonGroupTaskMenu", + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QDesignerTaskMenuExtension" + } + ] + }, + { + "className": "ButtonTaskMenu", + "lineNumber": 71, + "object": true, + "qualifiedClassName": "qdesigner_internal::ButtonTaskMenu", + "slots": [ + { + "access": "private", + "index": 0, + "name": "createGroup", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "a", + "type": "QAction*" + } + ], + "index": 1, + "name": "addToGroup", + "returnType": "void" + }, + { + "access": "private", + "index": 2, + "name": "removeFromGroup", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "fullyQualifiedName": "qdesigner_internal::QDesignerTaskMenu", + "name": "QDesignerTaskMenu" + } + ] + }, + { + "className": "CommandLinkButtonTaskMenu", + "lineNumber": 117, + "object": true, + "qualifiedClassName": "qdesigner_internal::CommandLinkButtonTaskMenu", + "superClasses": [ + { + "access": "public", + "fullyQualifiedName": "qdesigner_internal::ButtonTaskMenu", + "name": "ButtonTaskMenu" + } + ] + } + ], + "inputFile": "button_taskmenu.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "ComboBoxTaskMenu", + "lineNumber": 20, + "object": true, + "qualifiedClassName": "qdesigner_internal::ComboBoxTaskMenu", + "slots": [ + { + "access": "private", + "index": 0, + "name": "editItems", + "returnType": "void" + }, + { + "access": "private", + "index": 1, + "name": "updateSelection", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "fullyQualifiedName": "qdesigner_internal::QDesignerTaskMenu", + "name": "QDesignerTaskMenu" + } + ] + } + ], + "inputFile": "combobox_taskmenu.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "ContainerWidgetTaskMenu", + "lineNumber": 30, + "object": true, + "qualifiedClassName": "qdesigner_internal::ContainerWidgetTaskMenu", + "slots": [ + { + "access": "private", + "index": 0, + "name": "removeCurrentPage", + "returnType": "void" + }, + { + "access": "private", + "index": 1, + "name": "addPage", + "returnType": "void" + }, + { + "access": "private", + "index": 2, + "name": "addPageAfter", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "fullyQualifiedName": "qdesigner_internal::QDesignerTaskMenu", + "name": "QDesignerTaskMenu" + } + ] + }, + { + "className": "WizardContainerWidgetTaskMenu", + "lineNumber": 72, + "object": true, + "qualifiedClassName": "qdesigner_internal::WizardContainerWidgetTaskMenu", + "superClasses": [ + { + "access": "public", + "fullyQualifiedName": "qdesigner_internal::ContainerWidgetTaskMenu", + "name": "ContainerWidgetTaskMenu" + } + ] + }, + { + "className": "MdiContainerWidgetTaskMenu", + "lineNumber": 87, + "object": true, + "qualifiedClassName": "qdesigner_internal::MdiContainerWidgetTaskMenu", + "superClasses": [ + { + "access": "public", + "fullyQualifiedName": "qdesigner_internal::ContainerWidgetTaskMenu", + "name": "ContainerWidgetTaskMenu" + } + ] + }, + { + "className": "ContainerWidgetTaskMenuFactory", + "lineNumber": 102, + "object": true, + "qualifiedClassName": "qdesigner_internal::ContainerWidgetTaskMenuFactory", + "superClasses": [ + { + "access": "public", + "name": "QExtensionFactory" + } + ] + } + ], + "inputFile": "containerwidget_taskmenu.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "GroupBoxTaskMenu", + "lineNumber": 20, + "object": true, + "qualifiedClassName": "qdesigner_internal::GroupBoxTaskMenu", + "superClasses": [ + { + "access": "public", + "fullyQualifiedName": "qdesigner_internal::QDesignerTaskMenu", + "name": "QDesignerTaskMenu" + } + ] + } + ], + "inputFile": "groupbox_taskmenu.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "InPlaceEditor", + "lineNumber": 22, + "object": true, + "qualifiedClassName": "qdesigner_internal::InPlaceEditor", + "superClasses": [ + { + "access": "public", + "fullyQualifiedName": "qdesigner_internal::TextPropertyEditor", + "name": "TextPropertyEditor" + } + ] + }, + { + "className": "TaskMenuInlineEditor", + "lineNumber": 40, + "object": true, + "qualifiedClassName": "qdesigner_internal::TaskMenuInlineEditor", + "slots": [ + { + "access": "public", + "index": 0, + "name": "editText", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "text", + "type": "QString" + } + ], + "index": 1, + "name": "updateText", + "returnType": "void" + }, + { + "access": "private", + "index": 2, + "name": "updateSelection", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "inplace_editor.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "InPlaceWidgetHelper", + "lineNumber": 28, + "object": true, + "qualifiedClassName": "qdesigner_internal::InPlaceWidgetHelper", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "inplace_widget_helper.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "AbstractItemEditor", + "lineNumber": 40, + "object": true, + "qualifiedClassName": "qdesigner_internal::AbstractItemEditor", + "slots": [ + { + "access": "public", + "index": 0, + "name": "cacheReloaded", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + } + ], + "index": 1, + "name": "propertyChanged", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + } + ], + "index": 2, + "name": "resetProperty", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + }, + { + "className": "ItemListEditor", + "lineNumber": 87, + "object": true, + "qualifiedClassName": "qdesigner_internal::ItemListEditor", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "idx", + "type": "int" + } + ], + "index": 0, + "name": "indexChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "idx", + "type": "int" + }, + { + "name": "role", + "type": "int" + }, + { + "name": "v", + "type": "QVariant" + } + ], + "index": 1, + "name": "itemChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "idx", + "type": "int" + } + ], + "index": 2, + "name": "itemInserted", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "idx", + "type": "int" + } + ], + "index": 3, + "name": "itemDeleted", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "idx", + "type": "int" + } + ], + "index": 4, + "name": "itemMovedUp", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "idx", + "type": "int" + } + ], + "index": 5, + "name": "itemMovedDown", + "returnType": "void" + } + ], + "slots": [ + { + "access": "private", + "index": 6, + "name": "newListItemButtonClicked", + "returnType": "void" + }, + { + "access": "private", + "index": 7, + "name": "deleteListItemButtonClicked", + "returnType": "void" + }, + { + "access": "private", + "index": 8, + "name": "moveListItemUpButtonClicked", + "returnType": "void" + }, + { + "access": "private", + "index": 9, + "name": "moveListItemDownButtonClicked", + "returnType": "void" + }, + { + "access": "private", + "index": 10, + "name": "listWidgetCurrentRowChanged", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "item", + "type": "QListWidgetItem*" + } + ], + "index": 11, + "name": "listWidgetItemChanged", + "returnType": "void" + }, + { + "access": "private", + "index": 12, + "name": "togglePropertyBrowser", + "returnType": "void" + }, + { + "access": "private", + "index": 13, + "name": "cacheReloaded", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "fullyQualifiedName": "qdesigner_internal::AbstractItemEditor", + "name": "AbstractItemEditor" + } + ] + } + ], + "inputFile": "itemlisteditor.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "LabelTaskMenu", + "lineNumber": 19, + "object": true, + "qualifiedClassName": "qdesigner_internal::LabelTaskMenu", + "slots": [ + { + "access": "private", + "index": 0, + "name": "editRichText", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "fullyQualifiedName": "qdesigner_internal::QDesignerTaskMenu", + "name": "QDesignerTaskMenu" + } + ] + } + ], + "inputFile": "label_taskmenu.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "LayoutWidgetTaskMenu", + "interfaces": [ + [ + { + "className": "QDesignerTaskMenuExtension", + "id": "\"org.qt-project.Qt.Designer.TaskMenu\"" + } + ] + ], + "lineNumber": 21, + "object": true, + "qualifiedClassName": "LayoutWidgetTaskMenu", + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QDesignerTaskMenuExtension" + } + ] + }, + { + "className": "SpacerTaskMenu", + "interfaces": [ + [ + { + "className": "QDesignerTaskMenuExtension", + "id": "\"org.qt-project.Qt.Designer.TaskMenu\"" + } + ] + ], + "lineNumber": 38, + "object": true, + "qualifiedClassName": "SpacerTaskMenu", + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QDesignerTaskMenuExtension" + } + ] + } + ], + "inputFile": "layouttaskmenu.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "LineEditTaskMenu", + "lineNumber": 17, + "object": true, + "qualifiedClassName": "qdesigner_internal::LineEditTaskMenu", + "superClasses": [ + { + "access": "public", + "fullyQualifiedName": "qdesigner_internal::QDesignerTaskMenu", + "name": "QDesignerTaskMenu" + } + ] + } + ], + "inputFile": "lineedit_taskmenu.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "ListWidgetTaskMenu", + "lineNumber": 20, + "object": true, + "qualifiedClassName": "qdesigner_internal::ListWidgetTaskMenu", + "slots": [ + { + "access": "private", + "index": 0, + "name": "editItems", + "returnType": "void" + }, + { + "access": "private", + "index": 1, + "name": "updateSelection", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "fullyQualifiedName": "qdesigner_internal::QDesignerTaskMenu", + "name": "QDesignerTaskMenu" + } + ] + } + ], + "inputFile": "listwidget_taskmenu.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "ListWidgetEditor", + "lineNumber": 20, + "object": true, + "qualifiedClassName": "qdesigner_internal::ListWidgetEditor", + "superClasses": [ + { + "access": "public", + "name": "QDialog" + } + ] + } + ], + "inputFile": "listwidgeteditor.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "MenuTaskMenu", + "interfaces": [ + [ + { + "className": "QDesignerTaskMenuExtension", + "id": "\"org.qt-project.Qt.Designer.TaskMenu\"" + } + ] + ], + "lineNumber": 25, + "object": true, + "qualifiedClassName": "qdesigner_internal::MenuTaskMenu", + "slots": [ + { + "access": "private", + "index": 0, + "name": "removeMenu", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QDesignerTaskMenuExtension" + } + ] + }, + { + "className": "MenuBarTaskMenu", + "interfaces": [ + [ + { + "className": "QDesignerTaskMenuExtension", + "id": "\"org.qt-project.Qt.Designer.TaskMenu\"" + } + ] + ], + "lineNumber": 47, + "object": true, + "qualifiedClassName": "qdesigner_internal::MenuBarTaskMenu", + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QDesignerTaskMenuExtension" + } + ] + } + ], + "inputFile": "menutaskmenu.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "TableWidgetTaskMenu", + "lineNumber": 20, + "object": true, + "qualifiedClassName": "qdesigner_internal::TableWidgetTaskMenu", + "slots": [ + { + "access": "private", + "index": 0, + "name": "editItems", + "returnType": "void" + }, + { + "access": "private", + "index": 1, + "name": "updateSelection", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "fullyQualifiedName": "qdesigner_internal::QDesignerTaskMenu", + "name": "QDesignerTaskMenu" + } + ] + } + ], + "inputFile": "tablewidget_taskmenu.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "TableWidgetEditor", + "lineNumber": 23, + "object": true, + "qualifiedClassName": "qdesigner_internal::TableWidgetEditor", + "slots": [ + { + "access": "private", + "arguments": [ + { + "name": "currentRow", + "type": "int" + }, + { + "name": "currentCol", + "type": "int" + } + ], + "index": 0, + "name": "tableWidgetCurrentCellChanged", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "item", + "type": "QTableWidgetItem*" + } + ], + "index": 1, + "name": "tableWidgetItemChanged", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "idx", + "type": "int" + } + ], + "index": 2, + "name": "columnEditorIndexChanged", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "idx", + "type": "int" + }, + { + "name": "role", + "type": "int" + }, + { + "name": "v", + "type": "QVariant" + } + ], + "index": 3, + "name": "columnEditorItemChanged", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "idx", + "type": "int" + } + ], + "index": 4, + "name": "columnEditorItemInserted", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "idx", + "type": "int" + } + ], + "index": 5, + "name": "columnEditorItemDeleted", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "idx", + "type": "int" + } + ], + "index": 6, + "name": "columnEditorItemMovedUp", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "idx", + "type": "int" + } + ], + "index": 7, + "name": "columnEditorItemMovedDown", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "idx", + "type": "int" + } + ], + "index": 8, + "name": "rowEditorIndexChanged", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "idx", + "type": "int" + }, + { + "name": "role", + "type": "int" + }, + { + "name": "v", + "type": "QVariant" + } + ], + "index": 9, + "name": "rowEditorItemChanged", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "idx", + "type": "int" + } + ], + "index": 10, + "name": "rowEditorItemInserted", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "idx", + "type": "int" + } + ], + "index": 11, + "name": "rowEditorItemDeleted", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "idx", + "type": "int" + } + ], + "index": 12, + "name": "rowEditorItemMovedUp", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "idx", + "type": "int" + } + ], + "index": 13, + "name": "rowEditorItemMovedDown", + "returnType": "void" + }, + { + "access": "private", + "index": 14, + "name": "togglePropertyBrowser", + "returnType": "void" + }, + { + "access": "private", + "index": 15, + "name": "cacheReloaded", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "fullyQualifiedName": "qdesigner_internal::AbstractItemEditor", + "name": "AbstractItemEditor" + } + ] + }, + { + "className": "TableWidgetEditorDialog", + "lineNumber": 76, + "object": true, + "qualifiedClassName": "qdesigner_internal::TableWidgetEditorDialog", + "superClasses": [ + { + "access": "public", + "name": "QDialog" + } + ] + } + ], + "inputFile": "tablewidgeteditor.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "TaskMenuComponent", + "lineNumber": 18, + "object": true, + "qualifiedClassName": "qdesigner_internal::TaskMenuComponent", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "taskmenu_component.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "TextEditTaskMenu", + "lineNumber": 19, + "object": true, + "qualifiedClassName": "qdesigner_internal::TextEditTaskMenu", + "slots": [ + { + "access": "private", + "index": 0, + "name": "editText", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "fullyQualifiedName": "qdesigner_internal::QDesignerTaskMenu", + "name": "QDesignerTaskMenu" + } + ] + } + ], + "inputFile": "textedit_taskmenu.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "ToolBarTaskMenu", + "interfaces": [ + [ + { + "className": "QDesignerTaskMenuExtension", + "id": "\"org.qt-project.Qt.Designer.TaskMenu\"" + } + ] + ], + "lineNumber": 20, + "object": true, + "qualifiedClassName": "qdesigner_internal::ToolBarTaskMenu", + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QDesignerTaskMenuExtension" + } + ] + }, + { + "className": "StatusBarTaskMenu", + "interfaces": [ + [ + { + "className": "QDesignerTaskMenuExtension", + "id": "\"org.qt-project.Qt.Designer.TaskMenu\"" + } + ] + ], + "lineNumber": 35, + "object": true, + "qualifiedClassName": "qdesigner_internal::StatusBarTaskMenu", + "slots": [ + { + "access": "private", + "index": 0, + "name": "removeStatusBar", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QDesignerTaskMenuExtension" + } + ] + } + ], + "inputFile": "toolbar_taskmenu.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "TreeWidgetTaskMenu", + "lineNumber": 20, + "object": true, + "qualifiedClassName": "qdesigner_internal::TreeWidgetTaskMenu", + "slots": [ + { + "access": "private", + "index": 0, + "name": "editItems", + "returnType": "void" + }, + { + "access": "private", + "index": 1, + "name": "updateSelection", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "fullyQualifiedName": "qdesigner_internal::QDesignerTaskMenu", + "name": "QDesignerTaskMenu" + } + ] + } + ], + "inputFile": "treewidget_taskmenu.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "TreeWidgetEditor", + "lineNumber": 23, + "object": true, + "qualifiedClassName": "qdesigner_internal::TreeWidgetEditor", + "slots": [ + { + "access": "private", + "index": 0, + "name": "newItemButtonClicked", + "returnType": "void" + }, + { + "access": "private", + "index": 1, + "name": "newSubItemButtonClicked", + "returnType": "void" + }, + { + "access": "private", + "index": 2, + "name": "deleteItemButtonClicked", + "returnType": "void" + }, + { + "access": "private", + "index": 3, + "name": "moveItemUpButtonClicked", + "returnType": "void" + }, + { + "access": "private", + "index": 4, + "name": "moveItemDownButtonClicked", + "returnType": "void" + }, + { + "access": "private", + "index": 5, + "name": "moveItemRightButtonClicked", + "returnType": "void" + }, + { + "access": "private", + "index": 6, + "name": "moveItemLeftButtonClicked", + "returnType": "void" + }, + { + "access": "private", + "index": 7, + "name": "treeWidgetCurrentItemChanged", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "item", + "type": "QTreeWidgetItem*" + }, + { + "name": "column", + "type": "int" + } + ], + "index": 8, + "name": "treeWidgetItemChanged", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "idx", + "type": "int" + } + ], + "index": 9, + "name": "columnEditorIndexChanged", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "idx", + "type": "int" + }, + { + "name": "role", + "type": "int" + }, + { + "name": "v", + "type": "QVariant" + } + ], + "index": 10, + "name": "columnEditorItemChanged", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "idx", + "type": "int" + } + ], + "index": 11, + "name": "columnEditorItemInserted", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "idx", + "type": "int" + } + ], + "index": 12, + "name": "columnEditorItemDeleted", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "idx", + "type": "int" + } + ], + "index": 13, + "name": "columnEditorItemMovedUp", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "idx", + "type": "int" + } + ], + "index": 14, + "name": "columnEditorItemMovedDown", + "returnType": "void" + }, + { + "access": "private", + "index": 15, + "name": "togglePropertyBrowser", + "returnType": "void" + }, + { + "access": "private", + "index": 16, + "name": "cacheReloaded", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "fullyQualifiedName": "qdesigner_internal::AbstractItemEditor", + "name": "AbstractItemEditor" + } + ] + }, + { + "className": "TreeWidgetEditorDialog", + "lineNumber": 75, + "object": true, + "qualifiedClassName": "qdesigner_internal::TreeWidgetEditorDialog", + "superClasses": [ + { + "access": "public", + "name": "QDialog" + } + ] + } + ], + "inputFile": "treewidgeteditor.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "WidgetBox", + "lineNumber": 19, + "object": true, + "qualifiedClassName": "qdesigner_internal::WidgetBox", + "slots": [ + { + "access": "private", + "arguments": [ + { + "name": "name", + "type": "QString" + }, + { + "name": "xml", + "type": "QString" + }, + { + "name": "global_mouse_pos", + "type": "QPoint" + } + ], + "index": 0, + "name": "handleMousePress", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "fullyQualifiedName": "qdesigner_internal::QDesignerWidgetBox", + "name": "QDesignerWidgetBox" + } + ] + } + ], + "inputFile": "widgetbox.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "WidgetBoxCategoryListView", + "lineNumber": 25, + "object": true, + "qualifiedClassName": "qdesigner_internal::WidgetBoxCategoryListView", + "signals": [ + { + "access": "public", + "index": 0, + "name": "scratchPadChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "name", + "type": "QString" + }, + { + "name": "xml", + "type": "QString" + }, + { + "name": "globalPos", + "type": "QPoint" + } + ], + "index": 1, + "name": "widgetBoxPressed", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "itemRemoved", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "lastItemRemoved", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "needle", + "type": "QString" + }, + { + "name": "caseSensitivity", + "type": "Qt::CaseSensitivity" + } + ], + "index": 4, + "name": "filter", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "removeCurrentItem", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "editCurrentItem", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "index", + "type": "QModelIndex" + } + ], + "index": 7, + "name": "slotPressed", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QListView" + } + ] + } + ], + "inputFile": "widgetboxcategorylistview.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "WidgetBoxTreeWidget", + "lineNumber": 28, + "object": true, + "qualifiedClassName": "qdesigner_internal::WidgetBoxTreeWidget", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "name", + "type": "QString" + }, + { + "name": "dom_xml", + "type": "QString" + }, + { + "name": "global_mouse_pos", + "type": "QPoint" + } + ], + "index": 0, + "name": "widgetBoxPressed", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "type": "QString" + } + ], + "index": 1, + "name": "filter", + "returnType": "void" + }, + { + "access": "private", + "index": 2, + "name": "slotSave", + "returnType": "void" + }, + { + "access": "private", + "index": 3, + "name": "slotScratchPadItemDeleted", + "returnType": "void" + }, + { + "access": "private", + "index": 4, + "name": "slotLastScratchPadItemDeleted", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "item", + "type": "QTreeWidgetItem*" + } + ], + "index": 5, + "name": "handleMousePress", + "returnType": "void" + }, + { + "access": "private", + "index": 6, + "name": "deleteScratchpad", + "returnType": "void" + }, + { + "access": "private", + "index": 7, + "name": "slotListMode", + "returnType": "void" + }, + { + "access": "private", + "index": 8, + "name": "slotIconMode", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QTreeWidget" + } + ] + } + ], + "inputFile": "widgetboxtreewidget.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QToolBarActionProvider", + "interfaces": [ + [ + { + "className": "QDesignerActionProviderExtension", + "id": "\"org.qt-project.Qt.Designer.ActionProvider\"" + } + ] + ], + "lineNumber": 37, + "object": true, + "qualifiedClassName": "qdesigner_internal::QToolBarActionProvider", + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "ActionProviderBase" + } + ] + }, + { + "className": "QMenuBarActionProvider", + "interfaces": [ + [ + { + "className": "QDesignerActionProviderExtension", + "id": "\"org.qt-project.Qt.Designer.ActionProvider\"" + } + ] + ], + "lineNumber": 55, + "object": true, + "qualifiedClassName": "qdesigner_internal::QMenuBarActionProvider", + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "ActionProviderBase" + } + ] + }, + { + "className": "QMenuActionProvider", + "interfaces": [ + [ + { + "className": "QDesignerActionProviderExtension", + "id": "\"org.qt-project.Qt.Designer.ActionProvider\"" + } + ] + ], + "lineNumber": 70, + "object": true, + "qualifiedClassName": "qdesigner_internal::QMenuActionProvider", + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "ActionProviderBase" + } + ] + } + ], + "inputFile": "default_actionprovider.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QStackedWidgetContainer", + "interfaces": [ + [ + { + "className": "QDesignerContainerExtension", + "id": "\"org.qt-project.Qt.Designer.Container\"" + } + ] + ], + "lineNumber": 22, + "object": true, + "qualifiedClassName": "qdesigner_internal::QStackedWidgetContainer", + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QDesignerContainerExtension" + } + ] + }, + { + "className": "QTabWidgetContainer", + "interfaces": [ + [ + { + "className": "QDesignerContainerExtension", + "id": "\"org.qt-project.Qt.Designer.Container\"" + } + ] + ], + "lineNumber": 46, + "object": true, + "qualifiedClassName": "qdesigner_internal::QTabWidgetContainer", + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QDesignerContainerExtension" + } + ] + }, + { + "className": "QToolBoxContainer", + "interfaces": [ + [ + { + "className": "QDesignerContainerExtension", + "id": "\"org.qt-project.Qt.Designer.Container\"" + } + ] + ], + "lineNumber": 70, + "object": true, + "qualifiedClassName": "qdesigner_internal::QToolBoxContainer", + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QDesignerContainerExtension" + } + ] + }, + { + "className": "QScrollAreaContainer", + "interfaces": [ + [ + { + "className": "QDesignerContainerExtension", + "id": "\"org.qt-project.Qt.Designer.Container\"" + } + ] + ], + "lineNumber": 158, + "object": true, + "qualifiedClassName": "qdesigner_internal::QScrollAreaContainer", + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "SingleChildContainer" + } + ] + }, + { + "className": "QDockWidgetContainer", + "interfaces": [ + [ + { + "className": "QDesignerContainerExtension", + "id": "\"org.qt-project.Qt.Designer.Container\"" + } + ] + ], + "lineNumber": 167, + "object": true, + "qualifiedClassName": "qdesigner_internal::QDockWidgetContainer", + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "SingleChildContainer" + } + ] + } + ], + "inputFile": "default_container.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QDesignerLayoutDecorationFactory", + "interfaces": [ + [ + { + "className": "QAbstractExtensionFactory", + "id": "\"org.qt-project.Qt.QAbstractExtensionFactory\"" + } + ] + ], + "lineNumber": 16, + "object": true, + "qualifiedClassName": "qdesigner_internal::QDesignerLayoutDecorationFactory", + "superClasses": [ + { + "access": "public", + "name": "QExtensionFactory" + } + ] + } + ], + "inputFile": "default_layoutdecoration.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "DeviceProfileDialog", + "lineNumber": 37, + "object": true, + "qualifiedClassName": "qdesigner_internal::DeviceProfileDialog", + "slots": [ + { + "access": "private", + "arguments": [ + { + "type": "bool" + } + ], + "index": 0, + "name": "setOkButtonEnabled", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "name", + "type": "QString" + } + ], + "index": 1, + "name": "nameChanged", + "returnType": "void" + }, + { + "access": "private", + "index": 2, + "name": "save", + "returnType": "void" + }, + { + "access": "private", + "index": 3, + "name": "open", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QDialog" + } + ] + } + ], + "inputFile": "deviceprofiledialog.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "DPI_Chooser", + "lineNumber": 30, + "object": true, + "qualifiedClassName": "qdesigner_internal::DPI_Chooser", + "slots": [ + { + "access": "private", + "index": 0, + "name": "syncSpinBoxes", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + } + ], + "inputFile": "dpi_chooser.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "EmbeddedOptionsControl", + "lineNumber": 21, + "object": true, + "qualifiedClassName": "qdesigner_internal::EmbeddedOptionsControl", + "slots": [ + { + "access": "public", + "index": 0, + "name": "loadSettings", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "saveSettings", + "returnType": "void" + }, + { + "access": "private", + "index": 2, + "name": "slotAdd", + "returnType": "void" + }, + { + "access": "private", + "index": 3, + "name": "slotEdit", + "returnType": "void" + }, + { + "access": "private", + "index": 4, + "name": "slotDelete", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "type": "int" + } + ], + "index": 5, + "name": "slotProfileIndexChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + } + ], + "inputFile": "embeddedoptionspage.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "FormEditor", + "lineNumber": 17, + "object": true, + "qualifiedClassName": "qdesigner_internal::FormEditor", + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "path", + "type": "QString" + } + ], + "index": 0, + "name": "slotQrcFileChangedExternally", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QDesignerFormEditorInterface" + } + ] + } + ], + "inputFile": "formeditor.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "FormWindow", + "lineNumber": 44, + "object": true, + "qualifiedClassName": "qdesigner_internal::FormWindow", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "menu", + "type": "QMenu*" + }, + { + "name": "widget", + "type": "QWidget*" + } + ], + "index": 0, + "name": "contextMenuRequested", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "index": 1, + "name": "deleteWidgets", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "raiseWidgets", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "lowerWidgets", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "copy", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "cut", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "paste", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "selectAll", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "type", + "type": "int" + }, + { + "name": "container", + "type": "QWidget*" + } + ], + "index": 8, + "name": "createLayout", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "type", + "type": "int" + } + ], + "index": 9, + "isCloned": true, + "name": "createLayout", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "container", + "type": "QWidget*" + }, + { + "name": "newType", + "type": "int" + } + ], + "index": 10, + "name": "morphLayout", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "w", + "type": "QWidget*" + } + ], + "index": 11, + "name": "breakLayout", + "returnType": "void" + }, + { + "access": "public", + "index": 12, + "name": "editContents", + "returnType": "void" + }, + { + "access": "private", + "index": 13, + "name": "selectionChangedTimerDone", + "returnType": "void" + }, + { + "access": "private", + "index": 14, + "name": "checkSelection", + "returnType": "void" + }, + { + "access": "private", + "index": 15, + "name": "checkSelectionNow", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "type": "QAction*" + } + ], + "index": 16, + "name": "slotSelectWidget", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "type": "bool" + } + ], + "index": 17, + "name": "slotCleanChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "fullyQualifiedName": "qdesigner_internal::FormWindowBase", + "name": "FormWindowBase" + } + ] + } + ], + "inputFile": "formwindow.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "FormWindowWidgetStack", + "lineNumber": 20, + "object": true, + "qualifiedClassName": "qdesigner_internal::FormWindowWidgetStack", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + } + ], + "index": 0, + "name": "currentToolChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "tool", + "type": "QDesignerFormWindowToolInterface*" + } + ], + "index": 1, + "name": "addTool", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "tool", + "type": "QDesignerFormWindowToolInterface*" + } + ], + "index": 2, + "name": "setCurrentTool", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + } + ], + "index": 3, + "name": "setCurrentTool", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "setSenderAsCurrentTool", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "formwindow_widgetstack.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "FormWindowCursor", + "lineNumber": 17, + "object": true, + "qualifiedClassName": "qdesigner_internal::FormWindowCursor", + "slots": [ + { + "access": "public", + "index": 0, + "name": "update", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QDesignerFormWindowCursorInterface" + } + ] + } + ], + "inputFile": "formwindowcursor.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "FormWindowManager", + "lineNumber": 31, + "object": true, + "qualifiedClassName": "qdesigner_internal::FormWindowManager", + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "formWindow", + "type": "QDesignerFormWindowInterface*" + } + ], + "index": 0, + "name": "addFormWindow", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "formWindow", + "type": "QDesignerFormWindowInterface*" + } + ], + "index": 1, + "name": "removeFormWindow", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "formWindow", + "type": "QDesignerFormWindowInterface*" + } + ], + "index": 2, + "name": "setActiveFormWindow", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "closeAllPreviews", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "deviceProfilesChanged", + "returnType": "void" + }, + { + "access": "private", + "index": 5, + "name": "slotActionCutActivated", + "returnType": "void" + }, + { + "access": "private", + "index": 6, + "name": "slotActionCopyActivated", + "returnType": "void" + }, + { + "access": "private", + "index": 7, + "name": "slotActionPasteActivated", + "returnType": "void" + }, + { + "access": "private", + "index": 8, + "name": "slotActionDeleteActivated", + "returnType": "void" + }, + { + "access": "private", + "index": 9, + "name": "slotActionSelectAllActivated", + "returnType": "void" + }, + { + "access": "private", + "index": 10, + "name": "slotActionLowerActivated", + "returnType": "void" + }, + { + "access": "private", + "index": 11, + "name": "slotActionRaiseActivated", + "returnType": "void" + }, + { + "access": "private", + "index": 12, + "name": "createLayout", + "returnType": "void" + }, + { + "access": "private", + "index": 13, + "name": "slotActionBreakLayoutActivated", + "returnType": "void" + }, + { + "access": "private", + "index": 14, + "name": "slotActionAdjustSizeActivated", + "returnType": "void" + }, + { + "access": "private", + "index": 15, + "name": "slotActionSimplifyLayoutActivated", + "returnType": "void" + }, + { + "access": "private", + "index": 16, + "name": "showPreview", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "style", + "type": "QString" + }, + { + "name": "deviceProfileIndex", + "type": "int" + } + ], + "index": 17, + "name": "slotActionGroupPreviewInStyle", + "returnType": "void" + }, + { + "access": "private", + "index": 18, + "name": "slotActionShowFormWindowSettingsDialog", + "returnType": "void" + }, + { + "access": "private", + "index": 19, + "name": "slotUpdateActions", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "fullyQualifiedName": "qdesigner_internal::QDesignerFormWindowManager", + "name": "QDesignerFormWindowManager" + } + ] + } + ], + "inputFile": "formwindowmanager.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "FormWindowSettings", + "lineNumber": 25, + "object": true, + "qualifiedClassName": "qdesigner_internal::FormWindowSettings", + "superClasses": [ + { + "access": "public", + "name": "QDialog" + } + ] + } + ], + "inputFile": "formwindowsettings.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "ItemViewPropertySheet", + "interfaces": [ + [ + { + "className": "QDesignerPropertySheetExtension", + "id": "\"org.qt-project.Qt.Designer.PropertySheet\"" + } + ] + ], + "lineNumber": 19, + "object": true, + "qualifiedClassName": "qdesigner_internal::ItemViewPropertySheet", + "superClasses": [ + { + "access": "public", + "name": "QDesignerPropertySheet" + } + ] + } + ], + "inputFile": "itemview_propertysheet.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "LayoutPropertySheet", + "interfaces": [ + [ + { + "className": "QDesignerPropertySheetExtension", + "id": "\"org.qt-project.Qt.Designer.PropertySheet\"" + } + ] + ], + "lineNumber": 19, + "object": true, + "qualifiedClassName": "qdesigner_internal::LayoutPropertySheet", + "superClasses": [ + { + "access": "public", + "name": "QDesignerPropertySheet" + } + ] + } + ], + "inputFile": "layout_propertysheet.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "LinePropertySheet", + "interfaces": [ + [ + { + "className": "QDesignerPropertySheetExtension", + "id": "\"org.qt-project.Qt.Designer.PropertySheet\"" + } + ] + ], + "lineNumber": 15, + "object": true, + "qualifiedClassName": "qdesigner_internal::LinePropertySheet", + "superClasses": [ + { + "access": "public", + "name": "QDesignerPropertySheet" + } + ] + } + ], + "inputFile": "line_propertysheet.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "PreviewActionGroup", + "lineNumber": 29, + "object": true, + "qualifiedClassName": "qdesigner_internal::PreviewActionGroup", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "style", + "type": "QString" + }, + { + "name": "deviceProfileIndex", + "type": "int" + } + ], + "index": 0, + "name": "preview", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "index": 1, + "name": "updateDeviceProfiles", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "type": "QAction*" + } + ], + "index": 2, + "name": "slotTriggered", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QActionGroup" + } + ] + } + ], + "inputFile": "previewactiongroup.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QLayoutWidgetPropertySheet", + "interfaces": [ + [ + { + "className": "QDesignerPropertySheetExtension", + "id": "\"org.qt-project.Qt.Designer.PropertySheet\"" + } + ] + ], + "lineNumber": 15, + "object": true, + "qualifiedClassName": "qdesigner_internal::QLayoutWidgetPropertySheet", + "superClasses": [ + { + "access": "public", + "name": "QDesignerPropertySheet" + } + ] + } + ], + "inputFile": "qlayoutwidget_propertysheet.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QMainWindowContainer", + "interfaces": [ + [ + { + "className": "QDesignerContainerExtension", + "id": "\"org.qt-project.Qt.Designer.Container\"" + } + ] + ], + "lineNumber": 18, + "object": true, + "qualifiedClassName": "qdesigner_internal::QMainWindowContainer", + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QDesignerContainerExtension" + } + ] + } + ], + "inputFile": "qmainwindow_container.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QMdiAreaContainer", + "interfaces": [ + [ + { + "className": "QDesignerContainerExtension", + "id": "\"org.qt-project.Qt.Designer.Container\"" + } + ] + ], + "lineNumber": 20, + "object": true, + "qualifiedClassName": "qdesigner_internal::QMdiAreaContainer", + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QDesignerContainerExtension" + } + ] + }, + { + "className": "QMdiAreaPropertySheet", + "interfaces": [ + [ + { + "className": "QDesignerPropertySheetExtension", + "id": "\"org.qt-project.Qt.Designer.PropertySheet\"" + } + ] + ], + "lineNumber": 46, + "object": true, + "qualifiedClassName": "qdesigner_internal::QMdiAreaPropertySheet", + "superClasses": [ + { + "access": "public", + "name": "QDesignerPropertySheet" + } + ] + } + ], + "inputFile": "qmdiarea_container.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QWizardContainer", + "interfaces": [ + [ + { + "className": "QDesignerContainerExtension", + "id": "\"org.qt-project.Qt.Designer.Container\"" + } + ] + ], + "lineNumber": 23, + "object": true, + "qualifiedClassName": "qdesigner_internal::QWizardContainer", + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QDesignerContainerExtension" + } + ] + }, + { + "className": "QWizardPagePropertySheet", + "lineNumber": 49, + "object": true, + "qualifiedClassName": "qdesigner_internal::QWizardPagePropertySheet", + "superClasses": [ + { + "access": "public", + "name": "QDesignerPropertySheet" + } + ] + }, + { + "className": "QWizardPropertySheet", + "lineNumber": 67, + "object": true, + "qualifiedClassName": "qdesigner_internal::QWizardPropertySheet", + "superClasses": [ + { + "access": "public", + "name": "QDesignerPropertySheet" + } + ] + } + ], + "inputFile": "qwizard_container.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "SpacerPropertySheet", + "interfaces": [ + [ + { + "className": "QDesignerPropertySheetExtension", + "id": "\"org.qt-project.Qt.Designer.PropertySheet\"" + } + ] + ], + "lineNumber": 15, + "object": true, + "qualifiedClassName": "qdesigner_internal::SpacerPropertySheet", + "superClasses": [ + { + "access": "public", + "name": "QDesignerPropertySheet" + } + ] + } + ], + "inputFile": "spacer_propertysheet.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "TemplateOptionsWidget", + "lineNumber": 26, + "object": true, + "qualifiedClassName": "qdesigner_internal::TemplateOptionsWidget", + "slots": [ + { + "access": "private", + "index": 0, + "name": "addTemplatePath", + "returnType": "void" + }, + { + "access": "private", + "index": 1, + "name": "removeTemplatePath", + "returnType": "void" + }, + { + "access": "private", + "index": 2, + "name": "templatePathSelectionChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + } + ], + "inputFile": "templateoptionspage.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "WidgetEditorTool", + "lineNumber": 22, + "object": true, + "qualifiedClassName": "qdesigner_internal::WidgetEditorTool", + "superClasses": [ + { + "access": "public", + "name": "QDesignerFormWindowToolInterface" + } + ] + } + ], + "inputFile": "tool_widgeteditor.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "WidgetHandle", + "lineNumber": 24, + "object": true, + "qualifiedClassName": "qdesigner_internal::WidgetHandle", + "superClasses": [ + { + "access": "public", + "fullyQualifiedName": "qdesigner_internal::InvisibleWidget", + "name": "InvisibleWidget" + } + ] + }, + { + "className": "WidgetSelection", + "lineNumber": 73, + "object": true, + "qualifiedClassName": "qdesigner_internal::WidgetSelection", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "widgetselection.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "ObjectInspector", + "lineNumber": 19, + "object": true, + "qualifiedClassName": "qdesigner_internal::ObjectInspector", + "slots": [ + { + "access": "public", + "index": 0, + "name": "mainContainerChanged", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "selected", + "type": "QItemSelection" + }, + { + "name": "deselected", + "type": "QItemSelection" + } + ], + "index": 1, + "name": "slotSelectionChanged", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "pos", + "type": "QPoint" + } + ], + "index": 2, + "name": "slotPopupContextMenu", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "column", + "type": "int" + } + ], + "index": 3, + "name": "slotHeaderDoubleClicked", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "fullyQualifiedName": "qdesigner_internal::QDesignerObjectInspector", + "name": "QDesignerObjectInspector" + } + ] + } + ], + "inputFile": "objectinspector.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "TabOrderEditor", + "lineNumber": 22, + "object": true, + "qualifiedClassName": "qdesigner_internal::TabOrderEditor", + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "background", + "type": "QWidget*" + } + ], + "index": 0, + "name": "setBackground", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "updateBackground", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QWidget*" + } + ], + "index": 2, + "name": "widgetRemoved", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "initTabOrder", + "returnType": "void" + }, + { + "access": "private", + "index": 4, + "name": "showTabOrderDialog", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + } + ], + "inputFile": "tabordereditor.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "TabOrderEditorTool", + "lineNumber": 23, + "object": true, + "qualifiedClassName": "qdesigner_internal::TabOrderEditorTool", + "superClasses": [ + { + "access": "public", + "name": "QDesignerFormWindowToolInterface" + } + ] + } + ], + "inputFile": "tabordereditor_tool.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "ResetDecorator", + "lineNumber": 41, + "object": true, + "qualifiedClassName": "qdesigner_internal::ResetDecorator", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + } + ], + "index": 0, + "name": "resetProperty", + "returnType": "void" + } + ], + "slots": [ + { + "access": "private", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + } + ], + "index": 1, + "name": "slotPropertyChanged", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "object", + "type": "QObject*" + } + ], + "index": 2, + "name": "slotEditorDestroyed", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "className": "DesignerPropertyManager", + "lineNumber": 95, + "object": true, + "qualifiedClassName": "qdesigner_internal::DesignerPropertyManager", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "value", + "type": "QVariant" + }, + { + "name": "enableSubPropertyHandling", + "type": "bool" + } + ], + "index": 0, + "name": "valueChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "attribute", + "type": "QString" + }, + { + "name": "value", + "type": "QVariant" + } + ], + "index": 1, + "name": "setAttribute", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "value", + "type": "QVariant" + } + ], + "index": 2, + "name": "setValue", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "value", + "type": "QVariant" + } + ], + "index": 3, + "name": "slotValueChanged", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + } + ], + "index": 4, + "name": "slotPropertyDestroyed", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QtVariantPropertyManager" + } + ] + }, + { + "className": "DesignerEditorFactory", + "lineNumber": 230, + "object": true, + "qualifiedClassName": "qdesigner_internal::DesignerEditorFactory", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + } + ], + "index": 0, + "name": "resetProperty", + "returnType": "void" + } + ], + "slots": [ + { + "access": "private", + "arguments": [ + { + "name": "object", + "type": "QObject*" + } + ], + "index": 1, + "name": "slotEditorDestroyed", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "attribute", + "type": "QString" + }, + { + "name": "value", + "type": "QVariant" + } + ], + "index": 2, + "name": "slotAttributeChanged", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + } + ], + "index": 3, + "name": "slotPropertyChanged", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "value", + "type": "QVariant" + } + ], + "index": 4, + "name": "slotValueChanged", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "value", + "type": "QString" + } + ], + "index": 5, + "name": "slotStringTextChanged", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "value", + "type": "QKeySequence" + } + ], + "index": 6, + "name": "slotKeySequenceChanged", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "value", + "type": "QPalette" + } + ], + "index": 7, + "name": "slotPaletteChanged", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "value", + "type": "QString" + } + ], + "index": 8, + "name": "slotPixmapChanged", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "value", + "type": "QString" + } + ], + "index": 9, + "name": "slotIconChanged", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "value", + "type": "QString" + } + ], + "index": 10, + "name": "slotIconThemeChanged", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "value", + "type": "int" + } + ], + "index": 11, + "name": "slotIconThemeEnumChanged", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "value", + "type": "QString" + } + ], + "index": 12, + "name": "slotUintChanged", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "type": "int" + } + ], + "index": 13, + "name": "slotIntChanged", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "value", + "type": "QString" + } + ], + "index": 14, + "name": "slotLongLongChanged", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "value", + "type": "QString" + } + ], + "index": 15, + "name": "slotULongLongChanged", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "value", + "type": "QString" + } + ], + "index": 16, + "name": "slotUrlChanged", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "value", + "type": "QString" + } + ], + "index": 17, + "name": "slotByteArrayChanged", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "value", + "type": "QStringList" + } + ], + "index": 18, + "name": "slotStringListChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QtVariantEditorFactory" + } + ] + } + ], + "inputFile": "designerpropertymanager.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "NewDynamicPropertyDialog", + "lineNumber": 34, + "object": true, + "qualifiedClassName": "qdesigner_internal::NewDynamicPropertyDialog", + "slots": [ + { + "access": "private", + "arguments": [ + { + "name": "btn", + "type": "QAbstractButton*" + } + ], + "index": 0, + "name": "buttonBoxClicked", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "type": "QString" + } + ], + "index": 1, + "name": "nameChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QDialog" + } + ] + } + ], + "inputFile": "newdynamicpropertydialog.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "PaletteEditor", + "lineNumber": 21, + "object": true, + "qualifiedClassName": "qdesigner_internal::PaletteEditor", + "slots": [ + { + "access": "private", + "index": 0, + "name": "buildButtonColorChanged", + "returnType": "void" + }, + { + "access": "private", + "index": 1, + "name": "activeRadioClicked", + "returnType": "void" + }, + { + "access": "private", + "index": 2, + "name": "inactiveRadioClicked", + "returnType": "void" + }, + { + "access": "private", + "index": 3, + "name": "disabledRadioClicked", + "returnType": "void" + }, + { + "access": "private", + "index": 4, + "name": "computeRadioClicked", + "returnType": "void" + }, + { + "access": "private", + "index": 5, + "name": "detailsRadioClicked", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "palette", + "type": "QPalette" + } + ], + "index": 6, + "name": "paletteChanged", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "pos", + "type": "QPoint" + } + ], + "index": 7, + "name": "viewContextMenuRequested", + "returnType": "void" + }, + { + "access": "private", + "index": 8, + "name": "save", + "returnType": "void" + }, + { + "access": "private", + "index": 9, + "name": "load", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QDialog" + } + ] + }, + { + "className": "PaletteModel", + "lineNumber": 77, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "colorRole", + "read": "colorRole", + "required": false, + "scriptable": true, + "stored": true, + "type": "QPalette::ColorRole", + "user": false + } + ], + "qualifiedClassName": "qdesigner_internal::PaletteModel", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "palette", + "type": "QPalette" + } + ], + "index": 0, + "name": "paletteChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QAbstractTableModel" + } + ] + }, + { + "className": "BrushEditor", + "lineNumber": 122, + "object": true, + "qualifiedClassName": "qdesigner_internal::BrushEditor", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "widget", + "type": "QWidget*" + } + ], + "index": 0, + "name": "changed", + "returnType": "void" + } + ], + "slots": [ + { + "access": "private", + "index": 1, + "name": "brushChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + }, + { + "className": "RoleEditor", + "lineNumber": 141, + "object": true, + "qualifiedClassName": "qdesigner_internal::RoleEditor", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "widget", + "type": "QWidget*" + } + ], + "index": 0, + "name": "changed", + "returnType": "void" + } + ], + "slots": [ + { + "access": "private", + "index": 1, + "name": "emitResetProperty", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + }, + { + "className": "ColorDelegate", + "lineNumber": 159, + "object": true, + "qualifiedClassName": "qdesigner_internal::ColorDelegate", + "superClasses": [ + { + "access": "public", + "name": "QItemDelegate" + } + ] + } + ], + "inputFile": "paletteeditor.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "PaletteEditorButton", + "lineNumber": 18, + "object": true, + "qualifiedClassName": "qdesigner_internal::PaletteEditorButton", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "palette", + "type": "QPalette" + } + ], + "index": 0, + "name": "paletteChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "palette", + "type": "QPalette" + } + ], + "index": 1, + "name": "setPalette", + "returnType": "void" + }, + { + "access": "private", + "index": 2, + "name": "showPaletteEditor", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QToolButton" + } + ] + } + ], + "inputFile": "paletteeditorbutton.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "IconThemeDialog", + "lineNumber": 28, + "object": true, + "qualifiedClassName": "qdesigner_internal::IconThemeDialog", + "superClasses": [ + { + "access": "public", + "name": "QDialog" + } + ] + }, + { + "className": "IconThemeEnumDialog", + "lineNumber": 38, + "object": true, + "qualifiedClassName": "qdesigner_internal::IconThemeEnumDialog", + "superClasses": [ + { + "access": "public", + "name": "QDialog" + } + ] + }, + { + "className": "PixmapEditor", + "lineNumber": 49, + "object": true, + "qualifiedClassName": "qdesigner_internal::PixmapEditor", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "path", + "type": "QString" + } + ], + "index": 0, + "name": "pathChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "themeEnum", + "type": "int" + } + ], + "index": 1, + "name": "themeEnumChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "theme", + "type": "QString" + } + ], + "index": 2, + "name": "themeChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "path", + "type": "QString" + } + ], + "index": 3, + "name": "setPath", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "theme", + "type": "QString" + } + ], + "index": 4, + "name": "setTheme", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "e", + "type": "int" + } + ], + "index": 5, + "name": "setThemeEnum", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "pixmap", + "type": "QPixmap" + } + ], + "index": 6, + "name": "setDefaultPixmap", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "icon", + "type": "QIcon" + } + ], + "index": 7, + "name": "setDefaultPixmapIcon", + "returnType": "void" + }, + { + "access": "private", + "index": 8, + "name": "defaultActionActivated", + "returnType": "void" + }, + { + "access": "private", + "index": 9, + "name": "resourceActionActivated", + "returnType": "void" + }, + { + "access": "private", + "index": 10, + "name": "fileActionActivated", + "returnType": "void" + }, + { + "access": "private", + "index": 11, + "name": "themeEnumActionActivated", + "returnType": "void" + }, + { + "access": "private", + "index": 12, + "name": "themeActionActivated", + "returnType": "void" + }, + { + "access": "private", + "index": 13, + "name": "copyActionActivated", + "returnType": "void" + }, + { + "access": "private", + "index": 14, + "name": "pasteActionActivated", + "returnType": "void" + }, + { + "access": "private", + "index": 15, + "name": "clipboardDataChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + } + ], + "inputFile": "pixmapeditor.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "PreviewFrame", + "lineNumber": 17, + "object": true, + "qualifiedClassName": "qdesigner_internal::PreviewFrame", + "superClasses": [ + { + "access": "public", + "name": "QFrame" + } + ] + } + ], + "inputFile": "previewframe.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "PreviewWidget", + "lineNumber": 13, + "object": true, + "qualifiedClassName": "qdesigner_internal::PreviewWidget", + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + } + ], + "inputFile": "previewwidget.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "PropertyEditor", + "lineNumber": 37, + "object": true, + "qualifiedClassName": "qdesigner_internal::PropertyEditor", + "slots": [ + { + "access": "private", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + } + ], + "index": 0, + "name": "slotResetProperty", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "value", + "type": "QVariant" + }, + { + "name": "enableSubPropertyHandling", + "type": "bool" + } + ], + "index": 1, + "name": "slotValueChanged", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "action", + "type": "QAction*" + } + ], + "index": 2, + "name": "slotViewTriggered", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "action", + "type": "QAction*" + } + ], + "index": 3, + "name": "slotAddDynamicProperty", + "returnType": "void" + }, + { + "access": "private", + "index": 4, + "name": "slotRemoveDynamicProperty", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "sort", + "type": "bool" + } + ], + "index": 5, + "name": "slotSorting", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "color", + "type": "bool" + } + ], + "index": 6, + "name": "slotColoring", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "type": "QtBrowserItem*" + } + ], + "index": 7, + "name": "slotCurrentItemChanged", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "pattern", + "type": "QString" + } + ], + "index": 8, + "name": "setFilter", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "fullyQualifiedName": "qdesigner_internal::QDesignerPropertyEditor", + "name": "QDesignerPropertyEditor" + } + ] + } + ], + "inputFile": "propertyeditor.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QLongLongValidator", + "lineNumber": 13, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "bottom", + "read": "bottom", + "required": false, + "scriptable": true, + "stored": true, + "type": "qlonglong", + "user": false, + "write": "setBottom" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "top", + "read": "top", + "required": false, + "scriptable": true, + "stored": true, + "type": "qlonglong", + "user": false, + "write": "setTop" + } + ], + "qualifiedClassName": "qdesigner_internal::QLongLongValidator", + "superClasses": [ + { + "access": "public", + "name": "QValidator" + } + ] + }, + { + "className": "QULongLongValidator", + "lineNumber": 41, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "bottom", + "read": "bottom", + "required": false, + "scriptable": true, + "stored": true, + "type": "qulonglong", + "user": false, + "write": "setBottom" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "top", + "read": "top", + "required": false, + "scriptable": true, + "stored": true, + "type": "qulonglong", + "user": false, + "write": "setTop" + } + ], + "qualifiedClassName": "qdesigner_internal::QULongLongValidator", + "superClasses": [ + { + "access": "public", + "name": "QValidator" + } + ] + } + ], + "inputFile": "qlonglongvalidator.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "StringListEditor", + "lineNumber": 15, + "object": true, + "qualifiedClassName": "qdesigner_internal::StringListEditor", + "slots": [ + { + "access": "private", + "index": 0, + "name": "upButtonClicked", + "returnType": "void" + }, + { + "access": "private", + "index": 1, + "name": "downButtonClicked", + "returnType": "void" + }, + { + "access": "private", + "index": 2, + "name": "newButtonClicked", + "returnType": "void" + }, + { + "access": "private", + "index": 3, + "name": "deleteButtonClicked", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "text", + "type": "QString" + } + ], + "index": 4, + "name": "valueEdited", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "current", + "type": "QModelIndex" + }, + { + "name": "previous", + "type": "QModelIndex" + } + ], + "index": 5, + "name": "currentIndexChanged", + "returnType": "void" + }, + { + "access": "private", + "index": 6, + "name": "currentValueChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QDialog" + }, + { + "access": "private", + "name": "Ui::Dialog" + } + ] + } + ], + "inputFile": "stringlisteditor.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "StringListEditorButton", + "lineNumber": 16, + "object": true, + "qualifiedClassName": "qdesigner_internal::StringListEditorButton", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "stringList", + "type": "QStringList" + } + ], + "index": 0, + "name": "stringListChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "stringList", + "type": "QStringList" + } + ], + "index": 1, + "name": "setStringList", + "returnType": "void" + }, + { + "access": "private", + "index": 2, + "name": "showStringListEditor", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QToolButton" + } + ] + } + ], + "inputFile": "stringlisteditorbutton.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QtBoolEdit", + "lineNumber": 68, + "object": true, + "qualifiedClassName": "QtBoolEdit", + "signals": [ + { + "access": "public", + "arguments": [ + { + "type": "bool" + } + ], + "index": 0, + "name": "toggled", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + } + ], + "inputFile": "qtpropertybrowserutils_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "SignalSlotEditor", + "lineNumber": 19, + "object": true, + "qualifiedClassName": "qdesigner_internal::SignalSlotEditor", + "superClasses": [ + { + "access": "public", + "fullyQualifiedName": "qdesigner_internal::ConnectionEdit", + "name": "ConnectionEdit" + } + ] + } + ], + "inputFile": "signalsloteditor.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "ConnectionModel", + "lineNumber": 63, + "object": true, + "qualifiedClassName": "qdesigner_internal::ConnectionModel", + "slots": [ + { + "access": "private", + "arguments": [ + { + "name": "con", + "type": "qdesigner_internal::Connection*" + } + ], + "index": 0, + "name": "connectionAdded", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "idx", + "type": "int" + } + ], + "index": 1, + "name": "connectionRemoved", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "con", + "type": "qdesigner_internal::Connection*" + } + ], + "index": 2, + "name": "aboutToRemoveConnection", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "idx", + "type": "int" + } + ], + "index": 3, + "name": "aboutToAddConnection", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "con", + "type": "qdesigner_internal::Connection*" + } + ], + "index": 4, + "name": "connectionChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QAbstractItemModel" + } + ] + } + ], + "inputFile": "signalsloteditor_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "SignalSlotEditorTool", + "lineNumber": 23, + "object": true, + "qualifiedClassName": "qdesigner_internal::SignalSlotEditorTool", + "superClasses": [ + { + "access": "public", + "name": "QDesignerFormWindowToolInterface" + } + ] + } + ], + "inputFile": "signalsloteditor_tool.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "SignalSlotEditorWindow", + "lineNumber": 25, + "object": true, + "qualifiedClassName": "qdesigner_internal::SignalSlotEditorWindow", + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "form", + "type": "QDesignerFormWindowInterface*" + } + ], + "index": 0, + "name": "setActiveFormWindow", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "con", + "type": "qdesigner_internal::Connection*" + } + ], + "index": 1, + "name": "updateDialogSelection", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "index", + "type": "QModelIndex" + } + ], + "index": 2, + "name": "updateEditorSelection", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "formWindow", + "type": "QDesignerFormWindowInterface*" + }, + { + "name": "object", + "type": "QObject*" + }, + { + "name": "newName", + "type": "QString" + }, + { + "name": "oldName", + "type": "QString" + } + ], + "index": 3, + "name": "objectNameChanged", + "returnType": "void" + }, + { + "access": "private", + "index": 4, + "name": "addConnection", + "returnType": "void" + }, + { + "access": "private", + "index": 5, + "name": "removeConnection", + "returnType": "void" + }, + { + "access": "private", + "index": 6, + "name": "updateUi", + "returnType": "void" + }, + { + "access": "private", + "index": 7, + "name": "resizeColumns", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + } + ], + "inputFile": "signalsloteditorwindow.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "AbstractFindWidget", + "lineNumber": 32, + "object": true, + "qualifiedClassName": "AbstractFindWidget", + "slots": [ + { + "access": "public", + "index": 0, + "name": "activate", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "deactivate", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "findNext", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "findPrevious", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "findCurrentText", + "returnType": "void" + }, + { + "access": "private", + "index": 5, + "name": "updateButtons", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + } + ], + "inputFile": "abstractfindwidget_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "ItemViewFindWidget", + "lineNumber": 26, + "object": true, + "qualifiedClassName": "ItemViewFindWidget", + "superClasses": [ + { + "access": "public", + "name": "AbstractFindWidget" + } + ] + } + ], + "inputFile": "itemviewfindwidget_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "TextEditFindWidget", + "lineNumber": 24, + "object": true, + "qualifiedClassName": "TextEditFindWidget", + "superClasses": [ + { + "access": "public", + "name": "AbstractFindWidget" + } + ] + } + ], + "inputFile": "texteditfindwidget_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "TextEditor", + "lineNumber": 259, + "object": true, + "qualifiedClassName": "qdesigner_internal::TextEditor", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "text", + "type": "QString" + } + ], + "index": 0, + "name": "textChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "text", + "type": "QString" + } + ], + "index": 1, + "name": "setText", + "returnType": "void" + }, + { + "access": "private", + "index": 2, + "name": "buttonClicked", + "returnType": "void" + }, + { + "access": "private", + "index": 3, + "name": "resourceActionActivated", + "returnType": "void" + }, + { + "access": "private", + "index": 4, + "name": "fileActionActivated", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + }, + { + "className": "ResetWidget", + "lineNumber": 464, + "object": true, + "qualifiedClassName": "qdesigner_internal::ResetWidget", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + } + ], + "index": 0, + "name": "resetProperty", + "returnType": "void" + } + ], + "slots": [ + { + "access": "private", + "index": 1, + "name": "slotClicked", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + } + ], + "inputFile": "designerpropertymanager.cpp", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "ConnectDialog", + "lineNumber": 28, + "object": true, + "qualifiedClassName": "qdesigner_internal::ConnectDialog", + "slots": [ + { + "access": "private", + "index": 0, + "name": "populateLists", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "item", + "type": "QListWidgetItem*" + } + ], + "index": 1, + "name": "selectSignal", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "item", + "type": "QListWidgetItem*" + } + ], + "index": 2, + "name": "selectSlot", + "returnType": "void" + }, + { + "access": "private", + "index": 3, + "name": "populateSignalList", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "signal", + "type": "QString" + } + ], + "index": 4, + "name": "populateSlotList", + "returnType": "void" + }, + { + "access": "private", + "index": 5, + "isCloned": true, + "name": "populateSlotList", + "returnType": "void" + }, + { + "access": "private", + "index": 6, + "name": "editSignals", + "returnType": "void" + }, + { + "access": "private", + "index": 7, + "name": "editSlots", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QDialog" + } + ] + } + ], + "inputFile": "connectdialog_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QtButtonPropertyBrowser", + "lineNumber": 24, + "object": true, + "qualifiedClassName": "QtButtonPropertyBrowser", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "item", + "type": "QtBrowserItem*" + } + ], + "index": 0, + "name": "collapsed", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "item", + "type": "QtBrowserItem*" + } + ], + "index": 1, + "name": "expanded", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QtAbstractPropertyBrowser" + } + ] + } + ], + "inputFile": "qtbuttonpropertybrowser_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QtSpinBoxFactory", + "lineNumber": 26, + "object": true, + "qualifiedClassName": "QtSpinBoxFactory", + "superClasses": [ + { + "access": "public", + "name": "QtAbstractEditorFactory" + } + ] + }, + { + "className": "QtSliderFactory", + "lineNumber": 45, + "object": true, + "qualifiedClassName": "QtSliderFactory", + "superClasses": [ + { + "access": "public", + "name": "QtAbstractEditorFactory" + } + ] + }, + { + "className": "QtScrollBarFactory", + "lineNumber": 64, + "object": true, + "qualifiedClassName": "QtScrollBarFactory", + "superClasses": [ + { + "access": "public", + "name": "QtAbstractEditorFactory" + } + ] + }, + { + "className": "QtCheckBoxFactory", + "lineNumber": 83, + "object": true, + "qualifiedClassName": "QtCheckBoxFactory", + "superClasses": [ + { + "access": "public", + "name": "QtAbstractEditorFactory" + } + ] + }, + { + "className": "QtDoubleSpinBoxFactory", + "lineNumber": 102, + "object": true, + "qualifiedClassName": "QtDoubleSpinBoxFactory", + "superClasses": [ + { + "access": "public", + "name": "QtAbstractEditorFactory" + } + ] + }, + { + "className": "QtLineEditFactory", + "lineNumber": 121, + "object": true, + "qualifiedClassName": "QtLineEditFactory", + "superClasses": [ + { + "access": "public", + "name": "QtAbstractEditorFactory" + } + ] + }, + { + "className": "QtDateEditFactory", + "lineNumber": 140, + "object": true, + "qualifiedClassName": "QtDateEditFactory", + "superClasses": [ + { + "access": "public", + "name": "QtAbstractEditorFactory" + } + ] + }, + { + "className": "QtTimeEditFactory", + "lineNumber": 159, + "object": true, + "qualifiedClassName": "QtTimeEditFactory", + "superClasses": [ + { + "access": "public", + "name": "QtAbstractEditorFactory" + } + ] + }, + { + "className": "QtDateTimeEditFactory", + "lineNumber": 178, + "object": true, + "qualifiedClassName": "QtDateTimeEditFactory", + "superClasses": [ + { + "access": "public", + "name": "QtAbstractEditorFactory" + } + ] + }, + { + "className": "QtKeySequenceEditorFactory", + "lineNumber": 197, + "object": true, + "qualifiedClassName": "QtKeySequenceEditorFactory", + "superClasses": [ + { + "access": "public", + "name": "QtAbstractEditorFactory" + } + ] + }, + { + "className": "QtCharEditorFactory", + "lineNumber": 216, + "object": true, + "qualifiedClassName": "QtCharEditorFactory", + "superClasses": [ + { + "access": "public", + "name": "QtAbstractEditorFactory" + } + ] + }, + { + "className": "QtEnumEditorFactory", + "lineNumber": 235, + "object": true, + "qualifiedClassName": "QtEnumEditorFactory", + "superClasses": [ + { + "access": "public", + "name": "QtAbstractEditorFactory" + } + ] + }, + { + "className": "QtCursorEditorFactory", + "lineNumber": 254, + "object": true, + "qualifiedClassName": "QtCursorEditorFactory", + "superClasses": [ + { + "access": "public", + "name": "QtAbstractEditorFactory" + } + ] + }, + { + "className": "QtColorEditorFactory", + "lineNumber": 273, + "object": true, + "qualifiedClassName": "QtColorEditorFactory", + "superClasses": [ + { + "access": "public", + "name": "QtAbstractEditorFactory" + } + ] + }, + { + "className": "QtFontEditorFactory", + "lineNumber": 292, + "object": true, + "qualifiedClassName": "QtFontEditorFactory", + "superClasses": [ + { + "access": "public", + "name": "QtAbstractEditorFactory" + } + ] + } + ], + "inputFile": "qteditorfactory_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QtGroupBoxPropertyBrowser", + "lineNumber": 24, + "object": true, + "qualifiedClassName": "QtGroupBoxPropertyBrowser", + "superClasses": [ + { + "access": "public", + "name": "QtAbstractPropertyBrowser" + } + ] + } + ], + "inputFile": "qtgroupboxpropertybrowser_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QtAbstractPropertyManager", + "lineNumber": 70, + "object": true, + "qualifiedClassName": "QtAbstractPropertyManager", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "parent", + "type": "QtProperty*" + }, + { + "name": "after", + "type": "QtProperty*" + } + ], + "index": 0, + "name": "propertyInserted", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + } + ], + "index": 1, + "name": "propertyChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "parent", + "type": "QtProperty*" + } + ], + "index": 2, + "name": "propertyRemoved", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + } + ], + "index": 3, + "name": "propertyDestroyed", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "className": "QtAbstractEditorFactoryBase", + "lineNumber": 101, + "object": true, + "qualifiedClassName": "QtAbstractEditorFactoryBase", + "slots": [ + { + "access": "protected", + "arguments": [ + { + "name": "manager", + "type": "QObject*" + } + ], + "index": 0, + "name": "managerDestroyed", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "className": "QtAbstractPropertyBrowser", + "lineNumber": 211, + "object": true, + "qualifiedClassName": "QtAbstractPropertyBrowser", + "signals": [ + { + "access": "public", + "arguments": [ + { + "type": "QtBrowserItem*" + } + ], + "index": 0, + "name": "currentItemChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + } + ], + "index": 1, + "name": "addProperty", + "returnType": "QtBrowserItem*" + }, + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "afterProperty", + "type": "QtProperty*" + } + ], + "index": 2, + "name": "insertProperty", + "returnType": "QtBrowserItem*" + }, + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + } + ], + "index": 3, + "name": "removeProperty", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + } + ], + "inputFile": "qtpropertybrowser_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QtGroupPropertyManager", + "lineNumber": 28, + "object": true, + "qualifiedClassName": "QtGroupPropertyManager", + "superClasses": [ + { + "access": "public", + "name": "QtAbstractPropertyManager" + } + ] + }, + { + "className": "QtIntPropertyManager", + "lineNumber": 44, + "object": true, + "qualifiedClassName": "QtIntPropertyManager", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "val", + "type": "int" + } + ], + "index": 0, + "name": "valueChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "minVal", + "type": "int" + }, + { + "name": "maxVal", + "type": "int" + } + ], + "index": 1, + "name": "rangeChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "step", + "type": "int" + } + ], + "index": 2, + "name": "singleStepChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "val", + "type": "int" + } + ], + "index": 3, + "name": "setValue", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "minVal", + "type": "int" + } + ], + "index": 4, + "name": "setMinimum", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "maxVal", + "type": "int" + } + ], + "index": 5, + "name": "setMaximum", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "minVal", + "type": "int" + }, + { + "name": "maxVal", + "type": "int" + } + ], + "index": 6, + "name": "setRange", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "step", + "type": "int" + } + ], + "index": 7, + "name": "setSingleStep", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QtAbstractPropertyManager" + } + ] + }, + { + "className": "QtBoolPropertyManager", + "lineNumber": 78, + "object": true, + "qualifiedClassName": "QtBoolPropertyManager", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "val", + "type": "bool" + } + ], + "index": 0, + "name": "valueChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "val", + "type": "bool" + } + ], + "index": 1, + "name": "setValue", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QtAbstractPropertyManager" + } + ] + }, + { + "className": "QtDoublePropertyManager", + "lineNumber": 104, + "object": true, + "qualifiedClassName": "QtDoublePropertyManager", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "val", + "type": "double" + } + ], + "index": 0, + "name": "valueChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "minVal", + "type": "double" + }, + { + "name": "maxVal", + "type": "double" + } + ], + "index": 1, + "name": "rangeChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "step", + "type": "double" + } + ], + "index": 2, + "name": "singleStepChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "prec", + "type": "int" + } + ], + "index": 3, + "name": "decimalsChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "val", + "type": "double" + } + ], + "index": 4, + "name": "setValue", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "minVal", + "type": "double" + } + ], + "index": 5, + "name": "setMinimum", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "maxVal", + "type": "double" + } + ], + "index": 6, + "name": "setMaximum", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "minVal", + "type": "double" + }, + { + "name": "maxVal", + "type": "double" + } + ], + "index": 7, + "name": "setRange", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "step", + "type": "double" + } + ], + "index": 8, + "name": "setSingleStep", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "prec", + "type": "int" + } + ], + "index": 9, + "name": "setDecimals", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QtAbstractPropertyManager" + } + ] + }, + { + "className": "QtStringPropertyManager", + "lineNumber": 141, + "object": true, + "qualifiedClassName": "QtStringPropertyManager", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "val", + "type": "QString" + } + ], + "index": 0, + "name": "valueChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "regExp", + "type": "QRegularExpression" + } + ], + "index": 1, + "name": "regExpChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "val", + "type": "QString" + } + ], + "index": 2, + "name": "setValue", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "regExp", + "type": "QRegularExpression" + } + ], + "index": 3, + "name": "setRegExp", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QtAbstractPropertyManager" + } + ] + }, + { + "className": "QtDatePropertyManager", + "lineNumber": 169, + "object": true, + "qualifiedClassName": "QtDatePropertyManager", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "val", + "type": "QDate" + } + ], + "index": 0, + "name": "valueChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "minVal", + "type": "QDate" + }, + { + "name": "maxVal", + "type": "QDate" + } + ], + "index": 1, + "name": "rangeChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "val", + "type": "QDate" + } + ], + "index": 2, + "name": "setValue", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "minVal", + "type": "QDate" + } + ], + "index": 3, + "name": "setMinimum", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "maxVal", + "type": "QDate" + } + ], + "index": 4, + "name": "setMaximum", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "minVal", + "type": "QDate" + }, + { + "name": "maxVal", + "type": "QDate" + } + ], + "index": 5, + "name": "setRange", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QtAbstractPropertyManager" + } + ] + }, + { + "className": "QtTimePropertyManager", + "lineNumber": 200, + "object": true, + "qualifiedClassName": "QtTimePropertyManager", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "val", + "type": "QTime" + } + ], + "index": 0, + "name": "valueChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "val", + "type": "QTime" + } + ], + "index": 1, + "name": "setValue", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QtAbstractPropertyManager" + } + ] + }, + { + "className": "QtDateTimePropertyManager", + "lineNumber": 225, + "object": true, + "qualifiedClassName": "QtDateTimePropertyManager", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "val", + "type": "QDateTime" + } + ], + "index": 0, + "name": "valueChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "val", + "type": "QDateTime" + } + ], + "index": 1, + "name": "setValue", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QtAbstractPropertyManager" + } + ] + }, + { + "className": "QtKeySequencePropertyManager", + "lineNumber": 250, + "object": true, + "qualifiedClassName": "QtKeySequencePropertyManager", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "val", + "type": "QKeySequence" + } + ], + "index": 0, + "name": "valueChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "val", + "type": "QKeySequence" + } + ], + "index": 1, + "name": "setValue", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QtAbstractPropertyManager" + } + ] + }, + { + "className": "QtCharPropertyManager", + "lineNumber": 275, + "object": true, + "qualifiedClassName": "QtCharPropertyManager", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "val", + "type": "QChar" + } + ], + "index": 0, + "name": "valueChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "val", + "type": "QChar" + } + ], + "index": 1, + "name": "setValue", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QtAbstractPropertyManager" + } + ] + }, + { + "className": "QtLocalePropertyManager", + "lineNumber": 301, + "object": true, + "qualifiedClassName": "QtLocalePropertyManager", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "val", + "type": "QLocale" + } + ], + "index": 0, + "name": "valueChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "val", + "type": "QLocale" + } + ], + "index": 1, + "name": "setValue", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QtAbstractPropertyManager" + } + ] + }, + { + "className": "QtPointPropertyManager", + "lineNumber": 328, + "object": true, + "qualifiedClassName": "QtPointPropertyManager", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "val", + "type": "QPoint" + } + ], + "index": 0, + "name": "valueChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "val", + "type": "QPoint" + } + ], + "index": 1, + "name": "setValue", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QtAbstractPropertyManager" + } + ] + }, + { + "className": "QtPointFPropertyManager", + "lineNumber": 355, + "object": true, + "qualifiedClassName": "QtPointFPropertyManager", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "val", + "type": "QPointF" + } + ], + "index": 0, + "name": "valueChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "prec", + "type": "int" + } + ], + "index": 1, + "name": "decimalsChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "val", + "type": "QPointF" + } + ], + "index": 2, + "name": "setValue", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "prec", + "type": "int" + } + ], + "index": 3, + "name": "setDecimals", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QtAbstractPropertyManager" + } + ] + }, + { + "className": "QtSizePropertyManager", + "lineNumber": 385, + "object": true, + "qualifiedClassName": "QtSizePropertyManager", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "val", + "type": "QSize" + } + ], + "index": 0, + "name": "valueChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "minVal", + "type": "QSize" + }, + { + "name": "maxVal", + "type": "QSize" + } + ], + "index": 1, + "name": "rangeChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "val", + "type": "QSize" + } + ], + "index": 2, + "name": "setValue", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "minVal", + "type": "QSize" + } + ], + "index": 3, + "name": "setMinimum", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "maxVal", + "type": "QSize" + } + ], + "index": 4, + "name": "setMaximum", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "minVal", + "type": "QSize" + }, + { + "name": "maxVal", + "type": "QSize" + } + ], + "index": 5, + "name": "setRange", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QtAbstractPropertyManager" + } + ] + }, + { + "className": "QtSizeFPropertyManager", + "lineNumber": 418, + "object": true, + "qualifiedClassName": "QtSizeFPropertyManager", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "val", + "type": "QSizeF" + } + ], + "index": 0, + "name": "valueChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "minVal", + "type": "QSizeF" + }, + { + "name": "maxVal", + "type": "QSizeF" + } + ], + "index": 1, + "name": "rangeChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "prec", + "type": "int" + } + ], + "index": 2, + "name": "decimalsChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "val", + "type": "QSizeF" + } + ], + "index": 3, + "name": "setValue", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "minVal", + "type": "QSizeF" + } + ], + "index": 4, + "name": "setMinimum", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "maxVal", + "type": "QSizeF" + } + ], + "index": 5, + "name": "setMaximum", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "minVal", + "type": "QSizeF" + }, + { + "name": "maxVal", + "type": "QSizeF" + } + ], + "index": 6, + "name": "setRange", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "prec", + "type": "int" + } + ], + "index": 7, + "name": "setDecimals", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QtAbstractPropertyManager" + } + ] + }, + { + "className": "QtRectPropertyManager", + "lineNumber": 454, + "object": true, + "qualifiedClassName": "QtRectPropertyManager", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "val", + "type": "QRect" + } + ], + "index": 0, + "name": "valueChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "constraint", + "type": "QRect" + } + ], + "index": 1, + "name": "constraintChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "val", + "type": "QRect" + } + ], + "index": 2, + "name": "setValue", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "constraint", + "type": "QRect" + } + ], + "index": 3, + "name": "setConstraint", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QtAbstractPropertyManager" + } + ] + }, + { + "className": "QtRectFPropertyManager", + "lineNumber": 484, + "object": true, + "qualifiedClassName": "QtRectFPropertyManager", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "val", + "type": "QRectF" + } + ], + "index": 0, + "name": "valueChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "constraint", + "type": "QRectF" + } + ], + "index": 1, + "name": "constraintChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "prec", + "type": "int" + } + ], + "index": 2, + "name": "decimalsChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "val", + "type": "QRectF" + } + ], + "index": 3, + "name": "setValue", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "constraint", + "type": "QRectF" + } + ], + "index": 4, + "name": "setConstraint", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "prec", + "type": "int" + } + ], + "index": 5, + "name": "setDecimals", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QtAbstractPropertyManager" + } + ] + }, + { + "className": "QtEnumPropertyManager", + "lineNumber": 517, + "object": true, + "qualifiedClassName": "QtEnumPropertyManager", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "val", + "type": "int" + } + ], + "index": 0, + "name": "valueChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "names", + "type": "QStringList" + } + ], + "index": 1, + "name": "enumNamesChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "icons", + "type": "QMap" + } + ], + "index": 2, + "name": "enumIconsChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "val", + "type": "int" + } + ], + "index": 3, + "name": "setValue", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "names", + "type": "QStringList" + } + ], + "index": 4, + "name": "setEnumNames", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "icons", + "type": "QMap" + } + ], + "index": 5, + "name": "setEnumIcons", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QtAbstractPropertyManager" + } + ] + }, + { + "className": "QtFlagPropertyManager", + "lineNumber": 549, + "object": true, + "qualifiedClassName": "QtFlagPropertyManager", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "val", + "type": "int" + } + ], + "index": 0, + "name": "valueChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "names", + "type": "QStringList" + } + ], + "index": 1, + "name": "flagNamesChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "val", + "type": "int" + } + ], + "index": 2, + "name": "setValue", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "names", + "type": "QStringList" + } + ], + "index": 3, + "name": "setFlagNames", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QtAbstractPropertyManager" + } + ] + }, + { + "className": "QtSizePolicyPropertyManager", + "lineNumber": 579, + "object": true, + "qualifiedClassName": "QtSizePolicyPropertyManager", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "val", + "type": "QSizePolicy" + } + ], + "index": 0, + "name": "valueChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "val", + "type": "QSizePolicy" + } + ], + "index": 1, + "name": "setValue", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QtAbstractPropertyManager" + } + ] + }, + { + "className": "QtFontPropertyManager", + "lineNumber": 607, + "object": true, + "qualifiedClassName": "QtFontPropertyManager", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "val", + "type": "QFont" + } + ], + "index": 0, + "name": "valueChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "val", + "type": "QFont" + } + ], + "index": 1, + "name": "setValue", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QtAbstractPropertyManager" + } + ] + }, + { + "className": "QtColorPropertyManager", + "lineNumber": 637, + "object": true, + "qualifiedClassName": "QtColorPropertyManager", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "val", + "type": "QColor" + } + ], + "index": 0, + "name": "valueChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "val", + "type": "QColor" + } + ], + "index": 1, + "name": "setValue", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QtAbstractPropertyManager" + } + ] + }, + { + "className": "QtCursorPropertyManager", + "lineNumber": 665, + "object": true, + "qualifiedClassName": "QtCursorPropertyManager", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "val", + "type": "QCursor" + } + ], + "index": 0, + "name": "valueChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "val", + "type": "QCursor" + } + ], + "index": 1, + "name": "setValue", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QtAbstractPropertyManager" + } + ] + } + ], + "inputFile": "qtpropertymanager_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QtTreePropertyBrowser", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "ResizeMode", + "values": [ + "Interactive", + "Stretch", + "Fixed", + "ResizeToContents" + ] + } + ], + "lineNumber": 25, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "indentation", + "read": "indentation", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setIndentation" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "rootIsDecorated", + "read": "rootIsDecorated", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setRootIsDecorated" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "alternatingRowColors", + "read": "alternatingRowColors", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setAlternatingRowColors" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "headerVisible", + "read": "isHeaderVisible", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setHeaderVisible" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "resizeMode", + "read": "resizeMode", + "required": false, + "scriptable": true, + "stored": true, + "type": "ResizeMode", + "user": false, + "write": "setResizeMode" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "splitterPosition", + "read": "splitterPosition", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setSplitterPosition" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "propertiesWithoutValueMarked", + "read": "propertiesWithoutValueMarked", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setPropertiesWithoutValueMarked" + } + ], + "qualifiedClassName": "QtTreePropertyBrowser", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "item", + "type": "QtBrowserItem*" + } + ], + "index": 0, + "name": "collapsed", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "item", + "type": "QtBrowserItem*" + } + ], + "index": 1, + "name": "expanded", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QtAbstractPropertyBrowser" + } + ] + } + ], + "inputFile": "qttreepropertybrowser_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QtVariantPropertyManager", + "lineNumber": 46, + "object": true, + "qualifiedClassName": "QtVariantPropertyManager", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "val", + "type": "QVariant" + } + ], + "index": 0, + "name": "valueChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "attribute", + "type": "QString" + }, + { + "name": "val", + "type": "QVariant" + } + ], + "index": 1, + "name": "attributeChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "val", + "type": "QVariant" + } + ], + "index": 2, + "name": "setValue", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "QtProperty*" + }, + { + "name": "attribute", + "type": "QString" + }, + { + "name": "value", + "type": "QVariant" + } + ], + "index": 3, + "name": "setAttribute", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QtAbstractPropertyManager" + } + ] + }, + { + "className": "QtVariantEditorFactory", + "lineNumber": 92, + "object": true, + "qualifiedClassName": "QtVariantEditorFactory", + "superClasses": [ + { + "access": "public", + "name": "QtAbstractEditorFactory" + } + ] + } + ], + "inputFile": "qtvariantproperty_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "SignalSlotEditorPlugin", + "interfaces": [ + [ + { + "className": "QDesignerFormEditorPluginInterface", + "id": "\"org.qt-project.Qt.Designer.QDesignerFormEditorPluginInterface\"" + } + ] + ], + "lineNumber": 22, + "object": true, + "qualifiedClassName": "qdesigner_internal::SignalSlotEditorPlugin", + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "formWindow", + "type": "QDesignerFormWindowInterface*" + } + ], + "index": 0, + "name": "activeFormWindowChanged", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "formWindow", + "type": "QDesignerFormWindowInterface*" + } + ], + "index": 1, + "name": "addFormWindow", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "formWindow", + "type": "QDesignerFormWindowInterface*" + } + ], + "index": 2, + "name": "removeFormWindow", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QDesignerFormEditorPluginInterface" + } + ] + } + ], + "inputFile": "signalsloteditor_plugin.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "TabOrderEditorPlugin", + "interfaces": [ + [ + { + "className": "QDesignerFormEditorPluginInterface", + "id": "\"org.qt-project.Qt.Designer.QDesignerFormEditorPluginInterface\"" + } + ] + ], + "lineNumber": 23, + "object": true, + "qualifiedClassName": "qdesigner_internal::TabOrderEditorPlugin", + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "formWindow", + "type": "QDesignerFormWindowInterface*" + } + ], + "index": 0, + "name": "activeFormWindowChanged", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "formWindow", + "type": "QDesignerFormWindowInterface*" + } + ], + "index": 1, + "name": "addFormWindow", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "formWindow", + "type": "QDesignerFormWindowInterface*" + } + ], + "index": 2, + "name": "removeFormWindow", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QDesignerFormEditorPluginInterface" + } + ] + } + ], + "inputFile": "tabordereditor_plugin.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QtColorButtonPrivate", + "lineNumber": 14, + "object": true, + "qualifiedClassName": "QtColorButtonPrivate", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qtcolorbutton.cpp", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QtCharEdit", + "lineNumber": 1461, + "object": true, + "qualifiedClassName": "QtCharEdit", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "value", + "type": "QChar" + } + ], + "index": 0, + "name": "valueChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "value", + "type": "QChar" + } + ], + "index": 1, + "name": "setValue", + "returnType": "void" + }, + { + "access": "private", + "index": 2, + "name": "slotClearChar", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + }, + { + "className": "QtColorEditWidget", + "lineNumber": 2078, + "object": true, + "qualifiedClassName": "QtColorEditWidget", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "value", + "type": "QColor" + } + ], + "index": 0, + "name": "valueChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "value", + "type": "QColor" + } + ], + "index": 1, + "name": "setValue", + "returnType": "void" + }, + { + "access": "private", + "index": 2, + "name": "buttonClicked", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + }, + { + "className": "QtFontEditWidget", + "lineNumber": 2277, + "object": true, + "qualifiedClassName": "QtFontEditWidget", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "value", + "type": "QFont" + } + ], + "index": 0, + "name": "valueChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "value", + "type": "QFont" + } + ], + "index": 1, + "name": "setValue", + "returnType": "void" + }, + { + "access": "private", + "index": 2, + "name": "buttonClicked", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + } + ], + "inputFile": "qteditorfactory.cpp", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QtMetaEnumWrapper", + "lineNumber": 359, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "policy", + "read": "policy", + "required": false, + "scriptable": true, + "stored": true, + "type": "QSizePolicy::Policy", + "user": false + } + ], + "qualifiedClassName": "QtMetaEnumWrapper", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qtpropertymanager.cpp", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QtPropertyEditorView", + "lineNumber": 91, + "object": true, + "qualifiedClassName": "QtPropertyEditorView", + "superClasses": [ + { + "access": "public", + "name": "QTreeWidget" + } + ] + }, + { + "className": "QtPropertyEditorDelegate", + "lineNumber": 191, + "object": true, + "qualifiedClassName": "QtPropertyEditorDelegate", + "slots": [ + { + "access": "private", + "arguments": [ + { + "name": "object", + "type": "QObject*" + } + ], + "index": 0, + "name": "slotEditorDestroyed", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QItemDelegate" + } + ] + } + ], + "inputFile": "qttreepropertybrowser.cpp", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "InlineEditorModel", + "lineNumber": 379, + "object": true, + "qualifiedClassName": "InlineEditorModel", + "superClasses": [ + { + "access": "public", + "name": "QStandardItemModel" + } + ] + }, + { + "className": "InlineEditor", + "lineNumber": 467, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "text", + "read": "text", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": true, + "write": "setText" + } + ], + "qualifiedClassName": "InlineEditor", + "slots": [ + { + "access": "private", + "arguments": [ + { + "name": "idx", + "type": "int" + } + ], + "index": 0, + "name": "checkSelection", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QComboBox" + } + ] + }, + { + "className": "ConnectionDelegate", + "lineNumber": 540, + "object": true, + "qualifiedClassName": "ConnectionDelegate", + "slots": [ + { + "access": "private", + "index": 0, + "name": "emitCommitData", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QItemDelegate" + } + ] + } + ], + "inputFile": "signalsloteditorwindow.cpp", + "outputRevision": 68 + } +] diff --git a/qt/6.8.1/msvc2022_64/metatypes/qt6devicediscoverysupportprivate_metatypes.json b/qt/6.8.1/msvc2022_64/metatypes/qt6devicediscoverysupportprivate_metatypes.json new file mode 100644 index 0000000000000000000000000000000000000000..acf46be1c636d182259e735e22ae8bd28faf3043 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/metatypes/qt6devicediscoverysupportprivate_metatypes.json @@ -0,0 +1,84 @@ +[ + { + "classes": [ + { + "className": "QDeviceDiscoveryDummy", + "lineNumber": 22, + "object": true, + "qualifiedClassName": "QDeviceDiscoveryDummy", + "superClasses": [ + { + "access": "public", + "name": "QDeviceDiscovery" + } + ] + } + ], + "inputFile": "qdevicediscovery_dummy_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QDeviceDiscovery", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "QDeviceType", + "values": [ + "Device_Unknown", + "Device_Mouse", + "Device_Touchpad", + "Device_Touchscreen", + "Device_Keyboard", + "Device_DRM", + "Device_DRM_PrimaryGPU", + "Device_Tablet", + "Device_Joystick", + "Device_InputMask", + "Device_VideoMask" + ] + } + ], + "lineNumber": 33, + "object": true, + "qualifiedClassName": "QDeviceDiscovery", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "deviceNode", + "type": "QString" + } + ], + "index": 0, + "name": "deviceDetected", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "deviceNode", + "type": "QString" + } + ], + "index": 1, + "name": "deviceRemoved", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qdevicediscovery_p.h", + "outputRevision": 68 + } +] diff --git a/qt/6.8.1/msvc2022_64/metatypes/qt6exampleiconsprivate_metatypes.json b/qt/6.8.1/msvc2022_64/metatypes/qt6exampleiconsprivate_metatypes.json new file mode 100644 index 0000000000000000000000000000000000000000..0d4f101c7a37a4c875e6999bee1a287fdb733380 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/metatypes/qt6exampleiconsprivate_metatypes.json @@ -0,0 +1,2 @@ +[ +] diff --git a/qt/6.8.1/msvc2022_64/metatypes/qt6examplesassetdownloaderprivate_metatypes.json b/qt/6.8.1/msvc2022_64/metatypes/qt6examplesassetdownloaderprivate_metatypes.json new file mode 100644 index 0000000000000000000000000000000000000000..609bb495fa168fd29bf27dfe0fcd2f03932e0491 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/metatypes/qt6examplesassetdownloaderprivate_metatypes.json @@ -0,0 +1,566 @@ +[ + { + "classes": [ + { + "className": "Barrier", + "lineNumber": 27, + "object": true, + "qualifiedClassName": "Tasking::Barrier", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "success", + "type": "DoneResult" + } + ], + "index": 0, + "name": "done", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "barrier.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "NetworkQuery", + "lineNumber": 39, + "object": true, + "qualifiedClassName": "Tasking::NetworkQuery", + "signals": [ + { + "access": "public", + "index": 0, + "name": "started", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "result", + "type": "DoneResult" + } + ], + "index": 1, + "name": "done", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "networkquery.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "TaskInterface", + "lineNumber": 95, + "object": true, + "qualifiedClassName": "Tasking::TaskInterface", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "result", + "type": "DoneResult" + } + ], + "index": 0, + "name": "done", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "className": "TaskTree", + "lineNumber": 622, + "object": true, + "qualifiedClassName": "Tasking::TaskTree", + "signals": [ + { + "access": "public", + "index": 0, + "name": "started", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "result", + "type": "DoneWith" + } + ], + "index": 1, + "name": "done", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "count", + "type": "int" + } + ], + "index": 2, + "name": "asyncCountChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "value", + "type": "int" + } + ], + "index": 3, + "name": "progressValueChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "className": "Tasking", + "enums": [ + { + "isClass": true, + "isFlag": false, + "name": "WorkflowPolicy", + "values": [ + "StopOnError", + "ContinueOnError", + "StopOnSuccess", + "ContinueOnSuccess", + "StopOnSuccessOrError", + "FinishAllAndSuccess", + "FinishAllAndError" + ] + }, + { + "isClass": true, + "isFlag": false, + "name": "SetupResult", + "values": [ + "Continue", + "StopWithSuccess", + "StopWithError" + ] + }, + { + "isClass": true, + "isFlag": false, + "name": "DoneResult", + "values": [ + "Success", + "Error" + ] + }, + { + "isClass": true, + "isFlag": false, + "name": "DoneWith", + "values": [ + "Success", + "Error", + "Cancel" + ] + }, + { + "isClass": true, + "isFlag": false, + "name": "CallDoneIf", + "values": [ + "SuccessOrError", + "Success", + "Error" + ] + } + ], + "lineNumber": 30, + "namespace": true, + "qualifiedClassName": "Tasking" + } + ], + "inputFile": "tasktree.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "TaskTreeRunner", + "lineNumber": 28, + "object": true, + "qualifiedClassName": "Tasking::TaskTreeRunner", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "taskTree", + "type": "TaskTree*" + } + ], + "index": 0, + "name": "aboutToStart", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "result", + "type": "DoneWith" + } + ], + "index": 1, + "name": "done", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "tasktreerunner.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "TcpSocket", + "lineNumber": 35, + "object": true, + "qualifiedClassName": "Tasking::TcpSocket", + "signals": [ + { + "access": "public", + "index": 0, + "name": "started", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "result", + "type": "DoneResult" + } + ], + "index": 1, + "name": "done", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "tcpsocket.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "AssetDownloader", + "lineNumber": 29, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "downloadBase", + "notify": "downloadBaseChanged", + "read": "downloadBase", + "required": false, + "scriptable": true, + "stored": true, + "type": "QUrl", + "user": false, + "write": "setDownloadBase" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "preferredLocalDownloadDir", + "notify": "preferredLocalDownloadDirChanged", + "read": "preferredLocalDownloadDir", + "required": false, + "scriptable": true, + "stored": true, + "type": "QUrl", + "user": false, + "write": "setPreferredLocalDownloadDir" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "offlineAssetsFilePath", + "notify": "offlineAssetsFilePathChanged", + "read": "offlineAssetsFilePath", + "required": false, + "scriptable": true, + "stored": true, + "type": "QUrl", + "user": false, + "write": "setOfflineAssetsFilePath" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "jsonFileName", + "notify": "jsonFileNameChanged", + "read": "jsonFileName", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setJsonFileName" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "zipFileName", + "notify": "zipFileNameChanged", + "read": "zipFileName", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setZipFileName" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "localDownloadDir", + "notify": "localDownloadDirChanged", + "read": "localDownloadDir", + "required": false, + "scriptable": true, + "stored": true, + "type": "QUrl", + "user": false + } + ], + "qualifiedClassName": "Assets::Downloader::AssetDownloader", + "signals": [ + { + "access": "public", + "index": 0, + "name": "started", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "success", + "type": "bool" + } + ], + "index": 1, + "name": "finished", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "progressValue", + "type": "int" + }, + { + "name": "progressMaximum", + "type": "int" + }, + { + "name": "progressText", + "type": "QString" + } + ], + "index": 2, + "name": "progressChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "url", + "type": "QUrl" + } + ], + "index": 3, + "name": "localDownloadDirChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QUrl" + } + ], + "index": 4, + "name": "downloadBaseChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "url", + "type": "QUrl" + } + ], + "index": 5, + "name": "preferredLocalDownloadDirChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QUrl" + } + ], + "index": 6, + "name": "offlineAssetsFilePathChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QString" + } + ], + "index": 7, + "name": "jsonFileNameChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QString" + } + ], + "index": 8, + "name": "zipFileNameChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "index": 9, + "name": "start", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "assetdownloader.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "Reaper", + "lineNumber": 52, + "object": true, + "qualifiedClassName": "Tasking::Reaper", + "signals": [ + { + "access": "public", + "index": 0, + "name": "finished", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "className": "ProcessReaperPrivate", + "lineNumber": 119, + "object": true, + "qualifiedClassName": "Tasking::ProcessReaperPrivate", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qprocesstask.cpp", + "outputRevision": 68 + } +] diff --git a/qt/6.8.1/msvc2022_64/metatypes/qt6fbsupportprivate_metatypes.json b/qt/6.8.1/msvc2022_64/metatypes/qt6fbsupportprivate_metatypes.json new file mode 100644 index 0000000000000000000000000000000000000000..05909d1d0fe1d0fa160a471578ef682e6672b521 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/metatypes/qt6fbsupportprivate_metatypes.json @@ -0,0 +1,152 @@ +[ + { + "classes": [ + { + "className": "QFbCursorDeviceListener", + "lineNumber": 26, + "object": true, + "qualifiedClassName": "QFbCursorDeviceListener", + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "type", + "type": "QInputDeviceManager::DeviceType" + } + ], + "index": 0, + "name": "onDeviceListChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "className": "QFbCursor", + "lineNumber": 41, + "object": true, + "qualifiedClassName": "QFbCursor", + "superClasses": [ + { + "access": "public", + "name": "QPlatformCursor" + } + ] + } + ], + "inputFile": "qfbcursor_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QFbScreen", + "lineNumber": 30, + "object": true, + "qualifiedClassName": "QFbScreen", + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "rect", + "type": "QRect" + } + ], + "index": 0, + "name": "setDirty", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "size", + "type": "QSize" + } + ], + "index": 1, + "name": "setPhysicalSize", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "rect", + "type": "QRect" + } + ], + "index": 2, + "name": "setGeometry", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QPlatformScreen" + } + ] + } + ], + "inputFile": "qfbscreen_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QFbVtHandler", + "lineNumber": 25, + "object": true, + "qualifiedClassName": "QFbVtHandler", + "signals": [ + { + "access": "public", + "index": 0, + "name": "interrupted", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "aboutToSuspend", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "resumed", + "returnType": "void" + } + ], + "slots": [ + { + "access": "private", + "index": 3, + "name": "handleSignal", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qfbvthandler_p.h", + "outputRevision": 68 + } +] diff --git a/qt/6.8.1/msvc2022_64/metatypes/qt6gui_metatypes.json b/qt/6.8.1/msvc2022_64/metatypes/qt6gui_metatypes.json new file mode 100644 index 0000000000000000000000000000000000000000..f542f1a265f996228fb6d76f20236b1eb6580164 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/metatypes/qt6gui_metatypes.json @@ -0,0 +1,9004 @@ +[ + { + "classes": [ + { + "className": "QPlatformScreen", + "gadget": true, + "lineNumber": 43, + "qualifiedClassName": "QPlatformScreen" + } + ], + "inputFile": "qplatformscreen.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QAbstractTextDocumentLayout", + "lineNumber": 22, + "object": true, + "qualifiedClassName": "QAbstractTextDocumentLayout", + "signals": [ + { + "access": "public", + "arguments": [ + { + "type": "QRectF" + } + ], + "index": 0, + "name": "update", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "isCloned": true, + "name": "update", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "block", + "type": "QTextBlock" + } + ], + "index": 2, + "name": "updateBlock", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "newSize", + "type": "QSizeF" + } + ], + "index": 3, + "name": "documentSizeChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "newPages", + "type": "int" + } + ], + "index": 4, + "name": "pageCountChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "private", + "index": 5, + "name": "_q_dynamicPageCountSlot", + "returnType": "int" + }, + { + "access": "private", + "index": 6, + "name": "_q_dynamicDocumentSizeSlot", + "returnType": "QSizeF" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qabstracttextdocumentlayout.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QAccessible", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "Event", + "values": [ + "SoundPlayed", + "Alert", + "ForegroundChanged", + "MenuStart", + "MenuEnd", + "PopupMenuStart", + "PopupMenuEnd", + "ContextHelpStart", + "ContextHelpEnd", + "DragDropStart", + "DragDropEnd", + "DialogStart", + "DialogEnd", + "ScrollingStart", + "ScrollingEnd", + "MenuCommand", + "ActionChanged", + "ActiveDescendantChanged", + "AttributeChanged", + "DocumentContentChanged", + "DocumentLoadComplete", + "DocumentLoadStopped", + "DocumentReload", + "HyperlinkEndIndexChanged", + "HyperlinkNumberOfAnchorsChanged", + "HyperlinkSelectedLinkChanged", + "HypertextLinkActivated", + "HypertextLinkSelected", + "HyperlinkStartIndexChanged", + "HypertextChanged", + "HypertextNLinksChanged", + "ObjectAttributeChanged", + "PageChanged", + "SectionChanged", + "TableCaptionChanged", + "TableColumnDescriptionChanged", + "TableColumnHeaderChanged", + "TableModelChanged", + "TableRowDescriptionChanged", + "TableRowHeaderChanged", + "TableSummaryChanged", + "TextAttributeChanged", + "TextCaretMoved", + "TextColumnChanged", + "TextInserted", + "TextRemoved", + "TextUpdated", + "TextSelectionChanged", + "VisibleDataChanged", + "ObjectCreated", + "ObjectDestroyed", + "ObjectShow", + "ObjectHide", + "ObjectReorder", + "Focus", + "Selection", + "SelectionAdd", + "SelectionRemove", + "SelectionWithin", + "StateChanged", + "LocationChanged", + "NameChanged", + "DescriptionChanged", + "ValueChanged", + "ParentChanged", + "HelpChanged", + "DefaultActionChanged", + "AcceleratorChanged", + "Announcement", + "IdentifierChanged", + "InvalidEvent" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "Role", + "values": [ + "NoRole", + "TitleBar", + "MenuBar", + "ScrollBar", + "Grip", + "Sound", + "Cursor", + "Caret", + "AlertMessage", + "Window", + "Client", + "PopupMenu", + "MenuItem", + "ToolTip", + "Application", + "Document", + "Pane", + "Chart", + "Dialog", + "Border", + "Grouping", + "Separator", + "ToolBar", + "StatusBar", + "Table", + "ColumnHeader", + "RowHeader", + "Column", + "Row", + "Cell", + "Link", + "HelpBalloon", + "Assistant", + "List", + "ListItem", + "Tree", + "TreeItem", + "PageTab", + "PropertyPage", + "Indicator", + "Graphic", + "StaticText", + "EditableText", + "Button", + "PushButton", + "CheckBox", + "RadioButton", + "ComboBox", + "ProgressBar", + "Dial", + "HotkeyField", + "Slider", + "SpinBox", + "Canvas", + "Animation", + "Equation", + "ButtonDropDown", + "ButtonMenu", + "ButtonDropGrid", + "Whitespace", + "PageTabList", + "Clock", + "Splitter", + "LayeredPane", + "Terminal", + "Desktop", + "Paragraph", + "WebDocument", + "Section", + "Notification", + "ColorChooser", + "Footer", + "Form", + "Heading", + "Note", + "ComplementaryContent", + "UserRole" + ] + }, + { + "isClass": true, + "isFlag": false, + "name": "Attribute", + "values": [ + "Custom", + "Level" + ] + }, + { + "isClass": true, + "isFlag": false, + "name": "AnnouncementPoliteness", + "values": [ + "Polite", + "Assertive" + ] + } + ], + "gadget": true, + "lineNumber": 25, + "qualifiedClassName": "QAccessible" + } + ], + "inputFile": "qaccessible_base.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QAccessibleBridgePlugin", + "lineNumber": 29, + "object": true, + "qualifiedClassName": "QAccessibleBridgePlugin", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qaccessiblebridge.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QAccessibleCache", + "lineNumber": 30, + "object": true, + "qualifiedClassName": "QAccessibleCache", + "slots": [ + { + "access": "private", + "arguments": [ + { + "name": "obj", + "type": "QObject*" + } + ], + "index": 0, + "name": "objectDestroyed", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qaccessiblecache_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QAccessiblePlugin", + "lineNumber": 22, + "object": true, + "qualifiedClassName": "QAccessiblePlugin", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qaccessibleplugin.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QAction", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "MenuRole", + "values": [ + "NoRole", + "TextHeuristicRole", + "ApplicationSpecificRole", + "AboutQtRole", + "AboutRole", + "PreferencesRole", + "QuitRole" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "Priority", + "values": [ + "LowPriority", + "NormalPriority", + "HighPriority" + ] + } + ], + "lineNumber": 29, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "checkable", + "notify": "checkableChanged", + "read": "isCheckable", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setCheckable" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "checked", + "notify": "toggled", + "read": "isChecked", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setChecked" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "enabled", + "notify": "enabledChanged", + "read": "isEnabled", + "required": false, + "reset": "resetEnabled", + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setEnabled" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "icon", + "notify": "changed", + "read": "icon", + "required": false, + "scriptable": true, + "stored": true, + "type": "QIcon", + "user": false, + "write": "setIcon" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "text", + "notify": "changed", + "read": "text", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setText" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "iconText", + "notify": "changed", + "read": "iconText", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setIconText" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "toolTip", + "notify": "changed", + "read": "toolTip", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setToolTip" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 7, + "name": "statusTip", + "notify": "changed", + "read": "statusTip", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setStatusTip" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 8, + "name": "whatsThis", + "notify": "changed", + "read": "whatsThis", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setWhatsThis" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 9, + "name": "font", + "notify": "changed", + "read": "font", + "required": false, + "scriptable": true, + "stored": true, + "type": "QFont", + "user": false, + "write": "setFont" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 10, + "name": "shortcut", + "notify": "changed", + "read": "shortcut", + "required": false, + "scriptable": true, + "stored": true, + "type": "QKeySequence", + "user": false, + "write": "setShortcut" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 11, + "name": "shortcutContext", + "notify": "changed", + "read": "shortcutContext", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::ShortcutContext", + "user": false, + "write": "setShortcutContext" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 12, + "name": "autoRepeat", + "notify": "changed", + "read": "autoRepeat", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setAutoRepeat" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 13, + "name": "visible", + "notify": "visibleChanged", + "read": "isVisible", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setVisible" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 14, + "name": "menuRole", + "notify": "changed", + "read": "menuRole", + "required": false, + "scriptable": true, + "stored": true, + "type": "MenuRole", + "user": false, + "write": "setMenuRole" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 15, + "name": "iconVisibleInMenu", + "notify": "changed", + "read": "isIconVisibleInMenu", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setIconVisibleInMenu" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 16, + "name": "shortcutVisibleInContextMenu", + "notify": "changed", + "read": "isShortcutVisibleInContextMenu", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setShortcutVisibleInContextMenu" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 17, + "name": "priority", + "notify": "changed", + "read": "priority", + "required": false, + "scriptable": true, + "stored": true, + "type": "Priority", + "user": false, + "write": "setPriority" + } + ], + "qualifiedClassName": "QAction", + "signals": [ + { + "access": "public", + "index": 0, + "name": "changed", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "enabled", + "type": "bool" + } + ], + "index": 1, + "name": "enabledChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "checkable", + "type": "bool" + } + ], + "index": 2, + "name": "checkableChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "visibleChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "checked", + "type": "bool" + } + ], + "index": 4, + "name": "triggered", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "isCloned": true, + "name": "triggered", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "hovered", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "bool" + } + ], + "index": 7, + "name": "toggled", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "index": 8, + "name": "trigger", + "returnType": "void" + }, + { + "access": "public", + "index": 9, + "name": "hover", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "bool" + } + ], + "index": 10, + "name": "setChecked", + "returnType": "void" + }, + { + "access": "public", + "index": 11, + "name": "toggle", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "bool" + } + ], + "index": 12, + "name": "setEnabled", + "returnType": "void" + }, + { + "access": "public", + "index": 13, + "name": "resetEnabled", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "b", + "type": "bool" + } + ], + "index": 14, + "name": "setDisabled", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "bool" + } + ], + "index": 15, + "name": "setVisible", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qaction.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QActionGroup", + "enums": [ + { + "isClass": true, + "isFlag": false, + "name": "ExclusionPolicy", + "values": [ + "None", + "Exclusive", + "ExclusiveOptional" + ] + } + ], + "lineNumber": 16, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "exclusionPolicy", + "read": "exclusionPolicy", + "required": false, + "scriptable": true, + "stored": true, + "type": "QActionGroup::ExclusionPolicy", + "user": false, + "write": "setExclusionPolicy" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "enabled", + "read": "isEnabled", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setEnabled" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "visible", + "read": "isVisible", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setVisible" + } + ], + "qualifiedClassName": "QActionGroup", + "signals": [ + { + "access": "public", + "arguments": [ + { + "type": "QAction*" + } + ], + "index": 0, + "name": "triggered", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QAction*" + } + ], + "index": 1, + "name": "hovered", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "type": "bool" + } + ], + "index": 2, + "name": "setEnabled", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "b", + "type": "bool" + } + ], + "index": 3, + "name": "setDisabled", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "bool" + } + ], + "index": 4, + "name": "setVisible", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "bool" + } + ], + "index": 5, + "name": "setExclusive", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "policy", + "type": "ExclusionPolicy" + } + ], + "index": 6, + "name": "setExclusionPolicy", + "returnType": "void" + }, + { + "access": "private", + "index": 7, + "name": "_q_actionTriggered", + "returnType": "void" + }, + { + "access": "private", + "index": 8, + "name": "_q_actionHovered", + "returnType": "void" + }, + { + "access": "private", + "index": 9, + "name": "_q_actionChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qactiongroup.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QGradient", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "Type", + "values": [ + "LinearGradient", + "RadialGradient", + "ConicalGradient", + "NoGradient" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "Spread", + "values": [ + "PadSpread", + "ReflectSpread", + "RepeatSpread" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "CoordinateMode", + "values": [ + "LogicalMode", + "StretchToDeviceMode", + "ObjectBoundingMode", + "ObjectMode" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "Preset", + "values": [ + "WarmFlame", + "NightFade", + "SpringWarmth", + "JuicyPeach", + "YoungPassion", + "LadyLips", + "SunnyMorning", + "RainyAshville", + "FrozenDreams", + "WinterNeva", + "DustyGrass", + "TemptingAzure", + "HeavyRain", + "AmyCrisp", + "MeanFruit", + "DeepBlue", + "RipeMalinka", + "CloudyKnoxville", + "MalibuBeach", + "NewLife", + "TrueSunset", + "MorpheusDen", + "RareWind", + "NearMoon", + "WildApple", + "SaintPetersburg", + "PlumPlate", + "EverlastingSky", + "HappyFisher", + "Blessing", + "SharpeyeEagle", + "LadogaBottom", + "LemonGate", + "ItmeoBranding", + "ZeusMiracle", + "OldHat", + "StarWine", + "HappyAcid", + "AwesomePine", + "NewYork", + "ShyRainbow", + "MixedHopes", + "FlyHigh", + "StrongBliss", + "FreshMilk", + "SnowAgain", + "FebruaryInk", + "KindSteel", + "SoftGrass", + "GrownEarly", + "SharpBlues", + "ShadyWater", + "DirtyBeauty", + "GreatWhale", + "TeenNotebook", + "PoliteRumors", + "SweetPeriod", + "WideMatrix", + "SoftCherish", + "RedSalvation", + "BurningSpring", + "NightParty", + "SkyGlider", + "HeavenPeach", + "PurpleDivision", + "AquaSplash", + "SpikyNaga", + "LoveKiss", + "CleanMirror", + "PremiumDark", + "ColdEvening", + "CochitiLake", + "SummerGames", + "PassionateBed", + "MountainRock", + "DesertHump", + "JungleDay", + "PhoenixStart", + "OctoberSilence", + "FarawayRiver", + "AlchemistLab", + "OverSun", + "PremiumWhite", + "MarsParty", + "EternalConstance", + "JapanBlush", + "SmilingRain", + "CloudyApple", + "BigMango", + "HealthyWater", + "AmourAmour", + "RiskyConcrete", + "StrongStick", + "ViciousStance", + "PaloAlto", + "HappyMemories", + "MidnightBloom", + "Crystalline", + "PartyBliss", + "ConfidentCloud", + "LeCocktail", + "RiverCity", + "FrozenBerry", + "ChildCare", + "FlyingLemon", + "NewRetrowave", + "HiddenJaguar", + "AboveTheSky", + "Nega", + "DenseWater", + "Seashore", + "MarbleWall", + "CheerfulCaramel", + "NightSky", + "MagicLake", + "YoungGrass", + "ColorfulPeach", + "GentleCare", + "PlumBath", + "HappyUnicorn", + "AfricanField", + "SolidStone", + "OrangeJuice", + "GlassWater", + "NorthMiracle", + "FruitBlend", + "MillenniumPine", + "HighFlight", + "MoleHall", + "SpaceShift", + "ForestInei", + "RoyalGarden", + "RichMetal", + "JuicyCake", + "SmartIndigo", + "SandStrike", + "NorseBeauty", + "AquaGuidance", + "SunVeggie", + "SeaLord", + "BlackSea", + "GrassShampoo", + "LandingAircraft", + "WitchDance", + "SleeplessNight", + "AngelCare", + "CrystalRiver", + "SoftLipstick", + "SaltMountain", + "PerfectWhite", + "FreshOasis", + "StrictNovember", + "MorningSalad", + "DeepRelief", + "SeaStrike", + "NightCall", + "SupremeSky", + "LightBlue", + "MindCrawl", + "LilyMeadow", + "SugarLollipop", + "SweetDessert", + "MagicRay", + "TeenParty", + "FrozenHeat", + "GagarinView", + "FabledSunset", + "PerfectBlue", + "NumPresets" + ] + } + ], + "gadget": true, + "lineNumber": 134, + "qualifiedClassName": "QGradient" + } + ], + "inputFile": "qbrush.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QClipboard", + "lineNumber": 19, + "object": true, + "qualifiedClassName": "QClipboard", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "mode", + "type": "QClipboard::Mode" + } + ], + "index": 0, + "name": "changed", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "selectionChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "findBufferChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "dataChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qclipboard.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QColorSpace", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "NamedColorSpace", + "values": [ + "SRgb", + "SRgbLinear", + "AdobeRgb", + "DisplayP3", + "ProPhotoRgb", + "Bt2020", + "Bt2100Pq", + "Bt2100Hlg" + ] + }, + { + "isClass": true, + "isFlag": false, + "name": "Primaries", + "values": [ + "Custom", + "SRgb", + "AdobeRgb", + "DciP3D65", + "ProPhotoRgb", + "Bt2020" + ] + }, + { + "isClass": true, + "isFlag": false, + "name": "TransferFunction", + "values": [ + "Custom", + "Linear", + "Gamma", + "SRgb", + "ProPhotoRgb", + "Bt2020", + "St2084", + "Hlg" + ] + }, + { + "isClass": true, + "isFlag": false, + "name": "TransformModel", + "type": "uint8_t", + "values": [ + "ThreeComponentMatrix", + "ElementListProcessing" + ] + }, + { + "isClass": true, + "isFlag": false, + "name": "ColorModel", + "type": "uint8_t", + "values": [ + "Undefined", + "Rgb", + "Gray", + "Cmyk" + ] + } + ], + "gadget": true, + "lineNumber": 20, + "qualifiedClassName": "QColorSpace" + } + ], + "inputFile": "qcolorspace.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QDragManager", + "lineNumber": 57, + "object": true, + "qualifiedClassName": "QDragManager", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qdnd_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QDrag", + "lineNumber": 21, + "object": true, + "qualifiedClassName": "QDrag", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "action", + "type": "Qt::DropAction" + } + ], + "index": 0, + "name": "actionChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "newTarget", + "type": "QObject*" + } + ], + "index": 1, + "name": "targetChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qdrag.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QPointerEvent", + "gadget": true, + "lineNumber": 72, + "qualifiedClassName": "QPointerEvent", + "superClasses": [ + { + "access": "public", + "name": "QInputEvent" + } + ] + }, + { + "className": "QSinglePointEvent", + "gadget": true, + "lineNumber": 108, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "exclusivePointGrabber", + "read": "exclusivePointGrabber", + "required": false, + "scriptable": true, + "stored": true, + "type": "QObject*", + "user": false, + "write": "setExclusivePointGrabber" + } + ], + "qualifiedClassName": "QSinglePointEvent", + "superClasses": [ + { + "access": "public", + "name": "QPointerEvent" + } + ] + }, + { + "className": "QWheelEvent", + "gadget": true, + "lineNumber": 280, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "device", + "read": "pointingDevice", + "required": false, + "scriptable": true, + "stored": true, + "type": "const QPointingDevice*", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "pixelDelta", + "read": "pixelDelta", + "required": false, + "scriptable": true, + "stored": true, + "type": "QPoint", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "angleDelta", + "read": "angleDelta", + "required": false, + "scriptable": true, + "stored": true, + "type": "QPoint", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "phase", + "read": "phase", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::ScrollPhase", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "inverted", + "read": "inverted", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + } + ], + "qualifiedClassName": "QWheelEvent", + "superClasses": [ + { + "access": "public", + "name": "QSinglePointEvent" + } + ] + } + ], + "inputFile": "qevent.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QEventPoint", + "enums": [ + { + "alias": "State", + "isClass": false, + "isFlag": true, + "name": "States", + "type": "quint8", + "values": [ + "Unknown", + "Stationary", + "Pressed", + "Updated", + "Released" + ] + } + ], + "gadget": true, + "lineNumber": 19, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "accepted", + "read": "isAccepted", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setAccepted" + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 1, + "name": "device", + "read": "device", + "required": false, + "scriptable": true, + "stored": true, + "type": "const QPointingDevice*", + "user": false + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 2, + "name": "id", + "read": "id", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 3, + "name": "uniqueId", + "read": "uniqueId", + "required": false, + "scriptable": true, + "stored": true, + "type": "QPointingDeviceUniqueId", + "user": false + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 4, + "name": "state", + "read": "state", + "required": false, + "scriptable": true, + "stored": true, + "type": "State", + "user": false + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 5, + "name": "timestamp", + "read": "timestamp", + "required": false, + "scriptable": true, + "stored": true, + "type": "ulong", + "user": false + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 6, + "name": "pressTimestamp", + "read": "pressTimestamp", + "required": false, + "scriptable": true, + "stored": true, + "type": "ulong", + "user": false + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 7, + "name": "lastTimestamp", + "read": "lastTimestamp", + "required": false, + "scriptable": true, + "stored": true, + "type": "ulong", + "user": false + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 8, + "name": "timeHeld", + "read": "timeHeld", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 9, + "name": "pressure", + "read": "pressure", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 10, + "name": "rotation", + "read": "rotation", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 11, + "name": "ellipseDiameters", + "read": "ellipseDiameters", + "required": false, + "scriptable": true, + "stored": true, + "type": "QSizeF", + "user": false + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 12, + "name": "velocity", + "read": "velocity", + "required": false, + "scriptable": true, + "stored": true, + "type": "QVector2D", + "user": false + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 13, + "name": "position", + "read": "position", + "required": false, + "scriptable": true, + "stored": true, + "type": "QPointF", + "user": false + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 14, + "name": "pressPosition", + "read": "pressPosition", + "required": false, + "scriptable": true, + "stored": true, + "type": "QPointF", + "user": false + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 15, + "name": "grabPosition", + "read": "grabPosition", + "required": false, + "scriptable": true, + "stored": true, + "type": "QPointF", + "user": false + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 16, + "name": "lastPosition", + "read": "lastPosition", + "required": false, + "scriptable": true, + "stored": true, + "type": "QPointF", + "user": false + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 17, + "name": "scenePosition", + "read": "scenePosition", + "required": false, + "scriptable": true, + "stored": true, + "type": "QPointF", + "user": false + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 18, + "name": "scenePressPosition", + "read": "scenePressPosition", + "required": false, + "scriptable": true, + "stored": true, + "type": "QPointF", + "user": false + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 19, + "name": "sceneGrabPosition", + "read": "sceneGrabPosition", + "required": false, + "scriptable": true, + "stored": true, + "type": "QPointF", + "user": false + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 20, + "name": "sceneLastPosition", + "read": "sceneLastPosition", + "required": false, + "scriptable": true, + "stored": true, + "type": "QPointF", + "user": false + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 21, + "name": "globalPosition", + "read": "globalPosition", + "required": false, + "scriptable": true, + "stored": true, + "type": "QPointF", + "user": false + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 22, + "name": "globalPressPosition", + "read": "globalPressPosition", + "required": false, + "scriptable": true, + "stored": true, + "type": "QPointF", + "user": false + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 23, + "name": "globalGrabPosition", + "read": "globalGrabPosition", + "required": false, + "scriptable": true, + "stored": true, + "type": "QPointF", + "user": false + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 24, + "name": "globalLastPosition", + "read": "globalLastPosition", + "required": false, + "scriptable": true, + "stored": true, + "type": "QPointF", + "user": false + } + ], + "qualifiedClassName": "QEventPoint" + } + ], + "inputFile": "qeventpoint.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QFileInfoGatherer", + "lineNumber": 125, + "object": true, + "qualifiedClassName": "QFileInfoGatherer", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "directory", + "type": "QString" + }, + { + "name": "updates", + "type": "QList>" + } + ], + "index": 0, + "name": "updates", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "directory", + "type": "QString" + }, + { + "name": "listOfFiles", + "type": "QStringList" + } + ], + "index": 1, + "name": "newListOfFiles", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "fileName", + "type": "QString" + }, + { + "name": "resolvedName", + "type": "QString" + } + ], + "index": 2, + "name": "nameResolved", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "path", + "type": "QString" + } + ], + "index": 3, + "name": "directoryLoaded", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "directoryPath", + "type": "QString" + } + ], + "index": 4, + "name": "list", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "path", + "type": "QString" + }, + { + "name": "files", + "type": "QStringList" + } + ], + "index": 5, + "name": "fetchExtendedInformation", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "path", + "type": "QString" + } + ], + "index": 6, + "name": "updateFile", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "enable", + "type": "bool" + } + ], + "index": 7, + "name": "setResolveSymlinks", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "provider", + "type": "QAbstractFileIconProvider*" + } + ], + "index": 8, + "name": "setIconProvider", + "returnType": "void" + }, + { + "access": "private", + "index": 9, + "name": "driveAdded", + "returnType": "void" + }, + { + "access": "private", + "index": 10, + "name": "driveRemoved", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QThread" + } + ] + } + ], + "inputFile": "qfileinfogatherer_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QFileSystemModel", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "Option", + "values": [ + "DontWatchForChanges", + "DontResolveSymlinks", + "DontUseCustomDirectoryIcons" + ] + } + ], + "lineNumber": 21, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "resolveSymlinks", + "read": "resolveSymlinks", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setResolveSymlinks" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "readOnly", + "read": "isReadOnly", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setReadOnly" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "nameFilterDisables", + "read": "nameFilterDisables", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setNameFilterDisables" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "options", + "read": "options", + "required": false, + "scriptable": true, + "stored": true, + "type": "Options", + "user": false, + "write": "setOptions" + } + ], + "qualifiedClassName": "QFileSystemModel", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "newPath", + "type": "QString" + } + ], + "index": 0, + "name": "rootPathChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "path", + "type": "QString" + }, + { + "name": "oldName", + "type": "QString" + }, + { + "name": "newName", + "type": "QString" + } + ], + "index": 1, + "name": "fileRenamed", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "path", + "type": "QString" + } + ], + "index": 2, + "name": "directoryLoaded", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QAbstractItemModel" + } + ] + } + ], + "inputFile": "qfilesystemmodel.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QFont", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "StyleHint", + "values": [ + "Helvetica", + "SansSerif", + "Times", + "Serif", + "Courier", + "TypeWriter", + "OldEnglish", + "Decorative", + "System", + "AnyStyle", + "Cursive", + "Monospace", + "Fantasy" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "StyleStrategy", + "values": [ + "PreferDefault", + "PreferBitmap", + "PreferDevice", + "PreferOutline", + "ForceOutline", + "PreferMatch", + "PreferQuality", + "PreferAntialias", + "NoAntialias", + "NoSubpixelAntialias", + "PreferNoShaping", + "ContextFontMerging", + "PreferTypoLineMetrics", + "NoFontMerging" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "HintingPreference", + "values": [ + "PreferDefaultHinting", + "PreferNoHinting", + "PreferVerticalHinting", + "PreferFullHinting" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "Weight", + "values": [ + "Thin", + "ExtraLight", + "Light", + "Normal", + "Medium", + "DemiBold", + "Bold", + "ExtraBold", + "Black" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "Style", + "values": [ + "StyleNormal", + "StyleItalic", + "StyleOblique" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "Stretch", + "values": [ + "AnyStretch", + "UltraCondensed", + "ExtraCondensed", + "Condensed", + "SemiCondensed", + "Unstretched", + "SemiExpanded", + "Expanded", + "ExtraExpanded", + "UltraExpanded" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "Capitalization", + "values": [ + "MixedCase", + "AllUppercase", + "AllLowercase", + "SmallCaps", + "Capitalize" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "SpacingType", + "values": [ + "PercentageSpacing", + "AbsoluteSpacing" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "ResolveProperties", + "values": [ + "NoPropertiesResolved", + "FamilyResolved", + "SizeResolved", + "StyleHintResolved", + "StyleStrategyResolved", + "WeightResolved", + "StyleResolved", + "UnderlineResolved", + "OverlineResolved", + "StrikeOutResolved", + "FixedPitchResolved", + "StretchResolved", + "KerningResolved", + "CapitalizationResolved", + "LetterSpacingResolved", + "WordSpacingResolved", + "HintingPreferenceResolved", + "StyleNameResolved", + "FamiliesResolved", + "FeaturesResolved", + "VariableAxesResolved", + "AllPropertiesResolved" + ] + } + ], + "gadget": true, + "lineNumber": 21, + "qualifiedClassName": "QFont" + } + ], + "inputFile": "qfont.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QFontDatabase", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "WritingSystem", + "values": [ + "Any", + "Latin", + "Greek", + "Cyrillic", + "Armenian", + "Hebrew", + "Arabic", + "Syriac", + "Thaana", + "Devanagari", + "Bengali", + "Gurmukhi", + "Gujarati", + "Oriya", + "Tamil", + "Telugu", + "Kannada", + "Malayalam", + "Sinhala", + "Thai", + "Lao", + "Tibetan", + "Myanmar", + "Georgian", + "Khmer", + "SimplifiedChinese", + "TraditionalChinese", + "Japanese", + "Korean", + "Vietnamese", + "Symbol", + "Other", + "Ogham", + "Runic", + "Nko", + "WritingSystemsCount" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "SystemFont", + "values": [ + "GeneralFont", + "FixedFont", + "TitleFont", + "SmallestReadableFont" + ] + } + ], + "gadget": true, + "lineNumber": 18, + "qualifiedClassName": "QFontDatabase" + } + ], + "inputFile": "qfontdatabase.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QGenericPlugin", + "lineNumber": 15, + "object": true, + "qualifiedClassName": "QGenericPlugin", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qgenericplugin.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QGuiApplication", + "lineNumber": 36, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "windowIcon", + "read": "windowIcon", + "required": false, + "scriptable": true, + "stored": true, + "type": "QIcon", + "user": false, + "write": "setWindowIcon" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "applicationDisplayName", + "notify": "applicationDisplayNameChanged", + "read": "applicationDisplayName", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setApplicationDisplayName" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "desktopFileName", + "read": "desktopFileName", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setDesktopFileName" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "layoutDirection", + "notify": "layoutDirectionChanged", + "read": "layoutDirection", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::LayoutDirection", + "user": false, + "write": "setLayoutDirection" + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 4, + "name": "platformName", + "read": "platformName", + "required": false, + "scriptable": true, + "stored": false, + "type": "QString", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "quitOnLastWindowClosed", + "read": "quitOnLastWindowClosed", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setQuitOnLastWindowClosed" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "primaryScreen", + "notify": "primaryScreenChanged", + "read": "primaryScreen", + "required": false, + "scriptable": true, + "stored": false, + "type": "QScreen*", + "user": false + } + ], + "qualifiedClassName": "QGuiApplication", + "signals": [ + { + "access": "public", + "index": 0, + "name": "fontDatabaseChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "screen", + "type": "QScreen*" + } + ], + "index": 1, + "name": "screenAdded", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "screen", + "type": "QScreen*" + } + ], + "index": 2, + "name": "screenRemoved", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "screen", + "type": "QScreen*" + } + ], + "index": 3, + "name": "primaryScreenChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "lastWindowClosed", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "focusObject", + "type": "QObject*" + } + ], + "index": 5, + "name": "focusObjectChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "focusWindow", + "type": "QWindow*" + } + ], + "index": 6, + "name": "focusWindowChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "state", + "type": "Qt::ApplicationState" + } + ], + "index": 7, + "name": "applicationStateChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "direction", + "type": "Qt::LayoutDirection" + } + ], + "index": 8, + "name": "layoutDirectionChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "sessionManager", + "type": "QSessionManager&" + } + ], + "index": 9, + "name": "commitDataRequest", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "sessionManager", + "type": "QSessionManager&" + } + ], + "index": 10, + "name": "saveStateRequest", + "returnType": "void" + }, + { + "access": "public", + "index": 11, + "name": "applicationDisplayNameChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "pal", + "type": "QPalette" + } + ], + "index": 12, + "name": "paletteChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "font", + "type": "QFont" + } + ], + "index": 13, + "name": "fontChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "number", + "type": "qint64" + } + ], + "index": 14, + "name": "setBadgeNumber", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "object", + "type": "QObject*" + } + ], + "index": 15, + "name": "_q_updateFocusObject", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QCoreApplication" + } + ] + } + ], + "inputFile": "qguiapplication.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QHighDpiScaling", + "enums": [ + { + "isClass": true, + "isFlag": false, + "name": "DpiAdjustmentPolicy", + "values": [ + "Unset", + "Enabled", + "Disabled", + "UpOnly" + ] + } + ], + "gadget": true, + "lineNumber": 38, + "qualifiedClassName": "QHighDpiScaling" + } + ], + "inputFile": "qhighdpiscaling_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QIconEnginePlugin", + "lineNumber": 18, + "object": true, + "qualifiedClassName": "QIconEnginePlugin", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qiconengineplugin.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QImage", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "Format", + "values": [ + "Format_Invalid", + "Format_Mono", + "Format_MonoLSB", + "Format_Indexed8", + "Format_RGB32", + "Format_ARGB32", + "Format_ARGB32_Premultiplied", + "Format_RGB16", + "Format_ARGB8565_Premultiplied", + "Format_RGB666", + "Format_ARGB6666_Premultiplied", + "Format_RGB555", + "Format_ARGB8555_Premultiplied", + "Format_RGB888", + "Format_RGB444", + "Format_ARGB4444_Premultiplied", + "Format_RGBX8888", + "Format_RGBA8888", + "Format_RGBA8888_Premultiplied", + "Format_BGR30", + "Format_A2BGR30_Premultiplied", + "Format_RGB30", + "Format_A2RGB30_Premultiplied", + "Format_Alpha8", + "Format_Grayscale8", + "Format_RGBX64", + "Format_RGBA64", + "Format_RGBA64_Premultiplied", + "Format_Grayscale16", + "Format_BGR888", + "Format_RGBX16FPx4", + "Format_RGBA16FPx4", + "Format_RGBA16FPx4_Premultiplied", + "Format_RGBX32FPx4", + "Format_RGBA32FPx4", + "Format_RGBA32FPx4_Premultiplied", + "Format_CMYK8888", + "NImageFormats" + ] + } + ], + "gadget": true, + "lineNumber": 36, + "qualifiedClassName": "QImage", + "superClasses": [ + { + "access": "public", + "name": "QPaintDevice" + } + ] + } + ], + "inputFile": "qimage.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QImageIOPlugin", + "lineNumber": 101, + "object": true, + "qualifiedClassName": "QImageIOPlugin", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qimageiohandler.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QInputControl", + "lineNumber": 25, + "object": true, + "qualifiedClassName": "QInputControl", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qinputcontrol_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QInputDevice", + "enums": [ + { + "alias": "DeviceType", + "isClass": true, + "isFlag": true, + "name": "DeviceTypes", + "values": [ + "Unknown", + "Mouse", + "TouchScreen", + "TouchPad", + "Puck", + "Stylus", + "Airbrush", + "Keyboard", + "AllDevices" + ] + }, + { + "alias": "Capability", + "isClass": true, + "isFlag": true, + "name": "Capabilities", + "values": [ + "None", + "Position", + "Area", + "Pressure", + "Velocity", + "NormalizedPosition", + "MouseEmulation", + "PixelScroll", + "Scroll", + "Hover", + "Rotation", + "XTilt", + "YTilt", + "TangentialPressure", + "ZPosition", + "All" + ] + } + ], + "lineNumber": 16, + "object": true, + "properties": [ + { + "constant": true, + "designable": true, + "final": false, + "index": 0, + "name": "name", + "read": "name", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 1, + "name": "type", + "read": "type", + "required": false, + "scriptable": true, + "stored": true, + "type": "DeviceType", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "capabilities", + "read": "capabilities", + "required": false, + "scriptable": true, + "stored": true, + "type": "Capabilities", + "user": false + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 3, + "name": "systemId", + "read": "systemId", + "required": false, + "scriptable": true, + "stored": true, + "type": "qint64", + "user": false + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 4, + "name": "seatName", + "read": "seatName", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "availableVirtualGeometry", + "notify": "availableVirtualGeometryChanged", + "read": "availableVirtualGeometry", + "required": false, + "scriptable": true, + "stored": true, + "type": "QRect", + "user": false + } + ], + "qualifiedClassName": "QInputDevice", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "area", + "type": "QRect" + } + ], + "index": 0, + "name": "availableVirtualGeometryChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qinputdevice.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QInputDeviceManager", + "lineNumber": 25, + "object": true, + "qualifiedClassName": "QInputDeviceManager", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "type", + "type": "QInputDeviceManager::DeviceType" + } + ], + "index": 0, + "name": "deviceListChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "pos", + "type": "QPoint" + } + ], + "index": 1, + "name": "cursorPositionChangeRequested", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qinputdevicemanager_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QInputMethod", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "Action", + "values": [ + "Click", + "ContextMenu" + ] + } + ], + "lineNumber": 18, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "cursorRectangle", + "notify": "cursorRectangleChanged", + "read": "cursorRectangle", + "required": false, + "scriptable": true, + "stored": true, + "type": "QRectF", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "anchorRectangle", + "notify": "anchorRectangleChanged", + "read": "anchorRectangle", + "required": false, + "scriptable": true, + "stored": true, + "type": "QRectF", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "keyboardRectangle", + "notify": "keyboardRectangleChanged", + "read": "keyboardRectangle", + "required": false, + "scriptable": true, + "stored": true, + "type": "QRectF", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "inputItemClipRectangle", + "notify": "inputItemClipRectangleChanged", + "read": "inputItemClipRectangle", + "required": false, + "scriptable": true, + "stored": true, + "type": "QRectF", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "visible", + "notify": "visibleChanged", + "read": "isVisible", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "animating", + "notify": "animatingChanged", + "read": "isAnimating", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "locale", + "notify": "localeChanged", + "read": "locale", + "required": false, + "scriptable": true, + "stored": true, + "type": "QLocale", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 7, + "name": "inputDirection", + "notify": "inputDirectionChanged", + "read": "inputDirection", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::LayoutDirection", + "user": false + } + ], + "qualifiedClassName": "QInputMethod", + "signals": [ + { + "access": "public", + "index": 0, + "name": "cursorRectangleChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "anchorRectangleChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "keyboardRectangleChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "inputItemClipRectangleChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "visibleChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "animatingChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "localeChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "newDirection", + "type": "Qt::LayoutDirection" + } + ], + "index": 7, + "name": "inputDirectionChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "index": 8, + "name": "show", + "returnType": "void" + }, + { + "access": "public", + "index": 9, + "name": "hide", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "queries", + "type": "Qt::InputMethodQueries" + } + ], + "index": 10, + "name": "update", + "returnType": "void" + }, + { + "access": "public", + "index": 11, + "name": "reset", + "returnType": "void" + }, + { + "access": "public", + "index": 12, + "name": "commit", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "a", + "type": "Action" + }, + { + "name": "cursorPosition", + "type": "int" + } + ], + "index": 13, + "name": "invokeAction", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qinputmethod.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QInternalMimeData", + "lineNumber": 31, + "object": true, + "qualifiedClassName": "QInternalMimeData", + "superClasses": [ + { + "access": "public", + "name": "QMimeData" + } + ] + } + ], + "inputFile": "qinternalmimedata_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QKeyMapper", + "lineNumber": 28, + "object": true, + "qualifiedClassName": "QKeyMapper", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qkeymapper_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QKeySequence", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "StandardKey", + "values": [ + "UnknownKey", + "HelpContents", + "WhatsThis", + "Open", + "Close", + "Save", + "New", + "Delete", + "Cut", + "Copy", + "Paste", + "Undo", + "Redo", + "Back", + "Forward", + "Refresh", + "ZoomIn", + "ZoomOut", + "Print", + "AddTab", + "NextChild", + "PreviousChild", + "Find", + "FindNext", + "FindPrevious", + "Replace", + "SelectAll", + "Bold", + "Italic", + "Underline", + "MoveToNextChar", + "MoveToPreviousChar", + "MoveToNextWord", + "MoveToPreviousWord", + "MoveToNextLine", + "MoveToPreviousLine", + "MoveToNextPage", + "MoveToPreviousPage", + "MoveToStartOfLine", + "MoveToEndOfLine", + "MoveToStartOfBlock", + "MoveToEndOfBlock", + "MoveToStartOfDocument", + "MoveToEndOfDocument", + "SelectNextChar", + "SelectPreviousChar", + "SelectNextWord", + "SelectPreviousWord", + "SelectNextLine", + "SelectPreviousLine", + "SelectNextPage", + "SelectPreviousPage", + "SelectStartOfLine", + "SelectEndOfLine", + "SelectStartOfBlock", + "SelectEndOfBlock", + "SelectStartOfDocument", + "SelectEndOfDocument", + "DeleteStartOfWord", + "DeleteEndOfWord", + "DeleteEndOfLine", + "InsertParagraphSeparator", + "InsertLineSeparator", + "SaveAs", + "Preferences", + "Quit", + "FullScreen", + "Deselect", + "DeleteCompleteLine", + "Backspace", + "Cancel" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "SequenceFormat", + "values": [ + "NativeText", + "PortableText" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "SequenceMatch", + "values": [ + "NoMatch", + "PartialMatch", + "ExactMatch" + ] + } + ], + "gadget": true, + "lineNumber": 34, + "qualifiedClassName": "QKeySequence" + } + ], + "inputFile": "qkeysequence.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QLayoutPolicy", + "enums": [ + { + "alias": "PolicyFlag", + "isClass": false, + "isFlag": true, + "name": "Policy", + "values": [ + "GrowFlag", + "ExpandFlag", + "ShrinkFlag", + "IgnoreFlag" + ] + } + ], + "gadget": true, + "lineNumber": 31, + "qualifiedClassName": "QLayoutPolicy" + } + ], + "inputFile": "qlayoutpolicy_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QMovie", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "MovieState", + "values": [ + "NotRunning", + "Paused", + "Running" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "CacheMode", + "values": [ + "CacheNone", + "CacheAll" + ] + } + ], + "lineNumber": 27, + "object": true, + "properties": [ + { + "bindable": "bindableSpeed", + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "speed", + "read": "speed", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setSpeed" + }, + { + "bindable": "bindableCacheMode", + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "cacheMode", + "read": "cacheMode", + "required": false, + "scriptable": true, + "stored": true, + "type": "CacheMode", + "user": false, + "write": "setCacheMode" + } + ], + "qualifiedClassName": "QMovie", + "signals": [ + { + "access": "public", + "index": 0, + "name": "started", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "size", + "type": "QSize" + } + ], + "index": 1, + "name": "resized", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "rect", + "type": "QRect" + } + ], + "index": 2, + "name": "updated", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "state", + "type": "QMovie::MovieState" + } + ], + "index": 3, + "name": "stateChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "error", + "type": "QImageReader::ImageReaderError" + } + ], + "index": 4, + "name": "error", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "finished", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "frameNumber", + "type": "int" + } + ], + "index": 6, + "name": "frameChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "index": 7, + "name": "start", + "returnType": "void" + }, + { + "access": "public", + "index": 8, + "name": "jumpToNextFrame", + "returnType": "bool" + }, + { + "access": "public", + "arguments": [ + { + "name": "paused", + "type": "bool" + } + ], + "index": 9, + "name": "setPaused", + "returnType": "void" + }, + { + "access": "public", + "index": 10, + "name": "stop", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "percentSpeed", + "type": "int" + } + ], + "index": 11, + "name": "setSpeed", + "returnType": "void" + }, + { + "access": "private", + "index": 12, + "name": "_q_loadNextFrame", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qmovie.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QOffscreenSurface", + "lineNumber": 20, + "object": true, + "qualifiedClassName": "QOffscreenSurface", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "screen", + "type": "QScreen*" + } + ], + "index": 0, + "name": "screenChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "private", + "arguments": [ + { + "name": "screen", + "type": "QObject*" + } + ], + "index": 1, + "name": "screenDestroyed", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QSurface" + } + ] + } + ], + "inputFile": "qoffscreensurface.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QOpenGLContextGroup", + "lineNumber": 42, + "object": true, + "qualifiedClassName": "QOpenGLContextGroup", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "className": "QOpenGLContext", + "lineNumber": 66, + "object": true, + "qualifiedClassName": "QOpenGLContext", + "signals": [ + { + "access": "public", + "index": 0, + "name": "aboutToBeDestroyed", + "returnType": "void" + } + ], + "slots": [ + { + "access": "private", + "arguments": [ + { + "name": "object", + "type": "QObject*" + } + ], + "index": 1, + "name": "_q_screenDestroyed", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qopenglcontext.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QPaintDeviceWindow", + "lineNumber": 16, + "object": true, + "qualifiedClassName": "QPaintDeviceWindow", + "slots": [ + { + "access": "public", + "index": 0, + "name": "update", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWindow" + }, + { + "access": "public", + "name": "QPaintDevice" + } + ] + } + ], + "inputFile": "qpaintdevicewindow.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QPainter", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "RenderHint", + "values": [ + "Antialiasing", + "TextAntialiasing", + "SmoothPixmapTransform", + "VerticalSubpixelPositioning", + "LosslessImageRendering", + "NonCosmeticBrushPatterns" + ] + }, + { + "alias": "RenderHint", + "isClass": false, + "isFlag": true, + "name": "RenderHints", + "values": [ + "Antialiasing", + "TextAntialiasing", + "SmoothPixmapTransform", + "VerticalSubpixelPositioning", + "LosslessImageRendering", + "NonCosmeticBrushPatterns" + ] + } + ], + "gadget": true, + "lineNumber": 45, + "qualifiedClassName": "QPainter" + } + ], + "inputFile": "qpainter.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QPalette", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "ColorGroup", + "values": [ + "Active", + "Disabled", + "Inactive", + "NColorGroups", + "Current", + "All", + "Normal" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "ColorRole", + "values": [ + "WindowText", + "Button", + "Light", + "Midlight", + "Dark", + "Mid", + "Text", + "BrightText", + "ButtonText", + "Base", + "Window", + "Shadow", + "Highlight", + "HighlightedText", + "Link", + "LinkVisited", + "AlternateBase", + "NoRole", + "ToolTipBase", + "ToolTipText", + "PlaceholderText", + "Accent", + "NColorRoles" + ] + } + ], + "gadget": true, + "lineNumber": 18, + "qualifiedClassName": "QPalette" + } + ], + "inputFile": "qpalette.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QPdfWriter", + "enums": [ + { + "isClass": true, + "isFlag": false, + "name": "ColorModel", + "values": [ + "RGB", + "Grayscale", + "CMYK", + "Auto" + ] + } + ], + "lineNumber": 22, + "object": true, + "qualifiedClassName": "QPdfWriter", + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QPagedPaintDevice" + } + ] + } + ], + "inputFile": "qpdfwriter.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QPlatformBackingStoreRhiConfig", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "Api", + "values": [ + "OpenGL", + "Metal", + "Vulkan", + "D3D11", + "D3D12", + "Null" + ] + } + ], + "gadget": true, + "lineNumber": 40, + "qualifiedClassName": "QPlatformBackingStoreRhiConfig" + }, + { + "className": "QPlatformTextureList", + "lineNumber": 91, + "object": true, + "qualifiedClassName": "QPlatformTextureList", + "signals": [ + { + "access": "public", + "arguments": [ + { + "type": "bool" + } + ], + "index": 0, + "name": "locked", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qplatformbackingstore.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QPlatformDialogHelper", + "enums": [ + { + "alias": "StandardButton", + "isClass": false, + "isFlag": true, + "name": "StandardButtons", + "values": [ + "NoButton", + "Ok", + "Save", + "SaveAll", + "Open", + "Yes", + "YesToAll", + "No", + "NoToAll", + "Abort", + "Retry", + "Ignore", + "Close", + "Cancel", + "Discard", + "Help", + "Apply", + "Reset", + "RestoreDefaults", + "FirstButton", + "LastButton", + "LowestBit", + "HighestBit" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "ButtonRole", + "values": [ + "InvalidRole", + "AcceptRole", + "RejectRole", + "DestructiveRole", + "ActionRole", + "HelpRole", + "YesRole", + "NoRole", + "ResetRole", + "ApplyRole", + "NRoles", + "RoleMask", + "AlternateRole", + "Stretch", + "Reverse", + "EOL" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "ButtonLayout", + "values": [ + "UnknownLayout", + "WinLayout", + "MacLayout", + "KdeLayout", + "GnomeLayout", + "AndroidLayout" + ] + } + ], + "lineNumber": 44, + "object": true, + "qualifiedClassName": "QPlatformDialogHelper", + "signals": [ + { + "access": "public", + "index": 0, + "name": "accept", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "reject", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "className": "QColorDialogOptions", + "enums": [ + { + "alias": "ColorDialogOption", + "isClass": false, + "isFlag": true, + "name": "ColorDialogOptions", + "values": [ + "ShowAlphaChannel", + "NoButtons", + "DontUseNativeDialog", + "NoEyeDropperButton" + ] + } + ], + "gadget": true, + "lineNumber": 149, + "qualifiedClassName": "QColorDialogOptions" + }, + { + "className": "QPlatformColorDialogHelper", + "lineNumber": 191, + "object": true, + "qualifiedClassName": "QPlatformColorDialogHelper", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "color", + "type": "QColor" + } + ], + "index": 0, + "name": "currentColorChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "color", + "type": "QColor" + } + ], + "index": 1, + "name": "colorSelected", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QPlatformDialogHelper" + } + ] + }, + { + "className": "QFontDialogOptions", + "enums": [ + { + "alias": "FontDialogOption", + "isClass": false, + "isFlag": true, + "name": "FontDialogOptions", + "values": [ + "NoButtons", + "DontUseNativeDialog", + "ScalableFonts", + "NonScalableFonts", + "MonospacedFonts", + "ProportionalFonts" + ] + } + ], + "gadget": true, + "lineNumber": 209, + "qualifiedClassName": "QFontDialogOptions" + }, + { + "className": "QPlatformFontDialogHelper", + "lineNumber": 245, + "object": true, + "qualifiedClassName": "QPlatformFontDialogHelper", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "font", + "type": "QFont" + } + ], + "index": 0, + "name": "currentFontChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "font", + "type": "QFont" + } + ], + "index": 1, + "name": "fontSelected", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QPlatformDialogHelper" + } + ] + }, + { + "className": "QFileDialogOptions", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "ViewMode", + "values": [ + "Detail", + "List" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "FileMode", + "values": [ + "AnyFile", + "ExistingFile", + "Directory", + "ExistingFiles", + "DirectoryOnly" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "AcceptMode", + "values": [ + "AcceptOpen", + "AcceptSave" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "DialogLabel", + "values": [ + "LookIn", + "FileName", + "FileType", + "Accept", + "Reject", + "DialogLabelCount" + ] + }, + { + "alias": "FileDialogOption", + "isClass": false, + "isFlag": true, + "name": "FileDialogOptions", + "values": [ + "ShowDirsOnly", + "DontResolveSymlinks", + "DontConfirmOverwrite", + "DontUseNativeDialog", + "ReadOnly", + "HideNameFilterDetails", + "DontUseCustomDirectoryIcons" + ] + } + ], + "gadget": true, + "lineNumber": 263, + "qualifiedClassName": "QFileDialogOptions" + }, + { + "className": "QPlatformFileDialogHelper", + "lineNumber": 364, + "object": true, + "qualifiedClassName": "QPlatformFileDialogHelper", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "file", + "type": "QUrl" + } + ], + "index": 0, + "name": "fileSelected", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "files", + "type": "QList" + } + ], + "index": 1, + "name": "filesSelected", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "path", + "type": "QUrl" + } + ], + "index": 2, + "name": "currentChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "directory", + "type": "QUrl" + } + ], + "index": 3, + "name": "directoryEntered", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "filter", + "type": "QString" + } + ], + "index": 4, + "name": "filterSelected", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QPlatformDialogHelper" + } + ] + }, + { + "className": "QMessageDialogOptions", + "enums": [ + { + "alias": "Option", + "isClass": true, + "isFlag": true, + "name": "Options", + "values": [ + "DontUseNativeDialog" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "StandardIcon", + "values": [ + "NoIcon", + "Information", + "Warning", + "Critical", + "Question" + ] + } + ], + "gadget": true, + "lineNumber": 398, + "qualifiedClassName": "QMessageDialogOptions" + }, + { + "className": "QPlatformMessageDialogHelper", + "lineNumber": 482, + "object": true, + "qualifiedClassName": "QPlatformMessageDialogHelper", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "button", + "type": "QPlatformDialogHelper::StandardButton" + }, + { + "name": "role", + "type": "QPlatformDialogHelper::ButtonRole" + } + ], + "index": 0, + "name": "clicked", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "state", + "type": "Qt::CheckState" + } + ], + "index": 1, + "name": "checkBoxStateChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QPlatformDialogHelper" + } + ] + } + ], + "inputFile": "qplatformdialoghelper.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QPlatformGraphicsBuffer", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "AccessType", + "values": [ + "None", + "SWReadAccess", + "SWWriteAccess", + "TextureAccess", + "HWCompositor" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "Origin", + "values": [ + "OriginBottomLeft", + "OriginTopLeft" + ] + } + ], + "lineNumber": 26, + "object": true, + "qualifiedClassName": "QPlatformGraphicsBuffer", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "previousAccessTypes", + "type": "AccessTypes" + } + ], + "index": 0, + "name": "unlocked", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qplatformgraphicsbuffer.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QPlatformInputContext", + "lineNumber": 23, + "object": true, + "qualifiedClassName": "QPlatformInputContext", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qplatforminputcontext.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QPlatformInputContextPlugin", + "lineNumber": 29, + "object": true, + "qualifiedClassName": "QPlatformInputContextPlugin", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qplatforminputcontextplugin_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QPlatformIntegrationPlugin", + "lineNumber": 27, + "object": true, + "qualifiedClassName": "QPlatformIntegrationPlugin", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qplatformintegrationplugin.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QPlatformMenuItem", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "MenuRole", + "values": [ + "NoRole", + "TextHeuristicRole", + "ApplicationSpecificRole", + "AboutQtRole", + "AboutRole", + "PreferencesRole", + "QuitRole", + "CutRole", + "CopyRole", + "PasteRole", + "SelectAllRole", + "RoleCount" + ] + } + ], + "lineNumber": 28, + "object": true, + "qualifiedClassName": "QPlatformMenuItem", + "signals": [ + { + "access": "public", + "index": 0, + "name": "activated", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "hovered", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "className": "QPlatformMenu", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "MenuType", + "values": [ + "DefaultMenu", + "EditMenu" + ] + } + ], + "lineNumber": 71, + "object": true, + "qualifiedClassName": "QPlatformMenu", + "signals": [ + { + "access": "public", + "index": 0, + "name": "aboutToShow", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "aboutToHide", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "className": "QPlatformMenuBar", + "lineNumber": 120, + "object": true, + "qualifiedClassName": "QPlatformMenuBar", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qplatformmenu.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QPlatformNativeInterface", + "lineNumber": 30, + "object": true, + "qualifiedClassName": "QPlatformNativeInterface", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "window", + "type": "QPlatformWindow*" + }, + { + "name": "propertyName", + "type": "QString" + } + ], + "index": 0, + "name": "windowPropertyChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qplatformnativeinterface.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QPlatformServiceColorPicker", + "lineNumber": 24, + "object": true, + "qualifiedClassName": "QPlatformServiceColorPicker", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "color", + "type": "QColor" + } + ], + "index": 0, + "name": "colorPicked", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qplatformservices.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QPlatformSharedGraphicsCache", + "lineNumber": 22, + "object": true, + "qualifiedClassName": "QPlatformSharedGraphicsCache", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "cacheId", + "type": "QByteArray" + }, + { + "name": "itemIds", + "type": "QList" + } + ], + "index": 0, + "name": "itemsMissing", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "cacheId", + "type": "QByteArray" + }, + { + "name": "bufferId", + "type": "void*" + }, + { + "name": "itemIds", + "type": "QList" + }, + { + "name": "positionsInBuffer", + "type": "QList" + } + ], + "index": 1, + "name": "itemsAvailable", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "cacheId", + "type": "QByteArray" + }, + { + "name": "itemIds", + "type": "QList" + } + ], + "index": 2, + "name": "itemsInvalidated", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "cacheId", + "type": "QByteArray" + }, + { + "name": "bufferId", + "type": "void*" + }, + { + "name": "itemIds", + "type": "QList" + }, + { + "name": "positionsInBuffer", + "type": "QList" + } + ], + "index": 3, + "name": "itemsUpdated", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qplatformsharedgraphicscache.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QPlatformSystemTrayIcon", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "ActivationReason", + "values": [ + "Unknown", + "Context", + "DoubleClick", + "Trigger", + "MiddleClick" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "MessageIcon", + "values": [ + "NoIcon", + "Information", + "Warning", + "Critical" + ] + } + ], + "lineNumber": 21, + "object": true, + "qualifiedClassName": "QPlatformSystemTrayIcon", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "reason", + "type": "QPlatformSystemTrayIcon::ActivationReason" + } + ], + "index": 0, + "name": "activated", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "globalPos", + "type": "QPoint" + }, + { + "name": "screen", + "type": "const QPlatformScreen*" + } + ], + "index": 1, + "name": "contextMenuRequested", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "messageClicked", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qplatformsystemtrayicon.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QPlatformTheme", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "ThemeHint", + "values": [ + "CursorFlashTime", + "KeyboardInputInterval", + "MouseDoubleClickInterval", + "StartDragDistance", + "StartDragTime", + "KeyboardAutoRepeatRate", + "PasswordMaskDelay", + "StartDragVelocity", + "TextCursorWidth", + "DropShadow", + "MaximumScrollBarDragDistance", + "ToolButtonStyle", + "ToolBarIconSize", + "ItemViewActivateItemOnSingleClick", + "SystemIconThemeName", + "SystemIconFallbackThemeName", + "IconThemeSearchPaths", + "StyleNames", + "WindowAutoPlacement", + "DialogButtonBoxLayout", + "DialogButtonBoxButtonsHaveIcons", + "UseFullScreenForPopupMenu", + "KeyboardScheme", + "UiEffects", + "SpellCheckUnderlineStyle", + "TabFocusBehavior", + "IconPixmapSizes", + "PasswordMaskCharacter", + "DialogSnapToDefaultButton", + "ContextMenuOnMouseRelease", + "MousePressAndHoldInterval", + "MouseDoubleClickDistance", + "WheelScrollLines", + "TouchDoubleTapDistance", + "ShowShortcutsInContextMenus", + "IconFallbackSearchPaths", + "MouseQuickSelectionThreshold", + "InteractiveResizeAcrossScreens", + "ShowDirectoriesFirst", + "PreselectFirstFileInDirectory", + "ButtonPressKeys", + "SetFocusOnTouchRelease", + "FlickStartDistance", + "FlickMaximumVelocity", + "FlickDeceleration", + "MenuBarFocusOnAltPressRelease", + "MouseCursorTheme", + "MouseCursorSize", + "UnderlineShortcut", + "ShowIconsInMenus", + "PreferFileIconFromTheme" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "DialogType", + "values": [ + "FileDialog", + "ColorDialog", + "FontDialog", + "MessageDialog" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "Palette", + "values": [ + "SystemPalette", + "ToolTipPalette", + "ToolButtonPalette", + "ButtonPalette", + "CheckBoxPalette", + "RadioButtonPalette", + "HeaderPalette", + "ComboBoxPalette", + "ItemViewPalette", + "MessageBoxLabelPelette", + "MessageBoxLabelPalette", + "TabBarPalette", + "LabelPalette", + "GroupBoxPalette", + "MenuPalette", + "MenuBarPalette", + "TextEditPalette", + "TextLineEditPalette", + "NPalettes" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "Font", + "values": [ + "SystemFont", + "MenuFont", + "MenuBarFont", + "MenuItemFont", + "MessageBoxFont", + "LabelFont", + "TipLabelFont", + "StatusBarFont", + "TitleBarFont", + "MdiSubWindowTitleFont", + "DockWidgetTitleFont", + "PushButtonFont", + "CheckBoxFont", + "RadioButtonFont", + "ToolButtonFont", + "ItemViewFont", + "ListViewFont", + "HeaderViewFont", + "ListBoxFont", + "ComboMenuItemFont", + "ComboLineEditFont", + "SmallFont", + "MiniFont", + "FixedFont", + "GroupBoxTitleFont", + "TabButtonFont", + "EditorFont", + "NFonts" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "StandardPixmap", + "values": [ + "TitleBarMenuButton", + "TitleBarMinButton", + "TitleBarMaxButton", + "TitleBarCloseButton", + "TitleBarNormalButton", + "TitleBarShadeButton", + "TitleBarUnshadeButton", + "TitleBarContextHelpButton", + "DockWidgetCloseButton", + "MessageBoxInformation", + "MessageBoxWarning", + "MessageBoxCritical", + "MessageBoxQuestion", + "DesktopIcon", + "TrashIcon", + "ComputerIcon", + "DriveFDIcon", + "DriveHDIcon", + "DriveCDIcon", + "DriveDVDIcon", + "DriveNetIcon", + "DirOpenIcon", + "DirClosedIcon", + "DirLinkIcon", + "DirLinkOpenIcon", + "FileIcon", + "FileLinkIcon", + "ToolBarHorizontalExtensionButton", + "ToolBarVerticalExtensionButton", + "FileDialogStart", + "FileDialogEnd", + "FileDialogToParent", + "FileDialogNewFolder", + "FileDialogDetailedView", + "FileDialogInfoView", + "FileDialogContentsView", + "FileDialogListView", + "FileDialogBack", + "DirIcon", + "DialogOkButton", + "DialogCancelButton", + "DialogHelpButton", + "DialogOpenButton", + "DialogSaveButton", + "DialogCloseButton", + "DialogApplyButton", + "DialogResetButton", + "DialogDiscardButton", + "DialogYesButton", + "DialogNoButton", + "ArrowUp", + "ArrowDown", + "ArrowLeft", + "ArrowRight", + "ArrowBack", + "ArrowForward", + "DirHomeIcon", + "CommandLink", + "VistaShield", + "BrowserReload", + "BrowserStop", + "MediaPlay", + "MediaStop", + "MediaPause", + "MediaSkipForward", + "MediaSkipBackward", + "MediaSeekForward", + "MediaSeekBackward", + "MediaVolume", + "MediaVolumeMuted", + "LineEditClearButton", + "DialogYesToAllButton", + "DialogNoToAllButton", + "DialogSaveAllButton", + "DialogAbortButton", + "DialogRetryButton", + "DialogIgnoreButton", + "RestoreDefaultsButton", + "TabCloseButton", + "NStandardPixmap", + "CustomBase" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "KeyboardSchemes", + "values": [ + "WindowsKeyboardScheme", + "MacKeyboardScheme", + "X11KeyboardScheme", + "KdeKeyboardScheme", + "GnomeKeyboardScheme", + "CdeKeyboardScheme" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "UiEffect", + "values": [ + "GeneralUiEffect", + "AnimateMenuUiEffect", + "FadeMenuUiEffect", + "AnimateComboUiEffect", + "AnimateTooltipUiEffect", + "FadeTooltipUiEffect", + "AnimateToolBoxUiEffect", + "HoverEffect" + ] + } + ], + "gadget": true, + "lineNumber": 42, + "qualifiedClassName": "QPlatformTheme" + } + ], + "inputFile": "qplatformtheme.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QPlatformThemePlugin", + "lineNumber": 26, + "object": true, + "qualifiedClassName": "QPlatformThemePlugin", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qplatformthemeplugin.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QPointingDeviceUniqueId", + "gadget": true, + "lineNumber": 20, + "properties": [ + { + "constant": true, + "designable": true, + "final": false, + "index": 0, + "name": "numericId", + "read": "numericId", + "required": false, + "scriptable": true, + "stored": true, + "type": "qint64", + "user": false + } + ], + "qualifiedClassName": "QPointingDeviceUniqueId" + }, + { + "className": "QPointingDevice", + "enums": [ + { + "alias": "PointerType", + "isClass": true, + "isFlag": true, + "name": "PointerTypes", + "values": [ + "Unknown", + "Generic", + "Finger", + "Pen", + "Eraser", + "Cursor", + "AllPointerTypes" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "GrabTransition", + "values": [ + "GrabPassive", + "UngrabPassive", + "CancelGrabPassive", + "OverrideGrabPassive", + "GrabExclusive", + "UngrabExclusive", + "CancelGrabExclusive" + ] + } + ], + "lineNumber": 50, + "object": true, + "properties": [ + { + "constant": true, + "designable": true, + "final": false, + "index": 0, + "name": "pointerType", + "read": "pointerType", + "required": false, + "scriptable": true, + "stored": true, + "type": "PointerType", + "user": false + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 1, + "name": "maximumPoints", + "read": "maximumPoints", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 2, + "name": "buttonCount", + "read": "buttonCount", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 3, + "name": "uniqueId", + "read": "uniqueId", + "required": false, + "scriptable": true, + "stored": true, + "type": "QPointingDeviceUniqueId", + "user": false + } + ], + "qualifiedClassName": "QPointingDevice", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "grabber", + "type": "QObject*" + }, + { + "name": "transition", + "type": "GrabTransition" + }, + { + "name": "event", + "type": "const QPointerEvent*" + }, + { + "name": "point", + "type": "QEventPoint" + } + ], + "index": 0, + "name": "grabChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QInputDevice" + } + ] + } + ], + "inputFile": "qpointingdevice.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QRasterWindow", + "lineNumber": 14, + "object": true, + "qualifiedClassName": "QRasterWindow", + "superClasses": [ + { + "access": "public", + "name": "QPaintDeviceWindow" + } + ] + } + ], + "inputFile": "qrasterwindow.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QScreen", + "lineNumber": 31, + "object": true, + "properties": [ + { + "constant": true, + "designable": true, + "final": false, + "index": 0, + "name": "name", + "read": "name", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 1, + "name": "manufacturer", + "read": "manufacturer", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 2, + "name": "model", + "read": "model", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 3, + "name": "serialNumber", + "read": "serialNumber", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 4, + "name": "depth", + "read": "depth", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "size", + "notify": "geometryChanged", + "read": "size", + "required": false, + "scriptable": true, + "stored": true, + "type": "QSize", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "availableSize", + "notify": "availableGeometryChanged", + "read": "availableSize", + "required": false, + "scriptable": true, + "stored": true, + "type": "QSize", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 7, + "name": "virtualSize", + "notify": "virtualGeometryChanged", + "read": "virtualSize", + "required": false, + "scriptable": true, + "stored": true, + "type": "QSize", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 8, + "name": "availableVirtualSize", + "notify": "virtualGeometryChanged", + "read": "availableVirtualSize", + "required": false, + "scriptable": true, + "stored": true, + "type": "QSize", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 9, + "name": "geometry", + "notify": "geometryChanged", + "read": "geometry", + "required": false, + "scriptable": true, + "stored": true, + "type": "QRect", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 10, + "name": "availableGeometry", + "notify": "availableGeometryChanged", + "read": "availableGeometry", + "required": false, + "scriptable": true, + "stored": true, + "type": "QRect", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 11, + "name": "virtualGeometry", + "notify": "virtualGeometryChanged", + "read": "virtualGeometry", + "required": false, + "scriptable": true, + "stored": true, + "type": "QRect", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 12, + "name": "availableVirtualGeometry", + "notify": "virtualGeometryChanged", + "read": "availableVirtualGeometry", + "required": false, + "scriptable": true, + "stored": true, + "type": "QRect", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 13, + "name": "physicalSize", + "notify": "physicalSizeChanged", + "read": "physicalSize", + "required": false, + "scriptable": true, + "stored": true, + "type": "QSizeF", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 14, + "name": "physicalDotsPerInchX", + "notify": "physicalDotsPerInchChanged", + "read": "physicalDotsPerInchX", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 15, + "name": "physicalDotsPerInchY", + "notify": "physicalDotsPerInchChanged", + "read": "physicalDotsPerInchY", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 16, + "name": "physicalDotsPerInch", + "notify": "physicalDotsPerInchChanged", + "read": "physicalDotsPerInch", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 17, + "name": "logicalDotsPerInchX", + "notify": "logicalDotsPerInchChanged", + "read": "logicalDotsPerInchX", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 18, + "name": "logicalDotsPerInchY", + "notify": "logicalDotsPerInchChanged", + "read": "logicalDotsPerInchY", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 19, + "name": "logicalDotsPerInch", + "notify": "logicalDotsPerInchChanged", + "read": "logicalDotsPerInch", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 20, + "name": "devicePixelRatio", + "notify": "physicalDotsPerInchChanged", + "read": "devicePixelRatio", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 21, + "name": "primaryOrientation", + "notify": "primaryOrientationChanged", + "read": "primaryOrientation", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::ScreenOrientation", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 22, + "name": "orientation", + "notify": "orientationChanged", + "read": "orientation", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::ScreenOrientation", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 23, + "name": "nativeOrientation", + "read": "nativeOrientation", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::ScreenOrientation", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 24, + "name": "refreshRate", + "notify": "refreshRateChanged", + "read": "refreshRate", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + } + ], + "qualifiedClassName": "QScreen", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "geometry", + "type": "QRect" + } + ], + "index": 0, + "name": "geometryChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "geometry", + "type": "QRect" + } + ], + "index": 1, + "name": "availableGeometryChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "size", + "type": "QSizeF" + } + ], + "index": 2, + "name": "physicalSizeChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "dpi", + "type": "qreal" + } + ], + "index": 3, + "name": "physicalDotsPerInchChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "dpi", + "type": "qreal" + } + ], + "index": 4, + "name": "logicalDotsPerInchChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "rect", + "type": "QRect" + } + ], + "index": 5, + "name": "virtualGeometryChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "orientation", + "type": "Qt::ScreenOrientation" + } + ], + "index": 6, + "name": "primaryOrientationChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "orientation", + "type": "Qt::ScreenOrientation" + } + ], + "index": 7, + "name": "orientationChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "refreshRate", + "type": "qreal" + } + ], + "index": 8, + "name": "refreshRateChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qscreen.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QSessionManager", + "lineNumber": 22, + "object": true, + "qualifiedClassName": "QSessionManager", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qsessionmanager.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QShapedPixmapWindow", + "lineNumber": 26, + "object": true, + "qualifiedClassName": "QShapedPixmapWindow", + "superClasses": [ + { + "access": "public", + "name": "QRasterWindow" + } + ] + } + ], + "inputFile": "qshapedpixmapdndwindow_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QShortcut", + "lineNumber": 18, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "key", + "read": "key", + "required": false, + "scriptable": true, + "stored": true, + "type": "QKeySequence", + "user": false, + "write": "setKey" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "enabled", + "read": "isEnabled", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setEnabled" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "autoRepeat", + "read": "autoRepeat", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setAutoRepeat" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "context", + "read": "context", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::ShortcutContext", + "user": false, + "write": "setContext" + } + ], + "qualifiedClassName": "QShortcut", + "signals": [ + { + "access": "public", + "index": 0, + "name": "activated", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "activatedAmbiguously", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qshortcut.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QStandardItemModel", + "lineNumber": 278, + "object": true, + "properties": [ + { + "bindable": "bindableSortRole", + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "sortRole", + "read": "sortRole", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setSortRole" + } + ], + "qualifiedClassName": "QStandardItemModel", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "item", + "type": "QStandardItem*" + } + ], + "index": 0, + "name": "itemChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "private", + "arguments": [ + { + "name": "topLeft", + "type": "QModelIndex" + }, + { + "name": "bottomRight", + "type": "QModelIndex" + } + ], + "index": 1, + "name": "_q_emitItemChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QAbstractItemModel" + } + ] + } + ], + "inputFile": "qstandarditemmodel.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QStyleHints", + "lineNumber": 16, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "cursorFlashTime", + "notify": "cursorFlashTimeChanged", + "read": "cursorFlashTime", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 1, + "name": "fontSmoothingGamma", + "read": "fontSmoothingGamma", + "required": false, + "scriptable": true, + "stored": false, + "type": "qreal", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 2, + "name": "keyboardAutoRepeatRate", + "read": "keyboardAutoRepeatRate", + "required": false, + "scriptable": true, + "stored": false, + "type": "int", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 3, + "name": "keyboardAutoRepeatRateF", + "read": "keyboardAutoRepeatRateF", + "required": false, + "scriptable": true, + "stored": false, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "keyboardInputInterval", + "notify": "keyboardInputIntervalChanged", + "read": "keyboardInputInterval", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "mouseDoubleClickInterval", + "notify": "mouseDoubleClickIntervalChanged", + "read": "mouseDoubleClickInterval", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 6, + "name": "mousePressAndHoldInterval", + "notify": "mousePressAndHoldIntervalChanged", + "read": "mousePressAndHoldInterval", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 7, + "name": "passwordMaskCharacter", + "read": "passwordMaskCharacter", + "required": false, + "scriptable": true, + "stored": false, + "type": "QChar", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 8, + "name": "passwordMaskDelay", + "read": "passwordMaskDelay", + "required": false, + "scriptable": true, + "stored": false, + "type": "int", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 9, + "name": "setFocusOnTouchRelease", + "read": "setFocusOnTouchRelease", + "required": false, + "scriptable": true, + "stored": false, + "type": "bool", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 10, + "name": "showIsFullScreen", + "read": "showIsFullScreen", + "required": false, + "scriptable": true, + "stored": false, + "type": "bool", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 11, + "name": "showIsMaximized", + "read": "showIsMaximized", + "required": false, + "scriptable": true, + "stored": false, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 12, + "name": "showShortcutsInContextMenus", + "notify": "showShortcutsInContextMenusChanged", + "read": "showShortcutsInContextMenus", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setShowShortcutsInContextMenus" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 13, + "name": "contextMenuTrigger", + "notify": "contextMenuTriggerChanged", + "read": "contextMenuTrigger", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::ContextMenuTrigger", + "user": false, + "write": "setContextMenuTrigger" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 14, + "name": "startDragDistance", + "notify": "startDragDistanceChanged", + "read": "startDragDistance", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 15, + "name": "startDragTime", + "notify": "startDragTimeChanged", + "read": "startDragTime", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 16, + "name": "startDragVelocity", + "read": "startDragVelocity", + "required": false, + "scriptable": true, + "stored": false, + "type": "int", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 17, + "name": "useRtlExtensions", + "read": "useRtlExtensions", + "required": false, + "scriptable": true, + "stored": false, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 18, + "name": "tabFocusBehavior", + "notify": "tabFocusBehaviorChanged", + "read": "tabFocusBehavior", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::TabFocusBehavior", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 19, + "name": "singleClickActivation", + "read": "singleClickActivation", + "required": false, + "scriptable": true, + "stored": false, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 20, + "name": "useHoverEffects", + "notify": "useHoverEffectsChanged", + "read": "useHoverEffects", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setUseHoverEffects" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 21, + "name": "wheelScrollLines", + "notify": "wheelScrollLinesChanged", + "read": "wheelScrollLines", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 22, + "name": "mouseQuickSelectionThreshold", + "notify": "mouseQuickSelectionThresholdChanged", + "read": "mouseQuickSelectionThreshold", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setMouseQuickSelectionThreshold" + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 23, + "name": "mouseDoubleClickDistance", + "read": "mouseDoubleClickDistance", + "required": false, + "scriptable": true, + "stored": false, + "type": "int", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 24, + "name": "touchDoubleTapDistance", + "read": "touchDoubleTapDistance", + "required": false, + "scriptable": true, + "stored": false, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 25, + "name": "colorScheme", + "notify": "colorSchemeChanged", + "read": "colorScheme", + "required": false, + "reset": "unsetColorScheme", + "scriptable": true, + "stored": true, + "type": "Qt::ColorScheme", + "user": false, + "write": "setColorScheme" + } + ], + "qualifiedClassName": "QStyleHints", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "cursorFlashTime", + "type": "int" + } + ], + "index": 0, + "name": "cursorFlashTimeChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "keyboardInputInterval", + "type": "int" + } + ], + "index": 1, + "name": "keyboardInputIntervalChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "mouseDoubleClickInterval", + "type": "int" + } + ], + "index": 2, + "name": "mouseDoubleClickIntervalChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "mousePressAndHoldInterval", + "type": "int" + } + ], + "index": 3, + "name": "mousePressAndHoldIntervalChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "startDragDistance", + "type": "int" + } + ], + "index": 4, + "name": "startDragDistanceChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "startDragTime", + "type": "int" + } + ], + "index": 5, + "name": "startDragTimeChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "tabFocusBehavior", + "type": "Qt::TabFocusBehavior" + } + ], + "index": 6, + "name": "tabFocusBehaviorChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "useHoverEffects", + "type": "bool" + } + ], + "index": 7, + "name": "useHoverEffectsChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "bool" + } + ], + "index": 8, + "name": "showShortcutsInContextMenusChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "contextMenuTrigger", + "type": "Qt::ContextMenuTrigger" + } + ], + "index": 9, + "name": "contextMenuTriggerChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "scrollLines", + "type": "int" + } + ], + "index": 10, + "name": "wheelScrollLinesChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "threshold", + "type": "int" + } + ], + "index": 11, + "name": "mouseQuickSelectionThresholdChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "colorScheme", + "type": "Qt::ColorScheme" + } + ], + "index": 12, + "name": "colorSchemeChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qstylehints.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QSurface", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "SurfaceClass", + "values": [ + "Window", + "Offscreen" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "SurfaceType", + "values": [ + "RasterSurface", + "OpenGLSurface", + "RasterGLSurface", + "OpenVGSurface", + "VulkanSurface", + "MetalSurface", + "Direct3DSurface" + ] + } + ], + "gadget": true, + "lineNumber": 20, + "qualifiedClassName": "QSurface" + } + ], + "inputFile": "qsurface.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QSurfaceFormat", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "FormatOption", + "values": [ + "StereoBuffers", + "DebugContext", + "DeprecatedFunctions", + "ResetNotification", + "ProtectedContent" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "SwapBehavior", + "values": [ + "DefaultSwapBehavior", + "SingleBuffer", + "DoubleBuffer", + "TripleBuffer" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "RenderableType", + "values": [ + "DefaultRenderableType", + "OpenGL", + "OpenGLES", + "OpenVG" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "OpenGLContextProfile", + "values": [ + "NoProfile", + "CoreProfile", + "CompatibilityProfile" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "ColorSpace", + "values": [ + "DefaultColorSpace", + "sRGBColorSpace" + ] + } + ], + "gadget": true, + "lineNumber": 16, + "qualifiedClassName": "QSurfaceFormat" + } + ], + "inputFile": "qsurfaceformat.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QSyntaxHighlighter", + "lineNumber": 24, + "object": true, + "qualifiedClassName": "QSyntaxHighlighter", + "slots": [ + { + "access": "public", + "index": 0, + "name": "rehighlight", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "block", + "type": "QTextBlock" + } + ], + "index": 1, + "name": "rehighlightBlock", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "from", + "type": "int" + }, + { + "name": "charsRemoved", + "type": "int" + }, + { + "name": "charsAdded", + "type": "int" + } + ], + "index": 2, + "name": "_q_reformatBlocks", + "returnType": "void" + }, + { + "access": "private", + "index": 3, + "name": "_q_delayedRehighlight", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qsyntaxhighlighter.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QTextDocument", + "enums": [ + { + "alias": "MarkdownFeature", + "isClass": false, + "isFlag": true, + "name": "MarkdownFeatures", + "values": [ + "MarkdownNoHTML", + "MarkdownDialectCommonMark", + "MarkdownDialectGitHub" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "ResourceType", + "values": [ + "UnknownResource", + "HtmlResource", + "ImageResource", + "StyleSheetResource", + "MarkdownResource", + "UserResource" + ] + } + ], + "lineNumber": 55, + "methods": [ + { + "access": "protected", + "arguments": [ + { + "name": "type", + "type": "int" + }, + { + "name": "name", + "type": "QUrl" + } + ], + "index": 15, + "name": "loadResource", + "returnType": "QVariant" + } + ], + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "undoRedoEnabled", + "read": "isUndoRedoEnabled", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setUndoRedoEnabled" + }, + { + "constant": false, + "designable": false, + "final": false, + "index": 1, + "name": "modified", + "read": "isModified", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setModified" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "pageSize", + "read": "pageSize", + "required": false, + "scriptable": true, + "stored": true, + "type": "QSizeF", + "user": false, + "write": "setPageSize" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "defaultFont", + "read": "defaultFont", + "required": false, + "scriptable": true, + "stored": true, + "type": "QFont", + "user": false, + "write": "setDefaultFont" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "useDesignMetrics", + "read": "useDesignMetrics", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setUseDesignMetrics" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "layoutEnabled", + "read": "isLayoutEnabled", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setLayoutEnabled" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "size", + "read": "size", + "required": false, + "scriptable": true, + "stored": true, + "type": "QSizeF", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 7, + "name": "textWidth", + "read": "textWidth", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setTextWidth" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 8, + "name": "blockCount", + "read": "blockCount", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 9, + "name": "indentWidth", + "read": "indentWidth", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setIndentWidth" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 10, + "name": "defaultStyleSheet", + "read": "defaultStyleSheet", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setDefaultStyleSheet" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 11, + "name": "maximumBlockCount", + "read": "maximumBlockCount", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setMaximumBlockCount" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 12, + "name": "documentMargin", + "read": "documentMargin", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setDocumentMargin" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 13, + "name": "baseUrl", + "notify": "baseUrlChanged", + "read": "baseUrl", + "required": false, + "scriptable": true, + "stored": true, + "type": "QUrl", + "user": false, + "write": "setBaseUrl" + } + ], + "qualifiedClassName": "QTextDocument", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "from", + "type": "int" + }, + { + "name": "charsRemoved", + "type": "int" + }, + { + "name": "charsAdded", + "type": "int" + } + ], + "index": 0, + "name": "contentsChange", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "contentsChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "bool" + } + ], + "index": 2, + "name": "undoAvailable", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "bool" + } + ], + "index": 3, + "name": "redoAvailable", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "undoCommandAdded", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "m", + "type": "bool" + } + ], + "index": 5, + "name": "modificationChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "cursor", + "type": "QTextCursor" + } + ], + "index": 6, + "name": "cursorPositionChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "newBlockCount", + "type": "int" + } + ], + "index": 7, + "name": "blockCountChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "url", + "type": "QUrl" + } + ], + "index": 8, + "name": "baseUrlChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 9, + "name": "documentLayoutChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "index": 10, + "name": "undo", + "returnType": "void" + }, + { + "access": "public", + "index": 11, + "name": "redo", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QAbstractUndoItem*" + } + ], + "index": 12, + "name": "appendUndoItem", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "m", + "type": "bool" + } + ], + "index": 13, + "name": "setModified", + "returnType": "void" + }, + { + "access": "public", + "index": 14, + "isCloned": true, + "name": "setModified", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qtextdocument.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QTextDocumentLayout", + "lineNumber": 29, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "cursorWidth", + "read": "cursorWidth", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setCursorWidth" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "idealWidth", + "read": "idealWidth", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "contentHasAlignment", + "read": "contentHasAlignment", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + } + ], + "qualifiedClassName": "QTextDocumentLayout", + "superClasses": [ + { + "access": "public", + "name": "QAbstractTextDocumentLayout" + } + ] + } + ], + "inputFile": "qtextdocumentlayout_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QTextFormat", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "FormatType", + "values": [ + "InvalidFormat", + "BlockFormat", + "CharFormat", + "ListFormat", + "FrameFormat", + "UserFormat" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "Property", + "values": [ + "ObjectIndex", + "CssFloat", + "LayoutDirection", + "OutlinePen", + "BackgroundBrush", + "ForegroundBrush", + "BackgroundImageUrl", + "BlockAlignment", + "BlockTopMargin", + "BlockBottomMargin", + "BlockLeftMargin", + "BlockRightMargin", + "TextIndent", + "TabPositions", + "BlockIndent", + "LineHeight", + "LineHeightType", + "BlockNonBreakableLines", + "BlockTrailingHorizontalRulerWidth", + "HeadingLevel", + "BlockQuoteLevel", + "BlockCodeLanguage", + "BlockCodeFence", + "BlockMarker", + "FirstFontProperty", + "FontCapitalization", + "FontLetterSpacing", + "FontWordSpacing", + "FontStyleHint", + "FontStyleStrategy", + "FontKerning", + "FontHintingPreference", + "FontFamilies", + "FontStyleName", + "FontLetterSpacingType", + "FontStretch", + "FontFamily", + "FontPointSize", + "FontSizeAdjustment", + "FontSizeIncrement", + "FontWeight", + "FontItalic", + "FontUnderline", + "FontOverline", + "FontStrikeOut", + "FontFixedPitch", + "FontPixelSize", + "LastFontProperty", + "TextUnderlineColor", + "TextVerticalAlignment", + "TextOutline", + "TextUnderlineStyle", + "TextToolTip", + "TextSuperScriptBaseline", + "TextSubScriptBaseline", + "TextBaselineOffset", + "IsAnchor", + "AnchorHref", + "AnchorName", + "OldFontLetterSpacingType", + "OldFontStretch", + "OldTextUnderlineColor", + "OldFontFamily", + "ObjectType", + "ListStyle", + "ListIndent", + "ListNumberPrefix", + "ListNumberSuffix", + "ListStart", + "FrameBorder", + "FrameMargin", + "FramePadding", + "FrameWidth", + "FrameHeight", + "FrameTopMargin", + "FrameBottomMargin", + "FrameLeftMargin", + "FrameRightMargin", + "FrameBorderBrush", + "FrameBorderStyle", + "TableColumns", + "TableColumnWidthConstraints", + "TableCellSpacing", + "TableCellPadding", + "TableHeaderRowCount", + "TableBorderCollapse", + "TableCellRowSpan", + "TableCellColumnSpan", + "TableCellTopPadding", + "TableCellBottomPadding", + "TableCellLeftPadding", + "TableCellRightPadding", + "TableCellTopBorder", + "TableCellBottomBorder", + "TableCellLeftBorder", + "TableCellRightBorder", + "TableCellTopBorderStyle", + "TableCellBottomBorderStyle", + "TableCellLeftBorderStyle", + "TableCellRightBorderStyle", + "TableCellTopBorderBrush", + "TableCellBottomBorderBrush", + "TableCellLeftBorderBrush", + "TableCellRightBorderBrush", + "ImageName", + "ImageTitle", + "ImageAltText", + "ImageWidth", + "ImageHeight", + "ImageQuality", + "ImageMaxWidth", + "FullWidthSelection", + "PageBreakPolicy", + "UserProperty" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "ObjectTypes", + "values": [ + "NoObject", + "ImageObject", + "TableObject", + "TableCellObject", + "UserObject" + ] + } + ], + "gadget": true, + "lineNumber": 89, + "qualifiedClassName": "QTextFormat" + } + ], + "inputFile": "qtextformat.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QTextImageHandler", + "interfaces": [ + [ + { + "className": "QTextObjectInterface", + "id": "\"org.qt-project.Qt.QTextObjectInterface\"" + } + ] + ], + "lineNumber": 26, + "object": true, + "qualifiedClassName": "QTextImageHandler", + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QTextObjectInterface" + } + ] + } + ], + "inputFile": "qtextimagehandler_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QTextList", + "lineNumber": 17, + "object": true, + "qualifiedClassName": "QTextList", + "superClasses": [ + { + "access": "public", + "name": "QTextBlockGroup" + } + ] + } + ], + "inputFile": "qtextlist.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QTextObject", + "lineNumber": 24, + "object": true, + "qualifiedClassName": "QTextObject", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "className": "QTextBlockGroup", + "lineNumber": 52, + "object": true, + "qualifiedClassName": "QTextBlockGroup", + "superClasses": [ + { + "access": "public", + "name": "QTextObject" + } + ] + }, + { + "className": "QTextFrame", + "lineNumber": 80, + "object": true, + "qualifiedClassName": "QTextFrame", + "superClasses": [ + { + "access": "public", + "name": "QTextObject" + } + ] + } + ], + "inputFile": "qtextobject.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QTextTable", + "lineNumber": 62, + "object": true, + "qualifiedClassName": "QTextTable", + "superClasses": [ + { + "access": "public", + "name": "QTextFrame" + } + ] + } + ], + "inputFile": "qtexttable.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QUndoGroup", + "lineNumber": 19, + "object": true, + "qualifiedClassName": "QUndoGroup", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "stack", + "type": "QUndoStack*" + } + ], + "index": 0, + "name": "activeStackChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "idx", + "type": "int" + } + ], + "index": 1, + "name": "indexChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "clean", + "type": "bool" + } + ], + "index": 2, + "name": "cleanChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "canUndo", + "type": "bool" + } + ], + "index": 3, + "name": "canUndoChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "canRedo", + "type": "bool" + } + ], + "index": 4, + "name": "canRedoChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "undoText", + "type": "QString" + } + ], + "index": 5, + "name": "undoTextChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "redoText", + "type": "QString" + } + ], + "index": 6, + "name": "redoTextChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "index": 7, + "name": "undo", + "returnType": "void" + }, + { + "access": "public", + "index": 8, + "name": "redo", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "stack", + "type": "QUndoStack*" + } + ], + "index": 9, + "name": "setActiveStack", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qundogroup.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QUndoStack", + "lineNumber": 51, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "active", + "read": "isActive", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setActive" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "undoLimit", + "read": "undoLimit", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setUndoLimit" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "canUndo", + "notify": "canUndoChanged", + "read": "canUndo", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "canRedo", + "notify": "canRedoChanged", + "read": "canRedo", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "undoText", + "notify": "undoTextChanged", + "read": "undoText", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "redoText", + "notify": "redoTextChanged", + "read": "redoText", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "clean", + "notify": "cleanChanged", + "read": "isClean", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + } + ], + "qualifiedClassName": "QUndoStack", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "idx", + "type": "int" + } + ], + "index": 0, + "name": "indexChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "clean", + "type": "bool" + } + ], + "index": 1, + "name": "cleanChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "canUndo", + "type": "bool" + } + ], + "index": 2, + "name": "canUndoChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "canRedo", + "type": "bool" + } + ], + "index": 3, + "name": "canRedoChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "undoText", + "type": "QString" + } + ], + "index": 4, + "name": "undoTextChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "redoText", + "type": "QString" + } + ], + "index": 5, + "name": "redoTextChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "index": 6, + "name": "setClean", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "resetClean", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "idx", + "type": "int" + } + ], + "index": 8, + "name": "setIndex", + "returnType": "void" + }, + { + "access": "public", + "index": 9, + "name": "undo", + "returnType": "void" + }, + { + "access": "public", + "index": 10, + "name": "redo", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "active", + "type": "bool" + } + ], + "index": 11, + "name": "setActive", + "returnType": "void" + }, + { + "access": "public", + "index": 12, + "isCloned": true, + "name": "setActive", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qundostack.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QValidator", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "State", + "values": [ + "Invalid", + "Intermediate", + "Acceptable" + ] + } + ], + "lineNumber": 23, + "object": true, + "qualifiedClassName": "QValidator", + "signals": [ + { + "access": "public", + "index": 0, + "name": "changed", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "className": "QIntValidator", + "lineNumber": 55, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "bottom", + "notify": "bottomChanged", + "read": "bottom", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setBottom" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "top", + "notify": "topChanged", + "read": "top", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setTop" + } + ], + "qualifiedClassName": "QIntValidator", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "bottom", + "type": "int" + } + ], + "index": 0, + "name": "bottomChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "top", + "type": "int" + } + ], + "index": 1, + "name": "topChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QValidator" + } + ] + }, + { + "className": "QDoubleValidator", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "Notation", + "values": [ + "StandardNotation", + "ScientificNotation" + ] + } + ], + "lineNumber": 88, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "bottom", + "notify": "bottomChanged", + "read": "bottom", + "required": false, + "scriptable": true, + "stored": true, + "type": "double", + "user": false, + "write": "setBottom" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "top", + "notify": "topChanged", + "read": "top", + "required": false, + "scriptable": true, + "stored": true, + "type": "double", + "user": false, + "write": "setTop" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "decimals", + "notify": "decimalsChanged", + "read": "decimals", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setDecimals" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "notation", + "notify": "notationChanged", + "read": "notation", + "required": false, + "scriptable": true, + "stored": true, + "type": "Notation", + "user": false, + "write": "setNotation" + } + ], + "qualifiedClassName": "QDoubleValidator", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "bottom", + "type": "double" + } + ], + "index": 0, + "name": "bottomChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "top", + "type": "double" + } + ], + "index": 1, + "name": "topChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "decimals", + "type": "int" + } + ], + "index": 2, + "name": "decimalsChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "notation", + "type": "QDoubleValidator::Notation" + } + ], + "index": 3, + "name": "notationChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QValidator" + } + ] + }, + { + "className": "QRegularExpressionValidator", + "lineNumber": 140, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "regularExpression", + "notify": "regularExpressionChanged", + "read": "regularExpression", + "required": false, + "scriptable": true, + "stored": true, + "type": "QRegularExpression", + "user": false, + "write": "setRegularExpression" + } + ], + "qualifiedClassName": "QRegularExpressionValidator", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "re", + "type": "QRegularExpression" + } + ], + "index": 0, + "name": "regularExpressionChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "re", + "type": "QRegularExpression" + } + ], + "index": 1, + "name": "setRegularExpression", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QValidator" + } + ] + } + ], + "inputFile": "qvalidator.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QVulkanWindow", + "lineNumber": 65, + "object": true, + "qualifiedClassName": "QVulkanWindow", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "image", + "type": "QImage" + } + ], + "index": 0, + "name": "frameGrabbed", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWindow" + } + ] + } + ], + "inputFile": "qvulkanwindow.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QWindow", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "Visibility", + "values": [ + "Hidden", + "AutomaticVisibility", + "Windowed", + "Minimized", + "Maximized", + "FullScreen" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "AncestorMode", + "values": [ + "ExcludeTransients", + "IncludeTransients" + ] + } + ], + "lineNumber": 62, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "title", + "notify": "windowTitleChanged", + "read": "title", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setTitle" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "modality", + "notify": "modalityChanged", + "read": "modality", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::WindowModality", + "user": false, + "write": "setModality" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "flags", + "read": "flags", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::WindowFlags", + "user": false, + "write": "setFlags" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "x", + "notify": "xChanged", + "read": "x", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setX" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "y", + "notify": "yChanged", + "read": "y", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setY" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "width", + "notify": "widthChanged", + "read": "width", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setWidth" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "height", + "notify": "heightChanged", + "read": "height", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setHeight" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 7, + "name": "minimumWidth", + "notify": "minimumWidthChanged", + "read": "minimumWidth", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setMinimumWidth" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 8, + "name": "minimumHeight", + "notify": "minimumHeightChanged", + "read": "minimumHeight", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setMinimumHeight" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 9, + "name": "maximumWidth", + "notify": "maximumWidthChanged", + "read": "maximumWidth", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setMaximumWidth" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 10, + "name": "maximumHeight", + "notify": "maximumHeightChanged", + "read": "maximumHeight", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setMaximumHeight" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 11, + "name": "visible", + "notify": "visibleChanged", + "read": "isVisible", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setVisible" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 12, + "name": "active", + "notify": "activeChanged", + "read": "isActive", + "required": false, + "revision": 513, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 13, + "name": "visibility", + "notify": "visibilityChanged", + "read": "visibility", + "required": false, + "revision": 513, + "scriptable": true, + "stored": true, + "type": "Visibility", + "user": false, + "write": "setVisibility" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 14, + "name": "contentOrientation", + "notify": "contentOrientationChanged", + "read": "contentOrientation", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::ScreenOrientation", + "user": false, + "write": "reportContentOrientationChange" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 15, + "name": "opacity", + "notify": "opacityChanged", + "read": "opacity", + "required": false, + "revision": 513, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setOpacity" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 16, + "member": "transientParent", + "name": "transientParent", + "notify": "transientParentChanged", + "privateClass": "QWindow::d_func()", + "required": false, + "revision": 525, + "scriptable": true, + "stored": true, + "type": "QWindow*", + "user": false, + "write": "setTransientParent" + } + ], + "qualifiedClassName": "QWindow", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "screen", + "type": "QScreen*" + } + ], + "index": 0, + "name": "screenChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "modality", + "type": "Qt::WindowModality" + } + ], + "index": 1, + "name": "modalityChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "windowState", + "type": "Qt::WindowState" + } + ], + "index": 2, + "name": "windowStateChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "title", + "type": "QString" + } + ], + "index": 3, + "name": "windowTitleChanged", + "returnType": "void", + "revision": 514 + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "int" + } + ], + "index": 4, + "name": "xChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "int" + } + ], + "index": 5, + "name": "yChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "int" + } + ], + "index": 6, + "name": "widthChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "int" + } + ], + "index": 7, + "name": "heightChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "int" + } + ], + "index": 8, + "name": "minimumWidthChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "int" + } + ], + "index": 9, + "name": "minimumHeightChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "int" + } + ], + "index": 10, + "name": "maximumWidthChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "int" + } + ], + "index": 11, + "name": "maximumHeightChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "bool" + } + ], + "index": 12, + "name": "visibleChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "visibility", + "type": "QWindow::Visibility" + } + ], + "index": 13, + "name": "visibilityChanged", + "returnType": "void", + "revision": 513 + }, + { + "access": "public", + "index": 14, + "name": "activeChanged", + "returnType": "void", + "revision": 513 + }, + { + "access": "public", + "arguments": [ + { + "name": "orientation", + "type": "Qt::ScreenOrientation" + } + ], + "index": 15, + "name": "contentOrientationChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "object", + "type": "QObject*" + } + ], + "index": 16, + "name": "focusObjectChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "opacity", + "type": "qreal" + } + ], + "index": 17, + "name": "opacityChanged", + "returnType": "void", + "revision": 513 + }, + { + "access": "public", + "arguments": [ + { + "name": "transientParent", + "type": "QWindow*" + } + ], + "index": 18, + "name": "transientParentChanged", + "returnType": "void", + "revision": 525 + } + ], + "slots": [ + { + "access": "public", + "index": 19, + "name": "requestActivate", + "returnType": "void", + "revision": 513 + }, + { + "access": "public", + "arguments": [ + { + "name": "visible", + "type": "bool" + } + ], + "index": 20, + "name": "setVisible", + "returnType": "void" + }, + { + "access": "public", + "index": 21, + "name": "show", + "returnType": "void" + }, + { + "access": "public", + "index": 22, + "name": "hide", + "returnType": "void" + }, + { + "access": "public", + "index": 23, + "name": "showMinimized", + "returnType": "void" + }, + { + "access": "public", + "index": 24, + "name": "showMaximized", + "returnType": "void" + }, + { + "access": "public", + "index": 25, + "name": "showFullScreen", + "returnType": "void" + }, + { + "access": "public", + "index": 26, + "name": "showNormal", + "returnType": "void" + }, + { + "access": "public", + "index": 27, + "name": "close", + "returnType": "bool" + }, + { + "access": "public", + "index": 28, + "name": "raise", + "returnType": "void" + }, + { + "access": "public", + "index": 29, + "name": "lower", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "edges", + "type": "Qt::Edges" + } + ], + "index": 30, + "name": "startSystemResize", + "returnType": "bool" + }, + { + "access": "public", + "index": 31, + "name": "startSystemMove", + "returnType": "bool" + }, + { + "access": "public", + "arguments": [ + { + "type": "QString" + } + ], + "index": 32, + "name": "setTitle", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "int" + } + ], + "index": 33, + "name": "setX", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "int" + } + ], + "index": 34, + "name": "setY", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "int" + } + ], + "index": 35, + "name": "setWidth", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "int" + } + ], + "index": 36, + "name": "setHeight", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "posx", + "type": "int" + }, + { + "name": "posy", + "type": "int" + }, + { + "name": "w", + "type": "int" + }, + { + "name": "h", + "type": "int" + } + ], + "index": 37, + "name": "setGeometry", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "rect", + "type": "QRect" + } + ], + "index": 38, + "name": "setGeometry", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "w", + "type": "int" + } + ], + "index": 39, + "name": "setMinimumWidth", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "h", + "type": "int" + } + ], + "index": 40, + "name": "setMinimumHeight", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "w", + "type": "int" + } + ], + "index": 41, + "name": "setMaximumWidth", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "h", + "type": "int" + } + ], + "index": 42, + "name": "setMaximumHeight", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "msec", + "type": "int" + } + ], + "index": 43, + "name": "alert", + "returnType": "void", + "revision": 513 + }, + { + "access": "public", + "index": 44, + "name": "requestUpdate", + "returnType": "void", + "revision": 515 + }, + { + "access": "private", + "index": 45, + "name": "_q_clearAlert", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QSurface" + } + ] + } + ], + "inputFile": "qwindow.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QWindowsGuiEventDispatcher", + "lineNumber": 23, + "object": true, + "qualifiedClassName": "QWindowsGuiEventDispatcher", + "superClasses": [ + { + "access": "public", + "name": "QEventDispatcherWin32" + } + ] + } + ], + "inputFile": "qwindowsguieventdispatcher_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QPMCache", + "lineNumber": 176, + "object": true, + "qualifiedClassName": "QPMCache", + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QCache" + } + ] + } + ], + "inputFile": "qpixmapcache.cpp", + "outputRevision": 68 + } +] diff --git a/qt/6.8.1/msvc2022_64/metatypes/qt6help_metatypes.json b/qt/6.8.1/msvc2022_64/metatypes/qt6help_metatypes.json new file mode 100644 index 0000000000000000000000000000000000000000..3dbaf2a41586762c5deb18710751dd988f98021c --- /dev/null +++ b/qt/6.8.1/msvc2022_64/metatypes/qt6help_metatypes.json @@ -0,0 +1,933 @@ +[ + { + "classes": [ + { + "className": "QFilterNameDialog", + "lineNumber": 24, + "object": true, + "qualifiedClassName": "QFilterNameDialog", + "slots": [ + { + "access": "private", + "index": 0, + "name": "updateOkButton", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QDialog" + } + ] + } + ], + "inputFile": "qfilternamedialog_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QHelpCollectionHandler", + "lineNumber": 32, + "object": true, + "qualifiedClassName": "QHelpCollectionHandler", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "msg", + "type": "QString" + } + ], + "index": 0, + "name": "error", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qhelpcollectionhandler_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QHelpContentModel", + "lineNumber": 18, + "object": true, + "qualifiedClassName": "QHelpContentModel", + "signals": [ + { + "access": "public", + "index": 0, + "name": "contentsCreationStarted", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "contentsCreated", + "returnType": "void" + } + ], + "slots": [ + { + "access": "private", + "index": 2, + "name": "insertContents", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QAbstractItemModel" + } + ] + }, + { + "className": "QHelpContentWidget", + "lineNumber": 50, + "object": true, + "qualifiedClassName": "QHelpContentWidget", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "link", + "type": "QUrl" + } + ], + "index": 0, + "name": "linkActivated", + "returnType": "void" + } + ], + "slots": [ + { + "access": "private", + "arguments": [ + { + "name": "index", + "type": "QModelIndex" + } + ], + "index": 1, + "name": "showLink", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QTreeView" + } + ] + } + ], + "inputFile": "qhelpcontentwidget.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QHelpDBReader", + "lineNumber": 26, + "object": true, + "qualifiedClassName": "QHelpDBReader", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qhelpdbreader_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QHelpEngine", + "lineNumber": 18, + "object": true, + "qualifiedClassName": "QHelpEngine", + "superClasses": [ + { + "access": "public", + "name": "QHelpEngineCore" + } + ] + } + ], + "inputFile": "qhelpengine.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QHelpEngineCore", + "lineNumber": 24, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "autoSaveFilter", + "read": "autoSaveFilter", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setAutoSaveFilter" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "collectionFile", + "read": "collectionFile", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setCollectionFile" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "readOnly", + "read": "isReadOnly", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setReadOnly" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "currentFilter", + "read": "currentFilter", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setCurrentFilter" + } + ], + "qualifiedClassName": "QHelpEngineCore", + "signals": [ + { + "access": "public", + "index": 0, + "name": "setupStarted", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "setupFinished", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "msg", + "type": "QString" + } + ], + "index": 2, + "name": "warning", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "newFilter", + "type": "QString" + } + ], + "index": 3, + "name": "currentFilterChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "readersAboutToBeInvalidated", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qhelpenginecore.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QHelpFilterEngine", + "lineNumber": 21, + "object": true, + "qualifiedClassName": "QHelpFilterEngine", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "newFilter", + "type": "QString" + } + ], + "index": 0, + "name": "filterActivated", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qhelpfilterengine.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QHelpFilterSettingsWidget", + "lineNumber": 17, + "object": true, + "qualifiedClassName": "QHelpFilterSettingsWidget", + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + } + ], + "inputFile": "qhelpfiltersettingswidget.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QHelpIndexModel", + "lineNumber": 21, + "object": true, + "qualifiedClassName": "QHelpIndexModel", + "signals": [ + { + "access": "public", + "index": 0, + "name": "indexCreationStarted", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "indexCreated", + "returnType": "void" + } + ], + "slots": [ + { + "access": "private", + "index": 2, + "name": "insertIndices", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QStringListModel" + } + ] + }, + { + "className": "QHelpIndexWidget", + "lineNumber": 48, + "object": true, + "qualifiedClassName": "QHelpIndexWidget", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "link", + "type": "QUrl" + }, + { + "name": "keyword", + "type": "QString" + } + ], + "index": 0, + "name": "linkActivated", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "links", + "type": "QMultiMap" + }, + { + "name": "keyword", + "type": "QString" + } + ], + "index": 1, + "name": "linksActivated", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "document", + "type": "QHelpLink" + }, + { + "name": "keyword", + "type": "QString" + } + ], + "index": 2, + "name": "documentActivated", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "documents", + "type": "QList" + }, + { + "name": "keyword", + "type": "QString" + } + ], + "index": 3, + "name": "documentsActivated", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "filter", + "type": "QString" + }, + { + "name": "wildcard", + "type": "QString" + } + ], + "index": 4, + "name": "filterIndices", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "filter", + "type": "QString" + } + ], + "index": 5, + "isCloned": true, + "name": "filterIndices", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "activateCurrentItem", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "index", + "type": "QModelIndex" + } + ], + "index": 7, + "name": "showLink", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QListView" + } + ] + } + ], + "inputFile": "qhelpindexwidget.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QHelpSearchEngine", + "lineNumber": 39, + "object": true, + "qualifiedClassName": "QHelpSearchEngine", + "signals": [ + { + "access": "public", + "index": 0, + "name": "indexingStarted", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "indexingFinished", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "searchingStarted", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "searchResultCount", + "type": "int" + } + ], + "index": 3, + "name": "searchingFinished", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "index": 4, + "name": "reindexDocumentation", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "cancelIndexing", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "queryList", + "type": "QList" + } + ], + "index": 6, + "name": "search", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "searchInput", + "type": "QString" + } + ], + "index": 7, + "name": "search", + "returnType": "void" + }, + { + "access": "public", + "index": 8, + "name": "cancelSearching", + "returnType": "void" + }, + { + "access": "public", + "index": 9, + "name": "scheduleIndexDocumentation", + "returnType": "void" + }, + { + "access": "private", + "index": 10, + "name": "indexDocumentation", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qhelpsearchengine.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QHelpSearchEngineCore", + "lineNumber": 18, + "object": true, + "qualifiedClassName": "QHelpSearchEngineCore", + "signals": [ + { + "access": "public", + "index": 0, + "name": "indexingStarted", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "indexingFinished", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "searchingStarted", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "searchingFinished", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "index": 4, + "name": "reindexDocumentation", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "cancelIndexing", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "searchInput", + "type": "QString" + } + ], + "index": 6, + "name": "search", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "cancelSearching", + "returnType": "void" + }, + { + "access": "public", + "index": 8, + "name": "scheduleIndexDocumentation", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qhelpsearchenginecore.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QHelpSearchIndexReader", + "lineNumber": 29, + "object": true, + "qualifiedClassName": "fulltextsearch::QHelpSearchIndexReader", + "signals": [ + { + "access": "public", + "index": 0, + "name": "searchingStarted", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "searchingFinished", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QThread" + } + ] + } + ], + "inputFile": "qhelpsearchindexreader_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QHelpSearchIndexWriter", + "lineNumber": 28, + "object": true, + "qualifiedClassName": "fulltextsearch::QHelpSearchIndexWriter", + "signals": [ + { + "access": "public", + "index": 0, + "name": "indexingStarted", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "indexingFinished", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QThread" + } + ] + } + ], + "inputFile": "qhelpsearchindexwriter_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QHelpSearchQueryWidget", + "lineNumber": 17, + "object": true, + "qualifiedClassName": "QHelpSearchQueryWidget", + "signals": [ + { + "access": "public", + "index": 0, + "name": "search", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "on", + "type": "bool" + } + ], + "index": 1, + "name": "setCompactMode", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + } + ], + "inputFile": "qhelpsearchquerywidget.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QHelpSearchResultWidget", + "lineNumber": 18, + "object": true, + "qualifiedClassName": "QHelpSearchResultWidget", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "url", + "type": "QUrl" + } + ], + "index": 0, + "name": "requestShowLink", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + } + ], + "inputFile": "qhelpsearchresultwidget.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QOptionsWidget", + "lineNumber": 26, + "object": true, + "qualifiedClassName": "QOptionsWidget", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "options", + "type": "QStringList" + } + ], + "index": 0, + "name": "optionSelectionChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + } + ], + "inputFile": "qoptionswidget_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QResultWidget", + "lineNumber": 20, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "linkColor", + "read": "linkColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false, + "write": "setLinkColor" + } + ], + "qualifiedClassName": "QResultWidget", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "url", + "type": "QUrl" + } + ], + "index": 0, + "name": "requestShowLink", + "returnType": "void" + } + ], + "slots": [ + { + "access": "private", + "arguments": [ + { + "type": "QUrl" + }, + { + "type": "QTextDocument::ResourceType" + } + ], + "index": 1, + "name": "doSetSource", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QTextBrowser" + } + ] + } + ], + "inputFile": "qhelpsearchresultwidget.cpp", + "outputRevision": 68 + } +] diff --git a/qt/6.8.1/msvc2022_64/metatypes/qt6labsanimation_metatypes.json b/qt/6.8.1/msvc2022_64/metatypes/qt6labsanimation_metatypes.json new file mode 100644 index 0000000000000000000000000000000000000000..7c9e0cf85a1fa2e4edbffdb7fb16b231a5dab32d --- /dev/null +++ b/qt/6.8.1/msvc2022_64/metatypes/qt6labsanimation_metatypes.json @@ -0,0 +1,310 @@ +[ + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "BoundaryRule" + }, + { + "name": "QML.AddedInVersion", + "value": "256" + } + ], + "className": "QQuickBoundaryRule", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "OvershootFilter", + "values": [ + "None", + "Peak" + ] + } + ], + "interfaces": [ + [ + { + "className": "QQmlParserStatus", + "id": "\"org.qt-project.Qt.QQmlParserStatus\"" + } + ], + [ + { + "className": "QQmlPropertyValueInterceptor", + "id": "\"org.qt-project.Qt.QQmlPropertyValueInterceptor\"" + } + ] + ], + "lineNumber": 29, + "methods": [ + { + "access": "public", + "index": 12, + "name": "returnToBounds", + "returnType": "bool" + } + ], + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "enabled", + "notify": "enabledChanged", + "read": "enabled", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setEnabled" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "minimum", + "notify": "minimumChanged", + "read": "minimum", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setMinimum" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "minimumOvershoot", + "notify": "minimumOvershootChanged", + "read": "minimumOvershoot", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setMinimumOvershoot" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "maximum", + "notify": "maximumChanged", + "read": "maximum", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setMaximum" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "maximumOvershoot", + "notify": "maximumOvershootChanged", + "read": "maximumOvershoot", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setMaximumOvershoot" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "overshootScale", + "notify": "overshootScaleChanged", + "read": "overshootScale", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setOvershootScale" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 6, + "name": "currentOvershoot", + "notify": "currentOvershootChanged", + "read": "currentOvershoot", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 7, + "name": "peakOvershoot", + "notify": "peakOvershootChanged", + "read": "peakOvershoot", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 8, + "name": "overshootFilter", + "notify": "overshootFilterChanged", + "read": "overshootFilter", + "required": false, + "scriptable": true, + "stored": true, + "type": "OvershootFilter", + "user": false, + "write": "setOvershootFilter" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 9, + "name": "easing", + "notify": "easingChanged", + "read": "easing", + "required": false, + "scriptable": true, + "stored": true, + "type": "QEasingCurve", + "user": false, + "write": "setEasing" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 10, + "name": "returnDuration", + "notify": "returnDurationChanged", + "read": "returnDuration", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setReturnDuration" + } + ], + "qualifiedClassName": "QQuickBoundaryRule", + "signals": [ + { + "access": "public", + "index": 0, + "name": "enabledChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "minimumChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "minimumOvershootChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "maximumChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "maximumOvershootChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "overshootScaleChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "currentOvershootChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "peakOvershootChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 8, + "name": "overshootFilterChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 9, + "name": "easingChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 10, + "name": "returnDurationChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 11, + "name": "returnedToBounds", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QQmlPropertyValueInterceptor" + }, + { + "access": "public", + "name": "QQmlParserStatus" + } + ] + } + ], + "inputFile": "qquickboundaryrule_p.h", + "outputRevision": 68 + } +] diff --git a/qt/6.8.1/msvc2022_64/metatypes/qt6labsfolderlistmodel_metatypes.json b/qt/6.8.1/msvc2022_64/metatypes/qt6labsfolderlistmodel_metatypes.json new file mode 100644 index 0000000000000000000000000000000000000000..0a26de35db243b97a175446aba55aef417294d81 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/metatypes/qt6labsfolderlistmodel_metatypes.json @@ -0,0 +1,562 @@ +[ + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + } + ], + "className": "FileProperty", + "gadget": true, + "lineNumber": 26, + "qualifiedClassName": "FileProperty" + } + ], + "inputFile": "fileproperty_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "FileInfoThread", + "lineNumber": 32, + "object": true, + "qualifiedClassName": "FileInfoThread", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "directory", + "type": "QString" + }, + { + "name": "list", + "type": "QList" + } + ], + "index": 0, + "name": "directoryChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "directory", + "type": "QString" + }, + { + "name": "list", + "type": "QList" + }, + { + "name": "fromIndex", + "type": "int" + }, + { + "name": "toIndex", + "type": "int" + } + ], + "index": 1, + "name": "directoryUpdated", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "list", + "type": "QList" + } + ], + "index": 2, + "name": "sortFinished", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "status", + "type": "QQuickFolderListModel::Status" + } + ], + "index": 3, + "name": "statusChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "directoryPath", + "type": "QString" + } + ], + "index": 4, + "name": "dirChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "path", + "type": "QString" + } + ], + "index": 5, + "name": "updateFile", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QThread" + } + ] + } + ], + "inputFile": "fileinfothread_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "FolderListModel" + }, + { + "name": "QML.AddedInVersion", + "value": "256" + } + ], + "className": "QQuickFolderListModel", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "SortField", + "values": [ + "Unsorted", + "Name", + "Time", + "Size", + "Type" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "Status", + "values": [ + "Null", + "Ready", + "Loading" + ] + } + ], + "interfaces": [ + [ + { + "className": "QQmlParserStatus", + "id": "\"org.qt-project.Qt.QQmlParserStatus\"" + } + ] + ], + "lineNumber": 34, + "methods": [ + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + } + ], + "index": 8, + "name": "isFolder", + "returnType": "bool" + }, + { + "access": "public", + "arguments": [ + { + "name": "idx", + "type": "int" + }, + { + "name": "property", + "type": "QString" + } + ], + "index": 9, + "name": "get", + "returnType": "QVariant" + }, + { + "access": "public", + "arguments": [ + { + "name": "file", + "type": "QUrl" + } + ], + "index": 10, + "name": "indexOf", + "returnType": "int" + } + ], + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "folder", + "notify": "folderChanged", + "read": "folder", + "required": false, + "scriptable": true, + "stored": true, + "type": "QUrl", + "user": false, + "write": "setFolder" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "rootFolder", + "read": "rootFolder", + "required": false, + "scriptable": true, + "stored": true, + "type": "QUrl", + "user": false, + "write": "setRootFolder" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "parentFolder", + "notify": "folderChanged", + "read": "parentFolder", + "required": false, + "scriptable": true, + "stored": true, + "type": "QUrl", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "nameFilters", + "read": "nameFilters", + "required": false, + "scriptable": true, + "stored": true, + "type": "QStringList", + "user": false, + "write": "setNameFilters" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "sortField", + "read": "sortField", + "required": false, + "scriptable": true, + "stored": true, + "type": "SortField", + "user": false, + "write": "setSortField" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "sortReversed", + "read": "sortReversed", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setSortReversed" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 6, + "name": "showFiles", + "read": "showFiles", + "required": false, + "revision": 513, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setShowFiles" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 7, + "name": "showDirs", + "read": "showDirs", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setShowDirs" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 8, + "name": "showDirsFirst", + "read": "showDirsFirst", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setShowDirsFirst" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 9, + "name": "showDotAndDotDot", + "read": "showDotAndDotDot", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setShowDotAndDotDot" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 10, + "name": "showHidden", + "read": "showHidden", + "required": false, + "revision": 513, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setShowHidden" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 11, + "name": "showOnlyReadable", + "read": "showOnlyReadable", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setShowOnlyReadable" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 12, + "name": "caseSensitive", + "read": "caseSensitive", + "required": false, + "revision": 514, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setCaseSensitive" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 13, + "name": "count", + "notify": "countChanged", + "read": "count", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 14, + "name": "status", + "notify": "statusChanged", + "read": "status", + "required": false, + "revision": 523, + "scriptable": true, + "stored": true, + "type": "Status", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 15, + "name": "sortCaseSensitive", + "read": "sortCaseSensitive", + "required": false, + "revision": 524, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setSortCaseSensitive" + } + ], + "qualifiedClassName": "QQuickFolderListModel", + "signals": [ + { + "access": "public", + "index": 0, + "name": "folderChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "rowCountChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "countChanged", + "returnType": "void", + "revision": 513 + }, + { + "access": "public", + "index": 3, + "name": "statusChanged", + "returnType": "void", + "revision": 523 + } + ], + "slots": [ + { + "access": "private", + "arguments": [ + { + "name": "directory", + "type": "QString" + }, + { + "name": "list", + "type": "QList" + } + ], + "index": 4, + "name": "_q_directoryChanged", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "directory", + "type": "QString" + }, + { + "name": "list", + "type": "QList" + }, + { + "name": "fromIndex", + "type": "int" + }, + { + "name": "toIndex", + "type": "int" + } + ], + "index": 5, + "name": "_q_directoryUpdated", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "list", + "type": "QList" + } + ], + "index": 6, + "name": "_q_sortFinished", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "s", + "type": "QQuickFolderListModel::Status" + } + ], + "index": 7, + "name": "_q_statusChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QAbstractListModel" + }, + { + "access": "public", + "name": "QQmlParserStatus" + } + ] + } + ], + "inputFile": "qquickfolderlistmodel_p.h", + "outputRevision": 68 + } +] diff --git a/qt/6.8.1/msvc2022_64/metatypes/qt6labsplatform_metatypes.json b/qt/6.8.1/msvc2022_64/metatypes/qt6labsplatform_metatypes.json new file mode 100644 index 0000000000000000000000000000000000000000..96ac12fd90123a771f456f0ae1b31afcedc73e6f --- /dev/null +++ b/qt/6.8.1/msvc2022_64/metatypes/qt6labsplatform_metatypes.json @@ -0,0 +1,3051 @@ +[ + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "ColorDialog" + }, + { + "name": "QML.Extended", + "value": "QColorDialogOptions" + }, + { + "name": "QML.ExtensionIsNamespace", + "value": "true" + } + ], + "className": "QQuickLabsPlatformColorDialog", + "lineNumber": 24, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "color", + "notify": "colorChanged", + "read": "color", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false, + "write": "setColor" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "currentColor", + "notify": "currentColorChanged", + "read": "currentColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false, + "write": "setCurrentColor" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "options", + "notify": "optionsChanged", + "read": "options", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColorDialogOptions::ColorDialogOptions", + "user": false, + "write": "setOptions" + } + ], + "qualifiedClassName": "QQuickLabsPlatformColorDialog", + "signals": [ + { + "access": "public", + "index": 0, + "name": "colorChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "currentColorChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "optionsChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickLabsPlatformDialog" + } + ] + } + ], + "inputFile": "qquicklabsplatformcolordialog_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "Dialog" + }, + { + "name": "QML.Creatable", + "value": "false" + }, + { + "name": "QML.UncreatableReason", + "value": "Dialog is an abstract base class" + }, + { + "name": "DefaultProperty", + "value": "data" + } + ], + "className": "QQuickLabsPlatformDialog", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "StandardCode", + "values": [ + "Rejected", + "Accepted" + ] + } + ], + "interfaces": [ + [ + { + "className": "QQmlParserStatus", + "id": "\"org.qt-project.Qt.QQmlParserStatus\"" + } + ] + ], + "lineNumber": 31, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "data", + "read": "data", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlListProperty", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "parentWindow", + "notify": "parentWindowChanged", + "read": "parentWindow", + "required": false, + "scriptable": true, + "stored": true, + "type": "QWindow*", + "user": false, + "write": "setParentWindow" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "title", + "notify": "titleChanged", + "read": "title", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setTitle" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "flags", + "notify": "flagsChanged", + "read": "flags", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::WindowFlags", + "user": false, + "write": "setFlags" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "modality", + "notify": "modalityChanged", + "read": "modality", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::WindowModality", + "user": false, + "write": "setModality" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "visible", + "notify": "visibleChanged", + "read": "isVisible", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setVisible" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 6, + "name": "result", + "notify": "resultChanged", + "read": "result", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setResult" + } + ], + "qualifiedClassName": "QQuickLabsPlatformDialog", + "signals": [ + { + "access": "public", + "index": 0, + "name": "accepted", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "rejected", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "parentWindowChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "titleChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "flagsChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "modalityChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "visibleChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "resultChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "index": 8, + "name": "open", + "returnType": "void" + }, + { + "access": "public", + "index": 9, + "name": "close", + "returnType": "void" + }, + { + "access": "public", + "index": 10, + "name": "accept", + "returnType": "void" + }, + { + "access": "public", + "index": 11, + "name": "reject", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "result", + "type": "int" + } + ], + "index": 12, + "name": "done", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QQmlParserStatus" + } + ] + } + ], + "inputFile": "qquicklabsplatformdialog_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "FileDialog" + }, + { + "name": "QML.Extended", + "value": "QFileDialogOptions" + }, + { + "name": "QML.ExtensionIsNamespace", + "value": "true" + } + ], + "className": "QQuickLabsPlatformFileDialog", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "FileMode", + "values": [ + "OpenFile", + "OpenFiles", + "SaveFile" + ] + } + ], + "lineNumber": 26, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "fileMode", + "notify": "fileModeChanged", + "read": "fileMode", + "required": false, + "scriptable": true, + "stored": true, + "type": "FileMode", + "user": false, + "write": "setFileMode" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "file", + "notify": "fileChanged", + "read": "file", + "required": false, + "scriptable": true, + "stored": true, + "type": "QUrl", + "user": false, + "write": "setFile" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "files", + "notify": "filesChanged", + "read": "files", + "required": false, + "scriptable": true, + "stored": true, + "type": "QList", + "user": false, + "write": "setFiles" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "currentFile", + "notify": "currentFileChanged", + "read": "currentFile", + "required": false, + "scriptable": true, + "stored": true, + "type": "QUrl", + "user": false, + "write": "setCurrentFile" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "currentFiles", + "notify": "currentFilesChanged", + "read": "currentFiles", + "required": false, + "scriptable": true, + "stored": true, + "type": "QList", + "user": false, + "write": "setCurrentFiles" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "folder", + "notify": "folderChanged", + "read": "folder", + "required": false, + "scriptable": true, + "stored": true, + "type": "QUrl", + "user": false, + "write": "setFolder" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 6, + "name": "options", + "notify": "optionsChanged", + "read": "options", + "required": false, + "reset": "resetOptions", + "scriptable": true, + "stored": true, + "type": "QFileDialogOptions::FileDialogOptions", + "user": false, + "write": "setOptions" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 7, + "name": "nameFilters", + "notify": "nameFiltersChanged", + "read": "nameFilters", + "required": false, + "reset": "resetNameFilters", + "scriptable": true, + "stored": true, + "type": "QStringList", + "user": false, + "write": "setNameFilters" + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 8, + "name": "selectedNameFilter", + "read": "selectedNameFilter", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickLabsPlatformFileNameFilter*", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 9, + "name": "defaultSuffix", + "notify": "defaultSuffixChanged", + "read": "defaultSuffix", + "required": false, + "reset": "resetDefaultSuffix", + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setDefaultSuffix" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 10, + "name": "acceptLabel", + "notify": "acceptLabelChanged", + "read": "acceptLabel", + "required": false, + "reset": "resetAcceptLabel", + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setAcceptLabel" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 11, + "name": "rejectLabel", + "notify": "rejectLabelChanged", + "read": "rejectLabel", + "required": false, + "reset": "resetRejectLabel", + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setRejectLabel" + } + ], + "qualifiedClassName": "QQuickLabsPlatformFileDialog", + "signals": [ + { + "access": "public", + "index": 0, + "name": "fileModeChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "fileChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "filesChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "currentFileChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "currentFilesChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "folderChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "optionsChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "nameFiltersChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 8, + "name": "defaultSuffixChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 9, + "name": "acceptLabelChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 10, + "name": "rejectLabelChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickLabsPlatformDialog" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + } + ], + "className": "QQuickLabsPlatformFileNameFilter", + "lineNumber": 125, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "index", + "notify": "indexChanged", + "read": "index", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setIndex" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "name", + "notify": "nameChanged", + "read": "name", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "extensions", + "notify": "extensionsChanged", + "read": "extensions", + "required": false, + "scriptable": true, + "stored": true, + "type": "QStringList", + "user": false + } + ], + "qualifiedClassName": "QQuickLabsPlatformFileNameFilter", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + } + ], + "index": 0, + "name": "indexChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "name", + "type": "QString" + } + ], + "index": 1, + "name": "nameChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "extensions", + "type": "QStringList" + } + ], + "index": 2, + "name": "extensionsChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qquicklabsplatformfiledialog_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "FolderDialog" + }, + { + "name": "QML.Extended", + "value": "QFileDialogOptions" + }, + { + "name": "QML.ExtensionIsNamespace", + "value": "true" + } + ], + "className": "QQuickLabsPlatformFolderDialog", + "lineNumber": 24, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "folder", + "notify": "folderChanged", + "read": "folder", + "required": false, + "scriptable": true, + "stored": true, + "type": "QUrl", + "user": false, + "write": "setFolder" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "currentFolder", + "notify": "currentFolderChanged", + "read": "currentFolder", + "required": false, + "scriptable": true, + "stored": true, + "type": "QUrl", + "user": false, + "write": "setCurrentFolder" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "options", + "notify": "optionsChanged", + "read": "options", + "required": false, + "reset": "resetOptions", + "scriptable": true, + "stored": true, + "type": "QFileDialogOptions::FileDialogOptions", + "user": false, + "write": "setOptions" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "acceptLabel", + "notify": "acceptLabelChanged", + "read": "acceptLabel", + "required": false, + "reset": "resetAcceptLabel", + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setAcceptLabel" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "rejectLabel", + "notify": "rejectLabelChanged", + "read": "rejectLabel", + "required": false, + "reset": "resetRejectLabel", + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setRejectLabel" + } + ], + "qualifiedClassName": "QQuickLabsPlatformFolderDialog", + "signals": [ + { + "access": "public", + "index": 0, + "name": "folderChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "currentFolderChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "optionsChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "acceptLabelChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "rejectLabelChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickLabsPlatformDialog" + } + ] + } + ], + "inputFile": "qquicklabsplatformfolderdialog_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "FontDialog" + }, + { + "name": "QML.Extended", + "value": "QFontDialogOptions" + }, + { + "name": "QML.ExtensionIsNamespace", + "value": "true" + } + ], + "className": "QQuickLabsPlatformFontDialog", + "lineNumber": 24, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "font", + "notify": "fontChanged", + "read": "font", + "required": false, + "scriptable": true, + "stored": true, + "type": "QFont", + "user": false, + "write": "setFont" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "currentFont", + "notify": "currentFontChanged", + "read": "currentFont", + "required": false, + "scriptable": true, + "stored": true, + "type": "QFont", + "user": false, + "write": "setCurrentFont" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "options", + "notify": "optionsChanged", + "read": "options", + "required": false, + "scriptable": true, + "stored": true, + "type": "QFontDialogOptions::FontDialogOptions", + "user": false, + "write": "setOptions" + } + ], + "qualifiedClassName": "QQuickLabsPlatformFontDialog", + "signals": [ + { + "access": "public", + "index": 0, + "name": "fontChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "currentFontChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "optionsChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickLabsPlatformDialog" + } + ] + } + ], + "inputFile": "qquicklabsplatformfontdialog_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + } + ], + "className": "QQuickLabsPlatformIcon", + "gadget": true, + "lineNumber": 28, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "source", + "read": "source", + "required": false, + "scriptable": true, + "stored": true, + "type": "QUrl", + "user": false, + "write": "setSource" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "name", + "read": "name", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setName" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "mask", + "read": "isMask", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setMask" + } + ], + "qualifiedClassName": "QQuickLabsPlatformIcon" + } + ], + "inputFile": "qquicklabsplatformicon_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "Menu" + }, + { + "name": "QML.Extended", + "value": "QPlatformMenu" + }, + { + "name": "QML.ExtensionIsNamespace", + "value": "true" + }, + { + "name": "DefaultProperty", + "value": "data" + } + ], + "className": "QQuickLabsPlatformMenu", + "interfaces": [ + [ + { + "className": "QQmlParserStatus", + "id": "\"org.qt-project.Qt.QQmlParserStatus\"" + } + ] + ], + "lineNumber": 39, + "methods": [ + { + "access": "public", + "arguments": [ + { + "name": "item", + "type": "QQuickLabsPlatformMenuItem*" + } + ], + "index": 16, + "name": "addItem", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + }, + { + "name": "item", + "type": "QQuickLabsPlatformMenuItem*" + } + ], + "index": 17, + "name": "insertItem", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "item", + "type": "QQuickLabsPlatformMenuItem*" + } + ], + "index": 18, + "name": "removeItem", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "menu", + "type": "QQuickLabsPlatformMenu*" + } + ], + "index": 19, + "name": "addMenu", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + }, + { + "name": "menu", + "type": "QQuickLabsPlatformMenu*" + } + ], + "index": 20, + "name": "insertMenu", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "menu", + "type": "QQuickLabsPlatformMenu*" + } + ], + "index": 21, + "name": "removeMenu", + "returnType": "void" + }, + { + "access": "public", + "index": 22, + "name": "clear", + "returnType": "void" + } + ], + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "data", + "read": "data", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlListProperty", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "items", + "notify": "itemsChanged", + "read": "items", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlListProperty", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "menuBar", + "notify": "menuBarChanged", + "read": "menuBar", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickLabsPlatformMenuBar*", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "parentMenu", + "notify": "parentMenuChanged", + "read": "parentMenu", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickLabsPlatformMenu*", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "systemTrayIcon", + "notify": "systemTrayIconChanged", + "read": "systemTrayIcon", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickLabsPlatformSystemTrayIcon*", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 5, + "name": "menuItem", + "read": "menuItem", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickLabsPlatformMenuItem*", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 6, + "name": "enabled", + "notify": "enabledChanged", + "read": "isEnabled", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setEnabled" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 7, + "name": "visible", + "notify": "visibleChanged", + "read": "isVisible", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setVisible" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 8, + "name": "minimumWidth", + "notify": "minimumWidthChanged", + "read": "minimumWidth", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setMinimumWidth" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 9, + "name": "type", + "notify": "typeChanged", + "read": "type", + "required": false, + "scriptable": true, + "stored": true, + "type": "QPlatformMenu::MenuType", + "user": false, + "write": "setType" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 10, + "name": "title", + "notify": "titleChanged", + "read": "title", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setTitle" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 11, + "name": "font", + "notify": "fontChanged", + "read": "font", + "required": false, + "scriptable": true, + "stored": true, + "type": "QFont", + "user": false, + "write": "setFont" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 12, + "name": "icon", + "notify": "iconChanged", + "read": "icon", + "required": false, + "revision": 257, + "scriptable": true, + "stored": true, + "type": "QQuickLabsPlatformIcon", + "user": false, + "write": "setIcon" + } + ], + "qualifiedClassName": "QQuickLabsPlatformMenu", + "signals": [ + { + "access": "public", + "index": 0, + "name": "aboutToShow", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "aboutToHide", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "itemsChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "menuBarChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "parentMenuChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "systemTrayIconChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "titleChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "enabledChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 8, + "name": "visibleChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 9, + "name": "minimumWidthChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 10, + "name": "fontChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 11, + "name": "typeChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 12, + "name": "iconChanged", + "returnType": "void", + "revision": 513 + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "args", + "type": "QQmlV4FunctionPtr" + } + ], + "index": 13, + "name": "open", + "returnType": "void" + }, + { + "access": "public", + "index": 14, + "name": "close", + "returnType": "void" + }, + { + "access": "private", + "index": 15, + "name": "updateIcon", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QQmlParserStatus" + } + ] + } + ], + "inputFile": "qquicklabsplatformmenu_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "MenuBar" + }, + { + "name": "DefaultProperty", + "value": "data" + } + ], + "className": "QQuickLabsPlatformMenuBar", + "interfaces": [ + [ + { + "className": "QQmlParserStatus", + "id": "\"org.qt-project.Qt.QQmlParserStatus\"" + } + ] + ], + "lineNumber": 30, + "methods": [ + { + "access": "public", + "arguments": [ + { + "name": "menu", + "type": "QQuickLabsPlatformMenu*" + } + ], + "index": 2, + "name": "addMenu", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + }, + { + "name": "menu", + "type": "QQuickLabsPlatformMenu*" + } + ], + "index": 3, + "name": "insertMenu", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "menu", + "type": "QQuickLabsPlatformMenu*" + } + ], + "index": 4, + "name": "removeMenu", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "clear", + "returnType": "void" + } + ], + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "data", + "read": "data", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlListProperty", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "menus", + "notify": "menusChanged", + "read": "menus", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlListProperty", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "window", + "notify": "windowChanged", + "read": "window", + "required": false, + "scriptable": true, + "stored": true, + "type": "QWindow*", + "user": false, + "write": "setWindow" + } + ], + "qualifiedClassName": "QQuickLabsPlatformMenuBar", + "signals": [ + { + "access": "public", + "index": 0, + "name": "menusChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "windowChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QQmlParserStatus" + } + ] + } + ], + "inputFile": "qquicklabsplatformmenubar_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "MenuItem" + }, + { + "name": "QML.Extended", + "value": "QPlatformMenuItem" + }, + { + "name": "QML.ExtensionIsNamespace", + "value": "true" + } + ], + "className": "QQuickLabsPlatformMenuItem", + "interfaces": [ + [ + { + "className": "QQmlParserStatus", + "id": "\"org.qt-project.Qt.QQmlParserStatus\"" + } + ] + ], + "lineNumber": 34, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "menu", + "notify": "menuChanged", + "read": "menu", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickLabsPlatformMenu*", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "subMenu", + "notify": "subMenuChanged", + "read": "subMenu", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickLabsPlatformMenu*", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "group", + "notify": "groupChanged", + "read": "group", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickLabsPlatformMenuItemGroup*", + "user": false, + "write": "setGroup" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "enabled", + "notify": "enabledChanged", + "read": "isEnabled", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setEnabled" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "visible", + "notify": "visibleChanged", + "read": "isVisible", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setVisible" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "separator", + "notify": "separatorChanged", + "read": "isSeparator", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setSeparator" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 6, + "name": "checkable", + "notify": "checkableChanged", + "read": "isCheckable", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setCheckable" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 7, + "name": "checked", + "notify": "checkedChanged", + "read": "isChecked", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setChecked" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 8, + "name": "role", + "notify": "roleChanged", + "read": "role", + "required": false, + "scriptable": true, + "stored": true, + "type": "QPlatformMenuItem::MenuRole", + "user": false, + "write": "setRole" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 9, + "name": "text", + "notify": "textChanged", + "read": "text", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setText" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 10, + "name": "shortcut", + "notify": "shortcutChanged", + "read": "shortcut", + "required": false, + "scriptable": true, + "stored": true, + "type": "QVariant", + "user": false, + "write": "setShortcut" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 11, + "name": "font", + "notify": "fontChanged", + "read": "font", + "required": false, + "scriptable": true, + "stored": true, + "type": "QFont", + "user": false, + "write": "setFont" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 12, + "name": "icon", + "notify": "iconChanged", + "read": "icon", + "required": false, + "revision": 257, + "scriptable": true, + "stored": true, + "type": "QQuickLabsPlatformIcon", + "user": false, + "write": "setIcon" + } + ], + "qualifiedClassName": "QQuickLabsPlatformMenuItem", + "signals": [ + { + "access": "public", + "index": 0, + "name": "triggered", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "hovered", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "menuChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "subMenuChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "groupChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "enabledChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "visibleChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "separatorChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 8, + "name": "checkableChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 9, + "name": "checkedChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 10, + "name": "roleChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 11, + "name": "textChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 12, + "name": "shortcutChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 13, + "name": "fontChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 14, + "name": "iconChanged", + "returnType": "void", + "revision": 513 + } + ], + "slots": [ + { + "access": "public", + "index": 15, + "name": "toggle", + "returnType": "void" + }, + { + "access": "private", + "index": 16, + "name": "activate", + "returnType": "void" + }, + { + "access": "private", + "index": 17, + "name": "updateIcon", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QQmlParserStatus" + } + ] + } + ], + "inputFile": "qquicklabsplatformmenuitem_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "MenuItemGroup" + } + ], + "className": "QQuickLabsPlatformMenuItemGroup", + "lineNumber": 28, + "methods": [ + { + "access": "public", + "arguments": [ + { + "name": "item", + "type": "QQuickLabsPlatformMenuItem*" + } + ], + "index": 7, + "name": "addItem", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "item", + "type": "QQuickLabsPlatformMenuItem*" + } + ], + "index": 8, + "name": "removeItem", + "returnType": "void" + }, + { + "access": "public", + "index": 9, + "name": "clear", + "returnType": "void" + } + ], + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "enabled", + "notify": "enabledChanged", + "read": "isEnabled", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setEnabled" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "visible", + "notify": "visibleChanged", + "read": "isVisible", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setVisible" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "exclusive", + "notify": "exclusiveChanged", + "read": "isExclusive", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setExclusive" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "checkedItem", + "notify": "checkedItemChanged", + "read": "checkedItem", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickLabsPlatformMenuItem*", + "user": false, + "write": "setCheckedItem" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "items", + "notify": "itemsChanged", + "read": "items", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlListProperty", + "user": false + } + ], + "qualifiedClassName": "QQuickLabsPlatformMenuItemGroup", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "item", + "type": "QQuickLabsPlatformMenuItem*" + } + ], + "index": 0, + "name": "triggered", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "item", + "type": "QQuickLabsPlatformMenuItem*" + } + ], + "index": 1, + "name": "hovered", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "enabledChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "visibleChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "exclusiveChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "checkedItemChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "itemsChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qquicklabsplatformmenuitemgroup_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "MenuSeparator" + } + ], + "className": "QQuickLabsPlatformMenuSeparator", + "lineNumber": 22, + "object": true, + "qualifiedClassName": "QQuickLabsPlatformMenuSeparator", + "superClasses": [ + { + "access": "public", + "name": "QQuickLabsPlatformMenuItem" + } + ] + } + ], + "inputFile": "qquicklabsplatformmenuseparator_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "MessageDialog" + }, + { + "name": "QML.Extended", + "value": "QPlatformDialogHelper" + }, + { + "name": "QML.ExtensionIsNamespace", + "value": "true" + } + ], + "className": "QQuickLabsPlatformMessageDialog", + "lineNumber": 23, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "text", + "notify": "textChanged", + "read": "text", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setText" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "informativeText", + "notify": "informativeTextChanged", + "read": "informativeText", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setInformativeText" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "detailedText", + "notify": "detailedTextChanged", + "read": "detailedText", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setDetailedText" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "buttons", + "notify": "buttonsChanged", + "read": "buttons", + "required": false, + "scriptable": true, + "stored": true, + "type": "QPlatformDialogHelper::StandardButtons", + "user": false, + "write": "setButtons" + } + ], + "qualifiedClassName": "QQuickLabsPlatformMessageDialog", + "signals": [ + { + "access": "public", + "index": 0, + "name": "textChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "informativeTextChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "detailedTextChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "buttonsChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "button", + "type": "QPlatformDialogHelper::StandardButton" + } + ], + "index": 4, + "name": "clicked", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "okClicked", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "saveClicked", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "saveAllClicked", + "returnType": "void" + }, + { + "access": "public", + "index": 8, + "name": "openClicked", + "returnType": "void" + }, + { + "access": "public", + "index": 9, + "name": "yesClicked", + "returnType": "void" + }, + { + "access": "public", + "index": 10, + "name": "yesToAllClicked", + "returnType": "void" + }, + { + "access": "public", + "index": 11, + "name": "noClicked", + "returnType": "void" + }, + { + "access": "public", + "index": 12, + "name": "noToAllClicked", + "returnType": "void" + }, + { + "access": "public", + "index": 13, + "name": "abortClicked", + "returnType": "void" + }, + { + "access": "public", + "index": 14, + "name": "retryClicked", + "returnType": "void" + }, + { + "access": "public", + "index": 15, + "name": "ignoreClicked", + "returnType": "void" + }, + { + "access": "public", + "index": 16, + "name": "closeClicked", + "returnType": "void" + }, + { + "access": "public", + "index": 17, + "name": "cancelClicked", + "returnType": "void" + }, + { + "access": "public", + "index": 18, + "name": "discardClicked", + "returnType": "void" + }, + { + "access": "public", + "index": 19, + "name": "helpClicked", + "returnType": "void" + }, + { + "access": "public", + "index": 20, + "name": "applyClicked", + "returnType": "void" + }, + { + "access": "public", + "index": 21, + "name": "resetClicked", + "returnType": "void" + }, + { + "access": "public", + "index": 22, + "name": "restoreDefaultsClicked", + "returnType": "void" + } + ], + "slots": [ + { + "access": "private", + "arguments": [ + { + "name": "button", + "type": "QPlatformDialogHelper::StandardButton" + } + ], + "index": 23, + "name": "handleClick", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickLabsPlatformDialog" + } + ] + } + ], + "inputFile": "qquicklabsplatformmessagedialog_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Singleton", + "value": "true" + }, + { + "name": "QML.Element", + "value": "StandardPaths" + }, + { + "name": "QML.Extended", + "value": "QStandardPaths" + }, + { + "name": "QML.ExtensionIsNamespace", + "value": "true" + } + ], + "className": "QQuickLabsPlatformStandardPaths", + "lineNumber": 31, + "methods": [ + { + "access": "public", + "arguments": [ + { + "name": "type", + "type": "QStandardPaths::StandardLocation" + } + ], + "index": 0, + "name": "displayName", + "returnType": "QString" + }, + { + "access": "public", + "arguments": [ + { + "name": "executableName", + "type": "QString" + }, + { + "name": "paths", + "type": "QStringList" + } + ], + "index": 1, + "name": "findExecutable", + "returnType": "QUrl" + }, + { + "access": "public", + "arguments": [ + { + "name": "executableName", + "type": "QString" + } + ], + "index": 2, + "isCloned": true, + "name": "findExecutable", + "returnType": "QUrl" + }, + { + "access": "public", + "arguments": [ + { + "name": "type", + "type": "QStandardPaths::StandardLocation" + }, + { + "name": "fileName", + "type": "QString" + }, + { + "name": "options", + "type": "QStandardPaths::LocateOptions" + } + ], + "index": 3, + "name": "locate", + "returnType": "QUrl" + }, + { + "access": "public", + "arguments": [ + { + "name": "type", + "type": "QStandardPaths::StandardLocation" + }, + { + "name": "fileName", + "type": "QString" + } + ], + "index": 4, + "isCloned": true, + "name": "locate", + "returnType": "QUrl" + }, + { + "access": "public", + "arguments": [ + { + "name": "type", + "type": "QStandardPaths::StandardLocation" + }, + { + "name": "fileName", + "type": "QString" + }, + { + "name": "options", + "type": "QStandardPaths::LocateOptions" + } + ], + "index": 5, + "name": "locateAll", + "returnType": "QList" + }, + { + "access": "public", + "arguments": [ + { + "name": "type", + "type": "QStandardPaths::StandardLocation" + }, + { + "name": "fileName", + "type": "QString" + } + ], + "index": 6, + "isCloned": true, + "name": "locateAll", + "returnType": "QList" + }, + { + "access": "public", + "arguments": [ + { + "name": "testMode", + "type": "bool" + } + ], + "index": 7, + "name": "setTestModeEnabled", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "type", + "type": "QStandardPaths::StandardLocation" + } + ], + "index": 8, + "name": "standardLocations", + "returnType": "QList" + }, + { + "access": "public", + "arguments": [ + { + "name": "type", + "type": "QStandardPaths::StandardLocation" + } + ], + "index": 9, + "name": "writableLocation", + "returnType": "QUrl" + } + ], + "object": true, + "qualifiedClassName": "QQuickLabsPlatformStandardPaths", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qquicklabsplatformstandardpaths_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "SystemTrayIcon" + }, + { + "name": "QML.Extended", + "value": "QPlatformSystemTrayIcon" + }, + { + "name": "QML.ExtensionIsNamespace", + "value": "true" + } + ], + "className": "QQuickLabsPlatformSystemTrayIcon", + "interfaces": [ + [ + { + "className": "QQmlParserStatus", + "id": "\"org.qt-project.Qt.QQmlParserStatus\"" + } + ] + ], + "lineNumber": 33, + "object": true, + "properties": [ + { + "constant": true, + "designable": true, + "final": true, + "index": 0, + "name": "available", + "read": "isAvailable", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 1, + "name": "supportsMessages", + "read": "supportsMessages", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "visible", + "notify": "visibleChanged", + "read": "isVisible", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setVisible" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "tooltip", + "notify": "tooltipChanged", + "read": "tooltip", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setTooltip" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "menu", + "notify": "menuChanged", + "read": "menu", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickLabsPlatformMenu*", + "user": false, + "write": "setMenu" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "geometry", + "notify": "geometryChanged", + "read": "geometry", + "required": false, + "revision": 257, + "scriptable": true, + "stored": true, + "type": "QRect", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 6, + "name": "icon", + "notify": "iconChanged", + "read": "icon", + "required": false, + "revision": 257, + "scriptable": true, + "stored": true, + "type": "QQuickLabsPlatformIcon", + "user": false, + "write": "setIcon" + } + ], + "qualifiedClassName": "QQuickLabsPlatformSystemTrayIcon", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "reason", + "type": "QPlatformSystemTrayIcon::ActivationReason" + } + ], + "index": 0, + "name": "activated", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "messageClicked", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "visibleChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "tooltipChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "menuChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "geometryChanged", + "returnType": "void", + "revision": 513 + }, + { + "access": "public", + "index": 6, + "name": "iconChanged", + "returnType": "void", + "revision": 513 + } + ], + "slots": [ + { + "access": "public", + "index": 7, + "name": "show", + "returnType": "void" + }, + { + "access": "public", + "index": 8, + "name": "hide", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "title", + "type": "QString" + }, + { + "name": "message", + "type": "QString" + }, + { + "name": "iconType", + "type": "QPlatformSystemTrayIcon::MessageIcon" + }, + { + "name": "msecs", + "type": "int" + } + ], + "index": 9, + "name": "showMessage", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "title", + "type": "QString" + }, + { + "name": "message", + "type": "QString" + }, + { + "name": "iconType", + "type": "QPlatformSystemTrayIcon::MessageIcon" + } + ], + "index": 10, + "isCloned": true, + "name": "showMessage", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "title", + "type": "QString" + }, + { + "name": "message", + "type": "QString" + } + ], + "index": 11, + "isCloned": true, + "name": "showMessage", + "returnType": "void" + }, + { + "access": "private", + "index": 12, + "name": "updateIcon", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QQmlParserStatus" + } + ] + } + ], + "inputFile": "qquicklabsplatformsystemtrayicon_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QWidgetPlatformColorDialog", + "lineNumber": 25, + "object": true, + "qualifiedClassName": "QWidgetPlatformColorDialog", + "superClasses": [ + { + "access": "public", + "name": "QPlatformColorDialogHelper" + } + ] + } + ], + "inputFile": "qwidgetplatformcolordialog_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QWidgetPlatformFileDialog", + "lineNumber": 25, + "object": true, + "qualifiedClassName": "QWidgetPlatformFileDialog", + "superClasses": [ + { + "access": "public", + "name": "QPlatformFileDialogHelper" + } + ] + } + ], + "inputFile": "qwidgetplatformfiledialog_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QWidgetPlatformFontDialog", + "lineNumber": 25, + "object": true, + "qualifiedClassName": "QWidgetPlatformFontDialog", + "superClasses": [ + { + "access": "public", + "name": "QPlatformFontDialogHelper" + } + ] + } + ], + "inputFile": "qwidgetplatformfontdialog_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QWidgetPlatformMenu", + "lineNumber": 26, + "object": true, + "qualifiedClassName": "QWidgetPlatformMenu", + "superClasses": [ + { + "access": "public", + "name": "QPlatformMenu" + } + ] + } + ], + "inputFile": "qwidgetplatformmenu_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QWidgetPlatformMenuItem", + "lineNumber": 25, + "object": true, + "qualifiedClassName": "QWidgetPlatformMenuItem", + "superClasses": [ + { + "access": "public", + "name": "QPlatformMenuItem" + } + ] + } + ], + "inputFile": "qwidgetplatformmenuitem_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QWidgetPlatformMessageDialog", + "lineNumber": 25, + "object": true, + "qualifiedClassName": "QWidgetPlatformMessageDialog", + "superClasses": [ + { + "access": "public", + "name": "QPlatformMessageDialogHelper" + } + ] + } + ], + "inputFile": "qwidgetplatformmessagedialog_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QWidgetPlatformSystemTrayIcon", + "lineNumber": 27, + "object": true, + "qualifiedClassName": "QWidgetPlatformSystemTrayIcon", + "superClasses": [ + { + "access": "public", + "name": "QPlatformSystemTrayIcon" + } + ] + } + ], + "inputFile": "qwidgetplatformsystemtrayicon_p.h", + "outputRevision": 68 + } +] diff --git a/qt/6.8.1/msvc2022_64/metatypes/qt6labsqmlmodels_metatypes.json b/qt/6.8.1/msvc2022_64/metatypes/qt6labsqmlmodels_metatypes.json new file mode 100644 index 0000000000000000000000000000000000000000..01e9d84b7a1c0e5b2153bb23f87b50cb429b3acb --- /dev/null +++ b/qt/6.8.1/msvc2022_64/metatypes/qt6labsqmlmodels_metatypes.json @@ -0,0 +1,1127 @@ +[ + { + "classes": [ + { + "classInfos": [ + { + "name": "DefaultProperty", + "value": "delegate" + }, + { + "name": "QML.Element", + "value": "DelegateChoice" + }, + { + "name": "QML.AddedInVersion", + "value": "256" + } + ], + "className": "QQmlDelegateChoice", + "lineNumber": 28, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "roleValue", + "notify": "roleValueChanged", + "read": "roleValue", + "required": false, + "scriptable": true, + "stored": true, + "type": "QVariant", + "user": false, + "write": "setRoleValue" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "row", + "notify": "rowChanged", + "read": "row", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setRow" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "index", + "notify": "indexChanged", + "read": "row", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setRow" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "column", + "notify": "columnChanged", + "read": "column", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setColumn" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "delegate", + "notify": "delegateChanged", + "read": "delegate", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlComponent*", + "user": false, + "write": "setDelegate" + } + ], + "qualifiedClassName": "QQmlDelegateChoice", + "signals": [ + { + "access": "public", + "index": 0, + "name": "roleValueChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "rowChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "indexChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "columnChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "delegateChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "changed", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "classInfos": [ + { + "name": "DefaultProperty", + "value": "choices" + }, + { + "name": "QML.Element", + "value": "DelegateChooser" + }, + { + "name": "QML.AddedInVersion", + "value": "256" + } + ], + "className": "QQmlDelegateChooser", + "lineNumber": 70, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "role", + "notify": "roleChanged", + "read": "role", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setRole" + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 1, + "name": "choices", + "read": "choices", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlListProperty", + "user": false + } + ], + "qualifiedClassName": "QQmlDelegateChooser", + "signals": [ + { + "access": "public", + "index": 0, + "name": "roleChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQmlAbstractDelegateComponent" + } + ] + } + ], + "inputFile": "qqmldelegatecomponent_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "DefaultProperty", + "value": "columns" + }, + { + "name": "QML.Element", + "value": "TableModel" + }, + { + "name": "QML.AddedInVersion", + "value": "256" + } + ], + "className": "QQmlTableModel", + "interfaces": [ + [ + { + "className": "QQmlParserStatus", + "id": "\"org.qt-project.Qt.QQmlParserStatus\"" + } + ] + ], + "lineNumber": 33, + "methods": [ + { + "access": "public", + "arguments": [ + { + "name": "row", + "type": "QVariant" + } + ], + "index": 3, + "name": "appendRow", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "clear", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "rowIndex", + "type": "int" + } + ], + "index": 5, + "name": "getRow", + "returnType": "QVariant" + }, + { + "access": "public", + "arguments": [ + { + "name": "rowIndex", + "type": "int" + }, + { + "name": "row", + "type": "QVariant" + } + ], + "index": 6, + "name": "insertRow", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "fromRowIndex", + "type": "int" + }, + { + "name": "toRowIndex", + "type": "int" + }, + { + "name": "rows", + "type": "int" + } + ], + "index": 7, + "name": "moveRow", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "fromRowIndex", + "type": "int" + }, + { + "name": "toRowIndex", + "type": "int" + } + ], + "index": 8, + "isCloned": true, + "name": "moveRow", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "rowIndex", + "type": "int" + }, + { + "name": "rows", + "type": "int" + } + ], + "index": 9, + "name": "removeRow", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "rowIndex", + "type": "int" + } + ], + "index": 10, + "isCloned": true, + "name": "removeRow", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "rowIndex", + "type": "int" + }, + { + "name": "row", + "type": "QVariant" + } + ], + "index": 11, + "name": "setRow", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "QModelIndex" + }, + { + "name": "role", + "type": "QString" + } + ], + "index": 12, + "name": "data", + "returnType": "QVariant" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "QModelIndex" + }, + { + "name": "role", + "type": "QString" + }, + { + "name": "value", + "type": "QVariant" + } + ], + "index": 13, + "name": "setData", + "returnType": "bool" + } + ], + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "columnCount", + "notify": "columnCountChanged", + "read": "columnCount", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "rowCount", + "notify": "rowCountChanged", + "read": "rowCount", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "rows", + "notify": "rowsChanged", + "read": "rows", + "required": false, + "scriptable": true, + "stored": true, + "type": "QVariant", + "user": false, + "write": "setRows" + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 3, + "name": "columns", + "read": "columns", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlListProperty", + "user": false + } + ], + "qualifiedClassName": "QQmlTableModel", + "signals": [ + { + "access": "public", + "index": 0, + "name": "columnCountChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "rowCountChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "rowsChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QAbstractTableModel" + }, + { + "access": "public", + "name": "QQmlParserStatus" + } + ] + } + ], + "inputFile": "qqmltablemodel_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "TableModelColumn" + }, + { + "name": "QML.AddedInVersion", + "value": "256" + } + ], + "className": "QQmlTableModelColumn", + "lineNumber": 30, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "display", + "notify": "displayChanged", + "read": "display", + "required": false, + "scriptable": true, + "stored": true, + "type": "QJSValue", + "user": false, + "write": "setDisplay" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "setDisplay", + "notify": "setDisplayChanged", + "read": "getSetDisplay", + "required": false, + "scriptable": true, + "stored": true, + "type": "QJSValue", + "user": false, + "write": "setSetDisplay" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "decoration", + "notify": "decorationChanged", + "read": "decoration", + "required": false, + "scriptable": true, + "stored": true, + "type": "QJSValue", + "user": false, + "write": "setDecoration" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "setDecoration", + "notify": "setDecorationChanged", + "read": "getSetDecoration", + "required": false, + "scriptable": true, + "stored": true, + "type": "QJSValue", + "user": false, + "write": "setSetDecoration" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "edit", + "notify": "editChanged", + "read": "edit", + "required": false, + "scriptable": true, + "stored": true, + "type": "QJSValue", + "user": false, + "write": "setEdit" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "setEdit", + "notify": "setEditChanged", + "read": "getSetEdit", + "required": false, + "scriptable": true, + "stored": true, + "type": "QJSValue", + "user": false, + "write": "setSetEdit" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 6, + "name": "toolTip", + "notify": "toolTipChanged", + "read": "toolTip", + "required": false, + "scriptable": true, + "stored": true, + "type": "QJSValue", + "user": false, + "write": "setToolTip" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 7, + "name": "setToolTip", + "notify": "setToolTipChanged", + "read": "getSetToolTip", + "required": false, + "scriptable": true, + "stored": true, + "type": "QJSValue", + "user": false, + "write": "setSetToolTip" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 8, + "name": "statusTip", + "notify": "statusTipChanged", + "read": "statusTip", + "required": false, + "scriptable": true, + "stored": true, + "type": "QJSValue", + "user": false, + "write": "setStatusTip" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 9, + "name": "setStatusTip", + "notify": "setStatusTipChanged", + "read": "getSetStatusTip", + "required": false, + "scriptable": true, + "stored": true, + "type": "QJSValue", + "user": false, + "write": "setSetStatusTip" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 10, + "name": "whatsThis", + "notify": "whatsThisChanged", + "read": "whatsThis", + "required": false, + "scriptable": true, + "stored": true, + "type": "QJSValue", + "user": false, + "write": "setWhatsThis" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 11, + "name": "setWhatsThis", + "notify": "setWhatsThisChanged", + "read": "getSetWhatsThis", + "required": false, + "scriptable": true, + "stored": true, + "type": "QJSValue", + "user": false, + "write": "setSetWhatsThis" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 12, + "name": "font", + "notify": "fontChanged", + "read": "font", + "required": false, + "scriptable": true, + "stored": true, + "type": "QJSValue", + "user": false, + "write": "setFont" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 13, + "name": "setFont", + "notify": "setFontChanged", + "read": "getSetFont", + "required": false, + "scriptable": true, + "stored": true, + "type": "QJSValue", + "user": false, + "write": "setSetFont" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 14, + "name": "textAlignment", + "notify": "textAlignmentChanged", + "read": "textAlignment", + "required": false, + "scriptable": true, + "stored": true, + "type": "QJSValue", + "user": false, + "write": "setTextAlignment" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 15, + "name": "setTextAlignment", + "notify": "setTextAlignmentChanged", + "read": "getSetTextAlignment", + "required": false, + "scriptable": true, + "stored": true, + "type": "QJSValue", + "user": false, + "write": "setSetTextAlignment" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 16, + "name": "background", + "notify": "backgroundChanged", + "read": "background", + "required": false, + "scriptable": true, + "stored": true, + "type": "QJSValue", + "user": false, + "write": "setBackground" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 17, + "name": "setBackground", + "notify": "setBackgroundChanged", + "read": "getSetBackground", + "required": false, + "scriptable": true, + "stored": true, + "type": "QJSValue", + "user": false, + "write": "setSetBackground" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 18, + "name": "foreground", + "notify": "foregroundChanged", + "read": "foreground", + "required": false, + "scriptable": true, + "stored": true, + "type": "QJSValue", + "user": false, + "write": "setForeground" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 19, + "name": "setForeground", + "notify": "setForegroundChanged", + "read": "getSetForeground", + "required": false, + "scriptable": true, + "stored": true, + "type": "QJSValue", + "user": false, + "write": "setSetForeground" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 20, + "name": "checkState", + "notify": "checkStateChanged", + "read": "checkState", + "required": false, + "scriptable": true, + "stored": true, + "type": "QJSValue", + "user": false, + "write": "setCheckState" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 21, + "name": "setCheckState", + "notify": "setCheckStateChanged", + "read": "getSetCheckState", + "required": false, + "scriptable": true, + "stored": true, + "type": "QJSValue", + "user": false, + "write": "setSetCheckState" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 22, + "name": "accessibleText", + "notify": "accessibleTextChanged", + "read": "accessibleText", + "required": false, + "scriptable": true, + "stored": true, + "type": "QJSValue", + "user": false, + "write": "setAccessibleText" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 23, + "name": "setAccessibleText", + "notify": "setAccessibleTextChanged", + "read": "getSetAccessibleText", + "required": false, + "scriptable": true, + "stored": true, + "type": "QJSValue", + "user": false, + "write": "setSetAccessibleText" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 24, + "name": "accessibleDescription", + "notify": "accessibleDescriptionChanged", + "read": "accessibleDescription", + "required": false, + "scriptable": true, + "stored": true, + "type": "QJSValue", + "user": false, + "write": "setAccessibleDescription" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 25, + "name": "setAccessibleDescription", + "notify": "setAccessibleDescriptionChanged", + "read": "getSetAccessibleDescription", + "required": false, + "scriptable": true, + "stored": true, + "type": "QJSValue", + "user": false, + "write": "setSetAccessibleDescription" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 26, + "name": "sizeHint", + "notify": "sizeHintChanged", + "read": "sizeHint", + "required": false, + "scriptable": true, + "stored": true, + "type": "QJSValue", + "user": false, + "write": "setSizeHint" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 27, + "name": "setSizeHint", + "notify": "setSizeHintChanged", + "read": "getSetSizeHint", + "required": false, + "scriptable": true, + "stored": true, + "type": "QJSValue", + "user": false, + "write": "setSetSizeHint" + } + ], + "qualifiedClassName": "QQmlTableModelColumn", + "signals": [ + { + "access": "public", + "index": 0, + "name": "indexChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "displayChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "setDisplayChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "decorationChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "setDecorationChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "editChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "setEditChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "toolTipChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 8, + "name": "setToolTipChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 9, + "name": "statusTipChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 10, + "name": "setStatusTipChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 11, + "name": "whatsThisChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 12, + "name": "setWhatsThisChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 13, + "name": "fontChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 14, + "name": "setFontChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 15, + "name": "textAlignmentChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 16, + "name": "setTextAlignmentChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 17, + "name": "backgroundChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 18, + "name": "setBackgroundChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 19, + "name": "foregroundChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 20, + "name": "setForegroundChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 21, + "name": "checkStateChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 22, + "name": "setCheckStateChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 23, + "name": "accessibleTextChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 24, + "name": "setAccessibleTextChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 25, + "name": "accessibleDescriptionChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 26, + "name": "setAccessibleDescriptionChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 27, + "name": "sizeHintChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 28, + "name": "setSizeHintChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qqmltablemodelcolumn_p.h", + "outputRevision": 68 + } +] diff --git a/qt/6.8.1/msvc2022_64/metatypes/qt6labssettings_metatypes.json b/qt/6.8.1/msvc2022_64/metatypes/qt6labssettings_metatypes.json new file mode 100644 index 0000000000000000000000000000000000000000..7a6bc9be0b09fbee9dee53088034097db2f96527 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/metatypes/qt6labssettings_metatypes.json @@ -0,0 +1,133 @@ +[ + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "Settings" + }, + { + "name": "QML.AddedInVersion", + "value": "256" + } + ], + "className": "QQmlSettings", + "interfaces": [ + [ + { + "className": "QQmlParserStatus", + "id": "\"org.qt-project.Qt.QQmlParserStatus\"" + } + ] + ], + "lineNumber": 29, + "methods": [ + { + "access": "public", + "arguments": [ + { + "name": "key", + "type": "QString" + }, + { + "name": "defaultValue", + "type": "QVariant" + } + ], + "index": 1, + "name": "value", + "returnType": "QVariant" + }, + { + "access": "public", + "arguments": [ + { + "name": "key", + "type": "QString" + } + ], + "index": 2, + "isCloned": true, + "name": "value", + "returnType": "QVariant" + }, + { + "access": "public", + "arguments": [ + { + "name": "key", + "type": "QString" + }, + { + "name": "value", + "type": "QVariant" + } + ], + "index": 3, + "name": "setValue", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "sync", + "returnType": "void" + } + ], + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "category", + "read": "category", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setCategory" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "fileName", + "read": "fileName", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setFileName" + } + ], + "qualifiedClassName": "QQmlSettings", + "slots": [ + { + "access": "private", + "index": 0, + "name": "_q_propertyChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QQmlParserStatus" + } + ] + } + ], + "inputFile": "qqmlsettings_p.h", + "outputRevision": 68 + } +] diff --git a/qt/6.8.1/msvc2022_64/metatypes/qt6labssharedimage_metatypes.json b/qt/6.8.1/msvc2022_64/metatypes/qt6labssharedimage_metatypes.json new file mode 100644 index 0000000000000000000000000000000000000000..9873fb03fd41ad4920c35f9f2dbe669891c1c881 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/metatypes/qt6labssharedimage_metatypes.json @@ -0,0 +1,48 @@ +[ + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.AddedInVersion", + "value": "256" + } + ], + "className": "QSharedImageLoader", + "lineNumber": 31, + "object": true, + "qualifiedClassName": "QSharedImageLoader", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qsharedimageloader_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QuickSharedImageLoader", + "lineNumber": 30, + "object": true, + "qualifiedClassName": "QuickSharedImageLoader", + "superClasses": [ + { + "access": "public", + "name": "QSharedImageLoader" + } + ] + } + ], + "inputFile": "qsharedimageprovider_p.h", + "outputRevision": 68 + } +] diff --git a/qt/6.8.1/msvc2022_64/metatypes/qt6labswavefrontmesh_metatypes.json b/qt/6.8.1/msvc2022_64/metatypes/qt6labswavefrontmesh_metatypes.json new file mode 100644 index 0000000000000000000000000000000000000000..82bf101389c1ffcabe556993d85e5421f2164ce4 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/metatypes/qt6labswavefrontmesh_metatypes.json @@ -0,0 +1,145 @@ +[ + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "WavefrontMesh" + }, + { + "name": "QML.AddedInVersion", + "value": "256" + } + ], + "className": "QWavefrontMesh", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "Error", + "values": [ + "NoError", + "InvalidSourceError", + "UnsupportedFaceShapeError", + "UnsupportedIndexSizeError", + "FileNotFoundError", + "NoAttributesError", + "MissingPositionAttributeError", + "MissingTextureCoordinateAttributeError", + "MissingPositionAndTextureCoordinateAttributesError", + "TooManyAttributesError", + "InvalidPlaneDefinitionError" + ] + } + ], + "lineNumber": 28, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "source", + "notify": "sourceChanged", + "read": "source", + "required": false, + "scriptable": true, + "stored": true, + "type": "QUrl", + "user": false, + "write": "setSource" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "lastError", + "notify": "lastErrorChanged", + "read": "lastError", + "required": false, + "scriptable": true, + "stored": true, + "type": "Error", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "projectionPlaneV", + "notify": "projectionPlaneVChanged", + "read": "projectionPlaneV", + "required": false, + "scriptable": true, + "stored": true, + "type": "QVector3D", + "user": false, + "write": "setProjectionPlaneV" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "projectionPlaneW", + "notify": "projectionPlaneWChanged", + "read": "projectionPlaneW", + "required": false, + "scriptable": true, + "stored": true, + "type": "QVector3D", + "user": false, + "write": "setProjectionPlaneW" + } + ], + "qualifiedClassName": "QWavefrontMesh", + "signals": [ + { + "access": "public", + "index": 0, + "name": "sourceChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "lastErrorChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "projectionPlaneVChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "projectionPlaneWChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "protected", + "index": 4, + "name": "readData", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickShaderEffectMesh" + } + ] + } + ], + "inputFile": "qwavefrontmesh_p.h", + "outputRevision": 68 + } +] diff --git a/qt/6.8.1/msvc2022_64/metatypes/qt6network_metatypes.json b/qt/6.8.1/msvc2022_64/metatypes/qt6network_metatypes.json new file mode 100644 index 0000000000000000000000000000000000000000..c599046345c71fb64b82b1a9e7485fc78528f708 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/metatypes/qt6network_metatypes.json @@ -0,0 +1,5197 @@ +[ + { + "classes": [ + { + "className": "QNetworkConnectionMonitor", + "lineNumber": 28, + "object": true, + "qualifiedClassName": "QNetworkConnectionMonitor", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "isOnline", + "type": "bool" + } + ], + "index": 0, + "name": "reachabilityChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qnetconmonitor_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QHttpHeaders", + "enums": [ + { + "isClass": true, + "isFlag": false, + "name": "WellKnownHeader", + "values": [ + "AIM", + "Accept", + "AcceptAdditions", + "AcceptCH", + "AcceptDatetime", + "AcceptEncoding", + "AcceptFeatures", + "AcceptLanguage", + "AcceptPatch", + "AcceptPost", + "AcceptRanges", + "AcceptSignature", + "AccessControlAllowCredentials", + "AccessControlAllowHeaders", + "AccessControlAllowMethods", + "AccessControlAllowOrigin", + "AccessControlExposeHeaders", + "AccessControlMaxAge", + "AccessControlRequestHeaders", + "AccessControlRequestMethod", + "Age", + "Allow", + "ALPN", + "AltSvc", + "AltUsed", + "Alternates", + "ApplyToRedirectRef", + "AuthenticationControl", + "AuthenticationInfo", + "Authorization", + "CacheControl", + "CacheStatus", + "CalManagedID", + "CalDAVTimezones", + "CapsuleProtocol", + "CDNCacheControl", + "CDNLoop", + "CertNotAfter", + "CertNotBefore", + "ClearSiteData", + "ClientCert", + "ClientCertChain", + "Close", + "Connection", + "ContentDigest", + "ContentDisposition", + "ContentEncoding", + "ContentID", + "ContentLanguage", + "ContentLength", + "ContentLocation", + "ContentRange", + "ContentSecurityPolicy", + "ContentSecurityPolicyReportOnly", + "ContentType", + "Cookie", + "CrossOriginEmbedderPolicy", + "CrossOriginEmbedderPolicyReportOnly", + "CrossOriginOpenerPolicy", + "CrossOriginOpenerPolicyReportOnly", + "CrossOriginResourcePolicy", + "DASL", + "Date", + "DAV", + "DeltaBase", + "Depth", + "Destination", + "DifferentialID", + "DPoP", + "DPoPNonce", + "EarlyData", + "ETag", + "Expect", + "ExpectCT", + "Expires", + "Forwarded", + "From", + "Hobareg", + "Host", + "If", + "IfMatch", + "IfModifiedSince", + "IfNoneMatch", + "IfRange", + "IfScheduleTagMatch", + "IfUnmodifiedSince", + "IM", + "IncludeReferredTokenBindingID", + "KeepAlive", + "Label", + "LastEventID", + "LastModified", + "Link", + "Location", + "LockToken", + "MaxForwards", + "MementoDatetime", + "Meter", + "MIMEVersion", + "Negotiate", + "NEL", + "ODataEntityId", + "ODataIsolation", + "ODataMaxVersion", + "ODataVersion", + "OptionalWWWAuthenticate", + "OrderingType", + "Origin", + "OriginAgentCluster", + "OSCORE", + "OSLCCoreVersion", + "Overwrite", + "PingFrom", + "PingTo", + "Position", + "Prefer", + "PreferenceApplied", + "Priority", + "ProxyAuthenticate", + "ProxyAuthenticationInfo", + "ProxyAuthorization", + "ProxyStatus", + "PublicKeyPins", + "PublicKeyPinsReportOnly", + "Range", + "RedirectRef", + "Referer", + "Refresh", + "ReplayNonce", + "ReprDigest", + "RetryAfter", + "ScheduleReply", + "ScheduleTag", + "SecPurpose", + "SecTokenBinding", + "SecWebSocketAccept", + "SecWebSocketExtensions", + "SecWebSocketKey", + "SecWebSocketProtocol", + "SecWebSocketVersion", + "Server", + "ServerTiming", + "SetCookie", + "Signature", + "SignatureInput", + "SLUG", + "SoapAction", + "StatusURI", + "StrictTransportSecurity", + "Sunset", + "SurrogateCapability", + "SurrogateControl", + "TCN", + "TE", + "Timeout", + "Topic", + "Traceparent", + "Tracestate", + "Trailer", + "TransferEncoding", + "TTL", + "Upgrade", + "Urgency", + "UserAgent", + "VariantVary", + "Vary", + "Via", + "WantContentDigest", + "WantReprDigest", + "WWWAuthenticate", + "XContentTypeOptions", + "XFrameOptions", + "AcceptCharset", + "CPEPInfo", + "Pragma", + "ProtocolInfo", + "ProtocolQuery" + ] + } + ], + "gadget": true, + "lineNumber": 19, + "qualifiedClassName": "QHttpHeaders" + } + ], + "inputFile": "qhttpheaders.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QSslPreSharedKeyAuthenticator", + "gadget": true, + "lineNumber": 17, + "qualifiedClassName": "QSslPreSharedKeyAuthenticator" + } + ], + "inputFile": "qsslpresharedkeyauthenticator.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QAbstractNetworkCache", + "lineNumber": 78, + "object": true, + "qualifiedClassName": "QAbstractNetworkCache", + "slots": [ + { + "access": "public", + "index": 0, + "name": "clear", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qabstractnetworkcache.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QAbstractSocket", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "SocketType", + "values": [ + "TcpSocket", + "UdpSocket", + "SctpSocket", + "UnknownSocketType" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "NetworkLayerProtocol", + "values": [ + "IPv4Protocol", + "IPv6Protocol", + "AnyIPProtocol", + "UnknownNetworkLayerProtocol" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "SocketError", + "values": [ + "ConnectionRefusedError", + "RemoteHostClosedError", + "HostNotFoundError", + "SocketAccessError", + "SocketResourceError", + "SocketTimeoutError", + "DatagramTooLargeError", + "NetworkError", + "AddressInUseError", + "SocketAddressNotAvailableError", + "UnsupportedSocketOperationError", + "UnfinishedSocketOperationError", + "ProxyAuthenticationRequiredError", + "SslHandshakeFailedError", + "ProxyConnectionRefusedError", + "ProxyConnectionClosedError", + "ProxyConnectionTimeoutError", + "ProxyNotFoundError", + "ProxyProtocolError", + "OperationError", + "SslInternalError", + "SslInvalidUserDataError", + "TemporaryError", + "UnknownSocketError" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "SocketState", + "values": [ + "UnconnectedState", + "HostLookupState", + "ConnectingState", + "ConnectedState", + "BoundState", + "ListeningState", + "ClosingState" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "SocketOption", + "values": [ + "LowDelayOption", + "KeepAliveOption", + "MulticastTtlOption", + "MulticastLoopbackOption", + "TypeOfServiceOption", + "SendBufferSizeSocketOption", + "ReceiveBufferSizeSocketOption", + "PathMtuSocketOption" + ] + } + ], + "lineNumber": 30, + "object": true, + "qualifiedClassName": "QAbstractSocket", + "signals": [ + { + "access": "public", + "index": 0, + "name": "hostFound", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "connected", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "disconnected", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QAbstractSocket::SocketState" + } + ], + "index": 3, + "name": "stateChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QAbstractSocket::SocketError" + } + ], + "index": 4, + "name": "errorOccurred", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "proxy", + "type": "QNetworkProxy" + }, + { + "name": "authenticator", + "type": "QAuthenticator*" + } + ], + "index": 5, + "name": "proxyAuthenticationRequired", + "returnType": "void" + } + ], + "slots": [ + { + "access": "private", + "index": 6, + "name": "_q_connectToNextAddress", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "type": "QHostInfo" + } + ], + "index": 7, + "name": "_q_startConnecting", + "returnType": "void" + }, + { + "access": "private", + "index": 8, + "name": "_q_abortConnectionAttempt", + "returnType": "void" + }, + { + "access": "private", + "index": 9, + "name": "_q_testConnection", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QIODevice" + } + ] + } + ], + "inputFile": "qabstractsocket.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QAbstractSocketEngine", + "lineNumber": 50, + "object": true, + "qualifiedClassName": "QAbstractSocketEngine", + "slots": [ + { + "access": "public", + "index": 0, + "name": "readNotification", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "writeNotification", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "closeNotification", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "exceptionNotification", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "connectionNotification", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "proxy", + "type": "QNetworkProxy" + }, + { + "name": "authenticator", + "type": "QAuthenticator*" + } + ], + "index": 5, + "name": "proxyAuthenticationRequired", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qabstractsocketengine_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QAuthenticator", + "gadget": true, + "lineNumber": 17, + "qualifiedClassName": "QAuthenticator" + } + ], + "inputFile": "qauthenticator.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "RegisterEnumClassesUnscoped", + "value": "false" + } + ], + "className": "QDnsTlsAssociationRecord", + "enums": [ + { + "isClass": true, + "isFlag": false, + "name": "CertificateUsage", + "type": "quint8", + "values": [ + "CertificateAuthorityConstrait", + "ServiceCertificateConstraint", + "TrustAnchorAssertion", + "DomainIssuedCertificate", + "PrivateUse", + "PKIX_TA", + "PKIX_EE", + "DANE_TA", + "DANE_EE", + "PrivCert" + ] + }, + { + "isClass": true, + "isFlag": false, + "name": "Selector", + "type": "quint8", + "values": [ + "FullCertificate", + "SubjectPublicKeyInfo", + "PrivateUse", + "Cert", + "SPKI", + "PrivSel" + ] + }, + { + "isClass": true, + "isFlag": false, + "name": "MatchingType", + "type": "quint8", + "values": [ + "Exact", + "Sha256", + "Sha512", + "PrivateUse", + "PrivMatch" + ] + } + ], + "gadget": true, + "lineNumber": 144, + "qualifiedClassName": "QDnsTlsAssociationRecord" + }, + { + "className": "QDnsLookup", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "Error", + "values": [ + "NoError", + "ResolverError", + "OperationCancelledError", + "InvalidRequestError", + "InvalidReplyError", + "ServerFailureError", + "ServerRefusedError", + "NotFoundError", + "TimeoutError" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "Type", + "values": [ + "A", + "AAAA", + "ANY", + "CNAME", + "MX", + "NS", + "PTR", + "SRV", + "TLSA", + "TXT" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "Protocol", + "type": "quint8", + "values": [ + "Standard", + "DnsOverTls" + ] + } + ], + "lineNumber": 215, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "error", + "notify": "finished", + "read": "error", + "required": false, + "scriptable": true, + "stored": true, + "type": "Error", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "authenticData", + "notify": "finished", + "read": "isAuthenticData", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "errorString", + "notify": "finished", + "read": "errorString", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + }, + { + "bindable": "bindableName", + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "name", + "notify": "nameChanged", + "read": "name", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setName" + }, + { + "bindable": "bindableType", + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "type", + "notify": "typeChanged", + "read": "type", + "required": false, + "scriptable": true, + "stored": true, + "type": "Type", + "user": false, + "write": "setType" + }, + { + "bindable": "bindableNameserver", + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "nameserver", + "notify": "nameserverChanged", + "read": "nameserver", + "required": false, + "scriptable": true, + "stored": true, + "type": "QHostAddress", + "user": false, + "write": "setNameserver" + }, + { + "bindable": "bindableNameserverPort", + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "nameserverPort", + "notify": "nameserverPortChanged", + "read": "nameserverPort", + "required": false, + "scriptable": true, + "stored": true, + "type": "quint16", + "user": false, + "write": "setNameserverPort" + }, + { + "bindable": "bindableNameserverProtocol", + "constant": false, + "designable": true, + "final": false, + "index": 7, + "name": "nameserverProtocol", + "notify": "nameserverProtocolChanged", + "read": "nameserverProtocol", + "required": false, + "scriptable": true, + "stored": true, + "type": "Protocol", + "user": false, + "write": "setNameserverProtocol" + } + ], + "qualifiedClassName": "QDnsLookup", + "signals": [ + { + "access": "public", + "index": 0, + "name": "finished", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "name", + "type": "QString" + } + ], + "index": 1, + "name": "nameChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "type", + "type": "QDnsLookup::Type" + } + ], + "index": 2, + "name": "typeChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "nameserver", + "type": "QHostAddress" + } + ], + "index": 3, + "name": "nameserverChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "port", + "type": "quint16" + } + ], + "index": 4, + "name": "nameserverPortChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "protocol", + "type": "QDnsLookup::Protocol" + } + ], + "index": 5, + "name": "nameserverProtocolChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "index": 6, + "name": "abort", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "lookup", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qdnslookup.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QDnsLookupRunnable", + "lineNumber": 197, + "object": true, + "qualifiedClassName": "QDnsLookupRunnable", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "reply", + "type": "QDnsLookupReply" + } + ], + "index": 0, + "name": "finished", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QRunnable" + } + ] + } + ], + "inputFile": "qdnslookup_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QDtlsClientVerifier", + "lineNumber": 43, + "object": true, + "qualifiedClassName": "QDtlsClientVerifier", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "className": "QDtls", + "lineNumber": 82, + "object": true, + "qualifiedClassName": "QDtls", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "authenticator", + "type": "QSslPreSharedKeyAuthenticator*" + } + ], + "index": 0, + "name": "pskRequired", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "handshakeTimeout", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qdtls.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QHostAddress", + "gadget": true, + "lineNumber": 38, + "qualifiedClassName": "QHostAddress" + } + ], + "inputFile": "qhostaddress.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QHostInfo", + "gadget": true, + "lineNumber": 18, + "qualifiedClassName": "QHostInfo" + } + ], + "inputFile": "qhostinfo.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QHostInfoResult", + "lineNumber": 42, + "object": true, + "qualifiedClassName": "QHostInfoResult", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "info", + "type": "QHostInfo" + } + ], + "index": 0, + "name": "resultsReady", + "returnType": "void" + } + ], + "slots": [ + { + "access": "private", + "arguments": [ + { + "name": "info", + "type": "QHostInfo" + } + ], + "index": 1, + "name": "finalizePostResultsReady", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qhostinfo_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QHttp2Stream", + "enums": [ + { + "isClass": true, + "isFlag": false, + "name": "State", + "values": [ + "Idle", + "ReservedRemote", + "Open", + "HalfClosedLocal", + "HalfClosedRemote", + "Closed" + ] + } + ], + "lineNumber": 93, + "object": true, + "qualifiedClassName": "QHttp2Stream", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "headers", + "type": "HPack::HttpHeader" + }, + { + "name": "endStream", + "type": "bool" + } + ], + "index": 0, + "name": "headersReceived", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "headersUpdated", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "errorCode", + "type": "Http2::Http2Error" + }, + { + "name": "errorString", + "type": "QString" + } + ], + "index": 2, + "name": "errorOccurred", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "newState", + "type": "QHttp2Stream::State" + } + ], + "index": 3, + "name": "stateChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "newStreamID", + "type": "quint32" + } + ], + "index": 4, + "name": "promisedStreamReceived", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "uploadBlocked", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "data", + "type": "QByteArray" + }, + { + "name": "endStream", + "type": "bool" + } + ], + "index": 6, + "name": "dataReceived", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "errorCode", + "type": "quint32" + } + ], + "index": 7, + "name": "rstFrameRecived", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "bytesWritten", + "type": "qint64" + } + ], + "index": 8, + "name": "bytesWritten", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "errorString", + "type": "QString" + } + ], + "index": 9, + "name": "uploadDeviceError", + "returnType": "void" + }, + { + "access": "public", + "index": 10, + "name": "uploadFinished", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "errorCode", + "type": "Http2::Http2Error" + } + ], + "index": 11, + "name": "sendRST_STREAM", + "returnType": "bool" + }, + { + "access": "public", + "arguments": [ + { + "name": "headers", + "type": "HPack::HttpHeader" + }, + { + "name": "endStream", + "type": "bool" + }, + { + "name": "priority", + "type": "quint8" + } + ], + "index": 12, + "name": "sendHEADERS", + "returnType": "bool" + }, + { + "access": "public", + "arguments": [ + { + "name": "headers", + "type": "HPack::HttpHeader" + }, + { + "name": "endStream", + "type": "bool" + } + ], + "index": 13, + "isCloned": true, + "name": "sendHEADERS", + "returnType": "bool" + }, + { + "access": "public", + "arguments": [ + { + "name": "device", + "type": "QIODevice*" + }, + { + "name": "endStream", + "type": "bool" + } + ], + "index": 14, + "name": "sendDATA", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "device", + "type": "QNonContiguousByteDevice*" + }, + { + "name": "endStream", + "type": "bool" + } + ], + "index": 15, + "name": "sendDATA", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "delta", + "type": "quint32" + } + ], + "index": 16, + "name": "sendWINDOW_UPDATE", + "returnType": "void" + }, + { + "access": "private", + "index": 17, + "name": "maybeResumeUpload", + "returnType": "void" + }, + { + "access": "private", + "index": 18, + "name": "uploadDeviceReadChannelFinished", + "returnType": "void" + }, + { + "access": "private", + "index": 19, + "name": "uploadDeviceDestroyed", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "className": "QHttp2Connection", + "enums": [ + { + "isClass": true, + "isFlag": false, + "name": "CreateStreamError", + "values": [ + "MaxConcurrentStreamsReached", + "StreamIdsExhausted", + "ReceivedGOAWAY", + "UnknownError" + ] + } + ], + "lineNumber": 205, + "object": true, + "qualifiedClassName": "QHttp2Connection", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "stream", + "type": "QHttp2Stream*" + } + ], + "index": 0, + "name": "newIncomingStream", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "stream", + "type": "QHttp2Stream*" + } + ], + "index": 1, + "name": "newPromisedStream", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "errorReceived", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "connectionClosed", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "settingsFrameReceived", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "state", + "type": "QHttp2Connection::PingState" + } + ], + "index": 5, + "name": "pingFrameRecived", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "errorCode", + "type": "Http2::Http2Error" + }, + { + "name": "errorString", + "type": "QString" + } + ], + "index": 6, + "name": "errorOccurred", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "errorCode", + "type": "Http2::Http2Error" + }, + { + "name": "lastStreamID", + "type": "quint32" + } + ], + "index": 7, + "name": "receivedGOAWAY", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "streamID", + "type": "quint32" + } + ], + "index": 8, + "name": "receivedEND_STREAM", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "index": 9, + "name": "sendPing", + "returnType": "bool" + }, + { + "access": "public", + "arguments": [ + { + "name": "data", + "type": "QByteArrayView" + } + ], + "index": 10, + "name": "sendPing", + "returnType": "bool" + }, + { + "access": "public", + "index": 11, + "name": "handleReadyRead", + "returnType": "void" + }, + { + "access": "public", + "index": 12, + "name": "handleConnectionClosure", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qhttp2connection_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QHttp2ProtocolHandler", + "lineNumber": 46, + "methods": [ + { + "access": "public", + "index": 3, + "name": "handleConnectionClosure", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "ensureClientPrefaceSent", + "returnType": "void" + }, + { + "access": "private", + "index": 5, + "name": "_q_receiveReply", + "returnType": "void" + }, + { + "access": "private", + "index": 6, + "name": "sendRequest", + "returnType": "bool" + }, + { + "access": "private", + "arguments": [ + { + "name": "streamID", + "type": "quint32" + }, + { + "name": "delta", + "type": "quint32" + } + ], + "index": 7, + "name": "sendWINDOW_UPDATE", + "returnType": "bool" + }, + { + "access": "private", + "index": 8, + "name": "resumeSuspendedStreams", + "returnType": "void" + } + ], + "object": true, + "qualifiedClassName": "QHttp2ProtocolHandler", + "slots": [ + { + "access": "private", + "index": 0, + "name": "_q_uploadDataReadyRead", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "reply", + "type": "QObject*" + } + ], + "index": 1, + "name": "_q_replyDestroyed", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "uploadData", + "type": "QObject*" + } + ], + "index": 2, + "name": "_q_uploadDataDestroyed", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QAbstractProtocolHandler" + } + ] + } + ], + "inputFile": "qhttp2protocolhandler_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QHttpMultiPart", + "lineNumber": 58, + "object": true, + "qualifiedClassName": "QHttpMultiPart", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qhttpmultipart.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QHttpNetworkConnection", + "lineNumber": 55, + "object": true, + "qualifiedClassName": "QHttpNetworkConnection", + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "isOnline", + "type": "bool" + } + ], + "index": 0, + "name": "onlineStateChanged", + "returnType": "void" + }, + { + "access": "private", + "index": 1, + "name": "_q_startNextRequest", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "type": "QHostInfo" + } + ], + "index": 2, + "name": "_q_hostLookupFinished", + "returnType": "void" + }, + { + "access": "private", + "index": 3, + "name": "_q_connectDelayedChannel", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qhttpnetworkconnection_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QHttpNetworkConnectionChannel", + "lineNumber": 64, + "object": true, + "qualifiedClassName": "QHttpNetworkConnectionChannel", + "slots": [ + { + "access": "protected", + "index": 0, + "name": "_q_receiveReply", + "returnType": "void" + }, + { + "access": "protected", + "arguments": [ + { + "name": "bytes", + "type": "qint64" + } + ], + "index": 1, + "name": "_q_bytesWritten", + "returnType": "void" + }, + { + "access": "protected", + "index": 2, + "name": "_q_readyRead", + "returnType": "void" + }, + { + "access": "protected", + "index": 3, + "name": "_q_disconnected", + "returnType": "void" + }, + { + "access": "protected", + "arguments": [ + { + "name": "socket", + "type": "QAbstractSocket*" + } + ], + "index": 4, + "name": "_q_connected_abstract_socket", + "returnType": "void" + }, + { + "access": "protected", + "arguments": [ + { + "name": "socket", + "type": "QLocalSocket*" + } + ], + "index": 5, + "name": "_q_connected_local_socket", + "returnType": "void" + }, + { + "access": "protected", + "index": 6, + "name": "_q_connected", + "returnType": "void" + }, + { + "access": "protected", + "arguments": [ + { + "type": "QAbstractSocket::SocketError" + } + ], + "index": 7, + "name": "_q_error", + "returnType": "void" + }, + { + "access": "protected", + "arguments": [ + { + "name": "proxy", + "type": "QNetworkProxy" + }, + { + "name": "auth", + "type": "QAuthenticator*" + } + ], + "index": 8, + "name": "_q_proxyAuthenticationRequired", + "returnType": "void" + }, + { + "access": "protected", + "index": 9, + "name": "_q_uploadDataReadyRead", + "returnType": "void" + }, + { + "access": "protected", + "index": 10, + "name": "_q_encrypted", + "returnType": "void" + }, + { + "access": "protected", + "arguments": [ + { + "name": "errors", + "type": "QList" + } + ], + "index": 11, + "name": "_q_sslErrors", + "returnType": "void" + }, + { + "access": "protected", + "arguments": [ + { + "type": "QSslPreSharedKeyAuthenticator*" + } + ], + "index": 12, + "name": "_q_preSharedKeyAuthenticationRequired", + "returnType": "void" + }, + { + "access": "protected", + "arguments": [ + { + "name": "bytes", + "type": "qint64" + } + ], + "index": 13, + "name": "_q_encryptedBytesWritten", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qhttpnetworkconnectionchannel_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QHttpNetworkReply", + "lineNumber": 57, + "object": true, + "qualifiedClassName": "QHttpNetworkReply", + "signals": [ + { + "access": "public", + "index": 0, + "name": "encrypted", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "errors", + "type": "QList" + } + ], + "index": 1, + "name": "sslErrors", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "authenticator", + "type": "QSslPreSharedKeyAuthenticator*" + } + ], + "index": 2, + "name": "preSharedKeyAuthenticationRequired", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "socketStartedConnecting", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "requestSent", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "readyRead", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "finished", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "errorCode", + "type": "QNetworkReply::NetworkError" + }, + { + "name": "detail", + "type": "QString" + } + ], + "index": 7, + "name": "finishedWithError", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "errorCode", + "type": "QNetworkReply::NetworkError" + } + ], + "index": 8, + "isCloned": true, + "name": "finishedWithError", + "returnType": "void" + }, + { + "access": "public", + "index": 9, + "name": "headerChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "done", + "type": "qint64" + }, + { + "name": "total", + "type": "qint64" + } + ], + "index": 10, + "name": "dataReadProgress", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "done", + "type": "qint64" + }, + { + "name": "total", + "type": "qint64" + } + ], + "index": 11, + "name": "dataSendProgress", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "request", + "type": "QHttpNetworkRequest" + }, + { + "name": "authenticator", + "type": "QAuthenticator*" + } + ], + "index": 12, + "name": "cacheCredentials", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "proxy", + "type": "QNetworkProxy" + }, + { + "name": "authenticator", + "type": "QAuthenticator*" + } + ], + "index": 13, + "name": "proxyAuthenticationRequired", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "request", + "type": "QHttpNetworkRequest" + }, + { + "name": "authenticator", + "type": "QAuthenticator*" + } + ], + "index": 14, + "name": "authenticationRequired", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "url", + "type": "QUrl" + }, + { + "name": "httpStatus", + "type": "int" + }, + { + "name": "maxRedirectsRemaining", + "type": "int" + } + ], + "index": 15, + "name": "redirected", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QHttpNetworkHeader" + } + ] + } + ], + "inputFile": "qhttpnetworkreply_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QHttpSocketEngine", + "lineNumber": 36, + "object": true, + "qualifiedClassName": "QHttpSocketEngine", + "slots": [ + { + "access": "public", + "index": 0, + "name": "slotSocketConnected", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "slotSocketDisconnected", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "slotSocketReadNotification", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "slotSocketBytesWritten", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "error", + "type": "QAbstractSocket::SocketError" + } + ], + "index": 4, + "name": "slotSocketError", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "state", + "type": "QAbstractSocket::SocketState" + } + ], + "index": 5, + "name": "slotSocketStateChanged", + "returnType": "void" + }, + { + "access": "private", + "index": 6, + "name": "emitPendingReadNotification", + "returnType": "void" + }, + { + "access": "private", + "index": 7, + "name": "emitPendingWriteNotification", + "returnType": "void" + }, + { + "access": "private", + "index": 8, + "name": "emitPendingConnectionNotification", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QAbstractSocketEngine" + } + ] + } + ], + "inputFile": "qhttpsocketengine_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QHttpThreadDelegate", + "lineNumber": 48, + "object": true, + "qualifiedClassName": "QHttpThreadDelegate", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "request", + "type": "QHttpNetworkRequest" + }, + { + "type": "QAuthenticator*" + } + ], + "index": 0, + "name": "authenticationRequired", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QNetworkProxy" + }, + { + "type": "QAuthenticator*" + } + ], + "index": 1, + "name": "proxyAuthenticationRequired", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "encrypted", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QList" + }, + { + "type": "bool*" + }, + { + "type": "QList*" + } + ], + "index": 3, + "name": "sslErrors", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QSslConfiguration" + } + ], + "index": 4, + "name": "sslConfigurationChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QSslPreSharedKeyAuthenticator*" + } + ], + "index": 5, + "name": "preSharedKeyAuthenticationRequired", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "socketStartedConnecting", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "requestSent", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QHttpHeaders" + }, + { + "type": "int" + }, + { + "type": "QString" + }, + { + "type": "bool" + }, + { + "type": "QSharedPointer" + }, + { + "type": "qint64" + }, + { + "type": "qint64" + }, + { + "type": "bool" + }, + { + "type": "bool" + } + ], + "index": 8, + "name": "downloadMetaData", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "qint64" + }, + { + "type": "qint64" + } + ], + "index": 9, + "name": "downloadProgress", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QByteArray" + } + ], + "index": 10, + "name": "downloadData", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QNetworkReply::NetworkError" + }, + { + "type": "QString" + } + ], + "index": 11, + "name": "error", + "returnType": "void" + }, + { + "access": "public", + "index": 12, + "name": "downloadFinished", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "url", + "type": "QUrl" + }, + { + "name": "httpStatus", + "type": "int" + }, + { + "name": "maxRedirectsRemainig", + "type": "int" + } + ], + "index": 13, + "name": "redirected", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "index": 14, + "name": "startRequest", + "returnType": "void" + }, + { + "access": "public", + "index": 15, + "name": "abortRequest", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "size", + "type": "qint64" + } + ], + "index": 16, + "name": "readBufferSizeChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "size", + "type": "qint64" + } + ], + "index": 17, + "name": "readBufferFreed", + "returnType": "void" + }, + { + "access": "public", + "index": 18, + "name": "startRequestSynchronously", + "returnType": "void" + }, + { + "access": "protected", + "index": 19, + "name": "readyReadSlot", + "returnType": "void" + }, + { + "access": "protected", + "index": 20, + "name": "finishedSlot", + "returnType": "void" + }, + { + "access": "protected", + "arguments": [ + { + "name": "errorCode", + "type": "QNetworkReply::NetworkError" + }, + { + "name": "detail", + "type": "QString" + } + ], + "index": 21, + "name": "finishedWithErrorSlot", + "returnType": "void" + }, + { + "access": "protected", + "arguments": [ + { + "name": "errorCode", + "type": "QNetworkReply::NetworkError" + } + ], + "index": 22, + "isCloned": true, + "name": "finishedWithErrorSlot", + "returnType": "void" + }, + { + "access": "protected", + "index": 23, + "name": "synchronousFinishedSlot", + "returnType": "void" + }, + { + "access": "protected", + "arguments": [ + { + "name": "errorCode", + "type": "QNetworkReply::NetworkError" + }, + { + "name": "detail", + "type": "QString" + } + ], + "index": 24, + "name": "synchronousFinishedWithErrorSlot", + "returnType": "void" + }, + { + "access": "protected", + "arguments": [ + { + "name": "errorCode", + "type": "QNetworkReply::NetworkError" + } + ], + "index": 25, + "isCloned": true, + "name": "synchronousFinishedWithErrorSlot", + "returnType": "void" + }, + { + "access": "protected", + "index": 26, + "name": "headerChangedSlot", + "returnType": "void" + }, + { + "access": "protected", + "index": 27, + "name": "synchronousHeaderChangedSlot", + "returnType": "void" + }, + { + "access": "protected", + "arguments": [ + { + "name": "done", + "type": "qint64" + }, + { + "name": "total", + "type": "qint64" + } + ], + "index": 28, + "name": "dataReadProgressSlot", + "returnType": "void" + }, + { + "access": "protected", + "arguments": [ + { + "name": "request", + "type": "QHttpNetworkRequest" + }, + { + "name": "authenticator", + "type": "QAuthenticator*" + } + ], + "index": 29, + "name": "cacheCredentialsSlot", + "returnType": "void" + }, + { + "access": "protected", + "index": 30, + "name": "encryptedSlot", + "returnType": "void" + }, + { + "access": "protected", + "arguments": [ + { + "name": "errors", + "type": "QList" + } + ], + "index": 31, + "name": "sslErrorsSlot", + "returnType": "void" + }, + { + "access": "protected", + "arguments": [ + { + "name": "authenticator", + "type": "QSslPreSharedKeyAuthenticator*" + } + ], + "index": 32, + "name": "preSharedKeyAuthenticationRequiredSlot", + "returnType": "void" + }, + { + "access": "protected", + "arguments": [ + { + "name": "request", + "type": "QHttpNetworkRequest" + }, + { + "type": "QAuthenticator*" + } + ], + "index": 33, + "name": "synchronousAuthenticationRequiredSlot", + "returnType": "void" + }, + { + "access": "protected", + "arguments": [ + { + "type": "QNetworkProxy" + }, + { + "type": "QAuthenticator*" + } + ], + "index": 34, + "name": "synchronousProxyAuthenticationRequiredSlot", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "className": "QNonContiguousByteDeviceThreadForwardImpl", + "lineNumber": 163, + "object": true, + "qualifiedClassName": "QNonContiguousByteDeviceThreadForwardImpl", + "signals": [ + { + "access": "public", + "arguments": [ + { + "type": "qint64" + } + ], + "index": 0, + "name": "wantData", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "pos", + "type": "qint64" + }, + { + "name": "amount", + "type": "qint64" + } + ], + "index": 1, + "name": "processedData", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "b", + "type": "bool*" + } + ], + "index": 2, + "name": "resetData", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "pos", + "type": "qint64" + }, + { + "name": "dataArray", + "type": "QByteArray" + }, + { + "name": "dataAtEnd", + "type": "bool" + }, + { + "name": "dataSize", + "type": "qint64" + } + ], + "index": 3, + "name": "haveDataSlot", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QNonContiguousByteDevice" + } + ] + } + ], + "inputFile": "qhttpthreaddelegate_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QLocalServer", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "SocketOption", + "values": [ + "NoOptions", + "UserAccessOption", + "GroupAccessOption", + "OtherAccessOption", + "WorldAccessOption", + "AbstractNamespaceOption" + ] + }, + { + "alias": "SocketOption", + "isClass": false, + "isFlag": true, + "name": "SocketOptions", + "values": [ + "NoOptions", + "UserAccessOption", + "GroupAccessOption", + "OtherAccessOption", + "WorldAccessOption", + "AbstractNamespaceOption" + ] + } + ], + "lineNumber": 19, + "object": true, + "properties": [ + { + "bindable": "bindableSocketOptions", + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "socketOptions", + "read": "socketOptions", + "required": false, + "scriptable": true, + "stored": true, + "type": "SocketOptions", + "user": false, + "write": "setSocketOptions" + } + ], + "qualifiedClassName": "QLocalServer", + "signals": [ + { + "access": "public", + "index": 0, + "name": "newConnection", + "returnType": "void" + } + ], + "slots": [ + { + "access": "private", + "index": 1, + "name": "_q_onNewConnection", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qlocalserver.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QLocalSocket", + "enums": [ + { + "alias": "SocketOption", + "isClass": false, + "isFlag": true, + "name": "SocketOptions", + "values": [ + "NoOptions", + "AbstractNamespaceOption" + ] + } + ], + "lineNumber": 21, + "object": true, + "properties": [ + { + "bindable": "bindableSocketOptions", + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "socketOptions", + "read": "socketOptions", + "required": false, + "scriptable": true, + "stored": true, + "type": "SocketOptions", + "user": false, + "write": "setSocketOptions" + } + ], + "qualifiedClassName": "QLocalSocket", + "signals": [ + { + "access": "public", + "index": 0, + "name": "connected", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "disconnected", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "socketError", + "type": "QLocalSocket::LocalSocketError" + } + ], + "index": 2, + "name": "errorOccurred", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "socketState", + "type": "QLocalSocket::LocalSocketState" + } + ], + "index": 3, + "name": "stateChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "private", + "index": 4, + "name": "_q_pipeClosed", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "type": "ulong" + }, + { + "type": "QString" + } + ], + "index": 5, + "name": "_q_winError", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QIODevice" + } + ] + } + ], + "inputFile": "qlocalsocket.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QNativeSocketEngine", + "lineNumber": 101, + "object": true, + "qualifiedClassName": "QNativeSocketEngine", + "slots": [ + { + "access": "public", + "index": 0, + "name": "connectionNotification", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QAbstractSocketEngine" + } + ] + } + ], + "inputFile": "qnativesocketengine_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QNetworkAccessBackend", + "enums": [ + { + "isClass": true, + "isFlag": false, + "name": "TargetType", + "values": [ + "Networked", + "Local" + ] + }, + { + "isClass": true, + "isFlag": false, + "name": "SecurityFeature", + "values": [ + "None", + "TLS" + ] + }, + { + "isClass": true, + "isFlag": false, + "name": "IOFeature", + "values": [ + "None", + "ZeroCopy", + "NeedResetableUpload", + "SupportsSynchronousMode" + ] + } + ], + "lineNumber": 38, + "object": true, + "qualifiedClassName": "QNetworkAccessBackend", + "slots": [ + { + "access": "public", + "index": 0, + "name": "readyRead", + "returnType": "void" + }, + { + "access": "protected", + "index": 1, + "name": "finished", + "returnType": "void" + }, + { + "access": "protected", + "arguments": [ + { + "name": "code", + "type": "QNetworkReply::NetworkError" + }, + { + "name": "errorString", + "type": "QString" + } + ], + "index": 2, + "name": "error", + "returnType": "void" + }, + { + "access": "protected", + "arguments": [ + { + "name": "proxy", + "type": "QNetworkProxy" + }, + { + "name": "auth", + "type": "QAuthenticator*" + } + ], + "index": 3, + "name": "proxyAuthenticationRequired", + "returnType": "void" + }, + { + "access": "protected", + "arguments": [ + { + "name": "auth", + "type": "QAuthenticator*" + } + ], + "index": 4, + "name": "authenticationRequired", + "returnType": "void" + }, + { + "access": "protected", + "index": 5, + "name": "metaDataChanged", + "returnType": "void" + }, + { + "access": "protected", + "arguments": [ + { + "name": "destination", + "type": "QUrl" + } + ], + "index": 6, + "name": "redirectionRequested", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "className": "QNetworkAccessBackendFactory", + "lineNumber": 145, + "object": true, + "qualifiedClassName": "QNetworkAccessBackendFactory", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qnetworkaccessbackend_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QNetworkAccessCache", + "lineNumber": 34, + "object": true, + "qualifiedClassName": "QNetworkAccessCache", + "signals": [ + { + "access": "public", + "arguments": [ + { + "type": "QNetworkAccessCache::CacheableObject*" + } + ], + "index": 0, + "name": "entryReady", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qnetworkaccesscache_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QNetworkAccessFileBackend", + "lineNumber": 26, + "object": true, + "qualifiedClassName": "QNetworkAccessFileBackend", + "slots": [ + { + "access": "public", + "index": 0, + "name": "uploadReadyReadSlot", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QNetworkAccessBackend" + } + ] + } + ], + "inputFile": "qnetworkaccessfilebackend_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QNetworkAccessManager", + "lineNumber": 35, + "object": true, + "qualifiedClassName": "QNetworkAccessManager", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "proxy", + "type": "QNetworkProxy" + }, + { + "name": "authenticator", + "type": "QAuthenticator*" + } + ], + "index": 0, + "name": "proxyAuthenticationRequired", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "reply", + "type": "QNetworkReply*" + }, + { + "name": "authenticator", + "type": "QAuthenticator*" + } + ], + "index": 1, + "name": "authenticationRequired", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "reply", + "type": "QNetworkReply*" + } + ], + "index": 2, + "name": "finished", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "reply", + "type": "QNetworkReply*" + } + ], + "index": 3, + "name": "encrypted", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "reply", + "type": "QNetworkReply*" + }, + { + "name": "errors", + "type": "QList" + } + ], + "index": 4, + "name": "sslErrors", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "reply", + "type": "QNetworkReply*" + }, + { + "name": "authenticator", + "type": "QSslPreSharedKeyAuthenticator*" + } + ], + "index": 5, + "name": "preSharedKeyAuthenticationRequired", + "returnType": "void" + } + ], + "slots": [ + { + "access": "protected", + "index": 6, + "name": "supportedSchemesImplementation", + "returnType": "QStringList" + }, + { + "access": "private", + "arguments": [ + { + "type": "QList" + } + ], + "index": 7, + "name": "_q_replySslErrors", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "type": "QSslPreSharedKeyAuthenticator*" + } + ], + "index": 8, + "name": "_q_replyPreSharedKeyAuthenticationRequired", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qnetworkaccessmanager.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QNetworkCookie", + "enums": [ + { + "isClass": true, + "isFlag": false, + "name": "SameSite", + "values": [ + "Default", + "None", + "Lax", + "Strict" + ] + } + ], + "gadget": true, + "lineNumber": 22, + "qualifiedClassName": "QNetworkCookie" + } + ], + "inputFile": "qnetworkcookie.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QNetworkCookieJar", + "lineNumber": 17, + "object": true, + "qualifiedClassName": "QNetworkCookieJar", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qnetworkcookiejar.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QNetworkDiskCache", + "lineNumber": 15, + "object": true, + "qualifiedClassName": "QNetworkDiskCache", + "slots": [ + { + "access": "public", + "index": 0, + "name": "clear", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QAbstractNetworkCache" + } + ] + } + ], + "inputFile": "qnetworkdiskcache.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QNetworkFile", + "lineNumber": 24, + "object": true, + "qualifiedClassName": "QNetworkFile", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "ok", + "type": "bool" + } + ], + "index": 0, + "name": "finished", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QHttpHeaders::WellKnownHeader" + }, + { + "name": "value", + "type": "QByteArray" + } + ], + "index": 1, + "name": "headerRead", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "error", + "type": "QNetworkReply::NetworkError" + }, + { + "name": "message", + "type": "QString" + } + ], + "index": 2, + "name": "networkError", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "index": 3, + "name": "open", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "close", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QFile" + } + ] + } + ], + "inputFile": "qnetworkfile_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "RegisterEnumClassesUnscoped", + "value": "false" + } + ], + "className": "QNetworkInformation", + "enums": [ + { + "isClass": true, + "isFlag": false, + "name": "Reachability", + "values": [ + "Unknown", + "Disconnected", + "Local", + "Site", + "Online" + ] + }, + { + "isClass": true, + "isFlag": false, + "name": "TransportMedium", + "values": [ + "Unknown", + "Ethernet", + "Cellular", + "WiFi", + "Bluetooth" + ] + }, + { + "alias": "Feature", + "isClass": true, + "isFlag": true, + "name": "Features", + "values": [ + "Reachability", + "CaptivePortal", + "TransportMedium", + "Metered" + ] + } + ], + "lineNumber": 17, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "reachability", + "notify": "reachabilityChanged", + "read": "reachability", + "required": false, + "scriptable": true, + "stored": true, + "type": "Reachability", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "isBehindCaptivePortal", + "notify": "isBehindCaptivePortalChanged", + "read": "isBehindCaptivePortal", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "transportMedium", + "notify": "transportMediumChanged", + "read": "transportMedium", + "required": false, + "scriptable": true, + "stored": true, + "type": "TransportMedium", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "isMetered", + "notify": "isMeteredChanged", + "read": "isMetered", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + } + ], + "qualifiedClassName": "QNetworkInformation", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "newReachability", + "type": "QNetworkInformation::Reachability" + } + ], + "index": 0, + "name": "reachabilityChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "state", + "type": "bool" + } + ], + "index": 1, + "name": "isBehindCaptivePortalChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "current", + "type": "QNetworkInformation::TransportMedium" + } + ], + "index": 2, + "name": "transportMediumChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "isMetered", + "type": "bool" + } + ], + "index": 3, + "name": "isMeteredChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qnetworkinformation.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QNetworkInformationBackend", + "lineNumber": 27, + "object": true, + "qualifiedClassName": "QNetworkInformationBackend", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "reachability", + "type": "QNetworkInformation::Reachability" + } + ], + "index": 0, + "name": "reachabilityChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "behindPortal", + "type": "bool" + } + ], + "index": 1, + "name": "behindCaptivePortalChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "medium", + "type": "QNetworkInformation::TransportMedium" + } + ], + "index": 2, + "name": "transportMediumChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "isMetered", + "type": "bool" + } + ], + "index": 3, + "name": "isMeteredChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "className": "QNetworkInformationBackendFactory", + "lineNumber": 135, + "object": true, + "qualifiedClassName": "QNetworkInformationBackendFactory", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qnetworkinformation_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QNetworkInterface", + "enums": [ + { + "alias": "InterfaceFlag", + "isClass": false, + "isFlag": true, + "name": "InterfaceFlags", + "values": [ + "IsUp", + "IsRunning", + "CanBroadcast", + "IsLoopBack", + "IsPointToPoint", + "CanMulticast" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "InterfaceType", + "values": [ + "Loopback", + "Virtual", + "Ethernet", + "Slip", + "CanBus", + "Ppp", + "Fddi", + "Wifi", + "Ieee80211", + "Phonet", + "Ieee802154", + "SixLoWPAN", + "Ieee80216", + "Ieee1394", + "Unknown" + ] + } + ], + "gadget": true, + "lineNumber": 72, + "qualifiedClassName": "QNetworkInterface" + } + ], + "inputFile": "qnetworkinterface.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QNetworkProxyQuery", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "QueryType", + "values": [ + "TcpSocket", + "UdpSocket", + "SctpSocket", + "TcpServer", + "UrlRequest", + "SctpServer" + ] + } + ], + "gadget": true, + "lineNumber": 20, + "qualifiedClassName": "QNetworkProxyQuery" + }, + { + "className": "QNetworkProxy", + "gadget": true, + "lineNumber": 78, + "qualifiedClassName": "QNetworkProxy" + } + ], + "inputFile": "qnetworkproxy.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QNetworkReply", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "NetworkError", + "values": [ + "NoError", + "ConnectionRefusedError", + "RemoteHostClosedError", + "HostNotFoundError", + "TimeoutError", + "OperationCanceledError", + "SslHandshakeFailedError", + "TemporaryNetworkFailureError", + "NetworkSessionFailedError", + "BackgroundRequestNotAllowedError", + "TooManyRedirectsError", + "InsecureRedirectError", + "UnknownNetworkError", + "ProxyConnectionRefusedError", + "ProxyConnectionClosedError", + "ProxyNotFoundError", + "ProxyTimeoutError", + "ProxyAuthenticationRequiredError", + "UnknownProxyError", + "ContentAccessDenied", + "ContentOperationNotPermittedError", + "ContentNotFoundError", + "AuthenticationRequiredError", + "ContentReSendError", + "ContentConflictError", + "ContentGoneError", + "UnknownContentError", + "ProtocolUnknownError", + "ProtocolInvalidOperationError", + "ProtocolFailure", + "InternalServerError", + "OperationNotImplementedError", + "ServiceUnavailableError", + "UnknownServerError" + ] + } + ], + "lineNumber": 26, + "object": true, + "qualifiedClassName": "QNetworkReply", + "signals": [ + { + "access": "public", + "index": 0, + "name": "socketStartedConnecting", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "requestSent", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "metaDataChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "finished", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QNetworkReply::NetworkError" + } + ], + "index": 4, + "name": "errorOccurred", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "encrypted", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "errors", + "type": "QList" + } + ], + "index": 6, + "name": "sslErrors", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "authenticator", + "type": "QSslPreSharedKeyAuthenticator*" + } + ], + "index": 7, + "name": "preSharedKeyAuthenticationRequired", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "url", + "type": "QUrl" + } + ], + "index": 8, + "name": "redirected", + "returnType": "void" + }, + { + "access": "public", + "index": 9, + "name": "redirectAllowed", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "bytesSent", + "type": "qint64" + }, + { + "name": "bytesTotal", + "type": "qint64" + } + ], + "index": 10, + "name": "uploadProgress", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "bytesReceived", + "type": "qint64" + }, + { + "name": "bytesTotal", + "type": "qint64" + } + ], + "index": 11, + "name": "downloadProgress", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "index": 12, + "name": "abort", + "returnType": "void" + }, + { + "access": "public", + "index": 13, + "name": "ignoreSslErrors", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QIODevice" + } + ] + } + ], + "inputFile": "qnetworkreply.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QNetworkReplyDataImpl", + "lineNumber": 28, + "object": true, + "qualifiedClassName": "QNetworkReplyDataImpl", + "superClasses": [ + { + "access": "public", + "name": "QNetworkReply" + } + ] + } + ], + "inputFile": "qnetworkreplydataimpl_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QNetworkReplyFileImpl", + "lineNumber": 30, + "object": true, + "qualifiedClassName": "QNetworkReplyFileImpl", + "slots": [ + { + "access": "private", + "arguments": [ + { + "name": "isOpen", + "type": "bool" + } + ], + "index": 0, + "name": "fileOpenFinished", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QNetworkReply" + } + ] + } + ], + "inputFile": "qnetworkreplyfileimpl_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QNetworkReplyHttpImpl", + "lineNumber": 51, + "object": true, + "qualifiedClassName": "QNetworkReplyHttpImpl", + "signals": [ + { + "access": "public", + "index": 0, + "name": "startHttpRequest", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "abortHttpRequest", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "size", + "type": "qint64" + } + ], + "index": 2, + "name": "readBufferSizeChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "size", + "type": "qint64" + } + ], + "index": 3, + "name": "readBufferFreed", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "startHttpRequestSynchronously", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "pos", + "type": "qint64" + }, + { + "name": "dataArray", + "type": "QByteArray" + }, + { + "name": "dataAtEnd", + "type": "bool" + }, + { + "name": "dataSize", + "type": "qint64" + } + ], + "index": 5, + "name": "haveUploadData", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "index": 6, + "name": "_q_startOperation", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "_q_cacheLoadReadyRead", + "returnType": "void" + }, + { + "access": "public", + "index": 8, + "name": "_q_bufferOutgoingData", + "returnType": "void" + }, + { + "access": "public", + "index": 9, + "name": "_q_bufferOutgoingDataFinished", + "returnType": "void" + }, + { + "access": "public", + "index": 10, + "name": "_q_transferTimedOut", + "returnType": "void" + }, + { + "access": "public", + "index": 11, + "name": "_q_finished", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QNetworkReply::NetworkError" + }, + { + "type": "QString" + } + ], + "index": 12, + "name": "_q_error", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QByteArray" + } + ], + "index": 13, + "name": "replyDownloadData", + "returnType": "void" + }, + { + "access": "public", + "index": 14, + "name": "replyFinished", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "qint64" + }, + { + "type": "qint64" + } + ], + "index": 15, + "name": "replyDownloadProgressSlot", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QHttpNetworkRequest" + }, + { + "type": "QAuthenticator*" + } + ], + "index": 16, + "name": "httpAuthenticationRequired", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QNetworkReply::NetworkError" + }, + { + "type": "QString" + } + ], + "index": 17, + "name": "httpError", + "returnType": "void" + }, + { + "access": "public", + "index": 18, + "name": "replyEncrypted", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QList" + }, + { + "type": "bool*" + }, + { + "type": "QList*" + } + ], + "index": 19, + "name": "replySslErrors", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QSslConfiguration" + } + ], + "index": 20, + "name": "replySslConfigurationChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QSslPreSharedKeyAuthenticator*" + } + ], + "index": 21, + "name": "replyPreSharedKeyAuthenticationRequiredSlot", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "proxy", + "type": "QNetworkProxy" + }, + { + "name": "auth", + "type": "QAuthenticator*" + } + ], + "index": 22, + "name": "proxyAuthenticationRequired", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "r", + "type": "bool*" + } + ], + "index": 23, + "name": "resetUploadDataSlot", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "qint64" + } + ], + "index": 24, + "name": "wantUploadDataSlot", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "qint64" + }, + { + "type": "qint64" + } + ], + "index": 25, + "name": "sentUploadDataSlot", + "returnType": "void" + }, + { + "access": "public", + "index": 26, + "name": "uploadByteDeviceReadyReadSlot", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "qint64" + }, + { + "type": "qint64" + } + ], + "index": 27, + "name": "emitReplyUploadProgress", + "returnType": "void" + }, + { + "access": "public", + "index": 28, + "name": "_q_cacheSaveDeviceAboutToClose", + "returnType": "void" + }, + { + "access": "public", + "index": 29, + "name": "_q_metaDataChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QUrl" + }, + { + "type": "int" + }, + { + "type": "int" + } + ], + "index": 30, + "name": "onRedirected", + "returnType": "void" + }, + { + "access": "public", + "index": 31, + "name": "followRedirect", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QNetworkReply" + } + ] + } + ], + "inputFile": "qnetworkreplyhttpimpl_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QNetworkReplyImpl", + "lineNumber": 38, + "object": true, + "qualifiedClassName": "QNetworkReplyImpl", + "slots": [ + { + "access": "public", + "index": 0, + "name": "_q_startOperation", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "_q_copyReadyRead", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "_q_copyReadChannelFinished", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "_q_bufferOutgoingData", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "_q_bufferOutgoingDataFinished", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QNetworkReply" + } + ] + } + ], + "inputFile": "qnetworkreplyimpl_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QNetworkRequest", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "KnownHeaders", + "values": [ + "ContentTypeHeader", + "ContentLengthHeader", + "LocationHeader", + "LastModifiedHeader", + "CookieHeader", + "SetCookieHeader", + "ContentDispositionHeader", + "UserAgentHeader", + "ServerHeader", + "IfModifiedSinceHeader", + "ETagHeader", + "IfMatchHeader", + "IfNoneMatchHeader", + "NumKnownHeaders" + ] + } + ], + "gadget": true, + "lineNumber": 23, + "qualifiedClassName": "QNetworkRequest" + } + ], + "inputFile": "qnetworkrequest.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QRestAccessManager", + "lineNumber": 77, + "object": true, + "qualifiedClassName": "QRestAccessManager", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qrestaccessmanager.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QSocks5SocketEngine", + "lineNumber": 30, + "object": true, + "qualifiedClassName": "QSocks5SocketEngine", + "slots": [ + { + "access": "private", + "index": 0, + "name": "_q_controlSocketConnected", + "returnType": "void" + }, + { + "access": "private", + "index": 1, + "name": "_q_controlSocketReadNotification", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "type": "QAbstractSocket::SocketError" + } + ], + "index": 2, + "name": "_q_controlSocketErrorOccurred", + "returnType": "void" + }, + { + "access": "private", + "index": 3, + "name": "_q_udpSocketReadNotification", + "returnType": "void" + }, + { + "access": "private", + "index": 4, + "name": "_q_controlSocketBytesWritten", + "returnType": "void" + }, + { + "access": "private", + "index": 5, + "name": "_q_emitPendingReadNotification", + "returnType": "void" + }, + { + "access": "private", + "index": 6, + "name": "_q_emitPendingWriteNotification", + "returnType": "void" + }, + { + "access": "private", + "index": 7, + "name": "_q_emitPendingConnectionNotification", + "returnType": "void" + }, + { + "access": "private", + "index": 8, + "name": "_q_controlSocketDisconnected", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "type": "QAbstractSocket::SocketState" + } + ], + "index": 9, + "name": "_q_controlSocketStateChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QAbstractSocketEngine" + } + ] + } + ], + "inputFile": "qsocks5socketengine_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QSsl", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "KeyType", + "values": [ + "PrivateKey", + "PublicKey" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "EncodingFormat", + "values": [ + "Pem", + "Der" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "KeyAlgorithm", + "values": [ + "Opaque", + "Rsa", + "Dsa", + "Ec", + "Dh" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "AlternativeNameEntryType", + "values": [ + "EmailEntry", + "DnsEntry", + "IpAddressEntry" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "SslProtocol", + "values": [ + "TlsV1_0", + "TlsV1_1", + "TlsV1_2", + "AnyProtocol", + "SecureProtocols", + "TlsV1_0OrLater", + "TlsV1_1OrLater", + "TlsV1_2OrLater", + "DtlsV1_0", + "DtlsV1_0OrLater", + "DtlsV1_2", + "DtlsV1_2OrLater", + "TlsV1_3", + "TlsV1_3OrLater", + "UnknownProtocol" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "SslOption", + "values": [ + "SslOptionDisableEmptyFragments", + "SslOptionDisableSessionTickets", + "SslOptionDisableCompression", + "SslOptionDisableServerNameIndication", + "SslOptionDisableLegacyRenegotiation", + "SslOptionDisableSessionSharing", + "SslOptionDisableSessionPersistence", + "SslOptionDisableServerCipherPreference" + ] + }, + { + "isClass": true, + "isFlag": false, + "name": "AlertLevel", + "values": [ + "Warning", + "Fatal", + "Unknown" + ] + }, + { + "isClass": true, + "isFlag": false, + "name": "AlertType", + "values": [ + "CloseNotify", + "UnexpectedMessage", + "BadRecordMac", + "RecordOverflow", + "DecompressionFailure", + "HandshakeFailure", + "NoCertificate", + "BadCertificate", + "UnsupportedCertificate", + "CertificateRevoked", + "CertificateExpired", + "CertificateUnknown", + "IllegalParameter", + "UnknownCa", + "AccessDenied", + "DecodeError", + "DecryptError", + "ExportRestriction", + "ProtocolVersion", + "InsufficientSecurity", + "InternalError", + "InappropriateFallback", + "UserCancelled", + "NoRenegotiation", + "MissingExtension", + "UnsupportedExtension", + "CertificateUnobtainable", + "UnrecognizedName", + "BadCertificateStatusResponse", + "BadCertificateHashValue", + "UnknownPskIdentity", + "CertificateRequired", + "NoApplicationProtocol", + "UnknownAlertMessage" + ] + }, + { + "isClass": true, + "isFlag": false, + "name": "ImplementedClass", + "values": [ + "Key", + "Certificate", + "Socket", + "DiffieHellman", + "EllipticCurve", + "Dtls", + "DtlsCookie" + ] + }, + { + "isClass": true, + "isFlag": false, + "name": "SupportedFeature", + "values": [ + "CertificateVerification", + "ClientSideAlpn", + "ServerSideAlpn", + "Ocsp", + "Psk", + "SessionTicket", + "Alerts" + ] + } + ], + "lineNumber": 19, + "namespace": true, + "qualifiedClassName": "QSsl" + } + ], + "inputFile": "qssl.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QSslError", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "SslError", + "values": [ + "NoError", + "UnableToGetIssuerCertificate", + "UnableToDecryptCertificateSignature", + "UnableToDecodeIssuerPublicKey", + "CertificateSignatureFailed", + "CertificateNotYetValid", + "CertificateExpired", + "InvalidNotBeforeField", + "InvalidNotAfterField", + "SelfSignedCertificate", + "SelfSignedCertificateInChain", + "UnableToGetLocalIssuerCertificate", + "UnableToVerifyFirstCertificate", + "CertificateRevoked", + "InvalidCaCertificate", + "PathLengthExceeded", + "InvalidPurpose", + "CertificateUntrusted", + "CertificateRejected", + "SubjectIssuerMismatch", + "AuthorityIssuerSerialNumberMismatch", + "NoPeerCertificate", + "HostNameMismatch", + "NoSslSupport", + "CertificateBlacklisted", + "CertificateStatusUnknown", + "OcspNoResponseFound", + "OcspMalformedRequest", + "OcspMalformedResponse", + "OcspInternalError", + "OcspTryLater", + "OcspSigRequred", + "OcspUnauthorized", + "OcspResponseCannotBeTrusted", + "OcspResponseCertIdUnknown", + "OcspResponseExpired", + "OcspStatusUnknown", + "UnspecifiedError" + ] + } + ], + "gadget": true, + "lineNumber": 24, + "qualifiedClassName": "QSslError" + } + ], + "inputFile": "qsslerror.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QSslServer", + "lineNumber": 24, + "object": true, + "qualifiedClassName": "QSslServer", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "socket", + "type": "QSslSocket*" + }, + { + "name": "errors", + "type": "QList" + } + ], + "index": 0, + "name": "sslErrors", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "socket", + "type": "QSslSocket*" + }, + { + "name": "error", + "type": "QSslError" + } + ], + "index": 1, + "name": "peerVerifyError", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "socket", + "type": "QSslSocket*" + }, + { + "name": "error", + "type": "QAbstractSocket::SocketError" + } + ], + "index": 2, + "name": "errorOccurred", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "socket", + "type": "QSslSocket*" + }, + { + "name": "authenticator", + "type": "QSslPreSharedKeyAuthenticator*" + } + ], + "index": 3, + "name": "preSharedKeyAuthenticationRequired", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "socket", + "type": "QSslSocket*" + }, + { + "name": "level", + "type": "QSsl::AlertLevel" + }, + { + "name": "type", + "type": "QSsl::AlertType" + }, + { + "name": "description", + "type": "QString" + } + ], + "index": 4, + "name": "alertSent", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "socket", + "type": "QSslSocket*" + }, + { + "name": "level", + "type": "QSsl::AlertLevel" + }, + { + "name": "type", + "type": "QSsl::AlertType" + }, + { + "name": "description", + "type": "QString" + } + ], + "index": 5, + "name": "alertReceived", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "socket", + "type": "QSslSocket*" + }, + { + "name": "error", + "type": "QSslError" + } + ], + "index": 6, + "name": "handshakeInterruptedOnError", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "socket", + "type": "QSslSocket*" + } + ], + "index": 7, + "name": "startedEncryptionHandshake", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QTcpServer" + } + ] + } + ], + "inputFile": "qsslserver.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QSslSocket", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "SslMode", + "values": [ + "UnencryptedMode", + "SslClientMode", + "SslServerMode" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "PeerVerifyMode", + "values": [ + "VerifyNone", + "QueryPeer", + "VerifyPeer", + "AutoVerifyPeer" + ] + } + ], + "lineNumber": 28, + "object": true, + "qualifiedClassName": "QSslSocket", + "signals": [ + { + "access": "public", + "index": 0, + "name": "encrypted", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "error", + "type": "QSslError" + } + ], + "index": 1, + "name": "peerVerifyError", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "errors", + "type": "QList" + } + ], + "index": 2, + "name": "sslErrors", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "newMode", + "type": "QSslSocket::SslMode" + } + ], + "index": 3, + "name": "modeChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "totalBytes", + "type": "qint64" + } + ], + "index": 4, + "name": "encryptedBytesWritten", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "authenticator", + "type": "QSslPreSharedKeyAuthenticator*" + } + ], + "index": 5, + "name": "preSharedKeyAuthenticationRequired", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "newSessionTicketReceived", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "level", + "type": "QSsl::AlertLevel" + }, + { + "name": "type", + "type": "QSsl::AlertType" + }, + { + "name": "description", + "type": "QString" + } + ], + "index": 7, + "name": "alertSent", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "level", + "type": "QSsl::AlertLevel" + }, + { + "name": "type", + "type": "QSsl::AlertType" + }, + { + "name": "description", + "type": "QString" + } + ], + "index": 8, + "name": "alertReceived", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "error", + "type": "QSslError" + } + ], + "index": 9, + "name": "handshakeInterruptedOnError", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "index": 10, + "name": "startClientEncryption", + "returnType": "void" + }, + { + "access": "public", + "index": 11, + "name": "startServerEncryption", + "returnType": "void" + }, + { + "access": "public", + "index": 12, + "name": "ignoreSslErrors", + "returnType": "void" + }, + { + "access": "private", + "index": 13, + "name": "_q_connectedSlot", + "returnType": "void" + }, + { + "access": "private", + "index": 14, + "name": "_q_hostFoundSlot", + "returnType": "void" + }, + { + "access": "private", + "index": 15, + "name": "_q_disconnectedSlot", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "type": "QAbstractSocket::SocketState" + } + ], + "index": 16, + "name": "_q_stateChangedSlot", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "type": "QAbstractSocket::SocketError" + } + ], + "index": 17, + "name": "_q_errorSlot", + "returnType": "void" + }, + { + "access": "private", + "index": 18, + "name": "_q_readyReadSlot", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "type": "int" + } + ], + "index": 19, + "name": "_q_channelReadyReadSlot", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "type": "qint64" + } + ], + "index": 20, + "name": "_q_bytesWrittenSlot", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "type": "int" + }, + { + "type": "qint64" + } + ], + "index": 21, + "name": "_q_channelBytesWrittenSlot", + "returnType": "void" + }, + { + "access": "private", + "index": 22, + "name": "_q_readChannelFinishedSlot", + "returnType": "void" + }, + { + "access": "private", + "index": 23, + "name": "_q_flushWriteBuffer", + "returnType": "void" + }, + { + "access": "private", + "index": 24, + "name": "_q_flushReadBuffer", + "returnType": "void" + }, + { + "access": "private", + "index": 25, + "name": "_q_resumeImplementation", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QTcpSocket" + } + ] + } + ], + "inputFile": "qsslsocket.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QTcpServer", + "lineNumber": 21, + "object": true, + "qualifiedClassName": "QTcpServer", + "signals": [ + { + "access": "public", + "index": 0, + "name": "newConnection", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "pendingConnectionAvailable", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "socketError", + "type": "QAbstractSocket::SocketError" + } + ], + "index": 2, + "name": "acceptError", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qtcpserver.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QTcpSocket", + "lineNumber": 17, + "object": true, + "qualifiedClassName": "QTcpSocket", + "superClasses": [ + { + "access": "public", + "name": "QAbstractSocket" + } + ] + } + ], + "inputFile": "qtcpsocket.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QTlsBackend", + "lineNumber": 268, + "object": true, + "qualifiedClassName": "QTlsBackend", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qtlsbackend_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QUdpSocket", + "lineNumber": 20, + "object": true, + "qualifiedClassName": "QUdpSocket", + "superClasses": [ + { + "access": "public", + "name": "QAbstractSocket" + } + ] + } + ], + "inputFile": "qudpsocket.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QNetworkInformationDummyBackend", + "lineNumber": 55, + "object": true, + "qualifiedClassName": "QNetworkInformationDummyBackend", + "superClasses": [ + { + "access": "public", + "name": "QNetworkInformationBackend" + } + ] + } + ], + "inputFile": "qnetworkinformation.cpp", + "outputRevision": 68 + } +] diff --git a/qt/6.8.1/msvc2022_64/metatypes/qt6opengl_metatypes.json b/qt/6.8.1/msvc2022_64/metatypes/qt6opengl_metatypes.json new file mode 100644 index 0000000000000000000000000000000000000000..d5269c26d875d85a700328461aadf34ecaeb83fc --- /dev/null +++ b/qt/6.8.1/msvc2022_64/metatypes/qt6opengl_metatypes.json @@ -0,0 +1,629 @@ +[ + { + "classes": [ + { + "className": "QOpenGLDebugLogger", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "LoggingMode", + "values": [ + "AsynchronousLogging", + "SynchronousLogging" + ] + } + ], + "lineNumber": 119, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "loggingMode", + "read": "loggingMode", + "required": false, + "scriptable": true, + "stored": true, + "type": "LoggingMode", + "user": false + } + ], + "qualifiedClassName": "QOpenGLDebugLogger", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "debugMessage", + "type": "QOpenGLDebugMessage" + } + ], + "index": 0, + "name": "messageLogged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "debugMessage", + "type": "QOpenGLDebugMessage" + } + ], + "index": 1, + "name": "logMessage", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "loggingMode", + "type": "LoggingMode" + } + ], + "index": 2, + "name": "startLogging", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "isCloned": true, + "name": "startLogging", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "stopLogging", + "returnType": "void" + }, + { + "access": "private", + "index": 5, + "name": "_q_contextAboutToBeDestroyed", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qopengldebug.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QOpenGLEngineSharedShaders", + "gadget": true, + "lineNumber": 221, + "qualifiedClassName": "QOpenGLEngineSharedShaders" + }, + { + "className": "QOpenGLEngineShaderManager", + "lineNumber": 372, + "object": true, + "qualifiedClassName": "QOpenGLEngineShaderManager", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qopenglengineshadermanager_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QOpenGLShader", + "lineNumber": 23, + "object": true, + "qualifiedClassName": "QOpenGLShader", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "className": "QOpenGLShaderProgram", + "lineNumber": 69, + "object": true, + "qualifiedClassName": "QOpenGLShaderProgram", + "slots": [ + { + "access": "private", + "index": 0, + "name": "shaderDestroyed", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qopenglshaderprogram.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QOpenGLTexture", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "Target", + "values": [ + "Target1D", + "Target1DArray", + "Target2D", + "Target2DArray", + "Target3D", + "TargetCubeMap", + "TargetCubeMapArray", + "Target2DMultisample", + "Target2DMultisampleArray", + "TargetRectangle", + "TargetBuffer" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "BindingTarget", + "values": [ + "BindingTarget1D", + "BindingTarget1DArray", + "BindingTarget2D", + "BindingTarget2DArray", + "BindingTarget3D", + "BindingTargetCubeMap", + "BindingTargetCubeMapArray", + "BindingTarget2DMultisample", + "BindingTarget2DMultisampleArray", + "BindingTargetRectangle", + "BindingTargetBuffer" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "MipMapGeneration", + "values": [ + "GenerateMipMaps", + "DontGenerateMipMaps" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "TextureUnitReset", + "values": [ + "ResetTextureUnit", + "DontResetTextureUnit" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "TextureFormat", + "values": [ + "NoFormat", + "R8_UNorm", + "RG8_UNorm", + "RGB8_UNorm", + "RGBA8_UNorm", + "R16_UNorm", + "RG16_UNorm", + "RGB16_UNorm", + "RGBA16_UNorm", + "R8_SNorm", + "RG8_SNorm", + "RGB8_SNorm", + "RGBA8_SNorm", + "R16_SNorm", + "RG16_SNorm", + "RGB16_SNorm", + "RGBA16_SNorm", + "R8U", + "RG8U", + "RGB8U", + "RGBA8U", + "R16U", + "RG16U", + "RGB16U", + "RGBA16U", + "R32U", + "RG32U", + "RGB32U", + "RGBA32U", + "R8I", + "RG8I", + "RGB8I", + "RGBA8I", + "R16I", + "RG16I", + "RGB16I", + "RGBA16I", + "R32I", + "RG32I", + "RGB32I", + "RGBA32I", + "R16F", + "RG16F", + "RGB16F", + "RGBA16F", + "R32F", + "RG32F", + "RGB32F", + "RGBA32F", + "RGB9E5", + "RG11B10F", + "RG3B2", + "R5G6B5", + "RGB5A1", + "RGBA4", + "RGB10A2", + "D16", + "D24", + "D24S8", + "D32", + "D32F", + "D32FS8X24", + "S8", + "RGB_DXT1", + "RGBA_DXT1", + "RGBA_DXT3", + "RGBA_DXT5", + "R_ATI1N_UNorm", + "R_ATI1N_SNorm", + "RG_ATI2N_UNorm", + "RG_ATI2N_SNorm", + "RGB_BP_UNSIGNED_FLOAT", + "RGB_BP_SIGNED_FLOAT", + "RGB_BP_UNorm", + "R11_EAC_UNorm", + "R11_EAC_SNorm", + "RG11_EAC_UNorm", + "RG11_EAC_SNorm", + "RGB8_ETC2", + "SRGB8_ETC2", + "RGB8_PunchThrough_Alpha1_ETC2", + "SRGB8_PunchThrough_Alpha1_ETC2", + "RGBA8_ETC2_EAC", + "SRGB8_Alpha8_ETC2_EAC", + "RGB8_ETC1", + "RGBA_ASTC_4x4", + "RGBA_ASTC_5x4", + "RGBA_ASTC_5x5", + "RGBA_ASTC_6x5", + "RGBA_ASTC_6x6", + "RGBA_ASTC_8x5", + "RGBA_ASTC_8x6", + "RGBA_ASTC_8x8", + "RGBA_ASTC_10x5", + "RGBA_ASTC_10x6", + "RGBA_ASTC_10x8", + "RGBA_ASTC_10x10", + "RGBA_ASTC_12x10", + "RGBA_ASTC_12x12", + "SRGB8_Alpha8_ASTC_4x4", + "SRGB8_Alpha8_ASTC_5x4", + "SRGB8_Alpha8_ASTC_5x5", + "SRGB8_Alpha8_ASTC_6x5", + "SRGB8_Alpha8_ASTC_6x6", + "SRGB8_Alpha8_ASTC_8x5", + "SRGB8_Alpha8_ASTC_8x6", + "SRGB8_Alpha8_ASTC_8x8", + "SRGB8_Alpha8_ASTC_10x5", + "SRGB8_Alpha8_ASTC_10x6", + "SRGB8_Alpha8_ASTC_10x8", + "SRGB8_Alpha8_ASTC_10x10", + "SRGB8_Alpha8_ASTC_12x10", + "SRGB8_Alpha8_ASTC_12x12", + "SRGB8", + "SRGB8_Alpha8", + "SRGB_DXT1", + "SRGB_Alpha_DXT1", + "SRGB_Alpha_DXT3", + "SRGB_Alpha_DXT5", + "SRGB_BP_UNorm", + "DepthFormat", + "AlphaFormat", + "RGBFormat", + "RGBAFormat", + "LuminanceFormat", + "LuminanceAlphaFormat" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "CubeMapFace", + "values": [ + "CubeMapPositiveX", + "CubeMapNegativeX", + "CubeMapPositiveY", + "CubeMapNegativeY", + "CubeMapPositiveZ", + "CubeMapNegativeZ" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "PixelFormat", + "values": [ + "NoSourceFormat", + "Red", + "RG", + "RGB", + "BGR", + "RGBA", + "BGRA", + "Red_Integer", + "RG_Integer", + "RGB_Integer", + "BGR_Integer", + "RGBA_Integer", + "BGRA_Integer", + "Stencil", + "Depth", + "DepthStencil", + "Alpha", + "Luminance", + "LuminanceAlpha" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "PixelType", + "values": [ + "NoPixelType", + "Int8", + "UInt8", + "Int16", + "UInt16", + "Int32", + "UInt32", + "Float16", + "Float16OES", + "Float32", + "UInt32_RGB9_E5", + "UInt32_RG11B10F", + "UInt8_RG3B2", + "UInt8_RG3B2_Rev", + "UInt16_RGB5A1", + "UInt16_RGB5A1_Rev", + "UInt16_R5G6B5", + "UInt16_R5G6B5_Rev", + "UInt16_RGBA4", + "UInt16_RGBA4_Rev", + "UInt32_RGBA8", + "UInt32_RGBA8_Rev", + "UInt32_RGB10A2", + "UInt32_RGB10A2_Rev", + "UInt32_D24S8", + "Float32_D32_UInt32_S8_X24" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "SwizzleComponent", + "values": [ + "SwizzleRed", + "SwizzleGreen", + "SwizzleBlue", + "SwizzleAlpha" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "SwizzleValue", + "values": [ + "RedValue", + "GreenValue", + "BlueValue", + "AlphaValue", + "ZeroValue", + "OneValue" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "WrapMode", + "values": [ + "Repeat", + "MirroredRepeat", + "ClampToEdge", + "ClampToBorder" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "CoordinateDirection", + "values": [ + "DirectionS", + "DirectionT", + "DirectionR" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "Feature", + "values": [ + "ImmutableStorage", + "ImmutableMultisampleStorage", + "TextureRectangle", + "TextureArrays", + "Texture3D", + "TextureMultisample", + "TextureBuffer", + "TextureCubeMapArrays", + "Swizzle", + "StencilTexturing", + "AnisotropicFiltering", + "NPOTTextures", + "NPOTTextureRepeat", + "Texture1D", + "TextureComparisonOperators", + "TextureMipMapLevel", + "MaxFeatureFlag" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "DepthStencilMode", + "values": [ + "DepthMode", + "StencilMode" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "ComparisonFunction", + "values": [ + "CompareLessEqual", + "CompareGreaterEqual", + "CompareLess", + "CompareGreater", + "CompareEqual", + "CompareNotEqual", + "CompareAlways", + "CompareNever", + "CommpareNotEqual" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "Filter", + "values": [ + "Nearest", + "Linear", + "NearestMipMapNearest", + "NearestMipMapLinear", + "LinearMipMapNearest", + "LinearMipMapLinear" + ] + } + ], + "gadget": true, + "lineNumber": 21, + "qualifiedClassName": "QOpenGLTexture" + } + ], + "inputFile": "qopengltexture.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QOpenGLTimerQuery", + "lineNumber": 18, + "object": true, + "qualifiedClassName": "QOpenGLTimerQuery", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "className": "QOpenGLTimeMonitor", + "lineNumber": 46, + "object": true, + "qualifiedClassName": "QOpenGLTimeMonitor", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qopengltimerquery.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QOpenGLVertexArrayObject", + "lineNumber": 18, + "object": true, + "qualifiedClassName": "QOpenGLVertexArrayObject", + "slots": [ + { + "access": "private", + "index": 0, + "name": "_q_contextAboutToBeDestroyed", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qopenglvertexarrayobject.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QOpenGLWindow", + "lineNumber": 19, + "object": true, + "qualifiedClassName": "QOpenGLWindow", + "signals": [ + { + "access": "public", + "index": 0, + "name": "frameSwapped", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QPaintDeviceWindow" + } + ] + } + ], + "inputFile": "qopenglwindow.h", + "outputRevision": 68 + } +] diff --git a/qt/6.8.1/msvc2022_64/metatypes/qt6openglwidgets_metatypes.json b/qt/6.8.1/msvc2022_64/metatypes/qt6openglwidgets_metatypes.json new file mode 100644 index 0000000000000000000000000000000000000000..bce283cb8908f3c94d049b4e56505f26125f6750 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/metatypes/qt6openglwidgets_metatypes.json @@ -0,0 +1,67 @@ +[ + { + "classes": [ + { + "className": "QOpenGLWidget", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "UpdateBehavior", + "values": [ + "NoPartialUpdate", + "PartialUpdate" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "TargetBuffer", + "type": "uint8_t", + "values": [ + "LeftBuffer", + "RightBuffer" + ] + } + ], + "lineNumber": 17, + "object": true, + "qualifiedClassName": "QOpenGLWidget", + "signals": [ + { + "access": "public", + "index": 0, + "name": "aboutToCompose", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "frameSwapped", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "aboutToResize", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "resized", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + } + ], + "inputFile": "qopenglwidget.h", + "outputRevision": 68 + } +] diff --git a/qt/6.8.1/msvc2022_64/metatypes/qt6packetprotocolprivate_metatypes.json b/qt/6.8.1/msvc2022_64/metatypes/qt6packetprotocolprivate_metatypes.json new file mode 100644 index 0000000000000000000000000000000000000000..c944343188a5d5104e4bad4c72ba5da7c2f2e0e1 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/metatypes/qt6packetprotocolprivate_metatypes.json @@ -0,0 +1,34 @@ +[ + { + "classes": [ + { + "className": "QPacketProtocol", + "lineNumber": 25, + "object": true, + "qualifiedClassName": "QPacketProtocol", + "signals": [ + { + "access": "public", + "index": 0, + "name": "readyRead", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "error", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qpacketprotocol_p.h", + "outputRevision": 68 + } +] diff --git a/qt/6.8.1/msvc2022_64/metatypes/qt6printsupport_metatypes.json b/qt/6.8.1/msvc2022_64/metatypes/qt6printsupport_metatypes.json new file mode 100644 index 0000000000000000000000000000000000000000..6e267296065540b481583aeba5095767943bc67e --- /dev/null +++ b/qt/6.8.1/msvc2022_64/metatypes/qt6printsupport_metatypes.json @@ -0,0 +1,519 @@ +[ + { + "classes": [ + { + "className": "QPageSetupDialog", + "lineNumber": 18, + "object": true, + "qualifiedClassName": "QPageSetupDialog", + "superClasses": [ + { + "access": "public", + "name": "QDialog" + } + ] + } + ], + "inputFile": "qpagesetupdialog.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QAbstractPrintDialog", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "PrintDialogOption", + "values": [ + "PrintToFile", + "PrintSelection", + "PrintPageRange", + "PrintShowPageSize", + "PrintCollateCopies", + "PrintCurrentPage" + ] + }, + { + "alias": "PrintDialogOption", + "isClass": false, + "isFlag": true, + "name": "PrintDialogOptions", + "values": [ + "PrintToFile", + "PrintSelection", + "PrintPageRange", + "PrintShowPageSize", + "PrintCollateCopies", + "PrintCurrentPage" + ] + } + ], + "lineNumber": 18, + "object": true, + "qualifiedClassName": "QAbstractPrintDialog", + "superClasses": [ + { + "access": "public", + "name": "QDialog" + } + ] + } + ], + "inputFile": "qabstractprintdialog.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QPlatformPrinterSupportPlugin", + "lineNumber": 29, + "object": true, + "qualifiedClassName": "QPlatformPrinterSupportPlugin", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qplatformprintplugin.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QPrintDialog", + "lineNumber": 19, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "options", + "read": "options", + "required": false, + "scriptable": true, + "stored": true, + "type": "PrintDialogOptions", + "user": false, + "write": "setOptions" + } + ], + "qualifiedClassName": "QPrintDialog", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "printer", + "type": "QPrinter*" + } + ], + "index": 0, + "name": "accepted", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QAbstractPrintDialog" + } + ] + } + ], + "inputFile": "qprintdialog.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QPrintPreviewDialog", + "lineNumber": 19, + "object": true, + "qualifiedClassName": "QPrintPreviewDialog", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "printer", + "type": "QPrinter*" + } + ], + "index": 0, + "name": "paintRequested", + "returnType": "void" + } + ], + "slots": [ + { + "access": "private", + "arguments": [ + { + "name": "action", + "type": "QAction*" + } + ], + "index": 1, + "name": "_q_fit", + "returnType": "void" + }, + { + "access": "private", + "index": 2, + "name": "_q_zoomIn", + "returnType": "void" + }, + { + "access": "private", + "index": 3, + "name": "_q_zoomOut", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "action", + "type": "QAction*" + } + ], + "index": 4, + "name": "_q_navigate", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "action", + "type": "QAction*" + } + ], + "index": 5, + "name": "_q_setMode", + "returnType": "void" + }, + { + "access": "private", + "index": 6, + "name": "_q_pageNumEdited", + "returnType": "void" + }, + { + "access": "private", + "index": 7, + "name": "_q_print", + "returnType": "void" + }, + { + "access": "private", + "index": 8, + "name": "_q_pageSetup", + "returnType": "void" + }, + { + "access": "private", + "index": 9, + "name": "_q_previewChanged", + "returnType": "void" + }, + { + "access": "private", + "index": 10, + "name": "_q_zoomFactorChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QDialog" + } + ] + } + ], + "inputFile": "qprintpreviewdialog.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QPrintPreviewWidget", + "lineNumber": 18, + "object": true, + "qualifiedClassName": "QPrintPreviewWidget", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "printer", + "type": "QPrinter*" + } + ], + "index": 0, + "name": "paintRequested", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "previewChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "index": 2, + "name": "print", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "zoom", + "type": "qreal" + } + ], + "index": 3, + "name": "zoomIn", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "isCloned": true, + "name": "zoomIn", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "zoom", + "type": "qreal" + } + ], + "index": 5, + "name": "zoomOut", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "isCloned": true, + "name": "zoomOut", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "zoomFactor", + "type": "qreal" + } + ], + "index": 7, + "name": "setZoomFactor", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "orientation", + "type": "QPageLayout::Orientation" + } + ], + "index": 8, + "name": "setOrientation", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "viewMode", + "type": "ViewMode" + } + ], + "index": 9, + "name": "setViewMode", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "zoomMode", + "type": "ZoomMode" + } + ], + "index": 10, + "name": "setZoomMode", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "pageNumber", + "type": "int" + } + ], + "index": 11, + "name": "setCurrentPage", + "returnType": "void" + }, + { + "access": "public", + "index": 12, + "name": "fitToWidth", + "returnType": "void" + }, + { + "access": "public", + "index": 13, + "name": "fitInView", + "returnType": "void" + }, + { + "access": "public", + "index": 14, + "name": "setLandscapeOrientation", + "returnType": "void" + }, + { + "access": "public", + "index": 15, + "name": "setPortraitOrientation", + "returnType": "void" + }, + { + "access": "public", + "index": 16, + "name": "setSinglePageViewMode", + "returnType": "void" + }, + { + "access": "public", + "index": 17, + "name": "setFacingPagesViewMode", + "returnType": "void" + }, + { + "access": "public", + "index": 18, + "name": "setAllPagesViewMode", + "returnType": "void" + }, + { + "access": "public", + "index": 19, + "name": "updatePreview", + "returnType": "void" + }, + { + "access": "private", + "index": 20, + "name": "_q_fit", + "returnType": "void" + }, + { + "access": "private", + "index": 21, + "name": "_q_updateCurrentPage", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + } + ], + "inputFile": "qprintpreviewwidget.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "LineEdit", + "lineNumber": 83, + "object": true, + "qualifiedClassName": "LineEdit", + "slots": [ + { + "access": "private", + "index": 0, + "name": "handleReturnPressed", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QLineEdit" + } + ] + } + ], + "inputFile": "qprintpreviewdialog.cpp", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "GraphicsView", + "lineNumber": 107, + "object": true, + "qualifiedClassName": "QtPrivate::GraphicsView", + "signals": [ + { + "access": "public", + "index": 0, + "name": "resized", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QGraphicsView" + } + ] + } + ], + "inputFile": "qprintpreviewwidget.cpp", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QWindowsPrinterSupportPlugin", + "lineNumber": 56, + "object": true, + "qualifiedClassName": "QWindowsPrinterSupportPlugin", + "superClasses": [ + { + "access": "public", + "name": "QPlatformPrinterSupportPlugin" + } + ] + } + ], + "inputFile": "qwindowsprintersupport.cpp", + "outputRevision": 68 + } +] diff --git a/qt/6.8.1/msvc2022_64/metatypes/qt6qml_metatypes.json b/qt/6.8.1/msvc2022_64/metatypes/qt6qml_metatypes.json new file mode 100644 index 0000000000000000000000000000000000000000..204b8d985b24daab5d6a63a50cefa3d4f998ee28 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/metatypes/qt6qml_metatypes.json @@ -0,0 +1,6712 @@ +[ + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "TypeNotAvailable" + }, + { + "name": "QML.AddedInVersion", + "value": "527" + }, + { + "name": "QML.Creatable", + "value": "false" + }, + { + "name": "QML.UncreatableReason", + "value": "Type not available." + } + ], + "className": "QQmlTypeNotAvailable", + "lineNumber": 136, + "object": true, + "qualifiedClassName": "QQmlTypeNotAvailable", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qqml.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + } + ], + "className": "QQmlLoggingCategoryBase", + "lineNumber": 27, + "object": true, + "qualifiedClassName": "QQmlLoggingCategoryBase", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qqmlloggingcategorybase_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "void" + }, + { + "name": "QML.Extended", + "value": "undefined" + }, + { + "name": "QML.ExtensionIsJavaScript", + "value": "true" + }, + { + "name": "QML.Foreign", + "value": "void" + } + ], + "className": "QQmlVoidForeign", + "gadget": true, + "lineNumber": 88, + "qualifiedClassName": "QQmlVoidForeign" + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "var" + }, + { + "name": "QML.Element", + "value": "variant" + }, + { + "name": "QML.Foreign", + "value": "QVariant" + }, + { + "name": "QML.Extended", + "value": "QQmlVarForeign" + } + ], + "className": "QQmlVarForeign", + "gadget": true, + "lineNumber": 99, + "qualifiedClassName": "QQmlVarForeign" + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "QtObject" + }, + { + "name": "QML.Extended", + "value": "Object" + }, + { + "name": "QML.ExtensionIsJavaScript", + "value": "true" + }, + { + "name": "QML.Foreign", + "value": "QObject" + }, + { + "name": "QML.Root", + "value": "true" + } + ], + "className": "QQmlQtObjectForeign", + "gadget": true, + "lineNumber": 108, + "qualifiedClassName": "QQmlQtObjectForeign" + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "int" + }, + { + "name": "QML.Extended", + "value": "Number" + }, + { + "name": "QML.ExtensionIsJavaScript", + "value": "true" + }, + { + "name": "QML.Foreign", + "value": "int" + } + ], + "className": "QQmlIntForeign", + "gadget": true, + "lineNumber": 117, + "qualifiedClassName": "QQmlIntForeign" + }, + { + "classInfos": [ + { + "name": "QML.Foreign", + "value": "qint32" + }, + { + "name": "QML.Using", + "value": "int" + } + ], + "className": "QQmlQint32Foreign", + "gadget": true, + "lineNumber": 129, + "qualifiedClassName": "QQmlQint32Foreign" + }, + { + "classInfos": [ + { + "name": "QML.Foreign", + "value": "int32_t" + }, + { + "name": "QML.Using", + "value": "int" + } + ], + "className": "QQmlInt32TForeign", + "gadget": true, + "lineNumber": 136, + "qualifiedClassName": "QQmlInt32TForeign" + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "real" + }, + { + "name": "QML.Element", + "value": "double" + }, + { + "name": "QML.Extended", + "value": "Number" + }, + { + "name": "QML.ExtensionIsJavaScript", + "value": "true" + }, + { + "name": "QML.Foreign", + "value": "double" + } + ], + "className": "QQmlDoubleForeign", + "gadget": true, + "lineNumber": 143, + "qualifiedClassName": "QQmlDoubleForeign" + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "string" + }, + { + "name": "QML.Extended", + "value": "String" + }, + { + "name": "QML.ExtensionIsJavaScript", + "value": "true" + }, + { + "name": "QML.Foreign", + "value": "QString" + } + ], + "className": "QQmlStringForeign", + "gadget": true, + "lineNumber": 152, + "qualifiedClassName": "QQmlStringForeign" + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.Extended", + "value": "String" + }, + { + "name": "QML.ExtensionIsJavaScript", + "value": "true" + }, + { + "name": "QML.Foreign", + "value": "QAnyStringView" + } + ], + "className": "QQmlAnyStringViewForeign", + "gadget": true, + "lineNumber": 160, + "qualifiedClassName": "QQmlAnyStringViewForeign" + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "bool" + }, + { + "name": "QML.Extended", + "value": "Boolean" + }, + { + "name": "QML.ExtensionIsJavaScript", + "value": "true" + }, + { + "name": "QML.Foreign", + "value": "bool" + } + ], + "className": "QQmlBoolForeign", + "gadget": true, + "lineNumber": 168, + "qualifiedClassName": "QQmlBoolForeign" + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "date" + }, + { + "name": "QML.Extended", + "value": "Date" + }, + { + "name": "QML.ExtensionIsJavaScript", + "value": "true" + }, + { + "name": "QML.Foreign", + "value": "QDateTime" + } + ], + "className": "QQmlDateForeign", + "gadget": true, + "lineNumber": 176, + "qualifiedClassName": "QQmlDateForeign" + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "url" + }, + { + "name": "QML.Extended", + "value": "URL" + }, + { + "name": "QML.ExtensionIsJavaScript", + "value": "true" + }, + { + "name": "QML.Foreign", + "value": "QUrl" + } + ], + "className": "QQmlUrlForeign", + "gadget": true, + "lineNumber": 184, + "qualifiedClassName": "QQmlUrlForeign" + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "regexp" + }, + { + "name": "QML.Extended", + "value": "RegExp" + }, + { + "name": "QML.ExtensionIsJavaScript", + "value": "true" + }, + { + "name": "QML.Foreign", + "value": "QRegularExpression" + } + ], + "className": "QQmlRegexpForeign", + "gadget": true, + "lineNumber": 193, + "qualifiedClassName": "QQmlRegexpForeign" + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.Foreign", + "value": "std::nullptr_t" + }, + { + "name": "QML.Extended", + "value": "QQmlNullForeign" + } + ], + "className": "QQmlNullForeign", + "gadget": true, + "lineNumber": 202, + "qualifiedClassName": "QQmlNullForeign" + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.Foreign", + "value": "QVariantMap" + }, + { + "name": "QML.Extended", + "value": "Object" + }, + { + "name": "QML.ExtensionIsJavaScript", + "value": "true" + } + ], + "className": "QQmlQVariantMapForeign", + "gadget": true, + "lineNumber": 210, + "qualifiedClassName": "QQmlQVariantMapForeign" + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.Extended", + "value": "Number" + }, + { + "name": "QML.ExtensionIsJavaScript", + "value": "true" + }, + { + "name": "QML.Foreign", + "value": "qint8" + } + ], + "className": "QQmlQint8Foreign", + "gadget": true, + "lineNumber": 218, + "qualifiedClassName": "QQmlQint8Foreign" + }, + { + "classInfos": [ + { + "name": "QML.Foreign", + "value": "int8_t" + }, + { + "name": "QML.Using", + "value": "qint8" + } + ], + "className": "QQmlInt8TForeign", + "gadget": true, + "lineNumber": 226, + "qualifiedClassName": "QQmlInt8TForeign" + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.Extended", + "value": "Number" + }, + { + "name": "QML.ExtensionIsJavaScript", + "value": "true" + }, + { + "name": "QML.Foreign", + "value": "quint8" + } + ], + "className": "QQmlQuint8Foreign", + "gadget": true, + "lineNumber": 233, + "qualifiedClassName": "QQmlQuint8Foreign" + }, + { + "classInfos": [ + { + "name": "QML.Foreign", + "value": "uint8_t" + }, + { + "name": "QML.Using", + "value": "quint8" + } + ], + "className": "QQmlUint8TForeign", + "gadget": true, + "lineNumber": 241, + "qualifiedClassName": "QQmlUint8TForeign" + }, + { + "classInfos": [ + { + "name": "QML.Foreign", + "value": "uchar" + }, + { + "name": "QML.Using", + "value": "quint8" + } + ], + "className": "QQmlUcharForeign", + "gadget": true, + "lineNumber": 248, + "qualifiedClassName": "QQmlUcharForeign" + }, + { + "classInfos": [ + { + "name": "QML.Foreign", + "value": "char" + }, + { + "name": "QML.Using", + "value": "quint8" + } + ], + "className": "QQmlCharForeign", + "gadget": true, + "lineNumber": 255, + "qualifiedClassName": "QQmlCharForeign" + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.Extended", + "value": "Number" + }, + { + "name": "QML.ExtensionIsJavaScript", + "value": "true" + }, + { + "name": "QML.Foreign", + "value": "short" + } + ], + "className": "QQmlShortForeign", + "gadget": true, + "lineNumber": 268, + "qualifiedClassName": "QQmlShortForeign" + }, + { + "classInfos": [ + { + "name": "QML.Foreign", + "value": "qint16" + }, + { + "name": "QML.Using", + "value": "short" + } + ], + "className": "QQmlQint16Foreign", + "gadget": true, + "lineNumber": 276, + "qualifiedClassName": "QQmlQint16Foreign" + }, + { + "classInfos": [ + { + "name": "QML.Foreign", + "value": "int16_t" + }, + { + "name": "QML.Using", + "value": "short" + } + ], + "className": "QQmlInt16TForeign", + "gadget": true, + "lineNumber": 283, + "qualifiedClassName": "QQmlInt16TForeign" + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.Extended", + "value": "Number" + }, + { + "name": "QML.ExtensionIsJavaScript", + "value": "true" + }, + { + "name": "QML.Foreign", + "value": "ushort" + } + ], + "className": "QQmlUshortForeign", + "gadget": true, + "lineNumber": 290, + "qualifiedClassName": "QQmlUshortForeign" + }, + { + "classInfos": [ + { + "name": "QML.Foreign", + "value": "quint16" + }, + { + "name": "QML.Using", + "value": "ushort" + } + ], + "className": "QQmlQuint16Foreign", + "gadget": true, + "lineNumber": 298, + "qualifiedClassName": "QQmlQuint16Foreign" + }, + { + "classInfos": [ + { + "name": "QML.Foreign", + "value": "uint16_t" + }, + { + "name": "QML.Using", + "value": "ushort" + } + ], + "className": "QQmlUint16TForeign", + "gadget": true, + "lineNumber": 305, + "qualifiedClassName": "QQmlUint16TForeign" + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.Extended", + "value": "Number" + }, + { + "name": "QML.ExtensionIsJavaScript", + "value": "true" + }, + { + "name": "QML.Foreign", + "value": "uint" + } + ], + "className": "QQmlUintForeign", + "gadget": true, + "lineNumber": 312, + "qualifiedClassName": "QQmlUintForeign" + }, + { + "classInfos": [ + { + "name": "QML.Foreign", + "value": "quint32" + }, + { + "name": "QML.Using", + "value": "uint" + } + ], + "className": "QQmlQuint32Foreign", + "gadget": true, + "lineNumber": 320, + "qualifiedClassName": "QQmlQuint32Foreign" + }, + { + "classInfos": [ + { + "name": "QML.Foreign", + "value": "uint32_t" + }, + { + "name": "QML.Using", + "value": "uint" + } + ], + "className": "QQmlUint32TForeign", + "gadget": true, + "lineNumber": 327, + "qualifiedClassName": "QQmlUint32TForeign" + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.Extended", + "value": "Number" + }, + { + "name": "QML.ExtensionIsJavaScript", + "value": "true" + }, + { + "name": "QML.Foreign", + "value": "qlonglong" + }, + { + "name": "QML.PrimitiveAlias", + "value": "qsizetype" + } + ], + "className": "QQmlQlonglongForeign", + "gadget": true, + "lineNumber": 334, + "qualifiedClassName": "QQmlQlonglongForeign" + }, + { + "classInfos": [ + { + "name": "QML.Foreign", + "value": "qint64" + }, + { + "name": "QML.Using", + "value": "qlonglong" + } + ], + "className": "QQmlQint64Foreign", + "gadget": true, + "lineNumber": 346, + "qualifiedClassName": "QQmlQint64Foreign" + }, + { + "classInfos": [ + { + "name": "QML.Foreign", + "value": "int64_t" + }, + { + "name": "QML.Using", + "value": "qlonglong" + } + ], + "className": "QQmlInt64TForeign", + "gadget": true, + "lineNumber": 353, + "qualifiedClassName": "QQmlInt64TForeign" + }, + { + "classInfos": [ + { + "name": "QML.Foreign", + "value": "long" + }, + { + "name": "QML.Using", + "value": "int" + } + ], + "className": "QQmlLongForeign", + "gadget": true, + "lineNumber": 360, + "qualifiedClassName": "QQmlLongForeign" + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.Extended", + "value": "Number" + }, + { + "name": "QML.ExtensionIsJavaScript", + "value": "true" + }, + { + "name": "QML.Foreign", + "value": "qulonglong" + } + ], + "className": "QQmlQulonglongForeign", + "gadget": true, + "lineNumber": 373, + "qualifiedClassName": "QQmlQulonglongForeign" + }, + { + "classInfos": [ + { + "name": "QML.Foreign", + "value": "quint64" + }, + { + "name": "QML.Using", + "value": "qulonglong" + } + ], + "className": "QQmlQuint64Foreign", + "gadget": true, + "lineNumber": 381, + "qualifiedClassName": "QQmlQuint64Foreign" + }, + { + "classInfos": [ + { + "name": "QML.Foreign", + "value": "uint64_t" + }, + { + "name": "QML.Using", + "value": "qulonglong" + } + ], + "className": "QQmlUint64TForeign", + "gadget": true, + "lineNumber": 388, + "qualifiedClassName": "QQmlUint64TForeign" + }, + { + "classInfos": [ + { + "name": "QML.Foreign", + "value": "ulong" + }, + { + "name": "QML.Using", + "value": "uint" + } + ], + "className": "QQmlUlongForeign", + "gadget": true, + "lineNumber": 395, + "qualifiedClassName": "QQmlUlongForeign" + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.Extended", + "value": "Number" + }, + { + "name": "QML.ExtensionIsJavaScript", + "value": "true" + }, + { + "name": "QML.Foreign", + "value": "float" + } + ], + "className": "QQmlFloatForeign", + "gadget": true, + "lineNumber": 408, + "qualifiedClassName": "QQmlFloatForeign" + }, + { + "classInfos": [ + { + "name": "QML.Foreign", + "value": "qreal" + }, + { + "name": "QML.Using", + "value": "double" + } + ], + "className": "QQmlQRealForeign", + "gadget": true, + "lineNumber": 416, + "qualifiedClassName": "QQmlQRealForeign" + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.Foreign", + "value": "QChar" + }, + { + "name": "QML.Extended", + "value": "String" + }, + { + "name": "QML.ExtensionIsJavaScript", + "value": "true" + } + ], + "className": "QQmlQCharForeign", + "gadget": true, + "lineNumber": 429, + "qualifiedClassName": "QQmlQCharForeign" + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.Foreign", + "value": "QDate" + }, + { + "name": "QML.Extended", + "value": "Date" + }, + { + "name": "QML.ExtensionIsJavaScript", + "value": "true" + } + ], + "className": "QQmlQDateForeign", + "gadget": true, + "lineNumber": 437, + "qualifiedClassName": "QQmlQDateForeign" + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.Foreign", + "value": "QTime" + }, + { + "name": "QML.Extended", + "value": "Date" + }, + { + "name": "QML.ExtensionIsJavaScript", + "value": "true" + } + ], + "className": "QQmlQTimeForeign", + "gadget": true, + "lineNumber": 445, + "qualifiedClassName": "QQmlQTimeForeign" + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.Extended", + "value": "ArrayBuffer" + }, + { + "name": "QML.ExtensionIsJavaScript", + "value": "true" + }, + { + "name": "QML.Foreign", + "value": "QByteArray" + } + ], + "className": "QQmlQByteArrayForeign", + "gadget": true, + "lineNumber": 453, + "qualifiedClassName": "QQmlQByteArrayForeign" + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.Foreign", + "value": "QByteArrayList" + }, + { + "name": "QML.Sequence", + "value": "QByteArray" + } + ], + "className": "QQmlQByteArrayListForeign", + "gadget": true, + "lineNumber": 461, + "qualifiedClassName": "QQmlQByteArrayListForeign" + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.Foreign", + "value": "QStringList" + }, + { + "name": "QML.Sequence", + "value": "QString" + } + ], + "className": "QQmlQStringListForeign", + "gadget": true, + "lineNumber": 469, + "qualifiedClassName": "QQmlQStringListForeign" + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.Foreign", + "value": "QVariantList" + }, + { + "name": "QML.Sequence", + "value": "QVariant" + } + ], + "className": "QQmlQVariantListForeign", + "gadget": true, + "lineNumber": 477, + "qualifiedClassName": "QQmlQVariantListForeign" + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.Foreign", + "value": "QObjectList" + }, + { + "name": "QML.Sequence", + "value": "QObject*" + } + ], + "className": "QQmlQObjectListForeign", + "gadget": true, + "lineNumber": 485, + "qualifiedClassName": "QQmlQObjectListForeign" + }, + { + "classInfos": [ + { + "name": "QML.Foreign", + "value": "QList" + }, + { + "name": "QML.Using", + "value": "QObjectList" + } + ], + "className": "QQmlQListQObjectForeign", + "gadget": true, + "lineNumber": 493, + "qualifiedClassName": "QQmlQListQObjectForeign" + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.Foreign", + "value": "QJSValue" + }, + { + "name": "QML.Extended", + "value": "QQmlQJSValueForeign" + } + ], + "className": "QQmlQJSValueForeign", + "gadget": true, + "lineNumber": 500, + "qualifiedClassName": "QQmlQJSValueForeign" + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "Component" + }, + { + "name": "QML.Foreign", + "value": "QQmlComponent" + }, + { + "name": "QML.Attached", + "value": "QQmlComponentAttached" + } + ], + "className": "QQmlComponentForeign", + "gadget": true, + "lineNumber": 508, + "qualifiedClassName": "QQmlComponentForeign" + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.Foreign", + "value": "QQmlScriptString" + } + ], + "className": "QQmlScriptStringForeign", + "gadget": true, + "lineNumber": 516, + "qualifiedClassName": "QQmlScriptStringForeign" + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.Foreign", + "value": "QQmlV4FunctionPtr" + }, + { + "name": "QML.Extended", + "value": "QQmlV4FunctionPtrForeign" + } + ], + "className": "QQmlV4FunctionPtrForeign", + "gadget": true, + "lineNumber": 523, + "qualifiedClassName": "QQmlV4FunctionPtrForeign" + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.Foreign", + "value": "QJsonObject" + }, + { + "name": "QML.Extended", + "value": "Object" + }, + { + "name": "QML.ExtensionIsJavaScript", + "value": "true" + } + ], + "className": "QQmlQJsonObjectForeign", + "gadget": true, + "lineNumber": 531, + "qualifiedClassName": "QQmlQJsonObjectForeign" + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.Foreign", + "value": "QJsonValue" + }, + { + "name": "QML.Extended", + "value": "QQmlQJsonValueForeign" + } + ], + "className": "QQmlQJsonValueForeign", + "gadget": true, + "lineNumber": 539, + "qualifiedClassName": "QQmlQJsonValueForeign" + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.Foreign", + "value": "QJsonArray" + }, + { + "name": "QML.Sequence", + "value": "QJsonValue" + } + ], + "className": "QQmlQJsonArrayForeign", + "gadget": true, + "lineNumber": 547, + "qualifiedClassName": "QQmlQJsonArrayForeign" + } + ], + "inputFile": "qqmlbuiltins_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQmlAnimationTimer", + "lineNumber": 165, + "object": true, + "qualifiedClassName": "QQmlAnimationTimer", + "slots": [ + { + "access": "public", + "index": 0, + "name": "startAnimations", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "stopTimer", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QAbstractAnimationTimer" + } + ] + } + ], + "inputFile": "qabstractanimationjob_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QJSEngine", + "lineNumber": 24, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "uiLanguage", + "notify": "uiLanguageChanged", + "read": "uiLanguage", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setUiLanguage" + } + ], + "qualifiedClassName": "QJSEngine", + "signals": [ + { + "access": "public", + "index": 0, + "name": "uiLanguageChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qjsengine.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQmlAbstractProfilerAdapter", + "lineNumber": 29, + "object": true, + "qualifiedClassName": "QQmlAbstractProfilerAdapter", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "features", + "type": "quint64" + } + ], + "index": 0, + "name": "profilingEnabled", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "features", + "type": "quint64" + } + ], + "index": 1, + "name": "profilingEnabledWhileWaiting", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "profilingDisabled", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "profilingDisabledWhileWaiting", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "dataRequested", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "timer", + "type": "QElapsedTimer" + } + ], + "index": 5, + "name": "referenceTimeKnown", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QQmlProfilerDefinitions" + } + ] + }, + { + "className": "QQmlAbstractProfilerAdapterFactory", + "lineNumber": 74, + "object": true, + "qualifiedClassName": "QQmlAbstractProfilerAdapterFactory", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qqmlabstractprofileradapter_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQmlApplicationEngine", + "lineNumber": 16, + "object": true, + "qualifiedClassName": "QQmlApplicationEngine", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "object", + "type": "QObject*" + }, + { + "name": "url", + "type": "QUrl" + } + ], + "index": 0, + "name": "objectCreated", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "url", + "type": "QUrl" + } + ], + "index": 1, + "name": "objectCreationFailed", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "url", + "type": "QUrl" + } + ], + "index": 2, + "name": "load", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "filePath", + "type": "QString" + } + ], + "index": 3, + "name": "load", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "uri", + "type": "QAnyStringView" + }, + { + "name": "typeName", + "type": "QAnyStringView" + } + ], + "index": 4, + "name": "loadFromModule", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "initialProperties", + "type": "QVariantMap" + } + ], + "index": 5, + "name": "setInitialProperties", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "extraFileSelectors", + "type": "QStringList" + } + ], + "index": 6, + "name": "setExtraFileSelectors", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "data", + "type": "QByteArray" + }, + { + "name": "url", + "type": "QUrl" + } + ], + "index": 7, + "name": "loadData", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "data", + "type": "QByteArray" + } + ], + "index": 8, + "isCloned": true, + "name": "loadData", + "returnType": "void" + }, + { + "access": "private", + "index": 9, + "name": "_q_loadTranslations", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQmlEngine" + } + ] + } + ], + "inputFile": "qqmlapplicationengine.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "Qt" + }, + { + "name": "QML.Singleton", + "value": "true" + }, + { + "name": "QML.Extended", + "value": "Qt" + }, + { + "name": "QML.ExtensionIsNamespace", + "value": "true" + }, + { + "name": "QML.StrictArguments", + "value": "true" + } + ], + "className": "QtObject", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "LoadingMode", + "values": [ + "Asynchronous", + "Synchronous" + ] + } + ], + "lineNumber": 34, + "methods": [ + { + "access": "public", + "arguments": [ + { + "name": "url", + "type": "QString" + }, + { + "name": "callback", + "type": "QJSValue" + } + ], + "index": 0, + "name": "include", + "returnType": "QJSValue" + }, + { + "access": "public", + "arguments": [ + { + "name": "url", + "type": "QString" + } + ], + "index": 1, + "isCloned": true, + "name": "include", + "returnType": "QJSValue" + }, + { + "access": "public", + "arguments": [ + { + "name": "value", + "type": "QJSValue" + } + ], + "index": 2, + "name": "isQtObject", + "returnType": "bool" + }, + { + "access": "public", + "arguments": [ + { + "name": "name", + "type": "QString" + } + ], + "index": 3, + "name": "color", + "returnType": "QVariant" + }, + { + "access": "public", + "arguments": [ + { + "name": "r", + "type": "double" + }, + { + "name": "g", + "type": "double" + }, + { + "name": "b", + "type": "double" + }, + { + "name": "a", + "type": "double" + } + ], + "index": 4, + "name": "rgba", + "returnType": "QVariant" + }, + { + "access": "public", + "arguments": [ + { + "name": "r", + "type": "double" + }, + { + "name": "g", + "type": "double" + }, + { + "name": "b", + "type": "double" + } + ], + "index": 5, + "isCloned": true, + "name": "rgba", + "returnType": "QVariant" + }, + { + "access": "public", + "arguments": [ + { + "name": "h", + "type": "double" + }, + { + "name": "s", + "type": "double" + }, + { + "name": "l", + "type": "double" + }, + { + "name": "a", + "type": "double" + } + ], + "index": 6, + "name": "hsla", + "returnType": "QVariant" + }, + { + "access": "public", + "arguments": [ + { + "name": "h", + "type": "double" + }, + { + "name": "s", + "type": "double" + }, + { + "name": "l", + "type": "double" + } + ], + "index": 7, + "isCloned": true, + "name": "hsla", + "returnType": "QVariant" + }, + { + "access": "public", + "arguments": [ + { + "name": "h", + "type": "double" + }, + { + "name": "s", + "type": "double" + }, + { + "name": "v", + "type": "double" + }, + { + "name": "a", + "type": "double" + } + ], + "index": 8, + "name": "hsva", + "returnType": "QVariant" + }, + { + "access": "public", + "arguments": [ + { + "name": "h", + "type": "double" + }, + { + "name": "s", + "type": "double" + }, + { + "name": "v", + "type": "double" + } + ], + "index": 9, + "isCloned": true, + "name": "hsva", + "returnType": "QVariant" + }, + { + "access": "public", + "arguments": [ + { + "name": "lhs", + "type": "QVariant" + }, + { + "name": "rhs", + "type": "QVariant" + } + ], + "index": 10, + "name": "colorEqual", + "returnType": "bool" + }, + { + "access": "public", + "arguments": [ + { + "name": "x", + "type": "double" + }, + { + "name": "y", + "type": "double" + }, + { + "name": "width", + "type": "double" + }, + { + "name": "height", + "type": "double" + } + ], + "index": 11, + "name": "rect", + "returnType": "QRectF" + }, + { + "access": "public", + "arguments": [ + { + "name": "x", + "type": "double" + }, + { + "name": "y", + "type": "double" + } + ], + "index": 12, + "name": "point", + "returnType": "QPointF" + }, + { + "access": "public", + "arguments": [ + { + "name": "width", + "type": "double" + }, + { + "name": "height", + "type": "double" + } + ], + "index": 13, + "name": "size", + "returnType": "QSizeF" + }, + { + "access": "public", + "arguments": [ + { + "name": "x", + "type": "double" + }, + { + "name": "y", + "type": "double" + } + ], + "index": 14, + "name": "vector2d", + "returnType": "QVariant" + }, + { + "access": "public", + "arguments": [ + { + "name": "x", + "type": "double" + }, + { + "name": "y", + "type": "double" + }, + { + "name": "z", + "type": "double" + } + ], + "index": 15, + "name": "vector3d", + "returnType": "QVariant" + }, + { + "access": "public", + "arguments": [ + { + "name": "x", + "type": "double" + }, + { + "name": "y", + "type": "double" + }, + { + "name": "z", + "type": "double" + }, + { + "name": "w", + "type": "double" + } + ], + "index": 16, + "name": "vector4d", + "returnType": "QVariant" + }, + { + "access": "public", + "arguments": [ + { + "name": "scalar", + "type": "double" + }, + { + "name": "x", + "type": "double" + }, + { + "name": "y", + "type": "double" + }, + { + "name": "z", + "type": "double" + } + ], + "index": 17, + "name": "quaternion", + "returnType": "QVariant" + }, + { + "access": "public", + "index": 18, + "name": "matrix4x4", + "returnType": "QVariant" + }, + { + "access": "public", + "arguments": [ + { + "name": "m11", + "type": "double" + }, + { + "name": "m12", + "type": "double" + }, + { + "name": "m13", + "type": "double" + }, + { + "name": "m14", + "type": "double" + }, + { + "name": "m21", + "type": "double" + }, + { + "name": "m22", + "type": "double" + }, + { + "name": "m23", + "type": "double" + }, + { + "name": "m24", + "type": "double" + }, + { + "name": "m31", + "type": "double" + }, + { + "name": "m32", + "type": "double" + }, + { + "name": "m33", + "type": "double" + }, + { + "name": "m34", + "type": "double" + }, + { + "name": "m41", + "type": "double" + }, + { + "name": "m42", + "type": "double" + }, + { + "name": "m43", + "type": "double" + }, + { + "name": "m44", + "type": "double" + } + ], + "index": 19, + "name": "matrix4x4", + "returnType": "QVariant" + }, + { + "access": "public", + "arguments": [ + { + "name": "value", + "type": "QJSValue" + } + ], + "index": 20, + "name": "matrix4x4", + "returnType": "QVariant" + }, + { + "access": "public", + "arguments": [ + { + "name": "color", + "type": "QJSValue" + }, + { + "name": "factor", + "type": "double" + } + ], + "index": 21, + "name": "lighter", + "returnType": "QVariant" + }, + { + "access": "public", + "arguments": [ + { + "name": "color", + "type": "QJSValue" + } + ], + "index": 22, + "isCloned": true, + "name": "lighter", + "returnType": "QVariant" + }, + { + "access": "public", + "arguments": [ + { + "name": "color", + "type": "QJSValue" + }, + { + "name": "factor", + "type": "double" + } + ], + "index": 23, + "name": "darker", + "returnType": "QVariant" + }, + { + "access": "public", + "arguments": [ + { + "name": "color", + "type": "QJSValue" + } + ], + "index": 24, + "isCloned": true, + "name": "darker", + "returnType": "QVariant" + }, + { + "access": "public", + "arguments": [ + { + "name": "baseColor", + "type": "QJSValue" + }, + { + "name": "value", + "type": "double" + } + ], + "index": 25, + "name": "alpha", + "returnType": "QVariant" + }, + { + "access": "public", + "arguments": [ + { + "name": "baseColor", + "type": "QJSValue" + }, + { + "name": "tintColor", + "type": "QJSValue" + } + ], + "index": 26, + "name": "tint", + "returnType": "QVariant" + }, + { + "access": "public", + "arguments": [ + { + "name": "date", + "type": "QDate" + }, + { + "name": "format", + "type": "QString" + } + ], + "index": 27, + "name": "formatDate", + "returnType": "QString" + }, + { + "access": "public", + "arguments": [ + { + "name": "dateTime", + "type": "QDateTime" + }, + { + "name": "format", + "type": "QString" + } + ], + "index": 28, + "name": "formatDate", + "returnType": "QString" + }, + { + "access": "public", + "arguments": [ + { + "name": "string", + "type": "QString" + }, + { + "name": "format", + "type": "QString" + } + ], + "index": 29, + "name": "formatDate", + "returnType": "QString" + }, + { + "access": "public", + "arguments": [ + { + "name": "date", + "type": "QDate" + }, + { + "name": "format", + "type": "Qt::DateFormat" + } + ], + "index": 30, + "name": "formatDate", + "returnType": "QString" + }, + { + "access": "public", + "arguments": [ + { + "name": "dateTime", + "type": "QDateTime" + }, + { + "name": "format", + "type": "Qt::DateFormat" + } + ], + "index": 31, + "name": "formatDate", + "returnType": "QString" + }, + { + "access": "public", + "arguments": [ + { + "name": "string", + "type": "QString" + }, + { + "name": "format", + "type": "Qt::DateFormat" + } + ], + "index": 32, + "name": "formatDate", + "returnType": "QString" + }, + { + "access": "public", + "arguments": [ + { + "name": "time", + "type": "QTime" + }, + { + "name": "format", + "type": "QString" + } + ], + "index": 33, + "name": "formatTime", + "returnType": "QString" + }, + { + "access": "public", + "arguments": [ + { + "name": "dateTime", + "type": "QDateTime" + }, + { + "name": "format", + "type": "QString" + } + ], + "index": 34, + "name": "formatTime", + "returnType": "QString" + }, + { + "access": "public", + "arguments": [ + { + "name": "time", + "type": "QString" + }, + { + "name": "format", + "type": "QString" + } + ], + "index": 35, + "name": "formatTime", + "returnType": "QString" + }, + { + "access": "public", + "arguments": [ + { + "name": "time", + "type": "QTime" + }, + { + "name": "format", + "type": "Qt::DateFormat" + } + ], + "index": 36, + "name": "formatTime", + "returnType": "QString" + }, + { + "access": "public", + "arguments": [ + { + "name": "dateTime", + "type": "QDateTime" + }, + { + "name": "format", + "type": "Qt::DateFormat" + } + ], + "index": 37, + "name": "formatTime", + "returnType": "QString" + }, + { + "access": "public", + "arguments": [ + { + "name": "time", + "type": "QString" + }, + { + "name": "format", + "type": "Qt::DateFormat" + } + ], + "index": 38, + "name": "formatTime", + "returnType": "QString" + }, + { + "access": "public", + "arguments": [ + { + "name": "date", + "type": "QDateTime" + }, + { + "name": "format", + "type": "QString" + } + ], + "index": 39, + "name": "formatDateTime", + "returnType": "QString" + }, + { + "access": "public", + "arguments": [ + { + "name": "string", + "type": "QString" + }, + { + "name": "format", + "type": "QString" + } + ], + "index": 40, + "name": "formatDateTime", + "returnType": "QString" + }, + { + "access": "public", + "arguments": [ + { + "name": "date", + "type": "QDateTime" + }, + { + "name": "format", + "type": "Qt::DateFormat" + } + ], + "index": 41, + "name": "formatDateTime", + "returnType": "QString" + }, + { + "access": "public", + "arguments": [ + { + "name": "string", + "type": "QString" + }, + { + "name": "format", + "type": "Qt::DateFormat" + } + ], + "index": 42, + "name": "formatDateTime", + "returnType": "QString" + }, + { + "access": "public", + "arguments": [ + { + "name": "date", + "type": "QDate" + }, + { + "name": "locale", + "type": "QLocale" + }, + { + "name": "formatType", + "type": "QLocale::FormatType" + } + ], + "index": 43, + "name": "formatDate", + "returnType": "QString" + }, + { + "access": "public", + "arguments": [ + { + "name": "date", + "type": "QDate" + }, + { + "name": "locale", + "type": "QLocale" + } + ], + "index": 44, + "isCloned": true, + "name": "formatDate", + "returnType": "QString" + }, + { + "access": "public", + "arguments": [ + { + "name": "date", + "type": "QDate" + } + ], + "index": 45, + "isCloned": true, + "name": "formatDate", + "returnType": "QString" + }, + { + "access": "public", + "arguments": [ + { + "name": "dateTime", + "type": "QDateTime" + }, + { + "name": "locale", + "type": "QLocale" + }, + { + "name": "formatType", + "type": "QLocale::FormatType" + } + ], + "index": 46, + "name": "formatDate", + "returnType": "QString" + }, + { + "access": "public", + "arguments": [ + { + "name": "dateTime", + "type": "QDateTime" + }, + { + "name": "locale", + "type": "QLocale" + } + ], + "index": 47, + "isCloned": true, + "name": "formatDate", + "returnType": "QString" + }, + { + "access": "public", + "arguments": [ + { + "name": "dateTime", + "type": "QDateTime" + } + ], + "index": 48, + "isCloned": true, + "name": "formatDate", + "returnType": "QString" + }, + { + "access": "public", + "arguments": [ + { + "name": "string", + "type": "QString" + }, + { + "name": "locale", + "type": "QLocale" + }, + { + "name": "formatType", + "type": "QLocale::FormatType" + } + ], + "index": 49, + "name": "formatDate", + "returnType": "QString" + }, + { + "access": "public", + "arguments": [ + { + "name": "string", + "type": "QString" + }, + { + "name": "locale", + "type": "QLocale" + } + ], + "index": 50, + "isCloned": true, + "name": "formatDate", + "returnType": "QString" + }, + { + "access": "public", + "arguments": [ + { + "name": "string", + "type": "QString" + } + ], + "index": 51, + "isCloned": true, + "name": "formatDate", + "returnType": "QString" + }, + { + "access": "public", + "arguments": [ + { + "name": "time", + "type": "QTime" + }, + { + "name": "locale", + "type": "QLocale" + }, + { + "name": "formatType", + "type": "QLocale::FormatType" + } + ], + "index": 52, + "name": "formatTime", + "returnType": "QString" + }, + { + "access": "public", + "arguments": [ + { + "name": "time", + "type": "QTime" + }, + { + "name": "locale", + "type": "QLocale" + } + ], + "index": 53, + "isCloned": true, + "name": "formatTime", + "returnType": "QString" + }, + { + "access": "public", + "arguments": [ + { + "name": "time", + "type": "QTime" + } + ], + "index": 54, + "isCloned": true, + "name": "formatTime", + "returnType": "QString" + }, + { + "access": "public", + "arguments": [ + { + "name": "dateTime", + "type": "QDateTime" + }, + { + "name": "locale", + "type": "QLocale" + }, + { + "name": "formatType", + "type": "QLocale::FormatType" + } + ], + "index": 55, + "name": "formatTime", + "returnType": "QString" + }, + { + "access": "public", + "arguments": [ + { + "name": "dateTime", + "type": "QDateTime" + }, + { + "name": "locale", + "type": "QLocale" + } + ], + "index": 56, + "isCloned": true, + "name": "formatTime", + "returnType": "QString" + }, + { + "access": "public", + "arguments": [ + { + "name": "dateTime", + "type": "QDateTime" + } + ], + "index": 57, + "isCloned": true, + "name": "formatTime", + "returnType": "QString" + }, + { + "access": "public", + "arguments": [ + { + "name": "time", + "type": "QString" + }, + { + "name": "locale", + "type": "QLocale" + }, + { + "name": "formatType", + "type": "QLocale::FormatType" + } + ], + "index": 58, + "name": "formatTime", + "returnType": "QString" + }, + { + "access": "public", + "arguments": [ + { + "name": "time", + "type": "QString" + }, + { + "name": "locale", + "type": "QLocale" + } + ], + "index": 59, + "isCloned": true, + "name": "formatTime", + "returnType": "QString" + }, + { + "access": "public", + "arguments": [ + { + "name": "time", + "type": "QString" + } + ], + "index": 60, + "isCloned": true, + "name": "formatTime", + "returnType": "QString" + }, + { + "access": "public", + "arguments": [ + { + "name": "date", + "type": "QDateTime" + }, + { + "name": "locale", + "type": "QLocale" + }, + { + "name": "formatType", + "type": "QLocale::FormatType" + } + ], + "index": 61, + "name": "formatDateTime", + "returnType": "QString" + }, + { + "access": "public", + "arguments": [ + { + "name": "date", + "type": "QDateTime" + }, + { + "name": "locale", + "type": "QLocale" + } + ], + "index": 62, + "isCloned": true, + "name": "formatDateTime", + "returnType": "QString" + }, + { + "access": "public", + "arguments": [ + { + "name": "date", + "type": "QDateTime" + } + ], + "index": 63, + "isCloned": true, + "name": "formatDateTime", + "returnType": "QString" + }, + { + "access": "public", + "arguments": [ + { + "name": "string", + "type": "QString" + }, + { + "name": "locale", + "type": "QLocale" + }, + { + "name": "formatType", + "type": "QLocale::FormatType" + } + ], + "index": 64, + "name": "formatDateTime", + "returnType": "QString" + }, + { + "access": "public", + "arguments": [ + { + "name": "string", + "type": "QString" + }, + { + "name": "locale", + "type": "QLocale" + } + ], + "index": 65, + "isCloned": true, + "name": "formatDateTime", + "returnType": "QString" + }, + { + "access": "public", + "arguments": [ + { + "name": "string", + "type": "QString" + } + ], + "index": 66, + "isCloned": true, + "name": "formatDateTime", + "returnType": "QString" + }, + { + "access": "public", + "index": 67, + "name": "locale", + "returnType": "QLocale" + }, + { + "access": "public", + "arguments": [ + { + "name": "name", + "type": "QString" + } + ], + "index": 68, + "name": "locale", + "returnType": "QLocale" + }, + { + "access": "public", + "arguments": [ + { + "name": "url", + "type": "QUrl" + } + ], + "index": 69, + "name": "url", + "returnType": "QUrl" + }, + { + "access": "public", + "arguments": [ + { + "name": "url", + "type": "QUrl" + } + ], + "index": 70, + "name": "resolvedUrl", + "returnType": "QUrl" + }, + { + "access": "public", + "arguments": [ + { + "name": "url", + "type": "QUrl" + }, + { + "name": "context", + "type": "QObject*" + } + ], + "index": 71, + "name": "resolvedUrl", + "returnType": "QUrl" + }, + { + "access": "public", + "arguments": [ + { + "name": "url", + "type": "QUrl" + } + ], + "index": 72, + "name": "openUrlExternally", + "returnType": "bool" + }, + { + "access": "public", + "arguments": [ + { + "name": "fontSpecifier", + "type": "QJSValue" + } + ], + "index": 73, + "name": "font", + "returnType": "QVariant" + }, + { + "access": "public", + "index": 74, + "name": "fontFamilies", + "returnType": "QStringList" + }, + { + "access": "public", + "arguments": [ + { + "name": "data", + "type": "QString" + } + ], + "index": 75, + "name": "md5", + "returnType": "QString" + }, + { + "access": "public", + "arguments": [ + { + "name": "data", + "type": "QString" + } + ], + "index": 76, + "name": "btoa", + "returnType": "QString" + }, + { + "access": "public", + "arguments": [ + { + "name": "data", + "type": "QString" + } + ], + "index": 77, + "name": "atob", + "returnType": "QString" + }, + { + "access": "public", + "index": 78, + "name": "quit", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "retCode", + "type": "int" + } + ], + "index": 79, + "name": "exit", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "qml", + "type": "QString" + }, + { + "name": "parent", + "type": "QObject*" + }, + { + "name": "url", + "type": "QUrl" + } + ], + "index": 80, + "name": "createQmlObject", + "returnType": "QObject*" + }, + { + "access": "public", + "arguments": [ + { + "name": "qml", + "type": "QString" + }, + { + "name": "parent", + "type": "QObject*" + } + ], + "index": 81, + "isCloned": true, + "name": "createQmlObject", + "returnType": "QObject*" + }, + { + "access": "public", + "arguments": [ + { + "name": "url", + "type": "QUrl" + }, + { + "name": "parent", + "type": "QObject*" + } + ], + "index": 82, + "name": "createComponent", + "returnType": "QQmlComponent*" + }, + { + "access": "public", + "arguments": [ + { + "name": "url", + "type": "QUrl" + }, + { + "name": "mode", + "type": "QQmlComponent::CompilationMode" + }, + { + "name": "parent", + "type": "QObject*" + } + ], + "index": 83, + "name": "createComponent", + "returnType": "QQmlComponent*" + }, + { + "access": "public", + "arguments": [ + { + "name": "url", + "type": "QUrl" + }, + { + "name": "mode", + "type": "QQmlComponent::CompilationMode" + } + ], + "index": 84, + "isCloned": true, + "name": "createComponent", + "returnType": "QQmlComponent*" + }, + { + "access": "public", + "arguments": [ + { + "name": "url", + "type": "QUrl" + } + ], + "index": 85, + "isCloned": true, + "name": "createComponent", + "returnType": "QQmlComponent*" + }, + { + "access": "public", + "arguments": [ + { + "name": "moduleUri", + "type": "QString" + }, + { + "name": "typeName", + "type": "QString" + }, + { + "name": "parent", + "type": "QObject*" + } + ], + "index": 86, + "name": "createComponent", + "returnType": "QQmlComponent*" + }, + { + "access": "public", + "arguments": [ + { + "name": "moduleUri", + "type": "QString" + }, + { + "name": "typeName", + "type": "QString" + }, + { + "name": "mode", + "type": "QQmlComponent::CompilationMode" + }, + { + "name": "parent", + "type": "QObject*" + } + ], + "index": 87, + "name": "createComponent", + "returnType": "QQmlComponent*" + }, + { + "access": "public", + "arguments": [ + { + "name": "moduleUri", + "type": "QString" + }, + { + "name": "typeName", + "type": "QString" + }, + { + "name": "mode", + "type": "QQmlComponent::CompilationMode" + } + ], + "index": 88, + "isCloned": true, + "name": "createComponent", + "returnType": "QQmlComponent*" + }, + { + "access": "public", + "arguments": [ + { + "name": "moduleUri", + "type": "QString" + }, + { + "name": "typeName", + "type": "QString" + } + ], + "index": 89, + "isCloned": true, + "name": "createComponent", + "returnType": "QQmlComponent*" + }, + { + "access": "public", + "arguments": [ + { + "name": "function", + "type": "QJSValue" + } + ], + "index": 90, + "name": "binding", + "returnType": "QJSValue" + }, + { + "access": "public", + "arguments": [ + { + "name": "args", + "type": "QQmlV4FunctionPtr" + } + ], + "index": 91, + "name": "callLater", + "returnType": "void" + } + ], + "object": true, + "properties": [ + { + "constant": true, + "designable": true, + "final": false, + "index": 0, + "name": "application", + "read": "application", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlApplication*", + "user": false + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 1, + "name": "platform", + "read": "platform", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlPlatform*", + "user": false + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 2, + "name": "inputMethod", + "read": "inputMethod", + "required": false, + "scriptable": true, + "stored": true, + "type": "QObject*", + "user": false + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 3, + "name": "styleHints", + "read": "styleHints", + "required": false, + "scriptable": true, + "stored": true, + "type": "QObject*", + "user": false + }, + { + "bindable": "uiLanguageBindable", + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "uiLanguage", + "read": "uiLanguage", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setUiLanguage" + } + ], + "qualifiedClassName": "QtObject", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qqmlbuiltinfunctions_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQmlComponent", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "CompilationMode", + "values": [ + "PreferSynchronous", + "Asynchronous" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "Status", + "values": [ + "Null", + "Ready", + "Loading", + "Error" + ] + } + ], + "lineNumber": 31, + "methods": [ + { + "access": "public", + "index": 7, + "name": "errorString", + "returnType": "QString" + }, + { + "access": "protected", + "arguments": [ + { + "type": "QQmlV4FunctionPtr" + } + ], + "index": 8, + "name": "createObject", + "returnType": "void" + }, + { + "access": "protected", + "arguments": [ + { + "name": "parent", + "type": "QObject*" + }, + { + "name": "properties", + "type": "QVariantMap" + } + ], + "index": 9, + "name": "createObject", + "returnType": "QObject*" + }, + { + "access": "protected", + "arguments": [ + { + "name": "parent", + "type": "QObject*" + } + ], + "index": 10, + "isCloned": true, + "name": "createObject", + "returnType": "QObject*" + }, + { + "access": "protected", + "index": 11, + "isCloned": true, + "name": "createObject", + "returnType": "QObject*" + }, + { + "access": "protected", + "arguments": [ + { + "type": "QQmlV4FunctionPtr" + } + ], + "index": 12, + "name": "incubateObject", + "returnType": "void" + } + ], + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "progress", + "notify": "progressChanged", + "read": "progress", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "status", + "notify": "statusChanged", + "read": "status", + "required": false, + "scriptable": true, + "stored": true, + "type": "Status", + "user": false + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 2, + "name": "url", + "read": "url", + "required": false, + "scriptable": true, + "stored": true, + "type": "QUrl", + "user": false + } + ], + "qualifiedClassName": "QQmlComponent", + "signals": [ + { + "access": "public", + "arguments": [ + { + "type": "QQmlComponent::Status" + } + ], + "index": 0, + "name": "statusChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "qreal" + } + ], + "index": 1, + "name": "progressChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "url", + "type": "QUrl" + } + ], + "index": 2, + "name": "loadUrl", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "url", + "type": "QUrl" + }, + { + "name": "mode", + "type": "CompilationMode" + } + ], + "index": 3, + "name": "loadUrl", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "uri", + "type": "QAnyStringView" + }, + { + "name": "typeName", + "type": "QAnyStringView" + }, + { + "name": "mode", + "type": "QQmlComponent::CompilationMode" + } + ], + "index": 4, + "name": "loadFromModule", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "uri", + "type": "QAnyStringView" + }, + { + "name": "typeName", + "type": "QAnyStringView" + } + ], + "index": 5, + "isCloned": true, + "name": "loadFromModule", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QByteArray" + }, + { + "name": "baseUrl", + "type": "QUrl" + } + ], + "index": 6, + "name": "setData", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qqmlcomponent.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQmlComponentAttached", + "lineNumber": 27, + "object": true, + "qualifiedClassName": "QQmlComponentAttached", + "signals": [ + { + "access": "public", + "index": 0, + "name": "completed", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "destruction", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qqmlcomponentattached_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQmlContext", + "lineNumber": 24, + "object": true, + "qualifiedClassName": "QQmlContext", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qqmlcontext.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQmlDebugConnector", + "lineNumber": 53, + "object": true, + "qualifiedClassName": "QQmlDebugConnector", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "className": "QQmlDebugConnectorFactory", + "lineNumber": 90, + "object": true, + "qualifiedClassName": "QQmlDebugConnectorFactory", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qqmldebugconnector_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQmlDebugServer", + "lineNumber": 25, + "object": true, + "qualifiedClassName": "QQmlDebugServer", + "superClasses": [ + { + "access": "public", + "name": "QQmlDebugConnector" + } + ] + } + ], + "inputFile": "qqmldebugserver_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQmlDebugServerConnection", + "lineNumber": 24, + "object": true, + "qualifiedClassName": "QQmlDebugServerConnection", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "className": "QQmlDebugServerConnectionFactory", + "lineNumber": 40, + "object": true, + "qualifiedClassName": "QQmlDebugServerConnectionFactory", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qqmldebugserverconnection_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQmlDebugService", + "lineNumber": 30, + "object": true, + "qualifiedClassName": "QQmlDebugService", + "signals": [ + { + "access": "public", + "arguments": [ + { + "type": "QJSEngine*" + } + ], + "index": 0, + "name": "attachedToEngine", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QJSEngine*" + } + ], + "index": 1, + "name": "detachedFromEngine", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "name", + "type": "QString" + }, + { + "name": "message", + "type": "QByteArray" + } + ], + "index": 2, + "name": "messageToClient", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "name", + "type": "QString" + }, + { + "name": "messages", + "type": "QList" + } + ], + "index": 3, + "name": "messagesToClient", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qqmldebugservice_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQmlDebugServiceFactory", + "lineNumber": 22, + "object": true, + "qualifiedClassName": "QQmlDebugServiceFactory", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qqmldebugservicefactory_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QV4DebugService", + "lineNumber": 81, + "object": true, + "qualifiedClassName": "QV4DebugService", + "superClasses": [ + { + "access": "public", + "name": "QQmlDebugService" + } + ] + }, + { + "className": "QQmlProfilerService", + "lineNumber": 99, + "object": true, + "qualifiedClassName": "QQmlProfilerService", + "superClasses": [ + { + "access": "public", + "name": "QQmlDebugService" + } + ] + }, + { + "className": "QQmlEngineDebugService", + "lineNumber": 123, + "object": true, + "qualifiedClassName": "QQmlEngineDebugService", + "superClasses": [ + { + "access": "public", + "name": "QQmlDebugService" + } + ] + }, + { + "className": "QQmlDebugTranslationService", + "lineNumber": 163, + "object": true, + "qualifiedClassName": "QQmlDebugTranslationService", + "superClasses": [ + { + "access": "public", + "name": "QQmlDebugService" + } + ] + }, + { + "className": "QQmlInspectorService", + "lineNumber": 181, + "object": true, + "qualifiedClassName": "QQmlInspectorService", + "superClasses": [ + { + "access": "public", + "name": "QQmlDebugService" + } + ] + }, + { + "className": "QDebugMessageService", + "lineNumber": 200, + "object": true, + "qualifiedClassName": "QDebugMessageService", + "superClasses": [ + { + "access": "public", + "name": "QQmlDebugService" + } + ] + }, + { + "className": "QQmlEngineControlService", + "lineNumber": 217, + "object": true, + "qualifiedClassName": "QQmlEngineControlService", + "superClasses": [ + { + "access": "public", + "name": "QQmlDebugService" + } + ] + }, + { + "className": "QQmlNativeDebugService", + "lineNumber": 233, + "object": true, + "qualifiedClassName": "QQmlNativeDebugService", + "superClasses": [ + { + "access": "public", + "name": "QQmlDebugService" + } + ] + } + ], + "inputFile": "qqmldebugserviceinterfaces_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQmlDelayedCallQueue", + "lineNumber": 27, + "object": true, + "qualifiedClassName": "QQmlDelayedCallQueue", + "slots": [ + { + "access": "public", + "index": 0, + "name": "ticked", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qqmldelayedcallqueue_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQmlImageProviderBase", + "lineNumber": 17, + "object": true, + "qualifiedClassName": "QQmlImageProviderBase", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "className": "QQmlEngine", + "lineNumber": 56, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "offlineStoragePath", + "notify": "offlineStoragePathChanged", + "read": "offlineStoragePath", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setOfflineStoragePath" + } + ], + "qualifiedClassName": "QQmlEngine", + "signals": [ + { + "access": "public", + "index": 0, + "name": "offlineStoragePathChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "quit", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "retCode", + "type": "int" + } + ], + "index": 2, + "name": "exit", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "warnings", + "type": "QList" + } + ], + "index": 3, + "name": "warnings", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "index": 4, + "name": "retranslate", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QJSEngine" + } + ] + } + ], + "inputFile": "qqmlengine.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQmlExpression", + "lineNumber": 21, + "object": true, + "qualifiedClassName": "QQmlExpression", + "signals": [ + { + "access": "public", + "index": 0, + "name": "valueChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qqmlexpression.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQmlExtensionPlugin", + "interfaces": [ + [ + { + "className": "QQmlExtensionInterface", + "id": "\"org.qt-project.Qt.QQmlExtensionInterface/1.0\"" + } + ], + [ + { + "className": "QQmlTypesExtensionInterface", + "id": "\"org.qt-project.Qt.QQmlTypesExtensionInterface/1.0\"" + } + ] + ], + "lineNumber": 25, + "object": true, + "qualifiedClassName": "QQmlExtensionPlugin", + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QQmlExtensionInterface" + } + ] + }, + { + "className": "QQmlEngineExtensionPlugin", + "interfaces": [ + [ + { + "className": "QQmlEngineExtensionInterface", + "id": "\"org.qt-project.Qt.QQmlEngineExtensionInterface\"" + } + ] + ], + "lineNumber": 50, + "object": true, + "qualifiedClassName": "QQmlEngineExtensionPlugin", + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QQmlEngineExtensionInterface" + } + ] + } + ], + "inputFile": "qqmlextensionplugin.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQmlFileSelector", + "lineNumber": 16, + "object": true, + "qualifiedClassName": "QQmlFileSelector", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qqmlfileselector.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + } + ], + "className": "QQmlApplication", + "lineNumber": 265, + "object": true, + "properties": [ + { + "constant": true, + "designable": true, + "final": false, + "index": 0, + "name": "arguments", + "read": "args", + "required": false, + "scriptable": true, + "stored": true, + "type": "QStringList", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "name", + "notify": "nameChanged", + "read": "name", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setName" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "version", + "notify": "versionChanged", + "read": "version", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setVersion" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "organization", + "notify": "organizationChanged", + "read": "organization", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setOrganization" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "domain", + "notify": "domainChanged", + "read": "domain", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setDomain" + } + ], + "qualifiedClassName": "QQmlApplication", + "signals": [ + { + "access": "public", + "index": 0, + "name": "aboutToQuit", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "nameChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "versionChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "organizationChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "domainChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "QString" + } + ], + "index": 5, + "name": "setName", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "QString" + } + ], + "index": 6, + "name": "setVersion", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "QString" + } + ], + "index": 7, + "name": "setOrganization", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "QString" + } + ], + "index": 8, + "name": "setDomain", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qqmlglobal_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + } + ], + "className": "QQmlLocale", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "DayOfWeek", + "values": [ + "Sunday", + "Monday", + "Tuesday", + "Wednesday", + "Thursday", + "Friday", + "Saturday" + ] + } + ], + "gadget": true, + "lineNumber": 60, + "qualifiedClassName": "QQmlLocale", + "superClasses": [ + { + "access": "public", + "name": "QLocale" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.Foreign", + "value": "QList" + }, + { + "name": "QML.Sequence", + "value": "QQmlLocale::DayOfWeek" + } + ], + "className": "DayOfWeekList", + "gadget": true, + "lineNumber": 85, + "qualifiedClassName": "DayOfWeekList" + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.Foreign", + "value": "QLocale" + }, + { + "name": "QML.Extended", + "value": "QQmlLocaleValueType" + }, + { + "name": "QML.Creatable", + "value": "true" + }, + { + "name": "QML.CreationMethod", + "value": "construct" + } + ], + "className": "QQmlLocaleValueType", + "constructors": [ + { + "access": "public", + "arguments": [ + { + "name": "name", + "type": "QString" + } + ], + "index": 0, + "name": "QQmlLocaleValueType", + "returnType": "" + } + ], + "gadget": true, + "lineNumber": 93, + "methods": [ + { + "access": "public", + "arguments": [ + { + "name": "format", + "type": "QLocale::CurrencySymbolFormat" + } + ], + "index": 0, + "name": "currencySymbol", + "returnType": "QString" + }, + { + "access": "public", + "index": 1, + "isCloned": true, + "name": "currencySymbol", + "returnType": "QString" + }, + { + "access": "public", + "arguments": [ + { + "name": "format", + "type": "QLocale::FormatType" + } + ], + "index": 2, + "name": "dateTimeFormat", + "returnType": "QString" + }, + { + "access": "public", + "index": 3, + "isCloned": true, + "name": "dateTimeFormat", + "returnType": "QString" + }, + { + "access": "public", + "arguments": [ + { + "name": "format", + "type": "QLocale::FormatType" + } + ], + "index": 4, + "name": "timeFormat", + "returnType": "QString" + }, + { + "access": "public", + "index": 5, + "isCloned": true, + "name": "timeFormat", + "returnType": "QString" + }, + { + "access": "public", + "arguments": [ + { + "name": "format", + "type": "QLocale::FormatType" + } + ], + "index": 6, + "name": "dateFormat", + "returnType": "QString" + }, + { + "access": "public", + "index": 7, + "isCloned": true, + "name": "dateFormat", + "returnType": "QString" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + }, + { + "name": "format", + "type": "QLocale::FormatType" + } + ], + "index": 8, + "name": "monthName", + "returnType": "QString" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + } + ], + "index": 9, + "isCloned": true, + "name": "monthName", + "returnType": "QString" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + }, + { + "name": "format", + "type": "QLocale::FormatType" + } + ], + "index": 10, + "name": "standaloneMonthName", + "returnType": "QString" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + } + ], + "index": 11, + "isCloned": true, + "name": "standaloneMonthName", + "returnType": "QString" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + }, + { + "name": "format", + "type": "QLocale::FormatType" + } + ], + "index": 12, + "name": "dayName", + "returnType": "QString" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + } + ], + "index": 13, + "isCloned": true, + "name": "dayName", + "returnType": "QString" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + }, + { + "name": "format", + "type": "QLocale::FormatType" + } + ], + "index": 14, + "name": "standaloneDayName", + "returnType": "QString" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + } + ], + "index": 15, + "isCloned": true, + "name": "standaloneDayName", + "returnType": "QString" + }, + { + "access": "public", + "arguments": [ + { + "name": "args", + "type": "QQmlV4FunctionPtr" + } + ], + "index": 16, + "name": "formattedDataSize", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "bytes", + "type": "double" + }, + { + "name": "precision", + "type": "int" + }, + { + "name": "format", + "type": "QLocale::DataSizeFormats" + } + ], + "index": 17, + "name": "formattedDataSize", + "returnType": "QString" + }, + { + "access": "public", + "arguments": [ + { + "name": "bytes", + "type": "double" + }, + { + "name": "precision", + "type": "int" + } + ], + "index": 18, + "isCloned": true, + "name": "formattedDataSize", + "returnType": "QString" + }, + { + "access": "public", + "arguments": [ + { + "name": "bytes", + "type": "double" + } + ], + "index": 19, + "isCloned": true, + "name": "formattedDataSize", + "returnType": "QString" + }, + { + "access": "public", + "arguments": [ + { + "name": "args", + "type": "QQmlV4FunctionPtr" + } + ], + "index": 20, + "name": "toString", + "returnType": "void" + }, + { + "access": "public", + "index": 21, + "name": "toString", + "returnType": "QString" + }, + { + "access": "public", + "arguments": [ + { + "name": "i", + "type": "int" + } + ], + "index": 22, + "name": "toString", + "returnType": "QString" + }, + { + "access": "public", + "arguments": [ + { + "name": "f", + "type": "double" + } + ], + "index": 23, + "name": "toString", + "returnType": "QString" + }, + { + "access": "public", + "arguments": [ + { + "name": "f", + "type": "double" + }, + { + "name": "format", + "type": "QString" + }, + { + "name": "precision", + "type": "int" + } + ], + "index": 24, + "name": "toString", + "returnType": "QString" + }, + { + "access": "public", + "arguments": [ + { + "name": "f", + "type": "double" + }, + { + "name": "format", + "type": "QString" + } + ], + "index": 25, + "isCloned": true, + "name": "toString", + "returnType": "QString" + }, + { + "access": "public", + "arguments": [ + { + "name": "dateTime", + "type": "QDateTime" + }, + { + "name": "format", + "type": "QString" + } + ], + "index": 26, + "name": "toString", + "returnType": "QString" + }, + { + "access": "public", + "arguments": [ + { + "name": "dateTime", + "type": "QDateTime" + }, + { + "name": "format", + "type": "QLocale::FormatType" + } + ], + "index": 27, + "name": "toString", + "returnType": "QString" + }, + { + "access": "public", + "arguments": [ + { + "name": "dateTime", + "type": "QDateTime" + } + ], + "index": 28, + "isCloned": true, + "name": "toString", + "returnType": "QString" + } + ], + "properties": [ + { + "constant": true, + "designable": true, + "final": false, + "index": 0, + "name": "firstDayOfWeek", + "read": "firstDayOfWeek", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlLocale::DayOfWeek", + "user": false + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 1, + "name": "measurementSystem", + "read": "measurementSystem", + "required": false, + "scriptable": true, + "stored": true, + "type": "QLocale::MeasurementSystem", + "user": false + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 2, + "name": "textDirection", + "read": "textDirection", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::LayoutDirection", + "user": false + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 3, + "name": "weekDays", + "read": "weekDays", + "required": false, + "scriptable": true, + "stored": true, + "type": "QList", + "user": false + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 4, + "name": "uiLanguages", + "read": "uiLanguages", + "required": false, + "scriptable": true, + "stored": true, + "type": "QStringList", + "user": false + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 5, + "name": "name", + "read": "name", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 6, + "name": "nativeLanguageName", + "read": "nativeLanguageName", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 7, + "name": "nativeCountryName", + "read": "nativeCountryName", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 8, + "name": "nativeTerritoryName", + "read": "nativeTerritoryName", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 9, + "name": "decimalPoint", + "read": "decimalPoint", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 10, + "name": "groupSeparator", + "read": "groupSeparator", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 11, + "name": "percent", + "read": "percent", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 12, + "name": "zeroDigit", + "read": "zeroDigit", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 13, + "name": "negativeSign", + "read": "negativeSign", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 14, + "name": "positiveSign", + "read": "positiveSign", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 15, + "name": "exponential", + "read": "exponential", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 16, + "name": "amText", + "read": "amText", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 17, + "name": "pmText", + "read": "pmText", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 18, + "name": "numberOptions", + "read": "numberOptions", + "required": false, + "scriptable": true, + "stored": true, + "type": "QLocale::NumberOptions", + "user": false, + "write": "setNumberOptions" + } + ], + "qualifiedClassName": "QQmlLocaleValueType" + } + ], + "inputFile": "qqmllocale_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + } + ], + "className": "QQmlPlatform", + "lineNumber": 24, + "object": true, + "properties": [ + { + "constant": true, + "designable": true, + "final": false, + "index": 0, + "name": "os", + "read": "os", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 1, + "name": "pluginName", + "read": "pluginName", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + } + ], + "qualifiedClassName": "QQmlPlatform", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qqmlplatform_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQmlProfiler", + "lineNumber": 115, + "object": true, + "qualifiedClassName": "QQmlProfiler", + "signals": [ + { + "access": "public", + "arguments": [ + { + "type": "QList" + }, + { + "type": "QQmlProfiler::LocationHash" + } + ], + "index": 0, + "name": "dataReady", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QQmlProfilerDefinitions" + } + ] + } + ], + "inputFile": "qqmlprofiler_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + } + ], + "className": "QQmlProperty", + "gadget": true, + "lineNumber": 22, + "properties": [ + { + "constant": true, + "designable": true, + "final": true, + "index": 0, + "name": "object", + "read": "object", + "required": false, + "scriptable": true, + "stored": true, + "type": "QObject*", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 1, + "name": "name", + "read": "name", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + } + ], + "qualifiedClassName": "QQmlProperty" + } + ], + "inputFile": "qqmlproperty.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQmlPropertyMap", + "lineNumber": 18, + "methods": [ + { + "access": "public", + "index": 1, + "name": "keys", + "returnType": "QStringList" + } + ], + "object": true, + "qualifiedClassName": "QQmlPropertyMap", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "key", + "type": "QString" + }, + { + "name": "value", + "type": "QVariant" + } + ], + "index": 0, + "name": "valueChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qqmlpropertymap.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQmlScriptString", + "gadget": true, + "lineNumber": 23, + "qualifiedClassName": "QQmlScriptString" + } + ], + "inputFile": "qqmlscriptstring.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQmlTypeLoaderNetworkReplyProxy", + "lineNumber": 34, + "object": true, + "qualifiedClassName": "QQmlTypeLoaderNetworkReplyProxy", + "slots": [ + { + "access": "public", + "index": 0, + "name": "finished", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "qint64" + }, + { + "type": "qint64" + } + ], + "index": 1, + "name": "downloadProgress", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QNetworkReply*" + } + ], + "index": 2, + "name": "manualFinished", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qqmltypeloadernetworkreplyproxy_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQmlGadgetPtrWrapper", + "lineNumber": 63, + "object": true, + "qualifiedClassName": "QQmlGadgetPtrWrapper", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "point" + }, + { + "name": "QML.Foreign", + "value": "QPointF" + }, + { + "name": "QML.Extended", + "value": "QQmlPointFValueType" + }, + { + "name": "QML.Creatable", + "value": "true" + }, + { + "name": "QML.CreationMethod", + "value": "structured" + } + ], + "className": "QQmlPointFValueType", + "constructors": [ + { + "access": "public", + "index": 0, + "name": "QQmlPointFValueType", + "returnType": "" + }, + { + "access": "public", + "arguments": [ + { + "name": "point", + "type": "QPoint" + } + ], + "index": 1, + "name": "QQmlPointFValueType", + "returnType": "" + } + ], + "gadget": true, + "lineNumber": 106, + "methods": [ + { + "access": "public", + "index": 0, + "name": "toString", + "returnType": "QString" + } + ], + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "x", + "read": "x", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setX" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "y", + "read": "y", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setY" + } + ], + "qualifiedClassName": "QQmlPointFValueType" + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.Foreign", + "value": "QPoint" + }, + { + "name": "QML.Extended", + "value": "QQmlPointValueType" + }, + { + "name": "QML.Creatable", + "value": "true" + }, + { + "name": "QML.CreationMethod", + "value": "structured" + } + ], + "className": "QQmlPointValueType", + "constructors": [ + { + "access": "public", + "arguments": [ + { + "name": "point", + "type": "QPointF" + } + ], + "index": 0, + "name": "QQmlPointValueType", + "returnType": "" + } + ], + "gadget": true, + "lineNumber": 129, + "methods": [ + { + "access": "public", + "index": 0, + "name": "toString", + "returnType": "QString" + } + ], + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "x", + "read": "x", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setX" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "y", + "read": "y", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setY" + } + ], + "qualifiedClassName": "QQmlPointValueType" + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "size" + }, + { + "name": "QML.Foreign", + "value": "QSizeF" + }, + { + "name": "QML.Extended", + "value": "QQmlSizeFValueType" + }, + { + "name": "QML.Creatable", + "value": "true" + }, + { + "name": "QML.CreationMethod", + "value": "structured" + } + ], + "className": "QQmlSizeFValueType", + "constructors": [ + { + "access": "public", + "index": 0, + "name": "QQmlSizeFValueType", + "returnType": "" + }, + { + "access": "public", + "arguments": [ + { + "name": "size", + "type": "QSize" + } + ], + "index": 1, + "name": "QQmlSizeFValueType", + "returnType": "" + } + ], + "gadget": true, + "lineNumber": 152, + "methods": [ + { + "access": "public", + "index": 0, + "name": "toString", + "returnType": "QString" + } + ], + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "width", + "read": "width", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setWidth" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "height", + "read": "height", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setHeight" + } + ], + "qualifiedClassName": "QQmlSizeFValueType" + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.Foreign", + "value": "QSize" + }, + { + "name": "QML.Extended", + "value": "QQmlSizeValueType" + }, + { + "name": "QML.Creatable", + "value": "true" + }, + { + "name": "QML.CreationMethod", + "value": "structured" + } + ], + "className": "QQmlSizeValueType", + "constructors": [ + { + "access": "public", + "arguments": [ + { + "name": "size", + "type": "QSizeF" + } + ], + "index": 0, + "name": "QQmlSizeValueType", + "returnType": "" + } + ], + "gadget": true, + "lineNumber": 175, + "methods": [ + { + "access": "public", + "index": 0, + "name": "toString", + "returnType": "QString" + } + ], + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "width", + "read": "width", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setWidth" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "height", + "read": "height", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setHeight" + } + ], + "qualifiedClassName": "QQmlSizeValueType" + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "rect" + }, + { + "name": "QML.Foreign", + "value": "QRectF" + }, + { + "name": "QML.Extended", + "value": "QQmlRectFValueType" + }, + { + "name": "QML.Creatable", + "value": "true" + }, + { + "name": "QML.CreationMethod", + "value": "structured" + } + ], + "className": "QQmlRectFValueType", + "constructors": [ + { + "access": "public", + "index": 0, + "name": "QQmlRectFValueType", + "returnType": "" + }, + { + "access": "public", + "arguments": [ + { + "name": "rect", + "type": "QRect" + } + ], + "index": 1, + "name": "QQmlRectFValueType", + "returnType": "" + } + ], + "gadget": true, + "lineNumber": 198, + "methods": [ + { + "access": "public", + "index": 0, + "name": "toString", + "returnType": "QString" + } + ], + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "x", + "read": "x", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setX" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "y", + "read": "y", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setY" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "width", + "read": "width", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setWidth" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "height", + "read": "height", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setHeight" + }, + { + "constant": false, + "designable": false, + "final": true, + "index": 4, + "name": "left", + "read": "left", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": false, + "final": true, + "index": 5, + "name": "right", + "read": "right", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": false, + "final": true, + "index": 6, + "name": "top", + "read": "top", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": false, + "final": true, + "index": 7, + "name": "bottom", + "read": "bottom", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + } + ], + "qualifiedClassName": "QQmlRectFValueType" + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.Foreign", + "value": "QRect" + }, + { + "name": "QML.Extended", + "value": "QQmlRectValueType" + }, + { + "name": "QML.Creatable", + "value": "true" + }, + { + "name": "QML.CreationMethod", + "value": "structured" + } + ], + "className": "QQmlRectValueType", + "constructors": [ + { + "access": "public", + "arguments": [ + { + "name": "rect", + "type": "QRectF" + } + ], + "index": 0, + "name": "QQmlRectValueType", + "returnType": "" + } + ], + "gadget": true, + "lineNumber": 237, + "methods": [ + { + "access": "public", + "index": 0, + "name": "toString", + "returnType": "QString" + } + ], + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "x", + "read": "x", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setX" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "y", + "read": "y", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setY" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "width", + "read": "width", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setWidth" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "height", + "read": "height", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setHeight" + }, + { + "constant": false, + "designable": false, + "final": true, + "index": 4, + "name": "left", + "read": "left", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": false, + "final": true, + "index": 5, + "name": "right", + "read": "right", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": false, + "final": true, + "index": 6, + "name": "top", + "read": "top", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": false, + "final": true, + "index": 7, + "name": "bottom", + "read": "bottom", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + } + ], + "qualifiedClassName": "QQmlRectValueType" + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.Foreign", + "value": "QMarginsF" + }, + { + "name": "QML.Extended", + "value": "QQmlMarginsFValueType" + }, + { + "name": "QML.Creatable", + "value": "true" + }, + { + "name": "QML.CreationMethod", + "value": "structured" + } + ], + "className": "QQmlMarginsFValueType", + "constructors": [ + { + "access": "public", + "arguments": [ + { + "name": "margins", + "type": "QMargins" + } + ], + "index": 0, + "name": "QQmlMarginsFValueType", + "returnType": "" + } + ], + "gadget": true, + "lineNumber": 276, + "methods": [ + { + "access": "public", + "index": 0, + "name": "toString", + "returnType": "QString" + } + ], + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "left", + "read": "left", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setLeft" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "right", + "read": "right", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setRight" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "top", + "read": "top", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setTop" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "bottom", + "read": "bottom", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setBottom" + } + ], + "qualifiedClassName": "QQmlMarginsFValueType" + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.Foreign", + "value": "QMargins" + }, + { + "name": "QML.Extended", + "value": "QQmlMarginsValueType" + }, + { + "name": "QML.Creatable", + "value": "true" + }, + { + "name": "QML.CreationMethod", + "value": "structured" + } + ], + "className": "QQmlMarginsValueType", + "constructors": [ + { + "access": "public", + "arguments": [ + { + "name": "margins", + "type": "QMarginsF" + } + ], + "index": 0, + "name": "QQmlMarginsValueType", + "returnType": "" + } + ], + "gadget": true, + "lineNumber": 305, + "methods": [ + { + "access": "public", + "index": 0, + "name": "toString", + "returnType": "QString" + } + ], + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "left", + "read": "left", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setLeft" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "right", + "read": "right", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setRight" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "top", + "read": "top", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setTop" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "bottom", + "read": "bottom", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setBottom" + } + ], + "qualifiedClassName": "QQmlMarginsValueType" + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.Foreign", + "value": "QEasingCurve" + }, + { + "name": "QML.Extended", + "value": "QQmlEasingValueType" + }, + { + "name": "QML.Creatable", + "value": "true" + }, + { + "name": "QML.CreationMethod", + "value": "structured" + } + ], + "className": "QQmlEasingValueType", + "gadget": true, + "lineNumber": 371, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "type", + "read": "type", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlEasingEnums::Type", + "user": false, + "write": "setType" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "amplitude", + "read": "amplitude", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setAmplitude" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "overshoot", + "read": "overshoot", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setOvershoot" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "period", + "read": "period", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setPeriod" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "bezierCurve", + "read": "bezierCurve", + "required": false, + "scriptable": true, + "stored": true, + "type": "QVariantList", + "user": false, + "write": "setBezierCurve" + } + ], + "qualifiedClassName": "QQmlEasingValueType" + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.Foreign", + "value": "QQmlV4ExecutionEnginePtr" + }, + { + "name": "QML.Extended", + "value": "QQmlV4ExecutionEnginePtrForeign" + } + ], + "className": "QQmlV4ExecutionEnginePtrForeign", + "gadget": true, + "lineNumber": 402, + "qualifiedClassName": "QQmlV4ExecutionEnginePtrForeign" + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "Easing" + } + ], + "className": "QQmlEasingEnums", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "Type", + "values": [ + "Linear", + "InQuad", + "OutQuad", + "InOutQuad", + "OutInQuad", + "InCubic", + "OutCubic", + "InOutCubic", + "OutInCubic", + "InQuart", + "OutQuart", + "InOutQuart", + "OutInQuart", + "InQuint", + "OutQuint", + "InOutQuint", + "OutInQuint", + "InSine", + "OutSine", + "InOutSine", + "OutInSine", + "InExpo", + "OutExpo", + "InOutExpo", + "OutInExpo", + "InCirc", + "OutCirc", + "InOutCirc", + "OutInCirc", + "InElastic", + "OutElastic", + "InOutElastic", + "OutInElastic", + "InBack", + "OutBack", + "InOutBack", + "OutInBack", + "InBounce", + "OutBounce", + "InOutBounce", + "OutInBounce", + "InCurve", + "OutCurve", + "SineCurve", + "CosineCurve", + "BezierSpline", + "Bezier" + ] + } + ], + "lineNumber": 335, + "namespace": true, + "qualifiedClassName": "QQmlEasingEnums" + } + ], + "inputFile": "qqmlvaluetype_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "Debugger", + "lineNumber": 41, + "object": true, + "qualifiedClassName": "QV4::Debugging::Debugger", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qv4debugging_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QV4Include", + "lineNumber": 34, + "object": true, + "qualifiedClassName": "QV4Include", + "slots": [ + { + "access": "private", + "index": 0, + "name": "finished", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qv4include_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "GCStateMachine", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "GCState", + "values": [ + "MarkStart", + "MarkGlobalObject", + "MarkJSStack", + "InitMarkPersistentValues", + "MarkPersistentValues", + "InitMarkWeakValues", + "MarkWeakValues", + "MarkDrain", + "MarkReady", + "InitCallDestroyObjects", + "CallDestroyObjects", + "FreeWeakMaps", + "FreeWeakSets", + "HandleQObjectWrappers", + "DoSweep", + "Invalid", + "Count" + ] + } + ], + "gadget": true, + "lineNumber": 37, + "qualifiedClassName": "QV4::GCStateMachine" + } + ], + "inputFile": "qv4mm_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "Profiler", + "lineNumber": 165, + "object": true, + "qualifiedClassName": "QV4::Profiling::Profiler", + "signals": [ + { + "access": "public", + "arguments": [ + { + "type": "QV4::Profiling::FunctionLocationHash" + }, + { + "type": "QList" + }, + { + "type": "QList" + } + ], + "index": 0, + "name": "dataReady", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qv4profiling_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "ReactionHandler", + "lineNumber": 31, + "object": true, + "qualifiedClassName": "QV4::Promise::ReactionHandler", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qv4promiseobject_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "MultiplyWrappedQObjectMap", + "lineNumber": 434, + "object": true, + "qualifiedClassName": "QV4::MultiplyWrappedQObjectMap", + "slots": [ + { + "access": "private", + "arguments": [ + { + "type": "QObject*" + } + ], + "index": 0, + "name": "removeDestroyedObject", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "private", + "name": "QHash" + } + ] + } + ], + "inputFile": "qv4qobjectwrapper_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.Sequence", + "value": "double" + }, + { + "name": "QML.Foreign", + "value": "std::vector" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QRealStdVectorForeign", + "gadget": true, + "lineNumber": 140, + "qualifiedClassName": "QRealStdVectorForeign" + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.Sequence", + "value": "double" + }, + { + "name": "QML.Foreign", + "value": "QList" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QRealListForeign", + "gadget": true, + "lineNumber": 141, + "qualifiedClassName": "QRealListForeign" + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.Sequence", + "value": "double" + }, + { + "name": "QML.Foreign", + "value": "std::vector" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QDoubleStdVectorForeign", + "gadget": true, + "lineNumber": 144, + "qualifiedClassName": "QDoubleStdVectorForeign" + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.Sequence", + "value": "float" + }, + { + "name": "QML.Foreign", + "value": "std::vector" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QFloatStdVectorForeign", + "gadget": true, + "lineNumber": 145, + "qualifiedClassName": "QFloatStdVectorForeign" + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.Sequence", + "value": "int" + }, + { + "name": "QML.Foreign", + "value": "std::vector" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QIntStdVectorForeign", + "gadget": true, + "lineNumber": 146, + "qualifiedClassName": "QIntStdVectorForeign" + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.Sequence", + "value": "bool" + }, + { + "name": "QML.Foreign", + "value": "std::vector" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QBoolStdVectorForeign", + "gadget": true, + "lineNumber": 147, + "qualifiedClassName": "QBoolStdVectorForeign" + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.Sequence", + "value": "QString" + }, + { + "name": "QML.Foreign", + "value": "std::vector" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QStringStdVectorForeign", + "gadget": true, + "lineNumber": 148, + "qualifiedClassName": "QStringStdVectorForeign" + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.Sequence", + "value": "QUrl" + }, + { + "name": "QML.Foreign", + "value": "std::vector" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QUrlStdVectorForeign", + "gadget": true, + "lineNumber": 149, + "qualifiedClassName": "QUrlStdVectorForeign" + } + ], + "inputFile": "qv4sequenceobject_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "ObjectReferenceHash", + "lineNumber": 88, + "object": true, + "qualifiedClassName": "ObjectReferenceHash", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qqmldebugservice.cpp", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQmlFileNetworkReply", + "lineNumber": 49, + "object": true, + "qualifiedClassName": "QQmlFileNetworkReply", + "signals": [ + { + "access": "public", + "index": 0, + "name": "finished", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "qint64" + }, + { + "type": "qint64" + } + ], + "index": 1, + "name": "downloadProgress", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "index": 2, + "name": "networkFinished", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "qint64" + }, + { + "type": "qint64" + } + ], + "index": 3, + "name": "networkDownloadProgress", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qqmlfile.cpp", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQmlXMLHttpRequest", + "lineNumber": 967, + "object": true, + "qualifiedClassName": "QQmlXMLHttpRequest", + "slots": [ + { + "access": "private", + "index": 0, + "name": "readyRead", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "type": "QNetworkReply::NetworkError" + } + ], + "index": 1, + "name": "error", + "returnType": "void" + }, + { + "access": "private", + "index": 2, + "name": "finished", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qqmlxmlhttprequest.cpp", + "outputRevision": 68 + } +] diff --git a/qt/6.8.1/msvc2022_64/metatypes/qt6qmlassetdownloader_metatypes.json b/qt/6.8.1/msvc2022_64/metatypes/qt6qmlassetdownloader_metatypes.json new file mode 100644 index 0000000000000000000000000000000000000000..2d9dca392bcf83a5844dd51198f8c59ff9da0802 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/metatypes/qt6qmlassetdownloader_metatypes.json @@ -0,0 +1,41 @@ +[ + { + "classes": [ + { + "className": "AssetDownloaderHelper", + "lineNumber": 25, + "object": true, + "qualifiedClassName": "Assets::Downloader::AssetDownloaderHelper", + "superClasses": [ + { + "access": "public", + "fullyQualifiedName": "Assets::Downloader::AssetDownloader", + "name": "AssetDownloader" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Foreign", + "value": "AssetDownloaderHelper" + }, + { + "name": "QML.Element", + "value": "AssetDownloader" + }, + { + "name": "QML.AddedInVersion", + "value": "1544" + } + ], + "className": "QQmlAssetDownloader", + "gadget": true, + "lineNumber": 36, + "qualifiedClassName": "Assets::Downloader::QQmlAssetDownloader" + } + ], + "inputFile": "qqmlassetdownloader_p.h", + "outputRevision": 68 + } +] diff --git a/qt/6.8.1/msvc2022_64/metatypes/qt6qmlcompiler_metatypes.json b/qt/6.8.1/msvc2022_64/metatypes/qt6qmlcompiler_metatypes.json new file mode 100644 index 0000000000000000000000000000000000000000..0d4f101c7a37a4c875e6999bee1a287fdb733380 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/metatypes/qt6qmlcompiler_metatypes.json @@ -0,0 +1,2 @@ +[ +] diff --git a/qt/6.8.1/msvc2022_64/metatypes/qt6qmlcore_metatypes.json b/qt/6.8.1/msvc2022_64/metatypes/qt6qmlcore_metatypes.json new file mode 100644 index 0000000000000000000000000000000000000000..b01b4e53d65d128fd3c193c37ba9024ffc6c3f2d --- /dev/null +++ b/qt/6.8.1/msvc2022_64/metatypes/qt6qmlcore_metatypes.json @@ -0,0 +1,1023 @@ +[ + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "LocationPermission" + }, + { + "name": "QML.AddedInVersion", + "value": "1542" + }, + { + "name": "QML.Extended", + "value": "QLocationPermission" + }, + { + "name": "QML.ExtensionIsNamespace", + "value": "true" + } + ], + "className": "QQmlQLocationPermission", + "lineNumber": 68, + "methods": [ + { + "access": "public", + "index": 3, + "name": "request", + "returnType": "void" + } + ], + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "status", + "notify": "statusChanged", + "read": "status", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::PermissionStatus", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "availability", + "notify": "availabilityChanged", + "read": "availability", + "required": false, + "scriptable": true, + "stored": true, + "type": "QLocationPermission::Availability", + "user": false, + "write": "setAvailability" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "accuracy", + "notify": "accuracyChanged", + "read": "accuracy", + "required": false, + "scriptable": true, + "stored": true, + "type": "QLocationPermission::Accuracy", + "user": false, + "write": "setAccuracy" + } + ], + "qualifiedClassName": "QQmlQLocationPermission", + "signals": [ + { + "access": "public", + "index": 0, + "name": "statusChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "availabilityChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "accuracyChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "CalendarPermission" + }, + { + "name": "QML.AddedInVersion", + "value": "1542" + }, + { + "name": "QML.Extended", + "value": "QCalendarPermission" + }, + { + "name": "QML.ExtensionIsNamespace", + "value": "true" + } + ], + "className": "QQmlCalendarPermission", + "lineNumber": 77, + "methods": [ + { + "access": "public", + "index": 2, + "name": "request", + "returnType": "void" + } + ], + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "status", + "notify": "statusChanged", + "read": "status", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::PermissionStatus", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "accessMode", + "notify": "accessModeChanged", + "read": "accessMode", + "required": false, + "scriptable": true, + "stored": true, + "type": "QCalendarPermission::AccessMode", + "user": false, + "write": "setAccessMode" + } + ], + "qualifiedClassName": "QQmlCalendarPermission", + "signals": [ + { + "access": "public", + "index": 0, + "name": "statusChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "accessModeChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "ContactsPermission" + }, + { + "name": "QML.AddedInVersion", + "value": "1542" + }, + { + "name": "QML.Extended", + "value": "QContactsPermission" + }, + { + "name": "QML.ExtensionIsNamespace", + "value": "true" + } + ], + "className": "QQmlContactsPermission", + "lineNumber": 85, + "methods": [ + { + "access": "public", + "index": 2, + "name": "request", + "returnType": "void" + } + ], + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "status", + "notify": "statusChanged", + "read": "status", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::PermissionStatus", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "accessMode", + "notify": "accessModeChanged", + "read": "accessMode", + "required": false, + "scriptable": true, + "stored": true, + "type": "QContactsPermission::AccessMode", + "user": false, + "write": "setAccessMode" + } + ], + "qualifiedClassName": "QQmlContactsPermission", + "signals": [ + { + "access": "public", + "index": 0, + "name": "statusChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "accessModeChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "BluetoothPermission" + }, + { + "name": "QML.AddedInVersion", + "value": "1542" + }, + { + "name": "QML.Extended", + "value": "QBluetoothPermission" + }, + { + "name": "QML.ExtensionIsNamespace", + "value": "true" + } + ], + "className": "QQmlBluetoothPermission", + "lineNumber": 93, + "methods": [ + { + "access": "public", + "index": 2, + "name": "request", + "returnType": "void" + } + ], + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "status", + "notify": "statusChanged", + "read": "status", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::PermissionStatus", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "communicationModes", + "notify": "communicationModesChanged", + "read": "communicationModes", + "required": false, + "scriptable": true, + "stored": true, + "type": "QBluetoothPermission::CommunicationModes", + "user": false, + "write": "setCommunicationModes" + } + ], + "qualifiedClassName": "QQmlBluetoothPermission", + "signals": [ + { + "access": "public", + "index": 0, + "name": "statusChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "communicationModesChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "CameraPermission" + }, + { + "name": "QML.AddedInVersion", + "value": "1542" + } + ], + "className": "QQmlCameraPermission", + "lineNumber": 101, + "methods": [ + { + "access": "public", + "index": 1, + "name": "request", + "returnType": "void" + } + ], + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "status", + "notify": "statusChanged", + "read": "status", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::PermissionStatus", + "user": false + } + ], + "qualifiedClassName": "QQmlCameraPermission", + "signals": [ + { + "access": "public", + "index": 0, + "name": "statusChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "MicrophonePermission" + }, + { + "name": "QML.AddedInVersion", + "value": "1542" + } + ], + "className": "QQmlMicrophonePermission", + "lineNumber": 107, + "methods": [ + { + "access": "public", + "index": 1, + "name": "request", + "returnType": "void" + } + ], + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "status", + "notify": "statusChanged", + "read": "status", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::PermissionStatus", + "user": false + } + ], + "qualifiedClassName": "QQmlMicrophonePermission", + "signals": [ + { + "access": "public", + "index": 0, + "name": "statusChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qqmlpermissions_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "Settings" + }, + { + "name": "QML.AddedInVersion", + "value": "1541" + } + ], + "className": "QQmlSettings", + "interfaces": [ + [ + { + "className": "QQmlParserStatus", + "id": "\"org.qt-project.Qt.QQmlParserStatus\"" + } + ] + ], + "lineNumber": 29, + "methods": [ + { + "access": "public", + "arguments": [ + { + "name": "key", + "type": "QString" + }, + { + "name": "defaultValue", + "type": "QVariant" + } + ], + "index": 3, + "name": "value", + "returnType": "QVariant" + }, + { + "access": "public", + "arguments": [ + { + "name": "key", + "type": "QString" + } + ], + "index": 4, + "isCloned": true, + "name": "value", + "returnType": "QVariant" + }, + { + "access": "public", + "arguments": [ + { + "name": "key", + "type": "QString" + }, + { + "name": "value", + "type": "QVariant" + } + ], + "index": 5, + "name": "setValue", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "sync", + "returnType": "void" + } + ], + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "category", + "notify": "categoryChanged", + "read": "category", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setCategory" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "location", + "notify": "locationChanged", + "read": "location", + "required": false, + "scriptable": true, + "stored": true, + "type": "QUrl", + "user": false, + "write": "setLocation" + } + ], + "qualifiedClassName": "QQmlSettings", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "QString" + } + ], + "index": 0, + "name": "categoryChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "QUrl" + } + ], + "index": 1, + "name": "locationChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "private", + "index": 2, + "name": "_q_propertyChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QQmlParserStatus" + } + ] + } + ], + "inputFile": "qqmlsettings_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Singleton", + "value": "true" + }, + { + "name": "QML.Element", + "value": "StandardPaths" + }, + { + "name": "QML.AddedInVersion", + "value": "1538" + }, + { + "name": "QML.Extended", + "value": "QStandardPaths" + }, + { + "name": "QML.ExtensionIsNamespace", + "value": "true" + } + ], + "className": "QQmlStandardPaths", + "lineNumber": 29, + "methods": [ + { + "access": "public", + "arguments": [ + { + "name": "type", + "type": "QStandardPaths::StandardLocation" + } + ], + "index": 0, + "name": "displayName", + "returnType": "QString" + }, + { + "access": "public", + "arguments": [ + { + "name": "executableName", + "type": "QString" + }, + { + "name": "paths", + "type": "QStringList" + } + ], + "index": 1, + "name": "findExecutable", + "returnType": "QUrl" + }, + { + "access": "public", + "arguments": [ + { + "name": "executableName", + "type": "QString" + } + ], + "index": 2, + "isCloned": true, + "name": "findExecutable", + "returnType": "QUrl" + }, + { + "access": "public", + "arguments": [ + { + "name": "type", + "type": "QStandardPaths::StandardLocation" + }, + { + "name": "fileName", + "type": "QString" + }, + { + "name": "options", + "type": "QStandardPaths::LocateOptions" + } + ], + "index": 3, + "name": "locate", + "returnType": "QUrl" + }, + { + "access": "public", + "arguments": [ + { + "name": "type", + "type": "QStandardPaths::StandardLocation" + }, + { + "name": "fileName", + "type": "QString" + } + ], + "index": 4, + "isCloned": true, + "name": "locate", + "returnType": "QUrl" + }, + { + "access": "public", + "arguments": [ + { + "name": "type", + "type": "QStandardPaths::StandardLocation" + }, + { + "name": "fileName", + "type": "QString" + }, + { + "name": "options", + "type": "QStandardPaths::LocateOptions" + } + ], + "index": 5, + "name": "locateAll", + "returnType": "QList" + }, + { + "access": "public", + "arguments": [ + { + "name": "type", + "type": "QStandardPaths::StandardLocation" + }, + { + "name": "fileName", + "type": "QString" + } + ], + "index": 6, + "isCloned": true, + "name": "locateAll", + "returnType": "QList" + }, + { + "access": "public", + "arguments": [ + { + "name": "type", + "type": "QStandardPaths::StandardLocation" + } + ], + "index": 7, + "name": "standardLocations", + "returnType": "QList" + }, + { + "access": "public", + "arguments": [ + { + "name": "type", + "type": "QStandardPaths::StandardLocation" + } + ], + "index": 8, + "name": "writableLocation", + "returnType": "QUrl" + } + ], + "object": true, + "qualifiedClassName": "QQmlStandardPaths", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qqmlstandardpaths_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Singleton", + "value": "true" + }, + { + "name": "QML.Element", + "value": "SystemInformation" + }, + { + "name": "QML.AddedInVersion", + "value": "1540" + } + ], + "className": "QQmlSystemInformation", + "enums": [ + { + "isClass": true, + "isFlag": false, + "name": "Endian", + "values": [ + "Big", + "Little" + ] + } + ], + "lineNumber": 23, + "object": true, + "properties": [ + { + "constant": true, + "designable": true, + "final": true, + "index": 0, + "name": "wordSize", + "read": "wordSize", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 1, + "name": "byteOrder", + "read": "byteOrder", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlSystemInformation::Endian", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 2, + "name": "buildCpuArchitecture", + "read": "buildCpuArchitecture", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 3, + "name": "currentCpuArchitecture", + "read": "currentCpuArchitecture", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 4, + "name": "buildAbi", + "read": "buildAbi", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 5, + "name": "kernelType", + "read": "kernelType", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 6, + "name": "kernelVersion", + "read": "kernelVersion", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 7, + "name": "productType", + "read": "productType", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 8, + "name": "productVersion", + "read": "productVersion", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 9, + "name": "prettyProductName", + "read": "prettyProductName", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 10, + "name": "machineHostName", + "read": "machineHostName", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 11, + "name": "machineUniqueId", + "read": "machineUniqueId", + "required": false, + "scriptable": true, + "stored": true, + "type": "QByteArray", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 12, + "name": "bootUniqueId", + "read": "bootUniqueId", + "required": false, + "scriptable": true, + "stored": true, + "type": "QByteArray", + "user": false + } + ], + "qualifiedClassName": "QQmlSystemInformation", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qqmlsysteminformation_p.h", + "outputRevision": 68 + } +] diff --git a/qt/6.8.1/msvc2022_64/metatypes/qt6qmldebugprivate_metatypes.json b/qt/6.8.1/msvc2022_64/metatypes/qt6qmldebugprivate_metatypes.json new file mode 100644 index 0000000000000000000000000000000000000000..eca53820c1332d726dc317fc22328b0320f9b4fd --- /dev/null +++ b/qt/6.8.1/msvc2022_64/metatypes/qt6qmldebugprivate_metatypes.json @@ -0,0 +1,594 @@ +[ + { + "classes": [ + { + "className": "QQmlDebugClient", + "lineNumber": 25, + "object": true, + "qualifiedClassName": "QQmlDebugClient", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "state", + "type": "State" + } + ], + "index": 0, + "name": "stateChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qqmldebugclient_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQmlDebugConnection", + "lineNumber": 26, + "object": true, + "qualifiedClassName": "QQmlDebugConnection", + "signals": [ + { + "access": "public", + "index": 0, + "name": "connected", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "disconnected", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "socketError", + "type": "QAbstractSocket::SocketError" + } + ], + "index": 2, + "name": "socketError", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "socketState", + "type": "QAbstractSocket::SocketState" + } + ], + "index": 3, + "name": "socketStateChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qqmldebugconnection_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQmlDebugMessageClient", + "lineNumber": 31, + "object": true, + "qualifiedClassName": "QQmlDebugMessageClient", + "signals": [ + { + "access": "public", + "arguments": [ + { + "type": "QtMsgType" + }, + { + "type": "QString" + }, + { + "type": "QQmlDebugContextInfo" + } + ], + "index": 0, + "name": "message", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQmlDebugClient" + } + ] + } + ], + "inputFile": "qqmldebugmessageclient_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQmlDebugTranslationClient", + "lineNumber": 24, + "object": true, + "qualifiedClassName": "QQmlDebugTranslationClient", + "superClasses": [ + { + "access": "public", + "name": "QQmlDebugClient" + } + ] + } + ], + "inputFile": "qqmldebugtranslationclient_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQmlEngineControlClient", + "lineNumber": 23, + "object": true, + "qualifiedClassName": "QQmlEngineControlClient", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "engineId", + "type": "int" + }, + { + "name": "name", + "type": "QString" + } + ], + "index": 0, + "name": "engineAboutToBeAdded", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "engineId", + "type": "int" + }, + { + "name": "name", + "type": "QString" + } + ], + "index": 1, + "name": "engineAdded", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "engineId", + "type": "int" + }, + { + "name": "name", + "type": "QString" + } + ], + "index": 2, + "name": "engineAboutToBeRemoved", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "engineId", + "type": "int" + }, + { + "name": "name", + "type": "QString" + } + ], + "index": 3, + "name": "engineRemoved", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQmlDebugClient" + } + ] + } + ], + "inputFile": "qqmlenginecontrolclient_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQmlEngineDebugClient", + "lineNumber": 70, + "object": true, + "qualifiedClassName": "QQmlEngineDebugClient", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "objectId", + "type": "qint32" + } + ], + "index": 0, + "name": "newObject", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QByteArray" + }, + { + "type": "QVariant" + } + ], + "index": 1, + "name": "valueChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "result", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQmlDebugClient" + } + ] + } + ], + "inputFile": "qqmlenginedebugclient_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQmlInspectorClient", + "lineNumber": 23, + "object": true, + "qualifiedClassName": "QQmlInspectorClient", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "requestId", + "type": "int" + }, + { + "name": "result", + "type": "bool" + } + ], + "index": 0, + "name": "responseReceived", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQmlDebugClient" + } + ] + } + ], + "inputFile": "qqmlinspectorclient_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQmlPreviewClient", + "lineNumber": 25, + "object": true, + "qualifiedClassName": "QQmlPreviewClient", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "path", + "type": "QString" + } + ], + "index": 0, + "name": "request", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "message", + "type": "QString" + } + ], + "index": 1, + "name": "error", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "info", + "type": "FpsInfo" + } + ], + "index": 2, + "name": "fps", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQmlDebugClient" + } + ] + } + ], + "inputFile": "qqmlpreviewclient_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQmlProfilerClient", + "lineNumber": 28, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "recording", + "notify": "recordingChanged", + "read": "isRecording", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setRecording" + } + ], + "qualifiedClassName": "QQmlProfilerClient", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "maximumTime", + "type": "qint64" + } + ], + "index": 0, + "name": "complete", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "timestamp", + "type": "qint64" + }, + { + "name": "engineIds", + "type": "QList" + } + ], + "index": 1, + "name": "traceFinished", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "timestamp", + "type": "qint64" + }, + { + "name": "engineIds", + "type": "QList" + } + ], + "index": 2, + "name": "traceStarted", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "bool" + } + ], + "index": 3, + "name": "recordingChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "features", + "type": "quint64" + } + ], + "index": 4, + "name": "recordedFeaturesChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "cleared", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQmlDebugClient" + } + ] + } + ], + "inputFile": "qqmlprofilerclient_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQmlProfilerEventReceiver", + "lineNumber": 25, + "object": true, + "qualifiedClassName": "QQmlProfilerEventReceiver", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qqmlprofilereventreceiver_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QV4DebugClient", + "lineNumber": 24, + "object": true, + "qualifiedClassName": "QV4DebugClient", + "signals": [ + { + "access": "public", + "index": 0, + "name": "connected", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "interrupted", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "result", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "failure", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "stopped", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQmlDebugClient" + } + ] + } + ], + "inputFile": "qv4debugclient_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "LocalSocketSignalTranslator", + "lineNumber": 376, + "object": true, + "qualifiedClassName": "LocalSocketSignalTranslator", + "signals": [ + { + "access": "public", + "arguments": [ + { + "type": "QAbstractSocket::SocketError" + } + ], + "index": 0, + "name": "socketError", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QAbstractSocket::SocketState" + } + ], + "index": 1, + "name": "socketStateChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qqmldebugconnection.cpp", + "outputRevision": 68 + } +] diff --git a/qt/6.8.1/msvc2022_64/metatypes/qt6qmldomprivate_metatypes.json b/qt/6.8.1/msvc2022_64/metatypes/qt6qmldomprivate_metatypes.json new file mode 100644 index 0000000000000000000000000000000000000000..3b5c2dadfdf678080fa548c3c4469f44f0bf7760 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/metatypes/qt6qmldomprivate_metatypes.json @@ -0,0 +1,874 @@ +[ + { + "classes": [ + { + "className": "FormatTextStatus", + "enums": [ + { + "isClass": true, + "isFlag": false, + "name": "StateType", + "type": "quint8", + "values": [ + "Invalid", + "TopmostIntro", + "TopQml", + "TopJs", + "ObjectdefinitionOrJs", + "MultilineCommentStart", + "MultilineCommentCont", + "ImportStart", + "ImportMaybeDotOrVersionOrAs", + "ImportDot", + "ImportMaybeAs", + "ImportAs", + "PropertyStart", + "PropertyModifiers", + "RequiredProperty", + "PropertyListOpen", + "PropertyName", + "PropertyMaybeInitializer", + "ComponentStart", + "ComponentName", + "TypeAnnotation", + "TypeParameter", + "EnumStart", + "SignalStart", + "SignalMaybeArglist", + "SignalArglistOpen", + "FunctionStart", + "FunctionArglistOpen", + "FunctionArglistClosed", + "BindingOrObjectdefinition", + "BindingAssignment", + "ObjectdefinitionOpen", + "Expression", + "ExpressionContinuation", + "ExpressionMaybeContinuation", + "ExpressionOrObjectdefinition", + "ExpressionOrLabel", + "ParenOpen", + "BracketOpen", + "ObjectliteralOpen", + "ObjectliteralAssignment", + "BracketElementStart", + "BracketElementMaybeObjectdefinition", + "TernaryOp", + "TernaryOpAfterColon", + "JsblockOpen", + "EmptyStatement", + "BreakcontinueStatement", + "IfStatement", + "MaybeElse", + "ElseClause", + "ConditionOpen", + "Substatement", + "SubstatementOpen", + "LabelledStatement", + "ReturnStatement", + "ThrowStatement", + "StatementWithCondition", + "StatementWithConditionParenOpen", + "TryStatement", + "CatchStatement", + "FinallyStatement", + "MaybeCatchOrFinally", + "DoStatement", + "DoStatementWhileParenOpen", + "SwitchStatement", + "CaseStart", + "CaseCont" + ] + } + ], + "gadget": true, + "lineNumber": 34, + "qualifiedClassName": "QQmlJS::Dom::FormatTextStatus" + }, + { + "className": "FormatPartialStatus", + "gadget": true, + "lineNumber": 203, + "qualifiedClassName": "QQmlJS::Dom::FormatPartialStatus" + } + ], + "inputFile": "qqmldomcodeformatter_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "IndentingLineWriter", + "gadget": true, + "lineNumber": 30, + "qualifiedClassName": "QQmlJS::Dom::IndentingLineWriter", + "superClasses": [ + { + "access": "public", + "fullyQualifiedName": "QQmlJS::Dom::LineWriter", + "name": "LineWriter" + } + ] + } + ], + "inputFile": "qqmldomindentinglinewriter_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "Token", + "gadget": true, + "lineNumber": 31, + "qualifiedClassName": "QQmlJS::Dom::Token" + } + ], + "inputFile": "qqmldomscanner_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "AttachedInfo", + "enums": [ + { + "isClass": true, + "isFlag": false, + "name": "PathType", + "values": [ + "Relative", + "Canonical" + ] + } + ], + "gadget": true, + "lineNumber": 51, + "qualifiedClassName": "QQmlJS::Dom::AttachedInfo", + "superClasses": [ + { + "access": "public", + "name": "OwningItem" + } + ] + }, + { + "className": "UpdatedScriptExpression", + "gadget": true, + "lineNumber": 280, + "qualifiedClassName": "QQmlJS::Dom::UpdatedScriptExpression" + } + ], + "inputFile": "qqmldomattachedinfo_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "Dom", + "enums": [ + { + "isClass": true, + "isFlag": false, + "name": "PathRoot", + "values": [ + "Other", + "Modules", + "Cpp", + "Libs", + "Top", + "Env", + "Universe" + ] + }, + { + "isClass": true, + "isFlag": false, + "name": "PathCurrent", + "values": [ + "Other", + "Obj", + "ObjChain", + "ScopeChain", + "Component", + "Module", + "Ids", + "Types", + "LookupStrict", + "LookupDynamic", + "Lookup" + ] + }, + { + "isClass": true, + "isFlag": false, + "name": "Language", + "values": [ + "QmlQuick1", + "QmlQuick2", + "QmlQuick3", + "QmlCompiled", + "QmlAnnotation", + "Qbs" + ] + }, + { + "isClass": true, + "isFlag": false, + "name": "ResolveOption", + "values": [ + "None", + "TraceVisit" + ] + }, + { + "isClass": true, + "isFlag": false, + "name": "VisitOption", + "values": [ + "None", + "VisitSelf", + "VisitAdopted", + "Recurse", + "NoPath", + "Default" + ] + }, + { + "isClass": true, + "isFlag": false, + "name": "LookupOption", + "values": [ + "Normal", + "Strict", + "VisitTopClassType", + "SkipFirstScope" + ] + }, + { + "isClass": true, + "isFlag": false, + "name": "LookupType", + "values": [ + "PropertyDef", + "Binding", + "Property", + "Method", + "Type", + "CppType", + "Symbol" + ] + }, + { + "isClass": true, + "isFlag": false, + "name": "VisitPrototypesOption", + "values": [ + "Normal", + "SkipFirst", + "RevisitWarn", + "ManualProceedToScope" + ] + }, + { + "isClass": true, + "isFlag": false, + "name": "DomKind", + "values": [ + "Empty", + "Object", + "List", + "Map", + "Value", + "ScriptElement" + ] + }, + { + "isClass": true, + "isFlag": false, + "name": "DomType", + "values": [ + "Empty", + "ExternalItemInfo", + "ExternalItemPair", + "QmlDirectory", + "QmldirFile", + "JsFile", + "QmlFile", + "QmltypesFile", + "GlobalScope", + "EnumItem", + "EnumDecl", + "JsResource", + "QmltypesComponent", + "QmlComponent", + "GlobalComponent", + "ModuleAutoExport", + "ModuleIndex", + "ModuleScope", + "ImportScope", + "Export", + "Import", + "Pragma", + "Id", + "QmlObject", + "ConstantData", + "SimpleObjectWrap", + "ScriptExpression", + "Reference", + "PropertyDefinition", + "Binding", + "MethodParameter", + "MethodInfo", + "Version", + "Comment", + "CommentedElement", + "RegionComments", + "AstComments", + "FileLocations", + "UpdatedScriptExpression", + "PropertyInfo", + "MockObject", + "MockOwner", + "Map", + "List", + "ListP", + "LoadInfo", + "ErrorMessage", + "AttachedInfo", + "DomEnvironment", + "DomUniverse", + "ScriptElementWrap", + "ScriptElementStart", + "ScriptBlockStatement", + "ScriptIdentifierExpression", + "ScriptLiteral", + "ScriptRegExpLiteral", + "ScriptForStatement", + "ScriptIfStatement", + "ScriptPostExpression", + "ScriptUnaryExpression", + "ScriptBinaryExpression", + "ScriptVariableDeclaration", + "ScriptVariableDeclarationEntry", + "ScriptReturnStatement", + "ScriptGenericElement", + "ScriptCallExpression", + "ScriptFormalParameter", + "ScriptArray", + "ScriptObject", + "ScriptProperty", + "ScriptType", + "ScriptElision", + "ScriptArrayEntry", + "ScriptPattern", + "ScriptSwitchStatement", + "ScriptCaseBlock", + "ScriptCaseClause", + "ScriptDefaultClause", + "ScriptWhileStatement", + "ScriptDoWhileStatement", + "ScriptForEachStatement", + "ScriptTemplateLiteral", + "ScriptTemplateStringPart", + "ScriptTaggedTemplate", + "ScriptTryCatchStatement", + "ScriptThrowStatement", + "ScriptLabelledStatement", + "ScriptBreakStatement", + "ScriptContinueStatement", + "ScriptConditionalExpression", + "ScriptEmptyStatement", + "ScriptParenthesizedExpression", + "ScriptFunctionExpression", + "ScriptYieldExpression", + "ScriptNewExpression", + "ScriptNewMemberExpression", + "ScriptThisExpression", + "ScriptSuperLiteral", + "ScriptElementStop" + ] + }, + { + "isClass": true, + "isFlag": false, + "name": "SimpleWrapOption", + "values": [ + "None", + "ValueType" + ] + }, + { + "isClass": true, + "isFlag": false, + "name": "BindingValueKind", + "values": [ + "Object", + "ScriptExpression", + "Array", + "Empty" + ] + }, + { + "isClass": true, + "isFlag": false, + "name": "BindingType", + "values": [ + "Normal", + "OnBinding" + ] + }, + { + "isClass": true, + "isFlag": false, + "name": "ListOptions", + "values": [ + "Normal", + "Reverse" + ] + }, + { + "isClass": true, + "isFlag": false, + "name": "EscapeOptions", + "values": [ + "OuterQuotes", + "NoOuterQuotes" + ] + }, + { + "isClass": true, + "isFlag": false, + "name": "ErrorLevel", + "values": [ + "Debug", + "Info", + "Warning", + "Error", + "Fatal" + ] + }, + { + "isClass": true, + "isFlag": false, + "name": "AstDumperOption", + "values": [ + "None", + "NoLocations", + "NoAnnotations", + "DumpNode", + "SloppyCompare" + ] + }, + { + "isClass": true, + "isFlag": false, + "name": "GoTo", + "values": [ + "Strict", + "MostLikely" + ] + }, + { + "isClass": true, + "isFlag": false, + "name": "AddOption", + "values": [ + "KeepExisting", + "Overwrite" + ] + }, + { + "isClass": true, + "isFlag": false, + "name": "FilterUpOptions", + "values": [ + "ReturnOuter", + "ReturnOuterNoSelf", + "ReturnInner" + ] + }, + { + "isClass": true, + "isFlag": false, + "name": "WriteOutCheck", + "values": [ + "None", + "UpdatedDomCompare", + "UpdatedDomStable", + "Reparse", + "ReparseCompare", + "ReparseStable", + "DumpOnFailure", + "All", + "Default" + ] + }, + { + "isClass": true, + "isFlag": false, + "name": "LocalSymbolsType", + "values": [ + "None", + "ObjectType", + "ValueType", + "Signal", + "Method", + "Attribute", + "Id", + "Namespace", + "Global", + "MethodParameter", + "Singleton", + "AttachedType" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "FileLocationRegion", + "type": "int", + "values": [ + "AsTokenRegion", + "BreakKeywordRegion", + "DoKeywordRegion", + "CaseKeywordRegion", + "CatchKeywordRegion", + "ColonTokenRegion", + "CommaTokenRegion", + "ComponentKeywordRegion", + "ContinueKeywordRegion", + "DefaultKeywordRegion", + "EllipsisTokenRegion", + "ElseKeywordRegion", + "EnumKeywordRegion", + "EnumValueRegion", + "EqualTokenRegion", + "ForKeywordRegion", + "FinallyKeywordRegion", + "FirstSemicolonTokenRegion", + "FunctionKeywordRegion", + "IdColonTokenRegion", + "IdNameRegion", + "IdTokenRegion", + "IdentifierRegion", + "IfKeywordRegion", + "ImportTokenRegion", + "ImportUriRegion", + "InOfTokenRegion", + "LeftBraceRegion", + "LeftBracketRegion", + "LeftParenthesisRegion", + "MainRegion", + "NewKeywordRegion", + "OperatorTokenRegion", + "OnTargetRegion", + "OnTokenRegion", + "PragmaKeywordRegion", + "PragmaValuesRegion", + "PropertyKeywordRegion", + "QuestionMarkTokenRegion", + "ReadonlyKeywordRegion", + "RequiredKeywordRegion", + "ReturnKeywordRegion", + "RightBraceRegion", + "RightBracketRegion", + "RightParenthesisRegion", + "SecondSemicolonRegion", + "SemicolonTokenRegion", + "SignalKeywordRegion", + "SuperKeywordRegion", + "StarTokenRegion", + "SwitchKeywordRegion", + "ThisKeywordRegion", + "ThrowKeywordRegion", + "TryKeywordRegion", + "TypeIdentifierRegion", + "TypeModifierRegion", + "VersionRegion", + "WhileKeywordRegion", + "YieldKeywordRegion" + ] + } + ], + "lineNumber": 27, + "namespace": true, + "qualifiedClassName": "QQmlJS::Dom" + } + ], + "inputFile": "qqmldomconstants_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "ScriptExpression", + "enums": [ + { + "isClass": true, + "isFlag": false, + "name": "ExpressionType", + "values": [ + "BindingExpression", + "FunctionBody", + "ArgInitializer", + "ArgumentStructure", + "ReturnType", + "JSCode", + "ESMCode" + ] + } + ], + "gadget": true, + "lineNumber": 388, + "qualifiedClassName": "QQmlJS::Dom::ScriptExpression", + "superClasses": [ + { + "access": "public", + "name": "OwningItem" + } + ] + }, + { + "className": "MethodInfo", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "MethodType", + "values": [ + "Signal", + "Method" + ] + } + ], + "gadget": true, + "lineNumber": 748, + "qualifiedClassName": "QQmlJS::Dom::MethodInfo", + "superClasses": [ + { + "access": "public", + "name": "AttributeInfo" + } + ] + } + ], + "inputFile": "qqmldomelements_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "ErrorGroup", + "gadget": true, + "lineNumber": 45, + "qualifiedClassName": "QQmlJS::Dom::ErrorGroup" + }, + { + "className": "ErrorGroups", + "gadget": true, + "lineNumber": 63, + "qualifiedClassName": "QQmlJS::Dom::ErrorGroups" + }, + { + "className": "ErrorMessage", + "gadget": true, + "lineNumber": 101, + "qualifiedClassName": "QQmlJS::Dom::ErrorMessage" + } + ], + "inputFile": "qqmldomerrormessage_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "FieldFilter", + "gadget": true, + "lineNumber": 32, + "qualifiedClassName": "QQmlJS::Dom::FieldFilter" + } + ], + "inputFile": "qqmldomfieldfilter_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "FileWriter", + "gadget": true, + "lineNumber": 29, + "qualifiedClassName": "QQmlJS::Dom::FileWriter" + } + ], + "inputFile": "qqmldomfilewriter_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "Reference", + "gadget": true, + "lineNumber": 645, + "qualifiedClassName": "QQmlJS::Dom::Reference", + "superClasses": [ + { + "access": "public", + "name": "DomElement" + } + ] + } + ], + "inputFile": "qqmldomitem_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "LineWriterOptions", + "enums": [ + { + "isClass": true, + "isFlag": false, + "name": "LineEndings", + "values": [ + "Unix", + "Windows", + "OldMacOs" + ] + }, + { + "isClass": true, + "isFlag": false, + "name": "TrailingSpace", + "values": [ + "Preserve", + "Remove" + ] + }, + { + "isClass": true, + "isFlag": false, + "name": "Update", + "values": [ + "None", + "Expressions", + "Locations", + "All", + "Default" + ] + }, + { + "isClass": true, + "isFlag": false, + "name": "AttributesSequence", + "values": [ + "Normalize", + "Preserve" + ] + } + ], + "gadget": true, + "lineNumber": 74, + "qualifiedClassName": "QQmlJS::Dom::LineWriterOptions" + }, + { + "className": "PendingSourceLocation", + "gadget": true, + "lineNumber": 111, + "qualifiedClassName": "QQmlJS::Dom::PendingSourceLocation" + }, + { + "className": "LineWriter", + "gadget": true, + "lineNumber": 126, + "qualifiedClassName": "QQmlJS::Dom::LineWriter" + } + ], + "inputFile": "qqmldomlinewriter_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "Path", + "gadget": true, + "lineNumber": 596, + "qualifiedClassName": "QQmlJS::Dom::Path" + } + ], + "inputFile": "qqmldompath_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "DomUniverse", + "gadget": true, + "lineNumber": 173, + "qualifiedClassName": "QQmlJS::Dom::DomUniverse", + "superClasses": [ + { + "access": "public", + "name": "DomTop" + }, + { + "access": "public", + "name": "std::enable_shared_from_this" + } + ] + }, + { + "className": "RefCacheEntry", + "enums": [ + { + "isClass": true, + "isFlag": false, + "name": "Cached", + "values": [ + "None", + "First", + "All" + ] + } + ], + "gadget": true, + "lineNumber": 701, + "qualifiedClassName": "QQmlJS::Dom::RefCacheEntry" + }, + { + "className": "DomEnvironment", + "enums": [ + { + "isClass": true, + "isFlag": false, + "name": "Option", + "values": [ + "Default", + "KeepValid", + "Exported", + "NoReload", + "WeakLoad", + "SingleThreaded", + "NoDependencies" + ] + } + ], + "gadget": true, + "lineNumber": 716, + "qualifiedClassName": "QQmlJS::Dom::DomEnvironment", + "superClasses": [ + { + "access": "public", + "name": "DomTop" + }, + { + "access": "public", + "name": "std::enable_shared_from_this" + } + ] + } + ], + "inputFile": "qqmldomtop_p.h", + "outputRevision": 68 + } +] diff --git a/qt/6.8.1/msvc2022_64/metatypes/qt6qmllocalstorage_metatypes.json b/qt/6.8.1/msvc2022_64/metatypes/qt6qmllocalstorage_metatypes.json new file mode 100644 index 0000000000000000000000000000000000000000..a00b3d8890cf92fdfaca788a364f9c2e4ba40fed --- /dev/null +++ b/qt/6.8.1/msvc2022_64/metatypes/qt6qmllocalstorage_metatypes.json @@ -0,0 +1,48 @@ +[ + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "LocalStorage" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + }, + { + "name": "QML.Singleton", + "value": "true" + } + ], + "className": "QQmlLocalStorage", + "lineNumber": 26, + "methods": [ + { + "access": "public", + "arguments": [ + { + "name": "args", + "type": "QQmlV4FunctionPtr" + } + ], + "index": 0, + "name": "openDatabaseSync", + "returnType": "void" + } + ], + "object": true, + "qualifiedClassName": "QQmlLocalStorage", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qqmllocalstorage_p.h", + "outputRevision": 68 + } +] diff --git a/qt/6.8.1/msvc2022_64/metatypes/qt6qmllsprivate_metatypes.json b/qt/6.8.1/msvc2022_64/metatypes/qt6qmllsprivate_metatypes.json new file mode 100644 index 0000000000000000000000000000000000000000..291537f40dbd65e5ff3fcceb7e361e65da1991b8 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/metatypes/qt6qmllsprivate_metatypes.json @@ -0,0 +1,573 @@ +[ + { + "classes": [ + { + "className": "QLanguageServerModule", + "lineNumber": 29, + "object": true, + "qualifiedClassName": "QLanguageServerModule", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "className": "QLanguageServer", + "enums": [ + { + "isClass": true, + "isFlag": false, + "name": "RunStatus", + "values": [ + "NotSetup", + "SettingUp", + "DidSetup", + "Initializing", + "DidInitialize", + "WaitPending", + "Stopping", + "Stopped" + ] + } + ], + "lineNumber": 40, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "runStatus", + "notify": "runStatusChanged", + "read": "runStatus", + "required": false, + "scriptable": true, + "stored": true, + "type": "RunStatus", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "isInitialized", + "read": "isInitialized", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + } + ], + "qualifiedClassName": "QLanguageServer", + "signals": [ + { + "access": "public", + "arguments": [ + { + "type": "RunStatus" + } + ], + "index": 0, + "name": "runStatusChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "server", + "type": "QLanguageServer*" + } + ], + "index": 1, + "name": "clientInitialized", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "shutdown", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "exit", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "lifecycleError", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "readNextMessage", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "d", + "type": "QByteArray" + }, + { + "name": "isEndOfMessage", + "type": "bool" + } + ], + "index": 6, + "name": "receiveData", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qlanguageserver_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQmlCodeModel", + "lineNumber": 80, + "object": true, + "qualifiedClassName": "QmlLsp::QQmlCodeModel", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "url", + "type": "QByteArray" + } + ], + "index": 0, + "name": "updatedSnapshot", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "path", + "type": "QString" + } + ], + "index": 1, + "name": "documentationRootPathChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "private", + "arguments": [ + { + "type": "QString" + } + ], + "index": 2, + "name": "onCppFileChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qqmlcodemodel_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QmlCompletionSupport", + "lineNumber": 46, + "object": true, + "qualifiedClassName": "QmlCompletionSupport", + "superClasses": [ + { + "access": "public", + "name": "QQmlBaseModule" + } + ] + } + ], + "inputFile": "qqmlcompletionsupport_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQmlFindUsagesSupport", + "lineNumber": 28, + "object": true, + "qualifiedClassName": "QQmlFindUsagesSupport", + "superClasses": [ + { + "access": "public", + "name": "QQmlBaseModule" + } + ] + } + ], + "inputFile": "qqmlfindusagessupport_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQmlDocumentFormatting", + "lineNumber": 30, + "object": true, + "qualifiedClassName": "QQmlDocumentFormatting", + "superClasses": [ + { + "access": "public", + "name": "QQmlBaseModule" + } + ] + } + ], + "inputFile": "qqmlformatting_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QmlGoToDefinitionSupport", + "lineNumber": 29, + "object": true, + "qualifiedClassName": "QmlGoToDefinitionSupport", + "superClasses": [ + { + "access": "public", + "name": "QQmlBaseModule" + } + ] + } + ], + "inputFile": "qqmlgotodefinitionsupport_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QmlGoToTypeDefinitionSupport", + "lineNumber": 30, + "object": true, + "qualifiedClassName": "QmlGoToTypeDefinitionSupport", + "superClasses": [ + { + "access": "public", + "name": "QQmlBaseModule" + } + ] + } + ], + "inputFile": "qqmlgototypedefinitionsupport_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQmlHover", + "lineNumber": 30, + "object": true, + "qualifiedClassName": "QQmlHover", + "superClasses": [ + { + "access": "public", + "name": "QQmlBaseModule" + } + ] + } + ], + "inputFile": "qqmlhover_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQmlLanguageServer", + "lineNumber": 39, + "object": true, + "qualifiedClassName": "QmlLsp::QQmlLanguageServer", + "slots": [ + { + "access": "public", + "index": 0, + "name": "exit", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "errorExit", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QLanguageServerModule" + } + ] + } + ], + "inputFile": "qqmllanguageserver_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QmlLintSuggestions", + "lineNumber": 32, + "object": true, + "qualifiedClassName": "QmlLsp::QmlLintSuggestions", + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "uri", + "type": "QByteArray" + } + ], + "index": 0, + "name": "diagnose", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "server", + "type": "QLanguageServer*" + }, + { + "name": "protocol", + "type": "QLanguageServerProtocol*" + } + ], + "index": 1, + "name": "registerHandlers", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "clientInfo", + "type": "QLspSpecification::InitializeParams" + }, + { + "type": "QLspSpecification::InitializeResult&" + } + ], + "index": 2, + "name": "setupCapabilities", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QLanguageServerModule" + } + ] + } + ], + "inputFile": "qqmllintsuggestions_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQmlRangeFormatting", + "lineNumber": 30, + "object": true, + "qualifiedClassName": "QQmlRangeFormatting", + "superClasses": [ + { + "access": "public", + "name": "QQmlBaseModule" + } + ] + } + ], + "inputFile": "qqmlrangeformatting_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQmlRenameSymbolSupport", + "lineNumber": 28, + "object": true, + "qualifiedClassName": "QQmlRenameSymbolSupport", + "superClasses": [ + { + "access": "public", + "name": "QQmlBaseModule" + } + ] + } + ], + "inputFile": "qqmlrenamesymbolsupport_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "HighlightingUtils", + "enums": [ + { + "isClass": true, + "isFlag": false, + "name": "SemanticTokenProtocolTypes", + "values": [ + "Namespace", + "Type", + "Enum", + "Parameter", + "Variable", + "Property", + "EnumMember", + "Method", + "Keyword", + "Comment", + "String", + "Number", + "Regexp", + "Operator", + "Decorator", + "QmlLocalId", + "QmlExternalId", + "QmlRootObjectProperty", + "QmlScopeObjectProperty", + "QmlExternalObjectProperty", + "JsScopeVar", + "JsImportVar", + "JsGlobalVar", + "QmlStateName" + ] + } + ], + "lineNumber": 27, + "namespace": true, + "qualifiedClassName": "HighlightingUtils" + } + ], + "inputFile": "qqmlsemantictokens_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "TextSynchronization", + "lineNumber": 23, + "object": true, + "qualifiedClassName": "TextSynchronization", + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "params", + "type": "QLspSpecification::DidOpenTextDocumentParams" + } + ], + "index": 0, + "name": "didOpenTextDocument", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "params", + "type": "QLspSpecification::DidChangeTextDocumentParams" + } + ], + "index": 1, + "name": "didDidChangeTextDocument", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "params", + "type": "QLspSpecification::DidCloseTextDocumentParams" + } + ], + "index": 2, + "name": "didCloseTextDocument", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QLanguageServerModule" + } + ] + } + ], + "inputFile": "qtextsynchronization_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "WorkspaceHandlers", + "lineNumber": 23, + "object": true, + "qualifiedClassName": "WorkspaceHandlers", + "slots": [ + { + "access": "public", + "arguments": [ + { + "type": "QLanguageServer*" + } + ], + "index": 0, + "name": "clientInitialized", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QLanguageServerModule" + } + ] + } + ], + "inputFile": "qworkspace_p.h", + "outputRevision": 68 + } +] diff --git a/qt/6.8.1/msvc2022_64/metatypes/qt6qmlmeta_metatypes.json b/qt/6.8.1/msvc2022_64/metatypes/qt6qmlmeta_metatypes.json new file mode 100644 index 0000000000000000000000000000000000000000..b0ef17f69875dd331b94f18d5c3004d97a6de071 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/metatypes/qt6qmlmeta_metatypes.json @@ -0,0 +1,584 @@ +[ + { + "classes": [ + { + "className": "QQmlLocaleEnums", + "gadget": true, + "lineNumber": 30, + "qualifiedClassName": "QQmlLocaleEnums", + "superClasses": [ + { + "access": "public", + "name": "QQmlLocale" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "Locale" + }, + { + "name": "QML.AddedInVersion", + "value": "514" + }, + { + "name": "QML.Foreign", + "value": "QQmlLocaleEnums" + }, + { + "name": "QML.ForeignIsNamespace", + "value": "true" + } + ], + "className": "QQmlLocaleEnumsForeign", + "lineNumber": 37, + "namespace": true, + "qualifiedClassName": "QQmlLocaleEnumsForeign" + } + ], + "inputFile": "qqmllocaleenums_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "Binding" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + }, + { + "name": "ImmediatePropertyNames", + "value": "objectName,target,property,value,when,delayed,restoreMode" + } + ], + "className": "QQmlBind", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "RestorationMode", + "values": [ + "RestoreNone", + "RestoreBinding", + "RestoreValue", + "RestoreBindingOrValue" + ] + } + ], + "interfaces": [ + [ + { + "className": "QQmlParserStatus", + "id": "\"org.qt-project.Qt.QQmlParserStatus\"" + } + ], + [ + { + "className": "QQmlPropertyValueSource", + "id": "\"org.qt-project.Qt.QQmlPropertyValueSource\"" + } + ] + ], + "lineNumber": 26, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "target", + "read": "object", + "required": false, + "scriptable": true, + "stored": true, + "type": "QObject*", + "user": false, + "write": "setObject" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "property", + "read": "property", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setProperty" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "value", + "read": "value", + "required": false, + "scriptable": true, + "stored": true, + "type": "QVariant", + "user": false, + "write": "setValue" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "when", + "read": "when", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setWhen" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "delayed", + "read": "delayed", + "required": false, + "revision": 520, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setDelayed" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "restoreMode", + "notify": "restoreModeChanged", + "read": "restoreMode", + "required": false, + "revision": 526, + "scriptable": true, + "stored": true, + "type": "RestorationMode", + "user": false, + "write": "setRestoreMode" + } + ], + "qualifiedClassName": "QQmlBind", + "signals": [ + { + "access": "public", + "index": 0, + "name": "restoreModeChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "private", + "index": 1, + "name": "targetValueChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QQmlPropertyValueSource" + }, + { + "access": "public", + "name": "QQmlParserStatus" + } + ] + } + ], + "inputFile": "qqmlbind_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "Connections" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + }, + { + "name": "QML.HasCustomParser", + "value": "true" + } + ], + "className": "QQmlConnections", + "interfaces": [ + [ + { + "className": "QQmlParserStatus", + "id": "\"org.qt-project.Qt.QQmlParserStatus\"" + } + ] + ], + "lineNumber": 31, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "target", + "notify": "targetChanged", + "read": "target", + "required": false, + "scriptable": true, + "stored": true, + "type": "QObject*", + "user": false, + "write": "setTarget" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "enabled", + "notify": "enabledChanged", + "read": "isEnabled", + "required": false, + "revision": 515, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setEnabled" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "ignoreUnknownSignals", + "read": "ignoreUnknownSignals", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setIgnoreUnknownSignals" + } + ], + "qualifiedClassName": "QQmlConnections", + "signals": [ + { + "access": "public", + "index": 0, + "name": "targetChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "enabledChanged", + "returnType": "void", + "revision": 515 + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QQmlParserStatus" + } + ] + } + ], + "inputFile": "qqmlconnections_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "LoggingCategory" + }, + { + "name": "QML.AddedInVersion", + "value": "520" + } + ], + "className": "QQmlLoggingCategory", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "DefaultLogLevel", + "values": [ + "Debug", + "Info", + "Warning", + "Critical", + "Fatal" + ] + } + ], + "interfaces": [ + [ + { + "className": "QQmlParserStatus", + "id": "\"org.qt-project.Qt.QQmlParserStatus\"" + } + ] + ], + "lineNumber": 32, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "name", + "read": "name", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setName" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "defaultLogLevel", + "read": "defaultLogLevel", + "required": false, + "revision": 524, + "scriptable": true, + "stored": true, + "type": "DefaultLogLevel", + "user": false, + "write": "setDefaultLogLevel" + } + ], + "qualifiedClassName": "QQmlLoggingCategory", + "superClasses": [ + { + "access": "public", + "name": "QQmlLoggingCategoryBase" + }, + { + "access": "public", + "name": "QQmlParserStatus" + } + ] + } + ], + "inputFile": "qqmlloggingcategory_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "ParentProperty", + "value": "parent" + }, + { + "name": "QML.Element", + "value": "Timer" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQmlTimer", + "interfaces": [ + [ + { + "className": "QQmlParserStatus", + "id": "\"org.qt-project.Qt.QQmlParserStatus\"" + } + ] + ], + "lineNumber": 29, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "interval", + "notify": "intervalChanged", + "read": "interval", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setInterval" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "running", + "notify": "runningChanged", + "read": "isRunning", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setRunning" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "repeat", + "notify": "repeatChanged", + "read": "isRepeating", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setRepeating" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "triggeredOnStart", + "notify": "triggeredOnStartChanged", + "read": "triggeredOnStart", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setTriggeredOnStart" + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 4, + "name": "parent", + "read": "parent", + "required": false, + "scriptable": true, + "stored": true, + "type": "QObject*", + "user": false + } + ], + "qualifiedClassName": "QQmlTimer", + "signals": [ + { + "access": "public", + "index": 0, + "name": "triggered", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "runningChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "intervalChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "repeatChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "triggeredOnStartChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "index": 5, + "name": "start", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "stop", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "restart", + "returnType": "void" + }, + { + "access": "private", + "index": 8, + "name": "ticked", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QQmlParserStatus" + } + ] + } + ], + "inputFile": "qqmltimer_p.h", + "outputRevision": 68 + } +] diff --git a/qt/6.8.1/msvc2022_64/metatypes/qt6qmlmodels_metatypes.json b/qt/6.8.1/msvc2022_64/metatypes/qt6qmlmodels_metatypes.json new file mode 100644 index 0000000000000000000000000000000000000000..76ed3cd7307f92d913a48738ab8fcb7c24f5068a --- /dev/null +++ b/qt/6.8.1/msvc2022_64/metatypes/qt6qmlmodels_metatypes.json @@ -0,0 +1,3563 @@ +[ + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + } + ], + "className": "QQmlChangeSet", + "gadget": true, + "lineNumber": 25, + "qualifiedClassName": "QQmlChangeSet" + } + ], + "inputFile": "qqmlchangeset_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQmlDMAbstractItemModelData", + "lineNumber": 25, + "object": true, + "properties": [ + { + "constant": true, + "designable": true, + "final": false, + "index": 0, + "name": "hasModelChildren", + "read": "hasModelChildren", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "modelData", + "notify": "modelDataChanged", + "read": "modelData", + "required": false, + "scriptable": true, + "stored": true, + "type": "QVariant", + "user": false, + "write": "setModelData" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "", + "notify": "modelDataChanged", + "read": "modelData", + "required": false, + "scriptable": true, + "stored": true, + "type": "QVariant", + "user": false + } + ], + "qualifiedClassName": "QQmlDMAbstractItemModelData", + "signals": [ + { + "access": "public", + "index": 0, + "name": "modelDataChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQmlDelegateModelItem" + } + ] + } + ], + "inputFile": "qqmldmabstractitemmodeldata_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQmlDMListAccessorData", + "lineNumber": 26, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "modelData", + "notify": "modelDataChanged", + "read": "modelData", + "required": false, + "scriptable": true, + "stored": true, + "type": "QVariant", + "user": false, + "write": "setModelData" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "", + "notify": "modelDataChanged", + "read": "modelData", + "required": false, + "scriptable": true, + "stored": true, + "type": "QVariant", + "user": false, + "write": "setModelData" + } + ], + "qualifiedClassName": "QQmlDMListAccessorData", + "signals": [ + { + "access": "public", + "index": 0, + "name": "modelDataChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQmlDelegateModelItem" + } + ] + } + ], + "inputFile": "qqmldmlistaccessordata_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQmlDMObjectData", + "interfaces": [ + [ + { + "className": "QQmlAdaptorModelProxyInterface", + "id": "\"org.qt-project.Qt.QQmlAdaptorModelProxyInterface\"" + } + ] + ], + "lineNumber": 27, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "modelData", + "notify": "modelDataChanged", + "read": "modelData", + "required": false, + "scriptable": true, + "stored": true, + "type": "QObject*", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "", + "notify": "modelDataChanged", + "read": "modelData", + "required": false, + "scriptable": true, + "stored": true, + "type": "QObject*", + "user": false + } + ], + "qualifiedClassName": "QQmlDMObjectData", + "signals": [ + { + "access": "public", + "index": 0, + "name": "modelDataChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQmlDelegateModelItem" + }, + { + "access": "public", + "name": "QQmlAdaptorModelProxyInterface" + } + ] + } + ], + "inputFile": "qqmldmobjectdata_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "AbstractDelegateComponent" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + }, + { + "name": "QML.Creatable", + "value": "false" + }, + { + "name": "QML.UncreatableReason", + "value": "Cannot create instance of abstract class AbstractDelegateComponent." + } + ], + "className": "QQmlAbstractDelegateComponent", + "lineNumber": 28, + "object": true, + "qualifiedClassName": "QQmlAbstractDelegateComponent", + "signals": [ + { + "access": "public", + "index": 0, + "name": "delegateChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQmlComponent" + } + ] + } + ], + "inputFile": "qqmlabstractdelegatecomponent_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "DefaultProperty", + "value": "delegate" + }, + { + "name": "QML.Element", + "value": "DelegateModel" + }, + { + "name": "QML.AddedInVersion", + "value": "513" + }, + { + "name": "QML.Attached", + "value": "QQmlDelegateModelAttached" + } + ], + "className": "QQmlDelegateModel", + "interfaces": [ + [ + { + "className": "QQmlParserStatus", + "id": "\"org.qt-project.Qt.QQmlParserStatus\"" + } + ] + ], + "lineNumber": 37, + "methods": [ + { + "access": "public", + "arguments": [ + { + "name": "idx", + "type": "int" + } + ], + "index": 18, + "name": "modelIndex", + "returnType": "QVariant" + }, + { + "access": "public", + "index": 19, + "name": "parentModelIndex", + "returnType": "QVariant" + } + ], + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "model", + "read": "model", + "required": false, + "scriptable": true, + "stored": true, + "type": "QVariant", + "user": false, + "write": "setModel" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "delegate", + "notify": "delegateChanged", + "read": "delegate", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlComponent*", + "user": false, + "write": "setDelegate" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "filterOnGroup", + "notify": "filterGroupChanged", + "read": "filterGroup", + "required": false, + "reset": "resetFilterGroup", + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setFilterGroup" + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 3, + "name": "items", + "read": "items", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlDelegateModelGroup*", + "user": false + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 4, + "name": "persistedItems", + "read": "persistedItems", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlDelegateModelGroup*", + "user": false + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 5, + "name": "groups", + "read": "groups", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlListProperty", + "user": false + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 6, + "name": "parts", + "read": "parts", + "required": false, + "scriptable": true, + "stored": true, + "type": "QObject*", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 7, + "name": "rootIndex", + "notify": "rootIndexChanged", + "read": "rootIndex", + "required": false, + "scriptable": true, + "stored": true, + "type": "QVariant", + "user": false, + "write": "setRootIndex" + } + ], + "qualifiedClassName": "QQmlDelegateModel", + "signals": [ + { + "access": "public", + "index": 0, + "name": "filterGroupChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "defaultGroupsChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "rootIndexChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "delegateChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "private", + "arguments": [ + { + "name": "index", + "type": "int" + }, + { + "name": "count", + "type": "int" + }, + { + "name": "roles", + "type": "QList" + } + ], + "index": 4, + "name": "_q_itemsChanged", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "index", + "type": "int" + }, + { + "name": "count", + "type": "int" + } + ], + "index": 5, + "name": "_q_itemsInserted", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "index", + "type": "int" + }, + { + "name": "count", + "type": "int" + } + ], + "index": 6, + "name": "_q_itemsRemoved", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "from", + "type": "int" + }, + { + "name": "to", + "type": "int" + }, + { + "name": "count", + "type": "int" + } + ], + "index": 7, + "name": "_q_itemsMoved", + "returnType": "void" + }, + { + "access": "private", + "index": 8, + "name": "_q_modelAboutToBeReset", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "type": "QModelIndex" + }, + { + "type": "int" + }, + { + "type": "int" + } + ], + "index": 9, + "name": "_q_rowsInserted", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "type": "QModelIndex" + }, + { + "type": "int" + }, + { + "type": "int" + } + ], + "index": 10, + "name": "_q_columnsInserted", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "type": "QModelIndex" + }, + { + "type": "int" + }, + { + "type": "int" + } + ], + "index": 11, + "name": "_q_columnsRemoved", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "type": "QModelIndex" + }, + { + "type": "int" + }, + { + "type": "int" + }, + { + "type": "QModelIndex" + }, + { + "type": "int" + } + ], + "index": 12, + "name": "_q_columnsMoved", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "parent", + "type": "QModelIndex" + }, + { + "name": "begin", + "type": "int" + }, + { + "name": "end", + "type": "int" + } + ], + "index": 13, + "name": "_q_rowsAboutToBeRemoved", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "type": "QModelIndex" + }, + { + "type": "int" + }, + { + "type": "int" + } + ], + "index": 14, + "name": "_q_rowsRemoved", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "type": "QModelIndex" + }, + { + "type": "int" + }, + { + "type": "int" + }, + { + "type": "QModelIndex" + }, + { + "type": "int" + } + ], + "index": 15, + "name": "_q_rowsMoved", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "type": "QModelIndex" + }, + { + "type": "QModelIndex" + }, + { + "type": "QList" + } + ], + "index": 16, + "name": "_q_dataChanged", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "type": "QList" + }, + { + "type": "QAbstractItemModel::LayoutChangeHint" + } + ], + "index": 17, + "name": "_q_layoutChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQmlInstanceModel" + }, + { + "access": "public", + "name": "QQmlParserStatus" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "DelegateModelGroup" + }, + { + "name": "QML.AddedInVersion", + "value": "513" + } + ], + "className": "QQmlDelegateModelGroup", + "lineNumber": 135, + "methods": [ + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + } + ], + "index": 12, + "name": "get", + "returnType": "QJSValue" + } + ], + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "count", + "notify": "countChanged", + "read": "count", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "name", + "notify": "nameChanged", + "read": "name", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setName" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "includeByDefault", + "notify": "defaultIncludeChanged", + "read": "defaultInclude", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setDefaultInclude" + } + ], + "qualifiedClassName": "QQmlDelegateModelGroup", + "signals": [ + { + "access": "public", + "index": 0, + "name": "countChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "nameChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "defaultIncludeChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "removed", + "type": "QJSValue" + }, + { + "name": "inserted", + "type": "QJSValue" + } + ], + "index": 3, + "name": "changed", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "type": "QQmlV4FunctionPtr" + } + ], + "index": 4, + "name": "insert", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QQmlV4FunctionPtr" + } + ], + "index": 5, + "name": "create", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QQmlV4FunctionPtr" + } + ], + "index": 6, + "name": "resolve", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QQmlV4FunctionPtr" + } + ], + "index": 7, + "name": "remove", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QQmlV4FunctionPtr" + } + ], + "index": 8, + "name": "addGroups", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QQmlV4FunctionPtr" + } + ], + "index": 9, + "name": "removeGroups", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QQmlV4FunctionPtr" + } + ], + "index": 10, + "name": "setGroups", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QQmlV4FunctionPtr" + } + ], + "index": 11, + "name": "move", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "className": "QQmlDelegateModelAttached", + "lineNumber": 179, + "object": true, + "properties": [ + { + "constant": true, + "designable": true, + "final": true, + "index": 0, + "name": "model", + "read": "model", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlDelegateModel*", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "groups", + "notify": "groupsChanged", + "read": "groups", + "required": false, + "scriptable": true, + "stored": true, + "type": "QStringList", + "user": false, + "write": "setGroups" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "isUnresolved", + "notify": "unresolvedChanged", + "read": "isUnresolved", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "inPersistedItems", + "notify": "groupsChanged", + "read": "inPersistedItems", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setInPersistedItems" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "inItems", + "notify": "groupsChanged", + "read": "inItems", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setInItems" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "persistedItemsIndex", + "notify": "groupsChanged", + "read": "persistedItemsIndex", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 6, + "name": "itemsIndex", + "notify": "groupsChanged", + "read": "itemsIndex", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + } + ], + "qualifiedClassName": "QQmlDelegateModelAttached", + "signals": [ + { + "access": "public", + "index": 0, + "name": "groupsChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "unresolvedChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qqmldelegatemodel_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQmlDelegateModelItem", + "lineNumber": 65, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "index", + "notify": "modelIndexChanged", + "read": "modelIndex", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "row", + "notify": "rowChanged", + "read": "modelRow", + "required": false, + "revision": 524, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "column", + "notify": "columnChanged", + "read": "modelColumn", + "required": false, + "revision": 524, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 3, + "name": "model", + "read": "modelObject", + "required": false, + "scriptable": true, + "stored": true, + "type": "QObject*", + "user": false + } + ], + "qualifiedClassName": "QQmlDelegateModelItem", + "signals": [ + { + "access": "public", + "index": 0, + "name": "modelIndexChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "rowChanged", + "returnType": "void", + "revision": 524 + }, + { + "access": "public", + "index": 2, + "name": "columnChanged", + "returnType": "void", + "revision": 524 + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "className": "QQmlPartsModel", + "lineNumber": 361, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "filterOnGroup", + "notify": "filterGroupChanged", + "read": "filterGroup", + "required": false, + "reset": "resetFilterGroup", + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setFilterGroup" + } + ], + "qualifiedClassName": "QQmlPartsModel", + "signals": [ + { + "access": "public", + "index": 0, + "name": "filterGroupChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQmlInstanceModel" + }, + { + "access": "public", + "name": "QQmlDelegateModelGroupEmitter" + } + ] + }, + { + "className": "QQmlDelegateModelParts", + "lineNumber": 419, + "object": true, + "qualifiedClassName": "QQmlDelegateModelParts", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qqmldelegatemodel_p_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "DefaultProperty", + "value": "delegate" + }, + { + "name": "QML.Element", + "value": "Instantiator" + }, + { + "name": "QML.AddedInVersion", + "value": "513" + } + ], + "className": "QQmlInstantiator", + "interfaces": [ + [ + { + "className": "QQmlParserStatus", + "id": "\"org.qt-project.Qt.QQmlParserStatus\"" + } + ] + ], + "lineNumber": 27, + "methods": [ + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + } + ], + "index": 10, + "name": "objectAt", + "returnType": "QObject*" + } + ], + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "active", + "notify": "activeChanged", + "read": "isActive", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setActive" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "asynchronous", + "notify": "asynchronousChanged", + "read": "isAsync", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setAsync" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "model", + "notify": "modelChanged", + "read": "model", + "required": false, + "scriptable": true, + "stored": true, + "type": "QVariant", + "user": false, + "write": "setModel" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "count", + "notify": "countChanged", + "read": "count", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "delegate", + "notify": "delegateChanged", + "read": "delegate", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlComponent*", + "user": false, + "write": "setDelegate" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "object", + "notify": "objectChanged", + "read": "object", + "required": false, + "scriptable": true, + "stored": true, + "type": "QObject*", + "user": false + } + ], + "qualifiedClassName": "QQmlInstantiator", + "signals": [ + { + "access": "public", + "index": 0, + "name": "modelChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "delegateChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "countChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "objectChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "activeChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "asynchronousChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + }, + { + "name": "object", + "type": "QObject*" + } + ], + "index": 6, + "name": "objectAdded", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + }, + { + "name": "object", + "type": "QObject*" + } + ], + "index": 7, + "name": "objectRemoved", + "returnType": "void" + } + ], + "slots": [ + { + "access": "private", + "arguments": [ + { + "type": "int" + }, + { + "type": "QObject*" + } + ], + "index": 8, + "name": "_q_createdItem", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "type": "QQmlChangeSet" + }, + { + "type": "bool" + } + ], + "index": 9, + "name": "_q_modelUpdated", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QQmlParserStatus" + } + ] + } + ], + "inputFile": "qqmlinstantiator_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "ListModel" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + }, + { + "name": "QML.HasCustomParser", + "value": "true" + } + ], + "className": "QQmlListModel", + "lineNumber": 44, + "methods": [ + { + "access": "public", + "index": 1, + "name": "clear", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "args", + "type": "QQmlV4FunctionPtr" + } + ], + "index": 2, + "name": "remove", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "args", + "type": "QQmlV4FunctionPtr" + } + ], + "index": 3, + "name": "append", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "args", + "type": "QQmlV4FunctionPtr" + } + ], + "index": 4, + "name": "insert", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + } + ], + "index": 5, + "name": "get", + "returnType": "QJSValue" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + }, + { + "name": "value", + "type": "QJSValue" + } + ], + "index": 6, + "name": "set", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + }, + { + "name": "property", + "type": "QString" + }, + { + "name": "value", + "type": "QVariant" + } + ], + "index": 7, + "name": "setProperty", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "from", + "type": "int" + }, + { + "name": "to", + "type": "int" + }, + { + "name": "count", + "type": "int" + } + ], + "index": 8, + "name": "move", + "returnType": "void" + }, + { + "access": "public", + "index": 9, + "name": "sync", + "returnType": "void" + } + ], + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "count", + "notify": "countChanged", + "read": "count", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "dynamicRoles", + "read": "dynamicRoles", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setDynamicRoles" + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 2, + "name": "agent", + "read": "agent", + "required": false, + "revision": 526, + "scriptable": true, + "stored": true, + "type": "QObject*", + "user": false + } + ], + "qualifiedClassName": "QQmlListModel", + "signals": [ + { + "access": "public", + "index": 0, + "name": "countChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QAbstractListModel" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "ListElement" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQmlListElement", + "lineNumber": 144, + "object": true, + "qualifiedClassName": "QQmlListElement", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qqmllistmodel_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "DynamicRoleModelNode", + "lineNumber": 48, + "object": true, + "qualifiedClassName": "DynamicRoleModelNode", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qqmllistmodel_p_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQmlListModelWorkerAgent", + "lineNumber": 34, + "methods": [ + { + "access": "public", + "index": 1, + "name": "addref", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "release", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "clear", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "args", + "type": "QQmlV4FunctionPtr" + } + ], + "index": 4, + "name": "remove", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "args", + "type": "QQmlV4FunctionPtr" + } + ], + "index": 5, + "name": "append", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "args", + "type": "QQmlV4FunctionPtr" + } + ], + "index": 6, + "name": "insert", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + } + ], + "index": 7, + "name": "get", + "returnType": "QJSValue" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + }, + { + "name": "value", + "type": "QJSValue" + } + ], + "index": 8, + "name": "set", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + }, + { + "name": "property", + "type": "QString" + }, + { + "name": "value", + "type": "QVariant" + } + ], + "index": 9, + "name": "setProperty", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "from", + "type": "int" + }, + { + "name": "to", + "type": "int" + }, + { + "name": "count", + "type": "int" + } + ], + "index": 10, + "name": "move", + "returnType": "void" + }, + { + "access": "public", + "index": 11, + "name": "sync", + "returnType": "void" + } + ], + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "count", + "read": "count", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "engine", + "notify": "engineChanged", + "read": "engine", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlV4ExecutionEnginePtr", + "user": false, + "write": "setEngine" + } + ], + "qualifiedClassName": "QQmlListModelWorkerAgent", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "engine", + "type": "QQmlV4ExecutionEnginePtr" + } + ], + "index": 0, + "name": "engineChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qqmllistmodelworkeragent_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.Extended", + "value": "QQmlModelIndexValueType" + }, + { + "name": "QML.Foreign", + "value": "QModelIndex" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQmlModelIndexValueType", + "gadget": true, + "lineNumber": 25, + "methods": [ + { + "access": "public", + "index": 0, + "name": "toString", + "returnType": "QString" + }, + { + "access": "public", + "arguments": [ + { + "name": "role", + "type": "int" + } + ], + "index": 1, + "name": "data", + "returnType": "QVariant", + "revision": 1543 + }, + { + "access": "public", + "index": 2, + "isCloned": true, + "name": "data", + "returnType": "QVariant", + "revision": 1543 + } + ], + "properties": [ + { + "constant": true, + "designable": true, + "final": true, + "index": 0, + "name": "row", + "read": "row", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 1, + "name": "column", + "read": "column", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "parent", + "read": "parent", + "required": false, + "scriptable": true, + "stored": true, + "type": "QModelIndex", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 3, + "name": "valid", + "read": "isValid", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 4, + "name": "model", + "read": "model", + "required": false, + "scriptable": true, + "stored": true, + "type": "QAbstractItemModel*", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 5, + "name": "internalId", + "read": "internalId", + "required": false, + "scriptable": true, + "stored": true, + "type": "quint64", + "user": false + } + ], + "qualifiedClassName": "QQmlModelIndexValueType" + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.Extended", + "value": "QQmlPersistentModelIndexValueType" + }, + { + "name": "QML.Foreign", + "value": "QPersistentModelIndex" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQmlPersistentModelIndexValueType", + "gadget": true, + "lineNumber": 64, + "methods": [ + { + "access": "public", + "index": 0, + "name": "toString", + "returnType": "QString" + }, + { + "access": "public", + "arguments": [ + { + "name": "role", + "type": "int" + } + ], + "index": 1, + "name": "data", + "returnType": "QVariant", + "revision": 1543 + }, + { + "access": "public", + "index": 2, + "isCloned": true, + "name": "data", + "returnType": "QVariant", + "revision": 1543 + } + ], + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "row", + "read": "row", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "column", + "read": "column", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "parent", + "read": "parent", + "required": false, + "scriptable": true, + "stored": true, + "type": "QModelIndex", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "valid", + "read": "isValid", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "model", + "read": "model", + "required": false, + "scriptable": true, + "stored": true, + "type": "QAbstractItemModel*", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "internalId", + "read": "internalId", + "required": false, + "scriptable": true, + "stored": true, + "type": "quint64", + "user": false + } + ], + "qualifiedClassName": "QQmlPersistentModelIndexValueType" + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.Extended", + "value": "QQmlItemSelectionRangeValueType" + }, + { + "name": "QML.Foreign", + "value": "QItemSelectionRange" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQmlItemSelectionRangeValueType", + "gadget": true, + "lineNumber": 97, + "methods": [ + { + "access": "public", + "index": 0, + "name": "toString", + "returnType": "QString" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "QModelIndex" + } + ], + "index": 1, + "name": "contains", + "returnType": "bool" + }, + { + "access": "public", + "arguments": [ + { + "name": "row", + "type": "int" + }, + { + "name": "column", + "type": "int" + }, + { + "name": "parentIndex", + "type": "QModelIndex" + } + ], + "index": 2, + "name": "contains", + "returnType": "bool" + }, + { + "access": "public", + "arguments": [ + { + "name": "other", + "type": "QItemSelectionRange" + } + ], + "index": 3, + "name": "intersects", + "returnType": "bool" + }, + { + "access": "public", + "arguments": [ + { + "name": "other", + "type": "QItemSelectionRange" + } + ], + "index": 4, + "name": "intersected", + "returnType": "QItemSelectionRange" + } + ], + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "top", + "read": "top", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "left", + "read": "left", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "bottom", + "read": "bottom", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "right", + "read": "right", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "width", + "read": "width", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "height", + "read": "height", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 6, + "name": "topLeft", + "read": "topLeft", + "required": false, + "scriptable": true, + "stored": true, + "type": "QPersistentModelIndex", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 7, + "name": "bottomRight", + "read": "bottomRight", + "required": false, + "scriptable": true, + "stored": true, + "type": "QPersistentModelIndex", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 8, + "name": "parent", + "read": "parent", + "required": false, + "scriptable": true, + "stored": true, + "type": "QModelIndex", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 9, + "name": "valid", + "read": "isValid", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 10, + "name": "empty", + "read": "isEmpty", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 11, + "name": "model", + "read": "model", + "required": false, + "scriptable": true, + "stored": true, + "type": "QAbstractItemModel*", + "user": false + } + ], + "qualifiedClassName": "QQmlItemSelectionRangeValueType" + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.Sequence", + "value": "QModelIndex" + }, + { + "name": "QML.Foreign", + "value": "QModelIndexList" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QModelIndexListForeign", + "gadget": true, + "lineNumber": 146, + "qualifiedClassName": "QModelIndexListForeign" + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.Sequence", + "value": "QModelIndex" + }, + { + "name": "QML.Foreign", + "value": "std::vector" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QModelIndexStdVectorForeign", + "gadget": true, + "lineNumber": 155, + "qualifiedClassName": "QModelIndexStdVectorForeign" + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.Sequence", + "value": "QItemSelectionRange" + }, + { + "name": "QML.Foreign", + "value": "QItemSelection" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QItemSelectionForeign", + "gadget": true, + "lineNumber": 164, + "qualifiedClassName": "QItemSelectionForeign" + } + ], + "inputFile": "qqmlmodelindexvaluetype_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Foreign", + "value": "QItemSelectionModel" + }, + { + "name": "QML.Element", + "value": "ItemSelectionModel" + }, + { + "name": "QML.AddedInVersion", + "value": "514" + } + ], + "className": "QItemSelectionModelForeign", + "gadget": true, + "lineNumber": 30, + "qualifiedClassName": "QItemSelectionModelForeign" + }, + { + "classInfos": [ + { + "name": "QML.Foreign", + "value": "QAbstractItemModel" + }, + { + "name": "QML.Element", + "value": "AbstractItemModel" + }, + { + "name": "QML.AddedInVersion", + "value": "1541" + }, + { + "name": "QML.Creatable", + "value": "false" + }, + { + "name": "QML.UncreatableReason", + "value": "QAbstractItemModel is abstract in C++." + } + ], + "className": "QAbstractItemModelForeign", + "gadget": true, + "lineNumber": 38, + "qualifiedClassName": "QAbstractItemModelForeign" + }, + { + "classInfos": [ + { + "name": "QML.Foreign", + "value": "QAbstractListModel" + }, + { + "name": "QML.Element", + "value": "AbstractListModel" + }, + { + "name": "QML.AddedInVersion", + "value": "1541" + }, + { + "name": "QML.Creatable", + "value": "false" + }, + { + "name": "QML.UncreatableReason", + "value": "QAbstractListModel is abstract in C++." + } + ], + "className": "QAbstractListModelForeign", + "gadget": true, + "lineNumber": 47, + "qualifiedClassName": "QAbstractListModelForeign" + } + ], + "inputFile": "qqmlmodelsmodule_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQmlInstanceModel", + "lineNumber": 31, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "count", + "notify": "countChanged", + "read": "count", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + } + ], + "qualifiedClassName": "QQmlInstanceModel", + "signals": [ + { + "access": "public", + "index": 0, + "name": "countChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "changeSet", + "type": "QQmlChangeSet" + }, + { + "name": "reset", + "type": "bool" + } + ], + "index": 1, + "name": "modelUpdated", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + }, + { + "name": "object", + "type": "QObject*" + } + ], + "index": 2, + "name": "createdItem", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + }, + { + "name": "object", + "type": "QObject*" + } + ], + "index": 3, + "name": "initItem", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "object", + "type": "QObject*" + } + ], + "index": 4, + "name": "destroyingItem", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + }, + { + "name": "object", + "type": "QObject*" + } + ], + "index": 5, + "name": "itemPooled", + "returnType": "void", + "revision": 527 + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + }, + { + "name": "object", + "type": "QObject*" + } + ], + "index": 6, + "name": "itemReused", + "returnType": "void", + "revision": 527 + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "classInfos": [ + { + "name": "DefaultProperty", + "value": "children" + }, + { + "name": "QML.Element", + "value": "ObjectModel" + }, + { + "name": "QML.AddedInVersion", + "value": "513" + }, + { + "name": "QML.Attached", + "value": "QQmlObjectModelAttached" + } + ], + "className": "QQmlObjectModel", + "lineNumber": 85, + "methods": [ + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + } + ], + "index": 2, + "name": "get", + "returnType": "QObject*", + "revision": 515 + }, + { + "access": "public", + "arguments": [ + { + "name": "object", + "type": "QObject*" + } + ], + "index": 3, + "name": "append", + "returnType": "void", + "revision": 515 + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + }, + { + "name": "object", + "type": "QObject*" + } + ], + "index": 4, + "name": "insert", + "returnType": "void", + "revision": 515 + }, + { + "access": "public", + "arguments": [ + { + "name": "from", + "type": "int" + }, + { + "name": "to", + "type": "int" + }, + { + "name": "n", + "type": "int" + } + ], + "index": 5, + "name": "move", + "returnType": "void", + "revision": 515 + }, + { + "access": "public", + "arguments": [ + { + "name": "from", + "type": "int" + }, + { + "name": "to", + "type": "int" + } + ], + "index": 6, + "isCloned": true, + "name": "move", + "returnType": "void", + "revision": 515 + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + }, + { + "name": "n", + "type": "int" + } + ], + "index": 7, + "name": "remove", + "returnType": "void", + "revision": 515 + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + } + ], + "index": 8, + "isCloned": true, + "name": "remove", + "returnType": "void", + "revision": 515 + } + ], + "object": true, + "properties": [ + { + "constant": false, + "designable": false, + "final": false, + "index": 0, + "name": "children", + "notify": "childrenChanged", + "read": "children", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlListProperty", + "user": false + } + ], + "qualifiedClassName": "QQmlObjectModel", + "signals": [ + { + "access": "public", + "index": 0, + "name": "childrenChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "index": 1, + "name": "clear", + "returnType": "void", + "revision": 515 + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQmlInstanceModel" + } + ] + }, + { + "className": "QQmlObjectModelAttached", + "lineNumber": 130, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "index", + "notify": "indexChanged", + "read": "index", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + } + ], + "qualifiedClassName": "QQmlObjectModelAttached", + "signals": [ + { + "access": "public", + "index": 0, + "name": "indexChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qqmlobjectmodel_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQmlTableInstanceModel", + "lineNumber": 50, + "object": true, + "qualifiedClassName": "QQmlTableInstanceModel", + "superClasses": [ + { + "access": "public", + "name": "QQmlInstanceModel" + } + ] + } + ], + "inputFile": "qqmltableinstancemodel_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQmlTreeModelToTableModel", + "lineNumber": 29, + "methods": [ + { + "access": "public", + "arguments": [ + { + "name": "fromIndex", + "type": "QModelIndex" + }, + { + "name": "toIndex", + "type": "QModelIndex" + } + ], + "index": 31, + "name": "selectionForRowRange", + "returnType": "QItemSelection" + } + ], + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "model", + "notify": "modelChanged", + "read": "model", + "required": false, + "scriptable": true, + "stored": true, + "type": "QAbstractItemModel*", + "user": false, + "write": "setModel" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "rootIndex", + "notify": "rootIndexChanged", + "read": "rootIndex", + "required": false, + "reset": "resetRootIndex", + "scriptable": true, + "stored": true, + "type": "QModelIndex", + "user": false, + "write": "setRootIndex" + } + ], + "qualifiedClassName": "QQmlTreeModelToTableModel", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "model", + "type": "QAbstractItemModel*" + } + ], + "index": 0, + "name": "modelChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "rootIndexChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "QModelIndex" + } + ], + "index": 2, + "name": "expanded", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "QModelIndex" + } + ], + "index": 3, + "name": "collapsed", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "type": "QModelIndex" + } + ], + "index": 4, + "name": "expand", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QModelIndex" + } + ], + "index": 5, + "name": "collapse", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "model", + "type": "QAbstractItemModel*" + } + ], + "index": 6, + "name": "setModel", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QModelIndex" + } + ], + "index": 7, + "name": "isExpanded", + "returnType": "bool" + }, + { + "access": "public", + "arguments": [ + { + "name": "row", + "type": "int" + } + ], + "index": 8, + "name": "isExpanded", + "returnType": "bool" + }, + { + "access": "public", + "arguments": [ + { + "name": "row", + "type": "int" + } + ], + "index": 9, + "name": "hasChildren", + "returnType": "bool" + }, + { + "access": "public", + "arguments": [ + { + "name": "row", + "type": "int" + } + ], + "index": 10, + "name": "hasSiblings", + "returnType": "bool" + }, + { + "access": "public", + "arguments": [ + { + "name": "row", + "type": "int" + } + ], + "index": 11, + "name": "depthAtRow", + "returnType": "int" + }, + { + "access": "public", + "arguments": [ + { + "name": "n", + "type": "int" + } + ], + "index": 12, + "name": "expandRow", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "row", + "type": "int" + }, + { + "name": "depth", + "type": "int" + } + ], + "index": 13, + "name": "expandRecursively", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "n", + "type": "int" + } + ], + "index": 14, + "name": "collapseRow", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "row", + "type": "int" + } + ], + "index": 15, + "name": "collapseRecursively", + "returnType": "void" + }, + { + "access": "private", + "index": 16, + "name": "modelHasBeenDestroyed", + "returnType": "void" + }, + { + "access": "private", + "index": 17, + "name": "modelHasBeenReset", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "topLeft", + "type": "QModelIndex" + }, + { + "name": "bottomRight", + "type": "QModelIndex" + }, + { + "name": "roles", + "type": "QList" + } + ], + "index": 18, + "name": "modelDataChanged", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "parents", + "type": "QList" + }, + { + "name": "hint", + "type": "QAbstractItemModel::LayoutChangeHint" + } + ], + "index": 19, + "name": "modelLayoutAboutToBeChanged", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "parents", + "type": "QList" + }, + { + "name": "hint", + "type": "QAbstractItemModel::LayoutChangeHint" + } + ], + "index": 20, + "name": "modelLayoutChanged", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "parent", + "type": "QModelIndex" + }, + { + "name": "start", + "type": "int" + }, + { + "name": "end", + "type": "int" + } + ], + "index": 21, + "name": "modelRowsAboutToBeInserted", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "sourceParent", + "type": "QModelIndex" + }, + { + "name": "sourceStart", + "type": "int" + }, + { + "name": "sourceEnd", + "type": "int" + }, + { + "name": "destinationParent", + "type": "QModelIndex" + }, + { + "name": "destinationRow", + "type": "int" + } + ], + "index": 22, + "name": "modelRowsAboutToBeMoved", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "parent", + "type": "QModelIndex" + }, + { + "name": "start", + "type": "int" + }, + { + "name": "end", + "type": "int" + } + ], + "index": 23, + "name": "modelRowsAboutToBeRemoved", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "parent", + "type": "QModelIndex" + }, + { + "name": "start", + "type": "int" + }, + { + "name": "end", + "type": "int" + } + ], + "index": 24, + "name": "modelRowsInserted", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "sourceParent", + "type": "QModelIndex" + }, + { + "name": "sourceStart", + "type": "int" + }, + { + "name": "sourceEnd", + "type": "int" + }, + { + "name": "destinationParent", + "type": "QModelIndex" + }, + { + "name": "destinationRow", + "type": "int" + } + ], + "index": 25, + "name": "modelRowsMoved", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "parent", + "type": "QModelIndex" + }, + { + "name": "start", + "type": "int" + }, + { + "name": "end", + "type": "int" + } + ], + "index": 26, + "name": "modelRowsRemoved", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "parent", + "type": "QModelIndex" + }, + { + "name": "start", + "type": "int" + }, + { + "name": "end", + "type": "int" + } + ], + "index": 27, + "name": "modelColumnsAboutToBeInserted", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "parent", + "type": "QModelIndex" + }, + { + "name": "start", + "type": "int" + }, + { + "name": "end", + "type": "int" + } + ], + "index": 28, + "name": "modelColumnsAboutToBeRemoved", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "parent", + "type": "QModelIndex" + }, + { + "name": "start", + "type": "int" + }, + { + "name": "end", + "type": "int" + } + ], + "index": 29, + "name": "modelColumnsInserted", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "parent", + "type": "QModelIndex" + }, + { + "name": "start", + "type": "int" + }, + { + "name": "end", + "type": "int" + } + ], + "index": 30, + "name": "modelColumnsRemoved", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QAbstractItemModel" + } + ] + } + ], + "inputFile": "qqmltreemodeltotablemodel_p_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "DefaultProperty", + "value": "data" + }, + { + "name": "QML.Element", + "value": "Package" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + }, + { + "name": "QML.Attached", + "value": "QQuickPackageAttached" + } + ], + "className": "QQuickPackage", + "lineNumber": 27, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "data", + "read": "data", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlListProperty", + "user": false + } + ], + "qualifiedClassName": "QQuickPackage", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "className": "QQuickPackageAttached", + "lineNumber": 49, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "name", + "read": "name", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setName" + } + ], + "qualifiedClassName": "QQuickPackageAttached", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qquickpackage_p.h", + "outputRevision": 68 + } +] diff --git a/qt/6.8.1/msvc2022_64/metatypes/qt6qmlnetwork_metatypes.json b/qt/6.8.1/msvc2022_64/metatypes/qt6qmlnetwork_metatypes.json new file mode 100644 index 0000000000000000000000000000000000000000..acf0f4f3b25d391929a4f5290322dea6ea463edc --- /dev/null +++ b/qt/6.8.1/msvc2022_64/metatypes/qt6qmlnetwork_metatypes.json @@ -0,0 +1,354 @@ +[ + { + "classes": [ + { + "className": "QQmlSslConfiguration", + "gadget": true, + "lineNumber": 30, + "methods": [ + { + "access": "public", + "arguments": [ + { + "name": "certificateFiles", + "type": "QStringList" + } + ], + "index": 0, + "name": "setCertificateFiles", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "privateKey", + "type": "QQmlSslKey" + } + ], + "index": 1, + "name": "setPrivateKey", + "returnType": "void" + } + ], + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "ciphers", + "read": "ciphers", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setCiphers" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "sslOptions", + "read": "sslOptions", + "required": false, + "scriptable": true, + "stored": true, + "type": "QList", + "user": false, + "write": "setSslOptions" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "protocol", + "read": "protocol", + "required": false, + "scriptable": true, + "stored": true, + "type": "QSsl::SslProtocol", + "user": false, + "write": "setProtocol" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "peerVerifyMode", + "read": "peerVerifyMode", + "required": false, + "scriptable": true, + "stored": true, + "type": "QSslSocket::PeerVerifyMode", + "user": false, + "write": "setPeerVerifyMode" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "peerVerifyDepth", + "read": "peerVerifyDepth", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setPeerVerifyDepth" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "sessionTicket", + "read": "sessionTicket", + "required": false, + "scriptable": true, + "stored": true, + "type": "QByteArray", + "user": false, + "write": "setSessionTicket" + } + ], + "qualifiedClassName": "QQmlSslConfiguration" + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "sslConfiguration" + }, + { + "name": "QML.AddedInVersion", + "value": "1543" + } + ], + "className": "QQmlSslDefaultConfiguration", + "gadget": true, + "lineNumber": 87, + "qualifiedClassName": "QQmlSslDefaultConfiguration", + "superClasses": [ + { + "access": "public", + "name": "QQmlSslConfiguration" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "sslDtlsConfiguration" + }, + { + "name": "QML.AddedInVersion", + "value": "1543" + } + ], + "className": "QQmlSslDefaultDtlsConfiguration", + "gadget": true, + "lineNumber": 97, + "qualifiedClassName": "QQmlSslDefaultDtlsConfiguration", + "superClasses": [ + { + "access": "public", + "name": "QQmlSslConfiguration" + } + ] + } + ], + "inputFile": "qqmlsslconfiguration_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "sslKey" + }, + { + "name": "QML.AddedInVersion", + "value": "1543" + } + ], + "className": "QQmlSslKey", + "gadget": true, + "lineNumber": 28, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "keyFile", + "read": "keyFile", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setKeyFile" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "keyAlgorithm", + "read": "keyAlgorithm", + "required": false, + "scriptable": true, + "stored": true, + "type": "QSsl::KeyAlgorithm", + "user": false, + "write": "setKeyAlgorithm" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "keyFormat", + "read": "keyFormat", + "required": false, + "scriptable": true, + "stored": true, + "type": "QSsl::EncodingFormat", + "user": false, + "write": "setKeyFormat" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "keyPassPhrase", + "read": "keyPassPhrase", + "required": false, + "scriptable": true, + "stored": true, + "type": "QByteArray", + "user": false, + "write": "setKeyPassPhrase" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "keyType", + "read": "keyType", + "required": false, + "scriptable": true, + "stored": true, + "type": "QSsl::KeyType", + "user": false, + "write": "setKeyType" + } + ], + "qualifiedClassName": "QQmlSslKey" + } + ], + "inputFile": "qqmlsslkey_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Foreign", + "value": "QSsl" + }, + { + "name": "QML.ForeignIsNamespace", + "value": "true" + }, + { + "name": "QML.Element", + "value": "Ssl" + }, + { + "name": "QML.AddedInVersion", + "value": "1543" + } + ], + "className": "QSslForeignNamespace", + "lineNumber": 26, + "namespace": true, + "qualifiedClassName": "QSslForeignNamespace" + } + ], + "inputFile": "qqmlsslnamespace_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Foreign", + "value": "QSslSocket" + }, + { + "name": "QML.ForeignIsNamespace", + "value": "true" + }, + { + "name": "QML.Element", + "value": "SslSocket" + }, + { + "name": "QML.AddedInVersion", + "value": "1543" + } + ], + "className": "SslSocketForeignNamespace", + "lineNumber": 26, + "namespace": true, + "qualifiedClassName": "SslSocketForeignNamespace" + } + ], + "inputFile": "qqmlsslsocketnamespace_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Foreign", + "value": "QNetworkInformation" + }, + { + "name": "QML.Element", + "value": "NetworkInformation" + }, + { + "name": "QML.AddedInVersion", + "value": "1543" + }, + { + "name": "QML.Singleton", + "value": "true" + } + ], + "className": "QQmlNetworkInformation", + "gadget": true, + "lineNumber": 27, + "qualifiedClassName": "QQmlNetworkInformation" + } + ], + "inputFile": "qqmlnetworkinformation_p.h", + "outputRevision": 68 + } +] diff --git a/qt/6.8.1/msvc2022_64/metatypes/qt6qmltoolingsettingsprivate_metatypes.json b/qt/6.8.1/msvc2022_64/metatypes/qt6qmltoolingsettingsprivate_metatypes.json new file mode 100644 index 0000000000000000000000000000000000000000..0d4f101c7a37a4c875e6999bee1a287fdb733380 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/metatypes/qt6qmltoolingsettingsprivate_metatypes.json @@ -0,0 +1,2 @@ +[ +] diff --git a/qt/6.8.1/msvc2022_64/metatypes/qt6qmltyperegistrarprivate_metatypes.json b/qt/6.8.1/msvc2022_64/metatypes/qt6qmltyperegistrarprivate_metatypes.json new file mode 100644 index 0000000000000000000000000000000000000000..0d4f101c7a37a4c875e6999bee1a287fdb733380 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/metatypes/qt6qmltyperegistrarprivate_metatypes.json @@ -0,0 +1,2 @@ +[ +] diff --git a/qt/6.8.1/msvc2022_64/metatypes/qt6qmlworkerscript_metatypes.json b/qt/6.8.1/msvc2022_64/metatypes/qt6qmlworkerscript_metatypes.json new file mode 100644 index 0000000000000000000000000000000000000000..c157043d506ebc8ef5371f091b5ec51d8f222abe --- /dev/null +++ b/qt/6.8.1/msvc2022_64/metatypes/qt6qmlworkerscript_metatypes.json @@ -0,0 +1,152 @@ +[ + { + "classes": [ + { + "className": "QQuickWorkerScriptEngine", + "lineNumber": 31, + "object": true, + "qualifiedClassName": "QQuickWorkerScriptEngine", + "superClasses": [ + { + "access": "public", + "name": "QThread" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "WorkerScript" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickWorkerScript", + "interfaces": [ + [ + { + "className": "QQmlParserStatus", + "id": "\"org.qt-project.Qt.QQmlParserStatus\"" + } + ] + ], + "lineNumber": 50, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "source", + "notify": "sourceChanged", + "read": "source", + "required": false, + "scriptable": true, + "stored": true, + "type": "QUrl", + "user": false, + "write": "setSource" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "ready", + "notify": "readyChanged", + "read": "ready", + "required": false, + "revision": 527, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + } + ], + "qualifiedClassName": "QQuickWorkerScript", + "signals": [ + { + "access": "public", + "index": 0, + "name": "sourceChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "readyChanged", + "returnType": "void", + "revision": 527 + }, + { + "access": "public", + "arguments": [ + { + "name": "messageObject", + "type": "QJSValue" + } + ], + "index": 2, + "name": "message", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "type": "QQmlV4FunctionPtr" + } + ], + "index": 3, + "name": "sendMessage", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QQmlParserStatus" + } + ] + } + ], + "inputFile": "qquickworkerscript_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQuickWorkerScriptEnginePrivate", + "lineNumber": 107, + "object": true, + "qualifiedClassName": "QQuickWorkerScriptEnginePrivate", + "signals": [ + { + "access": "public", + "index": 0, + "name": "stopThread", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qquickworkerscript.cpp", + "outputRevision": 68 + } +] diff --git a/qt/6.8.1/msvc2022_64/metatypes/qt6qmlxmllistmodel_metatypes.json b/qt/6.8.1/msvc2022_64/metatypes/qt6qmlxmllistmodel_metatypes.json new file mode 100644 index 0000000000000000000000000000000000000000..f0293087fddd20afe22ba299828279859d4cfff8 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/metatypes/qt6qmlxmllistmodel_metatypes.json @@ -0,0 +1,351 @@ +[ + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + } + ], + "className": "QQmlXmlListModelQueryResult", + "gadget": true, + "lineNumber": 51, + "qualifiedClassName": "QQmlXmlListModelQueryResult" + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "XmlListModelRole" + } + ], + "className": "QQmlXmlListModelRole", + "lineNumber": 61, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "name", + "notify": "nameChanged", + "read": "name", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setName" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "elementName", + "notify": "elementNameChanged", + "read": "elementName", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setElementName" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "attributeName", + "notify": "attributeNameChanged", + "read": "attributeName", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setAttributeName" + } + ], + "qualifiedClassName": "QQmlXmlListModelRole", + "signals": [ + { + "access": "public", + "index": 0, + "name": "nameChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "elementNameChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "attributeNameChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "XmlListModel" + }, + { + "name": "DefaultProperty", + "value": "roles" + } + ], + "className": "QQmlXmlListModel", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "Status", + "values": [ + "Null", + "Ready", + "Loading", + "Error" + ] + } + ], + "interfaces": [ + [ + { + "className": "QQmlParserStatus", + "id": "\"org.qt-project.Qt.QQmlParserStatus\"" + } + ] + ], + "lineNumber": 95, + "methods": [ + { + "access": "public", + "index": 11, + "name": "errorString", + "returnType": "QString" + } + ], + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "status", + "notify": "statusChanged", + "read": "status", + "required": false, + "scriptable": true, + "stored": true, + "type": "Status", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "progress", + "notify": "progressChanged", + "read": "progress", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "source", + "notify": "sourceChanged", + "read": "source", + "required": false, + "scriptable": true, + "stored": true, + "type": "QUrl", + "user": false, + "write": "setSource" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "query", + "notify": "queryChanged", + "read": "query", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setQuery" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "roles", + "read": "roleObjects", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlListProperty", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "count", + "notify": "countChanged", + "read": "count", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + } + ], + "qualifiedClassName": "QQmlXmlListModel", + "signals": [ + { + "access": "public", + "arguments": [ + { + "type": "QQmlXmlListModel::Status" + } + ], + "index": 0, + "name": "statusChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "progress", + "type": "qreal" + } + ], + "index": 1, + "name": "progressChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "countChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "sourceChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "queryChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "index": 5, + "name": "reload", + "returnType": "void" + }, + { + "access": "private", + "index": 6, + "name": "requestFinished", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "type": "qint64" + }, + { + "type": "qint64" + } + ], + "index": 7, + "name": "requestProgress", + "returnType": "void" + }, + { + "access": "private", + "index": 8, + "name": "dataCleared", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "type": "QQmlXmlListModelQueryResult" + } + ], + "index": 9, + "name": "queryCompleted", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "object", + "type": "void*" + }, + { + "name": "error", + "type": "QString" + } + ], + "index": 10, + "name": "queryError", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QAbstractListModel" + }, + { + "access": "public", + "name": "QQmlParserStatus" + } + ] + } + ], + "inputFile": "qqmlxmllistmodel_p.h", + "outputRevision": 68 + } +] diff --git a/qt/6.8.1/msvc2022_64/metatypes/qt6quick_metatypes.json b/qt/6.8.1/msvc2022_64/metatypes/qt6quick_metatypes.json new file mode 100644 index 0000000000000000000000000000000000000000..c2e6257a54b128139d0f99b731e3b5cb3c4ac3a0 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/metatypes/qt6quick_metatypes.json @@ -0,0 +1,40798 @@ +[ + { + "classes": [ + { + "className": "QSGCurveFillNode", + "lineNumber": 32, + "object": true, + "qualifiedClassName": "QSGCurveFillNode", + "slots": [ + { + "access": "private", + "index": 0, + "name": "handleTextureChanged", + "returnType": "void" + }, + { + "access": "private", + "index": 1, + "name": "handleTextureProviderDestroyed", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QSGCurveAbstractNode" + } + ] + } + ], + "inputFile": "qsgcurvefillnode_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQuickRhiItem", + "enums": [ + { + "isClass": true, + "isFlag": false, + "name": "TextureFormat", + "values": [ + "RGBA8", + "RGBA16F", + "RGBA32F", + "RGB10A2" + ] + } + ], + "lineNumber": 48, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "sampleCount", + "notify": "sampleCountChanged", + "read": "sampleCount", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setSampleCount" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "colorBufferFormat", + "notify": "colorBufferFormatChanged", + "read": "colorBufferFormat", + "required": false, + "scriptable": true, + "stored": true, + "type": "TextureFormat", + "user": false, + "write": "setColorBufferFormat" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "mirrorVertically", + "notify": "mirrorVerticallyChanged", + "read": "isMirrorVerticallyEnabled", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setMirrorVertically" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "alphaBlending", + "notify": "alphaBlendingChanged", + "read": "alphaBlending", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setAlphaBlending" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "fixedColorBufferWidth", + "notify": "fixedColorBufferWidthChanged", + "read": "fixedColorBufferWidth", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setFixedColorBufferWidth" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "fixedColorBufferHeight", + "notify": "fixedColorBufferHeightChanged", + "read": "fixedColorBufferHeight", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setFixedColorBufferHeight" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 6, + "name": "effectiveColorBufferSize", + "notify": "effectiveColorBufferSizeChanged", + "read": "effectiveColorBufferSize", + "required": false, + "scriptable": true, + "stored": true, + "type": "QSize", + "user": false + } + ], + "qualifiedClassName": "QQuickRhiItem", + "signals": [ + { + "access": "public", + "index": 0, + "name": "sampleCountChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "colorBufferFormatChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "autoRenderTargetChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "mirrorVerticallyChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "alphaBlendingChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "fixedColorBufferWidthChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "fixedColorBufferHeightChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "effectiveColorBufferSizeChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "private", + "index": 8, + "name": "invalidateSceneGraph", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickItem" + } + ] + } + ], + "inputFile": "qquickrhiitem.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQuickRhiItemNode", + "lineNumber": 26, + "object": true, + "qualifiedClassName": "QQuickRhiItemNode", + "slots": [ + { + "access": "public", + "index": 0, + "name": "render", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QSGTextureProvider" + }, + { + "access": "public", + "name": "QSGSimpleTextureNode" + } + ] + } + ], + "inputFile": "qquickrhiitem_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "WindowContainer" + }, + { + "name": "QML.AddedInVersion", + "value": "1543" + } + ], + "className": "QQuickWindowContainer", + "lineNumber": 28, + "object": true, + "properties": [ + { + "constant": false, + "designable": false, + "final": true, + "index": 0, + "name": "window", + "notify": "containedWindowChanged", + "read": "containedWindow", + "required": false, + "scriptable": true, + "stored": true, + "type": "QWindow*", + "user": false, + "write": "setContainedWindow" + } + ], + "qualifiedClassName": "QQuickWindowContainer", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "window", + "type": "QWindow*" + } + ], + "index": 0, + "name": "containedWindowChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickImplicitSizeItem" + } + ] + } + ], + "inputFile": "qquickwindowcontainer_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQuickDefaultTextureFactory", + "lineNumber": 33, + "object": true, + "qualifiedClassName": "QQuickDefaultTextureFactory", + "superClasses": [ + { + "access": "public", + "name": "QQuickTextureFactory" + } + ] + } + ], + "inputFile": "qquickpixmap_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "Accessible" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + }, + { + "name": "QML.Creatable", + "value": "false" + }, + { + "name": "QML.UncreatableReason", + "value": "Accessible is only available via attached properties." + }, + { + "name": "QML.Attached", + "value": "QQuickAccessibleAttached" + }, + { + "name": "QML.Extended", + "value": "QAccessible" + }, + { + "name": "QML.ExtensionIsNamespace", + "value": "true" + } + ], + "className": "QQuickAccessibleAttached", + "lineNumber": 50, + "methods": [ + { + "access": "public", + "arguments": [ + { + "name": "html", + "type": "QString" + } + ], + "index": 33, + "name": "stripHtml", + "returnType": "QString", + "revision": 1538 + }, + { + "access": "public", + "arguments": [ + { + "name": "message", + "type": "QString" + }, + { + "name": "politeness", + "type": "QAccessible::AnnouncementPoliteness" + } + ], + "index": 34, + "name": "announce", + "returnType": "void", + "revision": 1544 + }, + { + "access": "public", + "arguments": [ + { + "name": "message", + "type": "QString" + } + ], + "index": 35, + "isCloned": true, + "name": "announce", + "returnType": "void", + "revision": 1544 + } + ], + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "role", + "notify": "roleChanged", + "read": "role", + "required": false, + "scriptable": true, + "stored": true, + "type": "QAccessible::Role", + "user": false, + "write": "setRole" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "name", + "notify": "nameChanged", + "read": "name", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setName" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "description", + "notify": "descriptionChanged", + "read": "description", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setDescription" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "id", + "notify": "idChanged", + "read": "id", + "required": false, + "revision": 1544, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setId" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "ignored", + "notify": "ignoredChanged", + "read": "ignored", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setIgnored" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "checkable", + "notify": "checkableChanged", + "read": "checkable", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "set_checkable" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 6, + "name": "checked", + "notify": "checkedChanged", + "read": "checked", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "set_checked" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 7, + "name": "editable", + "notify": "editableChanged", + "read": "editable", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "set_editable" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 8, + "name": "focusable", + "notify": "focusableChanged", + "read": "focusable", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "set_focusable" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 9, + "name": "focused", + "notify": "focusedChanged", + "read": "focused", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "set_focused" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 10, + "name": "multiLine", + "notify": "multiLineChanged", + "read": "multiLine", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "set_multiLine" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 11, + "name": "readOnly", + "notify": "readOnlyChanged", + "read": "readOnly", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "set_readOnly" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 12, + "name": "selected", + "notify": "selectedChanged", + "read": "selected", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "set_selected" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 13, + "name": "selectable", + "notify": "selectableChanged", + "read": "selectable", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "set_selectable" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 14, + "name": "pressed", + "notify": "pressedChanged", + "read": "pressed", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "set_pressed" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 15, + "name": "checkStateMixed", + "notify": "checkStateMixedChanged", + "read": "checkStateMixed", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "set_checkStateMixed" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 16, + "name": "defaultButton", + "notify": "defaultButtonChanged", + "read": "defaultButton", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "set_defaultButton" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 17, + "name": "passwordEdit", + "notify": "passwordEditChanged", + "read": "passwordEdit", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "set_passwordEdit" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 18, + "name": "selectableText", + "notify": "selectableTextChanged", + "read": "selectableText", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "set_selectableText" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 19, + "name": "searchEdit", + "notify": "searchEditChanged", + "read": "searchEdit", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "set_searchEdit" + } + ], + "qualifiedClassName": "QQuickAccessibleAttached", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "bool" + } + ], + "index": 0, + "name": "checkableChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "bool" + } + ], + "index": 1, + "name": "checkedChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "bool" + } + ], + "index": 2, + "name": "editableChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "bool" + } + ], + "index": 3, + "name": "focusableChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "bool" + } + ], + "index": 4, + "name": "focusedChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "bool" + } + ], + "index": 5, + "name": "multiLineChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "bool" + } + ], + "index": 6, + "name": "readOnlyChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "bool" + } + ], + "index": 7, + "name": "selectedChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "bool" + } + ], + "index": 8, + "name": "selectableChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "bool" + } + ], + "index": 9, + "name": "pressedChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "bool" + } + ], + "index": 10, + "name": "checkStateMixedChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "bool" + } + ], + "index": 11, + "name": "defaultButtonChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "bool" + } + ], + "index": 12, + "name": "passwordEditChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "bool" + } + ], + "index": 13, + "name": "selectableTextChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "bool" + } + ], + "index": 14, + "name": "searchEditChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 15, + "name": "roleChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 16, + "name": "nameChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 17, + "name": "descriptionChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 18, + "name": "idChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 19, + "name": "ignoredChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 20, + "name": "pressAction", + "returnType": "void" + }, + { + "access": "public", + "index": 21, + "name": "toggleAction", + "returnType": "void" + }, + { + "access": "public", + "index": 22, + "name": "increaseAction", + "returnType": "void" + }, + { + "access": "public", + "index": 23, + "name": "decreaseAction", + "returnType": "void" + }, + { + "access": "public", + "index": 24, + "name": "scrollUpAction", + "returnType": "void" + }, + { + "access": "public", + "index": 25, + "name": "scrollDownAction", + "returnType": "void" + }, + { + "access": "public", + "index": 26, + "name": "scrollLeftAction", + "returnType": "void" + }, + { + "access": "public", + "index": 27, + "name": "scrollRightAction", + "returnType": "void" + }, + { + "access": "public", + "index": 28, + "name": "previousPageAction", + "returnType": "void" + }, + { + "access": "public", + "index": 29, + "name": "nextPageAction", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "index": 30, + "name": "valueChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 31, + "name": "cursorPositionChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "ignored", + "type": "bool" + } + ], + "index": 32, + "name": "setIgnored", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qquickaccessibleattached_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickAnchors", + "enums": [ + { + "alias": "Anchor", + "isClass": false, + "isFlag": true, + "name": "Anchors", + "type": "uint", + "values": [ + "InvalidAnchor", + "LeftAnchor", + "RightAnchor", + "TopAnchor", + "BottomAnchor", + "HCenterAnchor", + "VCenterAnchor", + "BaselineAnchor", + "Horizontal_Mask", + "Vertical_Mask" + ] + } + ], + "lineNumber": 29, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "left", + "notify": "leftChanged", + "read": "left", + "required": false, + "reset": "resetLeft", + "scriptable": true, + "stored": true, + "type": "QQuickAnchorLine", + "user": false, + "write": "setLeft" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "right", + "notify": "rightChanged", + "read": "right", + "required": false, + "reset": "resetRight", + "scriptable": true, + "stored": true, + "type": "QQuickAnchorLine", + "user": false, + "write": "setRight" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "horizontalCenter", + "notify": "horizontalCenterChanged", + "read": "horizontalCenter", + "required": false, + "reset": "resetHorizontalCenter", + "scriptable": true, + "stored": true, + "type": "QQuickAnchorLine", + "user": false, + "write": "setHorizontalCenter" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "top", + "notify": "topChanged", + "read": "top", + "required": false, + "reset": "resetTop", + "scriptable": true, + "stored": true, + "type": "QQuickAnchorLine", + "user": false, + "write": "setTop" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "bottom", + "notify": "bottomChanged", + "read": "bottom", + "required": false, + "reset": "resetBottom", + "scriptable": true, + "stored": true, + "type": "QQuickAnchorLine", + "user": false, + "write": "setBottom" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "verticalCenter", + "notify": "verticalCenterChanged", + "read": "verticalCenter", + "required": false, + "reset": "resetVerticalCenter", + "scriptable": true, + "stored": true, + "type": "QQuickAnchorLine", + "user": false, + "write": "setVerticalCenter" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 6, + "name": "baseline", + "notify": "baselineChanged", + "read": "baseline", + "required": false, + "reset": "resetBaseline", + "scriptable": true, + "stored": true, + "type": "QQuickAnchorLine", + "user": false, + "write": "setBaseline" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 7, + "name": "margins", + "notify": "marginsChanged", + "read": "margins", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setMargins" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 8, + "name": "leftMargin", + "notify": "leftMarginChanged", + "read": "leftMargin", + "required": false, + "reset": "resetLeftMargin", + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setLeftMargin" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 9, + "name": "rightMargin", + "notify": "rightMarginChanged", + "read": "rightMargin", + "required": false, + "reset": "resetRightMargin", + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setRightMargin" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 10, + "name": "horizontalCenterOffset", + "notify": "horizontalCenterOffsetChanged", + "read": "horizontalCenterOffset", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setHorizontalCenterOffset" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 11, + "name": "topMargin", + "notify": "topMarginChanged", + "read": "topMargin", + "required": false, + "reset": "resetTopMargin", + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setTopMargin" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 12, + "name": "bottomMargin", + "notify": "bottomMarginChanged", + "read": "bottomMargin", + "required": false, + "reset": "resetBottomMargin", + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setBottomMargin" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 13, + "name": "verticalCenterOffset", + "notify": "verticalCenterOffsetChanged", + "read": "verticalCenterOffset", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setVerticalCenterOffset" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 14, + "name": "baselineOffset", + "notify": "baselineOffsetChanged", + "read": "baselineOffset", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setBaselineOffset" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 15, + "name": "fill", + "notify": "fillChanged", + "read": "fill", + "required": false, + "reset": "resetFill", + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false, + "write": "setFill" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 16, + "name": "centerIn", + "notify": "centerInChanged", + "read": "centerIn", + "required": false, + "reset": "resetCenterIn", + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false, + "write": "setCenterIn" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 17, + "name": "alignWhenCentered", + "notify": "centerAlignedChanged", + "read": "alignWhenCentered", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setAlignWhenCentered" + } + ], + "qualifiedClassName": "QQuickAnchors", + "signals": [ + { + "access": "public", + "index": 0, + "name": "leftChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "rightChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "topChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "bottomChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "verticalCenterChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "horizontalCenterChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "baselineChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "fillChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 8, + "name": "centerInChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 9, + "name": "leftMarginChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 10, + "name": "rightMarginChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 11, + "name": "topMarginChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 12, + "name": "bottomMarginChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 13, + "name": "marginsChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 14, + "name": "verticalCenterOffsetChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 15, + "name": "horizontalCenterOffsetChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 16, + "name": "baselineOffsetChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 17, + "name": "centerAlignedChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qquickanchors_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickAnchorLine", + "gadget": true, + "lineNumber": 24, + "qualifiedClassName": "QQuickAnchorLine" + } + ], + "inputFile": "qquickanchors_p_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "AnimatedImage" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickAnimatedImage", + "lineNumber": 29, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "playing", + "notify": "playingChanged", + "read": "isPlaying", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setPlaying" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "paused", + "notify": "pausedChanged", + "read": "isPaused", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setPaused" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "currentFrame", + "notify": "frameChanged", + "read": "currentFrame", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setCurrentFrame" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "frameCount", + "notify": "frameCountChanged", + "read": "frameCount", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "speed", + "notify": "speedChanged", + "read": "speed", + "required": false, + "revision": 523, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setSpeed" + } + ], + "qualifiedClassName": "QQuickAnimatedImage", + "signals": [ + { + "access": "public", + "index": 0, + "name": "playingChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "pausedChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "frameChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "currentFrameChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "frameCountChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "speedChanged", + "returnType": "void", + "revision": 523 + } + ], + "slots": [ + { + "access": "private", + "index": 6, + "name": "movieUpdate", + "returnType": "void" + }, + { + "access": "private", + "index": 7, + "name": "movieRequestFinished", + "returnType": "void" + }, + { + "access": "private", + "index": 8, + "name": "playingStatusChanged", + "returnType": "void" + }, + { + "access": "private", + "index": 9, + "name": "onCacheChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickImage" + } + ] + } + ], + "inputFile": "qquickanimatedimage_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "AnimatedSprite" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickAnimatedSprite", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "LoopParameters", + "values": [ + "Infinite" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "FinishBehavior", + "values": [ + "FinishAtInitialFrame", + "FinishAtFinalFrame" + ] + } + ], + "lineNumber": 34, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "running", + "notify": "runningChanged", + "read": "running", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setRunning" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "interpolate", + "notify": "interpolateChanged", + "read": "interpolate", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setInterpolate" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "source", + "notify": "sourceChanged", + "read": "source", + "required": false, + "scriptable": true, + "stored": true, + "type": "QUrl", + "user": false, + "write": "setSource" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "reverse", + "notify": "reverseChanged", + "read": "reverse", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setReverse" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "frameSync", + "notify": "frameSyncChanged", + "read": "frameSync", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setFrameSync" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "frameCount", + "notify": "frameCountChanged", + "read": "frameCount", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setFrameCount" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "frameHeight", + "notify": "frameHeightChanged", + "read": "frameHeight", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setFrameHeight" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 7, + "name": "frameWidth", + "notify": "frameWidthChanged", + "read": "frameWidth", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setFrameWidth" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 8, + "name": "frameX", + "notify": "frameXChanged", + "read": "frameX", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setFrameX" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 9, + "name": "frameY", + "notify": "frameYChanged", + "read": "frameY", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setFrameY" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 10, + "name": "frameRate", + "notify": "frameRateChanged", + "read": "frameRate", + "required": false, + "reset": "resetFrameRate", + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setFrameRate" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 11, + "name": "frameDuration", + "notify": "frameDurationChanged", + "read": "frameDuration", + "required": false, + "reset": "resetFrameDuration", + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setFrameDuration" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 12, + "name": "loops", + "notify": "loopsChanged", + "read": "loops", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setLoops" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 13, + "name": "paused", + "notify": "pausedChanged", + "read": "paused", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setPaused" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 14, + "name": "currentFrame", + "notify": "currentFrameChanged", + "read": "currentFrame", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setCurrentFrame" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 15, + "name": "finishBehavior", + "notify": "finishBehaviorChanged", + "read": "finishBehavior", + "required": false, + "revision": 527, + "scriptable": true, + "stored": true, + "type": "FinishBehavior", + "user": false, + "write": "setFinishBehavior" + } + ], + "qualifiedClassName": "QQuickAnimatedSprite", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "bool" + } + ], + "index": 0, + "name": "pausedChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "bool" + } + ], + "index": 1, + "name": "runningChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "bool" + } + ], + "index": 2, + "name": "interpolateChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "QUrl" + } + ], + "index": 3, + "name": "sourceChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "bool" + } + ], + "index": 4, + "name": "reverseChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "bool" + } + ], + "index": 5, + "name": "frameSyncChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "int" + } + ], + "index": 6, + "name": "frameCountChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "int" + } + ], + "index": 7, + "name": "frameHeightChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "int" + } + ], + "index": 8, + "name": "frameWidthChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "int" + } + ], + "index": 9, + "name": "frameXChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "int" + } + ], + "index": 10, + "name": "frameYChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 11, + "name": "frameRateChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "int" + } + ], + "index": 12, + "name": "frameDurationChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "int" + } + ], + "index": 13, + "name": "loopsChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "int" + } + ], + "index": 14, + "name": "currentFrameChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "FinishBehavior" + } + ], + "index": 15, + "name": "finishBehaviorChanged", + "returnType": "void", + "revision": 527 + }, + { + "access": "public", + "index": 16, + "name": "finished", + "returnType": "void", + "revision": 524 + } + ], + "slots": [ + { + "access": "public", + "index": 17, + "name": "start", + "returnType": "void" + }, + { + "access": "public", + "index": 18, + "name": "stop", + "returnType": "void" + }, + { + "access": "public", + "index": 19, + "name": "restart", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "frames", + "type": "int" + } + ], + "index": 20, + "name": "advance", + "returnType": "void" + }, + { + "access": "public", + "index": 21, + "isCloned": true, + "name": "advance", + "returnType": "void" + }, + { + "access": "public", + "index": 22, + "name": "pause", + "returnType": "void" + }, + { + "access": "public", + "index": 23, + "name": "resume", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "bool" + } + ], + "index": 24, + "name": "setRunning", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "bool" + } + ], + "index": 25, + "name": "setPaused", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "bool" + } + ], + "index": 26, + "name": "setInterpolate", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "QUrl" + } + ], + "index": 27, + "name": "setSource", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "bool" + } + ], + "index": 28, + "name": "setReverse", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "bool" + } + ], + "index": 29, + "name": "setFrameSync", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "int" + } + ], + "index": 30, + "name": "setFrameCount", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "int" + } + ], + "index": 31, + "name": "setFrameHeight", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "int" + } + ], + "index": 32, + "name": "setFrameWidth", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "int" + } + ], + "index": 33, + "name": "setFrameX", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "int" + } + ], + "index": 34, + "name": "setFrameY", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 35, + "name": "setFrameRate", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "int" + } + ], + "index": 36, + "name": "setFrameDuration", + "returnType": "void" + }, + { + "access": "public", + "index": 37, + "name": "resetFrameRate", + "returnType": "void" + }, + { + "access": "public", + "index": 38, + "name": "resetFrameDuration", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "int" + } + ], + "index": 39, + "name": "setLoops", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "int" + } + ], + "index": 40, + "name": "setCurrentFrame", + "returnType": "void" + }, + { + "access": "private", + "index": 41, + "name": "createEngine", + "returnType": "void" + }, + { + "access": "protected", + "index": 42, + "name": "reset", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickItem" + } + ] + } + ], + "inputFile": "qquickanimatedsprite_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "DefaultMethod", + "value": "start()" + }, + { + "name": "QML.Element", + "value": "Animation" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + }, + { + "name": "QML.Creatable", + "value": "false" + }, + { + "name": "QML.UncreatableReason", + "value": "Animation is an abstract class" + } + ], + "className": "QQuickAbstractAnimation", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "Loops", + "values": [ + "Infinite" + ] + } + ], + "interfaces": [ + [ + { + "className": "QQmlParserStatus", + "id": "\"org.qt-project.Qt.QQmlParserStatus\"" + } + ], + [ + { + "className": "QQmlPropertyValueSource", + "id": "\"org.qt-project.Qt.QQmlPropertyValueSource\"" + } + ] + ], + "lineNumber": 34, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "running", + "notify": "runningChanged", + "read": "isRunning", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setRunning" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "paused", + "notify": "pausedChanged", + "read": "isPaused", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setPaused" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "alwaysRunToEnd", + "notify": "alwaysRunToEndChanged", + "read": "alwaysRunToEnd", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setAlwaysRunToEnd" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "loops", + "notify": "loopCountChanged", + "read": "loops", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setLoops" + } + ], + "qualifiedClassName": "QQuickAbstractAnimation", + "signals": [ + { + "access": "public", + "index": 0, + "name": "started", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "stopped", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "bool" + } + ], + "index": 2, + "name": "runningChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "bool" + } + ], + "index": 3, + "name": "pausedChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "bool" + } + ], + "index": 4, + "name": "alwaysRunToEndChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "int" + } + ], + "index": 5, + "name": "loopCountChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "finished", + "returnType": "void", + "revision": 524 + } + ], + "slots": [ + { + "access": "public", + "index": 7, + "name": "restart", + "returnType": "void" + }, + { + "access": "public", + "index": 8, + "name": "start", + "returnType": "void" + }, + { + "access": "public", + "index": 9, + "name": "pause", + "returnType": "void" + }, + { + "access": "public", + "index": 10, + "name": "resume", + "returnType": "void" + }, + { + "access": "public", + "index": 11, + "name": "stop", + "returnType": "void" + }, + { + "access": "public", + "index": 12, + "name": "complete", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QQmlPropertyValueSource" + }, + { + "access": "public", + "name": "QQmlParserStatus" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "PauseAnimation" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickPauseAnimation", + "lineNumber": 128, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "duration", + "notify": "durationChanged", + "read": "duration", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setDuration" + } + ], + "qualifiedClassName": "QQuickPauseAnimation", + "signals": [ + { + "access": "public", + "arguments": [ + { + "type": "int" + } + ], + "index": 0, + "name": "durationChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickAbstractAnimation" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "ScriptAction" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickScriptAction", + "lineNumber": 155, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "script", + "read": "script", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlScriptString", + "user": false, + "write": "setScript" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "scriptName", + "read": "stateChangeScriptName", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setStateChangeScriptName" + } + ], + "qualifiedClassName": "QQuickScriptAction", + "superClasses": [ + { + "access": "public", + "name": "QQuickAbstractAnimation" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "PropertyAction" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickPropertyAction", + "lineNumber": 183, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "target", + "notify": "targetChanged", + "read": "target", + "required": false, + "scriptable": true, + "stored": true, + "type": "QObject*", + "user": false, + "write": "setTargetObject" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "property", + "notify": "propertyChanged", + "read": "property", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setProperty" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "properties", + "notify": "propertiesChanged", + "read": "properties", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setProperties" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "targets", + "read": "targets", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlListProperty", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "exclude", + "read": "exclude", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlListProperty", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "value", + "notify": "valueChanged", + "read": "value", + "required": false, + "scriptable": true, + "stored": true, + "type": "QVariant", + "user": false, + "write": "setValue" + } + ], + "qualifiedClassName": "QQuickPropertyAction", + "signals": [ + { + "access": "public", + "arguments": [ + { + "type": "QVariant" + } + ], + "index": 0, + "name": "valueChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QString" + } + ], + "index": 1, + "name": "propertiesChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "targetChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "propertyChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickAbstractAnimation" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "PropertyAnimation" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickPropertyAnimation", + "lineNumber": 230, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "duration", + "notify": "durationChanged", + "read": "duration", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setDuration" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "from", + "notify": "fromChanged", + "read": "from", + "required": false, + "scriptable": true, + "stored": true, + "type": "QVariant", + "user": false, + "write": "setFrom" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "to", + "notify": "toChanged", + "read": "to", + "required": false, + "scriptable": true, + "stored": true, + "type": "QVariant", + "user": false, + "write": "setTo" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "easing", + "notify": "easingChanged", + "read": "easing", + "required": false, + "scriptable": true, + "stored": true, + "type": "QEasingCurve", + "user": false, + "write": "setEasing" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "target", + "notify": "targetChanged", + "read": "target", + "required": false, + "scriptable": true, + "stored": true, + "type": "QObject*", + "user": false, + "write": "setTargetObject" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "property", + "notify": "propertyChanged", + "read": "property", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setProperty" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "properties", + "notify": "propertiesChanged", + "read": "properties", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setProperties" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 7, + "name": "targets", + "read": "targets", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlListProperty", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 8, + "name": "exclude", + "read": "exclude", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlListProperty", + "user": false + } + ], + "qualifiedClassName": "QQuickPropertyAnimation", + "signals": [ + { + "access": "public", + "arguments": [ + { + "type": "int" + } + ], + "index": 0, + "name": "durationChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "fromChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "toChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QEasingCurve" + } + ], + "index": 3, + "name": "easingChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QString" + } + ], + "index": 4, + "name": "propertiesChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "targetChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "propertyChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickAbstractAnimation" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "ColorAnimation" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickColorAnimation", + "lineNumber": 295, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "from", + "read": "from", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false, + "write": "setFrom" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "to", + "read": "to", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false, + "write": "setTo" + } + ], + "qualifiedClassName": "QQuickColorAnimation", + "superClasses": [ + { + "access": "public", + "name": "QQuickPropertyAnimation" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "NumberAnimation" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickNumberAnimation", + "lineNumber": 315, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "from", + "notify": "fromChanged", + "read": "from", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setFrom" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "to", + "notify": "toChanged", + "read": "to", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setTo" + } + ], + "qualifiedClassName": "QQuickNumberAnimation", + "superClasses": [ + { + "access": "public", + "name": "QQuickPropertyAnimation" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "Vector3dAnimation" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickVector3dAnimation", + "lineNumber": 342, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "from", + "notify": "fromChanged", + "read": "from", + "required": false, + "scriptable": true, + "stored": true, + "type": "QVector3D", + "user": false, + "write": "setFrom" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "to", + "notify": "toChanged", + "read": "to", + "required": false, + "scriptable": true, + "stored": true, + "type": "QVector3D", + "user": false, + "write": "setTo" + } + ], + "qualifiedClassName": "QQuickVector3dAnimation", + "superClasses": [ + { + "access": "public", + "name": "QQuickPropertyAnimation" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "RotationAnimation" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickRotationAnimation", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "RotationDirection", + "values": [ + "Numerical", + "Shortest", + "Clockwise", + "Counterclockwise" + ] + } + ], + "lineNumber": 364, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "from", + "notify": "fromChanged", + "read": "from", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setFrom" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "to", + "notify": "toChanged", + "read": "to", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setTo" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "direction", + "notify": "directionChanged", + "read": "direction", + "required": false, + "scriptable": true, + "stored": true, + "type": "RotationDirection", + "user": false, + "write": "setDirection" + } + ], + "qualifiedClassName": "QQuickRotationAnimation", + "signals": [ + { + "access": "public", + "index": 0, + "name": "directionChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickPropertyAnimation" + } + ] + }, + { + "classInfos": [ + { + "name": "DefaultProperty", + "value": "animations" + } + ], + "className": "QQuickAnimationGroup", + "lineNumber": 395, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "animations", + "read": "animations", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlListProperty", + "user": false + } + ], + "qualifiedClassName": "QQuickAnimationGroup", + "superClasses": [ + { + "access": "public", + "name": "QQuickAbstractAnimation" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "SequentialAnimation" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickSequentialAnimation", + "lineNumber": 414, + "object": true, + "qualifiedClassName": "QQuickSequentialAnimation", + "superClasses": [ + { + "access": "public", + "name": "QQuickAnimationGroup" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "ParallelAnimation" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickParallelAnimation", + "lineNumber": 433, + "object": true, + "qualifiedClassName": "QQuickParallelAnimation", + "superClasses": [ + { + "access": "public", + "name": "QQuickAnimationGroup" + } + ] + } + ], + "inputFile": "qquickanimation_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "DefaultProperty", + "value": "animation" + }, + { + "name": "QML.Element", + "value": "AnimationController" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickAnimationController", + "interfaces": [ + [ + { + "className": "QQmlFinalizerHook", + "id": "\"org.qt-project.Qt.QQmlFinalizerHook\"" + } + ] + ], + "lineNumber": 25, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "progress", + "notify": "progressChanged", + "read": "progress", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setProgress" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "animation", + "notify": "animationChanged", + "read": "animation", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickAbstractAnimation*", + "user": false, + "write": "setAnimation" + } + ], + "qualifiedClassName": "QQuickAnimationController", + "signals": [ + { + "access": "public", + "index": 0, + "name": "progressChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "animationChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "index": 2, + "name": "reload", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "completeToBeginning", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "completeToEnd", + "returnType": "void" + }, + { + "access": "private", + "index": 5, + "name": "updateProgress", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QQmlFinalizerHook" + } + ] + } + ], + "inputFile": "qquickanimationcontroller_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "Animator" + }, + { + "name": "QML.AddedInVersion", + "value": "514" + }, + { + "name": "QML.Creatable", + "value": "false" + }, + { + "name": "QML.UncreatableReason", + "value": "Animator is an abstract class" + } + ], + "className": "QQuickAnimator", + "lineNumber": 26, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "target", + "notify": "targetItemChanged", + "read": "targetItem", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false, + "write": "setTargetItem" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "easing", + "notify": "easingChanged", + "read": "easing", + "required": false, + "scriptable": true, + "stored": true, + "type": "QEasingCurve", + "user": false, + "write": "setEasing" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "duration", + "notify": "durationChanged", + "read": "duration", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setDuration" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "to", + "notify": "toChanged", + "read": "to", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setTo" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "from", + "notify": "fromChanged", + "read": "from", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setFrom" + } + ], + "qualifiedClassName": "QQuickAnimator", + "signals": [ + { + "access": "public", + "arguments": [ + { + "type": "QQuickItem*" + } + ], + "index": 0, + "name": "targetItemChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "duration", + "type": "int" + } + ], + "index": 1, + "name": "durationChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "curve", + "type": "QEasingCurve" + } + ], + "index": 2, + "name": "easingChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "to", + "type": "qreal" + } + ], + "index": 3, + "name": "toChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "from", + "type": "qreal" + } + ], + "index": 4, + "name": "fromChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickAbstractAnimation" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "ScaleAnimator" + }, + { + "name": "QML.AddedInVersion", + "value": "514" + } + ], + "className": "QQuickScaleAnimator", + "lineNumber": 76, + "object": true, + "qualifiedClassName": "QQuickScaleAnimator", + "superClasses": [ + { + "access": "public", + "name": "QQuickAnimator" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "XAnimator" + }, + { + "name": "QML.AddedInVersion", + "value": "514" + } + ], + "className": "QQuickXAnimator", + "lineNumber": 88, + "object": true, + "qualifiedClassName": "QQuickXAnimator", + "superClasses": [ + { + "access": "public", + "name": "QQuickAnimator" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "YAnimator" + }, + { + "name": "QML.AddedInVersion", + "value": "514" + } + ], + "className": "QQuickYAnimator", + "lineNumber": 100, + "object": true, + "qualifiedClassName": "QQuickYAnimator", + "superClasses": [ + { + "access": "public", + "name": "QQuickAnimator" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "OpacityAnimator" + }, + { + "name": "QML.AddedInVersion", + "value": "514" + } + ], + "className": "QQuickOpacityAnimator", + "lineNumber": 112, + "object": true, + "qualifiedClassName": "QQuickOpacityAnimator", + "superClasses": [ + { + "access": "public", + "name": "QQuickAnimator" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "RotationAnimator" + }, + { + "name": "QML.AddedInVersion", + "value": "514" + } + ], + "className": "QQuickRotationAnimator", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "RotationDirection", + "values": [ + "Numerical", + "Shortest", + "Clockwise", + "Counterclockwise" + ] + } + ], + "lineNumber": 125, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "direction", + "notify": "directionChanged", + "read": "direction", + "required": false, + "scriptable": true, + "stored": true, + "type": "RotationDirection", + "user": false, + "write": "setDirection" + } + ], + "qualifiedClassName": "QQuickRotationAnimator", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "dir", + "type": "RotationDirection" + } + ], + "index": 0, + "name": "directionChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickAnimator" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "UniformAnimator" + }, + { + "name": "QML.AddedInVersion", + "value": "514" + } + ], + "className": "QQuickUniformAnimator", + "lineNumber": 152, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "uniform", + "notify": "uniformChanged", + "read": "uniform", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setUniform" + } + ], + "qualifiedClassName": "QQuickUniformAnimator", + "signals": [ + { + "access": "public", + "arguments": [ + { + "type": "QString" + } + ], + "index": 0, + "name": "uniformChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickAnimator" + } + ] + } + ], + "inputFile": "qquickanimator_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQuickAnimatorController", + "lineNumber": 28, + "object": true, + "qualifiedClassName": "QQuickAnimatorController", + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QAnimationJobChangeListener" + } + ] + } + ], + "inputFile": "qquickanimatorcontroller_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQuickAnimatorProxyJob", + "lineNumber": 39, + "object": true, + "qualifiedClassName": "QQuickAnimatorProxyJob", + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "window", + "type": "QQuickWindow*" + } + ], + "index": 0, + "name": "windowChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "sceneGraphInitialized", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QAbstractAnimationJob" + } + ] + } + ], + "inputFile": "qquickanimatorjob_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "Application" + }, + { + "name": "QML.Singleton", + "value": "true" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickApplication", + "lineNumber": 31, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "active", + "notify": "activeChanged", + "read": "active", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "layoutDirection", + "notify": "layoutDirectionChanged", + "read": "layoutDirection", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::LayoutDirection", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 2, + "name": "supportsMultipleWindows", + "read": "supportsMultipleWindows", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "state", + "notify": "stateChanged", + "read": "state", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::ApplicationState", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 4, + "name": "font", + "read": "font", + "required": false, + "scriptable": true, + "stored": true, + "type": "QFont", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "displayName", + "notify": "displayNameChanged", + "read": "displayName", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setDisplayName" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 6, + "name": "screens", + "notify": "screensChanged", + "read": "screens", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlListProperty", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 7, + "name": "styleHints", + "read": "styleHints", + "required": false, + "scriptable": true, + "stored": true, + "type": "QStyleHints*", + "user": false + } + ], + "qualifiedClassName": "QQuickApplication", + "signals": [ + { + "access": "public", + "index": 0, + "name": "activeChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "displayNameChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "layoutDirectionChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "state", + "type": "Qt::ApplicationState" + } + ], + "index": 3, + "name": "stateChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "screensChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "private", + "index": 5, + "name": "updateScreens", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQmlApplication" + } + ] + } + ], + "inputFile": "qquickapplication_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "DefaultProperty", + "value": "animation" + }, + { + "name": "DeferredPropertyNames", + "value": "animation" + }, + { + "name": "QML.Element", + "value": "Behavior" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickBehavior", + "interfaces": [ + [ + { + "className": "QQmlFinalizerHook", + "id": "\"org.qt-project.Qt.QQmlFinalizerHook\"" + } + ], + [ + { + "className": "QQmlPropertyValueInterceptor", + "id": "\"org.qt-project.Qt.QQmlPropertyValueInterceptor\"" + } + ] + ], + "lineNumber": 29, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "animation", + "read": "animation", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickAbstractAnimation*", + "user": false, + "write": "setAnimation" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "enabled", + "notify": "enabledChanged", + "read": "enabled", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setEnabled" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "targetValue", + "notify": "targetValueChanged", + "read": "targetValue", + "required": false, + "revision": 525, + "scriptable": true, + "stored": true, + "type": "QVariant", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "targetProperty", + "notify": "targetPropertyChanged", + "read": "targetProperty", + "required": false, + "revision": 527, + "scriptable": true, + "stored": true, + "type": "QQmlProperty", + "user": false + } + ], + "qualifiedClassName": "QQuickBehavior", + "signals": [ + { + "access": "public", + "index": 0, + "name": "enabledChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "targetValueChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "targetPropertyChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QQmlPropertyValueInterceptor" + }, + { + "access": "public", + "name": "QQmlFinalizerHook" + } + ] + } + ], + "inputFile": "qquickbehavior_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "BorderImage" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickBorderImage", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "TileMode", + "values": [ + "Stretch", + "Repeat", + "Round" + ] + } + ], + "lineNumber": 25, + "object": true, + "properties": [ + { + "constant": true, + "designable": true, + "final": false, + "index": 0, + "name": "border", + "read": "border", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickScaleGrid*", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "horizontalTileMode", + "notify": "horizontalTileModeChanged", + "read": "horizontalTileMode", + "required": false, + "scriptable": true, + "stored": true, + "type": "TileMode", + "user": false, + "write": "setHorizontalTileMode" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "verticalTileMode", + "notify": "verticalTileModeChanged", + "read": "verticalTileMode", + "required": false, + "scriptable": true, + "stored": true, + "type": "TileMode", + "user": false, + "write": "setVerticalTileMode" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "sourceSize", + "notify": "sourceSizeChanged", + "read": "sourceSize", + "required": false, + "scriptable": true, + "stored": true, + "type": "QSize", + "user": false + } + ], + "qualifiedClassName": "QQuickBorderImage", + "signals": [ + { + "access": "public", + "index": 0, + "name": "horizontalTileModeChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "verticalTileModeChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "sourceSizeChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "private", + "index": 3, + "name": "doUpdate", + "returnType": "void" + }, + { + "access": "private", + "index": 4, + "name": "requestFinished", + "returnType": "void" + }, + { + "access": "private", + "index": 5, + "name": "sciRequestFinished", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickImageBase" + } + ] + } + ], + "inputFile": "qquickborderimage_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQuickCanvasContext", + "lineNumber": 34, + "object": true, + "qualifiedClassName": "QQuickCanvasContext", + "signals": [ + { + "access": "public", + "index": 0, + "name": "textureChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qquickcanvascontext_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "Canvas" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickCanvasItem", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "RenderTarget", + "values": [ + "Image", + "FramebufferObject" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "RenderStrategy", + "values": [ + "Immediate", + "Threaded", + "Cooperative" + ] + } + ], + "lineNumber": 54, + "methods": [ + { + "access": "public", + "arguments": [ + { + "name": "args", + "type": "QQmlV4FunctionPtr" + } + ], + "index": 21, + "name": "getContext", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "args", + "type": "QQmlV4FunctionPtr" + } + ], + "index": 22, + "name": "requestAnimationFrame", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "args", + "type": "QQmlV4FunctionPtr" + } + ], + "index": 23, + "name": "cancelRequestAnimationFrame", + "returnType": "void" + }, + { + "access": "public", + "index": 24, + "name": "requestPaint", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "dirtyRect", + "type": "QRectF" + } + ], + "index": 25, + "name": "markDirty", + "returnType": "void" + }, + { + "access": "public", + "index": 26, + "isCloned": true, + "name": "markDirty", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "filename", + "type": "QString" + }, + { + "name": "imageSize", + "type": "QSizeF" + } + ], + "index": 27, + "name": "save", + "returnType": "bool" + }, + { + "access": "public", + "arguments": [ + { + "name": "filename", + "type": "QString" + } + ], + "index": 28, + "isCloned": true, + "name": "save", + "returnType": "bool" + }, + { + "access": "public", + "arguments": [ + { + "name": "type", + "type": "QString" + } + ], + "index": 29, + "name": "toDataURL", + "returnType": "QString" + }, + { + "access": "public", + "index": 30, + "isCloned": true, + "name": "toDataURL", + "returnType": "QString" + }, + { + "access": "private", + "index": 31, + "name": "delayedCreate", + "returnType": "void" + } + ], + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "available", + "notify": "availableChanged", + "read": "isAvailable", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "contextType", + "notify": "contextTypeChanged", + "read": "contextType", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setContextType" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "context", + "notify": "contextChanged", + "read": "context", + "required": false, + "scriptable": true, + "stored": true, + "type": "QJSValue", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "canvasSize", + "notify": "canvasSizeChanged", + "read": "canvasSize", + "required": false, + "scriptable": true, + "stored": true, + "type": "QSizeF", + "user": false, + "write": "setCanvasSize" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "tileSize", + "notify": "tileSizeChanged", + "read": "tileSize", + "required": false, + "scriptable": true, + "stored": true, + "type": "QSize", + "user": false, + "write": "setTileSize" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "canvasWindow", + "notify": "canvasWindowChanged", + "read": "canvasWindow", + "required": false, + "scriptable": true, + "stored": true, + "type": "QRectF", + "user": false, + "write": "setCanvasWindow" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "renderTarget", + "notify": "renderTargetChanged", + "read": "renderTarget", + "required": false, + "scriptable": true, + "stored": true, + "type": "RenderTarget", + "user": false, + "write": "setRenderTarget" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 7, + "name": "renderStrategy", + "notify": "renderStrategyChanged", + "read": "renderStrategy", + "required": false, + "scriptable": true, + "stored": true, + "type": "RenderStrategy", + "user": false, + "write": "setRenderStrategy" + } + ], + "qualifiedClassName": "QQuickCanvasItem", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "region", + "type": "QRect" + } + ], + "index": 0, + "name": "paint", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "painted", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "availableChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "contextTypeChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "contextChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "canvasSizeChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "tileSizeChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "canvasWindowChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 8, + "name": "renderTargetChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 9, + "name": "renderStrategyChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 10, + "name": "imageLoaded", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "url", + "type": "QUrl" + }, + { + "name": "sourceSize", + "type": "QSizeF" + } + ], + "index": 11, + "name": "loadImage", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "url", + "type": "QUrl" + } + ], + "index": 12, + "isCloned": true, + "name": "loadImage", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "url", + "type": "QUrl" + } + ], + "index": 13, + "name": "unloadImage", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "url", + "type": "QUrl" + } + ], + "index": 14, + "name": "isImageLoaded", + "returnType": "bool" + }, + { + "access": "public", + "arguments": [ + { + "name": "url", + "type": "QUrl" + } + ], + "index": 15, + "name": "isImageLoading", + "returnType": "bool" + }, + { + "access": "public", + "arguments": [ + { + "name": "url", + "type": "QUrl" + } + ], + "index": 16, + "name": "isImageError", + "returnType": "bool" + }, + { + "access": "private", + "index": 17, + "name": "sceneGraphInitialized", + "returnType": "void" + }, + { + "access": "private", + "index": 18, + "name": "checkAnimationCallbacks", + "returnType": "void" + }, + { + "access": "private", + "index": 19, + "name": "invalidateSceneGraph", + "returnType": "void" + }, + { + "access": "private", + "index": 20, + "name": "schedulePolish", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickItem" + } + ] + }, + { + "className": "QQuickContext2DRenderThread", + "lineNumber": 170, + "object": true, + "qualifiedClassName": "QQuickContext2DRenderThread", + "superClasses": [ + { + "access": "public", + "name": "QThread" + } + ] + } + ], + "inputFile": "qquickcanvasitem_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "ColorGroup" + }, + { + "name": "QML.AddedInVersion", + "value": "1536" + } + ], + "className": "QQuickColorGroup", + "lineNumber": 32, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "alternateBase", + "notify": "alternateBaseChanged", + "read": "alternateBase", + "required": false, + "reset": "resetAlternateBase", + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false, + "write": "setAlternateBase" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "base", + "notify": "baseChanged", + "read": "base", + "required": false, + "reset": "resetBase", + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false, + "write": "setBase" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "brightText", + "notify": "brightTextChanged", + "read": "brightText", + "required": false, + "reset": "resetBrightText", + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false, + "write": "setBrightText" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "button", + "notify": "buttonChanged", + "read": "button", + "required": false, + "reset": "resetButton", + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false, + "write": "setButton" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "buttonText", + "notify": "buttonTextChanged", + "read": "buttonText", + "required": false, + "reset": "resetButtonText", + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false, + "write": "setButtonText" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "dark", + "notify": "darkChanged", + "read": "dark", + "required": false, + "reset": "resetDark", + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false, + "write": "setDark" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 6, + "name": "highlight", + "notify": "highlightChanged", + "read": "highlight", + "required": false, + "reset": "resetHighlight", + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false, + "write": "setHighlight" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 7, + "name": "highlightedText", + "notify": "highlightedTextChanged", + "read": "highlightedText", + "required": false, + "reset": "resetHighlightedText", + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false, + "write": "setHighlightedText" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 8, + "name": "light", + "notify": "lightChanged", + "read": "light", + "required": false, + "reset": "resetLight", + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false, + "write": "setLight" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 9, + "name": "link", + "notify": "linkChanged", + "read": "link", + "required": false, + "reset": "resetLink", + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false, + "write": "setLink" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 10, + "name": "linkVisited", + "notify": "linkVisitedChanged", + "read": "linkVisited", + "required": false, + "reset": "resetLinkVisited", + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false, + "write": "setLinkVisited" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 11, + "name": "mid", + "notify": "midChanged", + "read": "mid", + "required": false, + "reset": "resetMid", + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false, + "write": "setMid" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 12, + "name": "midlight", + "notify": "midlightChanged", + "read": "midlight", + "required": false, + "reset": "resetMidlight", + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false, + "write": "setMidlight" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 13, + "name": "shadow", + "notify": "shadowChanged", + "read": "shadow", + "required": false, + "reset": "resetShadow", + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false, + "write": "setShadow" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 14, + "name": "text", + "notify": "textChanged", + "read": "text", + "required": false, + "reset": "resetText", + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false, + "write": "setText" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 15, + "name": "toolTipBase", + "notify": "toolTipBaseChanged", + "read": "toolTipBase", + "required": false, + "reset": "resetToolTipBase", + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false, + "write": "setToolTipBase" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 16, + "name": "toolTipText", + "notify": "toolTipTextChanged", + "read": "toolTipText", + "required": false, + "reset": "resetToolTipText", + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false, + "write": "setToolTipText" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 17, + "name": "window", + "notify": "windowChanged", + "read": "window", + "required": false, + "reset": "resetWindow", + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false, + "write": "setWindow" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 18, + "name": "windowText", + "notify": "windowTextChanged", + "read": "windowText", + "required": false, + "reset": "resetWindowText", + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false, + "write": "setWindowText" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 19, + "name": "placeholderText", + "notify": "placeholderTextChanged", + "read": "placeholderText", + "required": false, + "reset": "resetPlaceholderText", + "revision": 1538, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false, + "write": "setPlaceholderText" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 20, + "name": "accent", + "notify": "accentChanged", + "read": "accent", + "required": false, + "reset": "resetAccent", + "revision": 1542, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false, + "write": "setAccent" + } + ], + "qualifiedClassName": "QQuickColorGroup", + "signals": [ + { + "access": "public", + "index": 0, + "name": "alternateBaseChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "baseChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "brightTextChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "buttonChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "buttonTextChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "darkChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "highlightChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "highlightedTextChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 8, + "name": "lightChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 9, + "name": "linkChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 10, + "name": "linkVisitedChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 11, + "name": "midChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 12, + "name": "midlightChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 13, + "name": "shadowChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 14, + "name": "textChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 15, + "name": "toolTipBaseChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 16, + "name": "toolTipTextChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 17, + "name": "windowChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 18, + "name": "windowTextChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 19, + "name": "placeholderTextChanged", + "returnType": "void", + "revision": 1538 + }, + { + "access": "public", + "index": 20, + "name": "accentChanged", + "returnType": "void", + "revision": 1542 + }, + { + "access": "public", + "index": 21, + "name": "changed", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qquickcolorgroup_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQuickContext2D", + "lineNumber": 54, + "object": true, + "qualifiedClassName": "QQuickContext2D", + "superClasses": [ + { + "access": "public", + "name": "QQuickCanvasContext" + } + ] + } + ], + "inputFile": "qquickcontext2d_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQuickContext2DTexture", + "lineNumber": 34, + "object": true, + "qualifiedClassName": "QQuickContext2DTexture", + "signals": [ + { + "access": "public", + "index": 0, + "name": "textureChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "canvasSize", + "type": "QSize" + }, + { + "name": "tileSize", + "type": "QSize" + }, + { + "name": "canvasWindow", + "type": "QRect" + }, + { + "name": "dirtyRect", + "type": "QRect" + }, + { + "name": "smooth", + "type": "bool" + }, + { + "name": "antialiasing", + "type": "bool" + } + ], + "index": 1, + "name": "canvasChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "ccb", + "type": "QQuickContext2DCommandBuffer*" + } + ], + "index": 2, + "name": "paint", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "markDirtyTexture", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "item", + "type": "QQuickCanvasItem*" + } + ], + "index": 4, + "name": "setItem", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "region", + "type": "QRectF" + } + ], + "index": 5, + "name": "grabImage", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "isCloned": true, + "name": "grabImage", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "className": "QQuickContext2DImageTexture", + "lineNumber": 137, + "object": true, + "qualifiedClassName": "QQuickContext2DImageTexture", + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "region", + "type": "QRectF" + } + ], + "index": 0, + "name": "grabImage", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "isCloned": true, + "name": "grabImage", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickContext2DTexture" + } + ] + } + ], + "inputFile": "qquickcontext2dtexture_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQuickDeliveryAgent", + "lineNumber": 31, + "object": true, + "qualifiedClassName": "QQuickDeliveryAgent", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qquickdeliveryagent_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQuickDesignerCustomParserObject", + "lineNumber": 23, + "object": true, + "qualifiedClassName": "QQuickDesignerCustomParserObject", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qquickdesignercustomparserobject_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQuickDragMimeData", + "lineNumber": 101, + "object": true, + "qualifiedClassName": "QQuickDragMimeData", + "superClasses": [ + { + "access": "public", + "name": "QMimeData" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "Drag" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + }, + { + "name": "QML.Creatable", + "value": "false" + }, + { + "name": "QML.UncreatableReason", + "value": "Drag is only available via attached properties." + }, + { + "name": "QML.Attached", + "value": "QQuickDragAttached" + } + ], + "className": "QQuickDrag", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "DragType", + "values": [ + "None", + "Automatic", + "Internal" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "Axis", + "values": [ + "XAxis", + "YAxis", + "XAndYAxis", + "XandYAxis" + ] + } + ], + "lineNumber": 123, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "target", + "notify": "targetChanged", + "read": "target", + "required": false, + "reset": "resetTarget", + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false, + "write": "setTarget" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "axis", + "notify": "axisChanged", + "read": "axis", + "required": false, + "scriptable": true, + "stored": true, + "type": "Axis", + "user": false, + "write": "setAxis" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "minimumX", + "notify": "minimumXChanged", + "read": "xmin", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setXmin" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "maximumX", + "notify": "maximumXChanged", + "read": "xmax", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setXmax" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "minimumY", + "notify": "minimumYChanged", + "read": "ymin", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setYmin" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "maximumY", + "notify": "maximumYChanged", + "read": "ymax", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setYmax" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 6, + "name": "active", + "notify": "activeChanged", + "read": "active", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 7, + "name": "filterChildren", + "notify": "filterChildrenChanged", + "read": "filterChildren", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setFilterChildren" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 8, + "name": "smoothed", + "notify": "smoothedChanged", + "read": "smoothed", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setSmoothed" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 9, + "name": "threshold", + "notify": "thresholdChanged", + "read": "threshold", + "required": false, + "reset": "resetThreshold", + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setThreshold" + } + ], + "qualifiedClassName": "QQuickDrag", + "signals": [ + { + "access": "public", + "index": 0, + "name": "targetChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "axisChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "minimumXChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "maximumXChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "minimumYChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "maximumYChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "activeChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "filterChildrenChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 8, + "name": "smoothedChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 9, + "name": "thresholdChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickDragAttached", + "lineNumber": 213, + "methods": [ + { + "access": "public", + "index": 16, + "name": "drop", + "returnType": "int" + } + ], + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "active", + "notify": "activeChanged", + "read": "isActive", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setActive" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "source", + "notify": "sourceChanged", + "read": "source", + "required": false, + "reset": "resetSource", + "scriptable": true, + "stored": true, + "type": "QObject*", + "user": false, + "write": "setSource" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "target", + "notify": "targetChanged", + "read": "target", + "required": false, + "scriptable": true, + "stored": true, + "type": "QObject*", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "hotSpot", + "notify": "hotSpotChanged", + "read": "hotSpot", + "required": false, + "scriptable": true, + "stored": true, + "type": "QPointF", + "user": false, + "write": "setHotSpot" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "imageSource", + "notify": "imageSourceChanged", + "read": "imageSource", + "required": false, + "scriptable": true, + "stored": true, + "type": "QUrl", + "user": false, + "write": "setImageSource" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "imageSourceSize", + "notify": "imageSourceSizeChanged", + "read": "imageSourceSize", + "required": false, + "scriptable": true, + "stored": true, + "type": "QSize", + "user": false, + "write": "setImageSourceSize" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 6, + "name": "keys", + "notify": "keysChanged", + "read": "keys", + "required": false, + "scriptable": true, + "stored": true, + "type": "QStringList", + "user": false, + "write": "setKeys" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 7, + "name": "mimeData", + "notify": "mimeDataChanged", + "read": "mimeData", + "required": false, + "scriptable": true, + "stored": true, + "type": "QVariantMap", + "user": false, + "write": "setMimeData" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 8, + "name": "supportedActions", + "notify": "supportedActionsChanged", + "read": "supportedActions", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::DropActions", + "user": false, + "write": "setSupportedActions" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 9, + "name": "proposedAction", + "notify": "proposedActionChanged", + "read": "proposedAction", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::DropAction", + "user": false, + "write": "setProposedAction" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 10, + "name": "dragType", + "notify": "dragTypeChanged", + "read": "dragType", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickDrag::DragType", + "user": false, + "write": "setDragType" + } + ], + "qualifiedClassName": "QQuickDragAttached", + "signals": [ + { + "access": "public", + "index": 0, + "name": "dragStarted", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "dropAction", + "type": "Qt::DropAction" + } + ], + "index": 1, + "name": "dragFinished", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "activeChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "sourceChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "targetChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "hotSpotChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "imageSourceChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "imageSourceSizeChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 8, + "name": "keysChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 9, + "name": "mimeDataChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 10, + "name": "supportedActionsChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 11, + "name": "proposedActionChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 12, + "name": "dragTypeChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "type": "QQmlV4FunctionPtr" + } + ], + "index": 13, + "name": "start", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QQmlV4FunctionPtr" + } + ], + "index": 14, + "name": "startDrag", + "returnType": "void" + }, + { + "access": "public", + "index": 15, + "name": "cancel", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qquickdrag_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "DragAxis" + }, + { + "name": "QML.AddedInVersion", + "value": "524" + }, + { + "name": "QML.Creatable", + "value": "false" + }, + { + "name": "QML.UncreatableReason", + "value": "DragAxis is only available as a grouped property of DragHandler or PinchHandler." + } + ], + "className": "QQuickDragAxis", + "lineNumber": 27, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "minimum", + "notify": "minimumChanged", + "read": "minimum", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setMinimum" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "maximum", + "notify": "maximumChanged", + "read": "maximum", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setMaximum" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "enabled", + "notify": "enabledChanged", + "read": "enabled", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setEnabled" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "activeValue", + "notify": "activeValueChanged", + "read": "activeValue", + "required": false, + "revision": 1541, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + } + ], + "qualifiedClassName": "QQuickDragAxis", + "signals": [ + { + "access": "public", + "index": 0, + "name": "minimumChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "maximumChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "enabledChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "delta", + "type": "qreal" + } + ], + "index": 3, + "name": "activeValueChanged", + "returnType": "void", + "revision": 1541 + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qquickdragaxis_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "DragHandler" + }, + { + "name": "QML.AddedInVersion", + "value": "524" + } + ], + "className": "QQuickDragHandler", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "SnapMode", + "values": [ + "NoSnap", + "SnapAuto", + "SnapIfPressedOutsideTarget", + "SnapAlways" + ] + } + ], + "lineNumber": 25, + "object": true, + "properties": [ + { + "constant": true, + "designable": true, + "final": false, + "index": 0, + "name": "xAxis", + "read": "xAxis", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickDragAxis*", + "user": false + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 1, + "name": "yAxis", + "read": "yAxis", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickDragAxis*", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "translation", + "notify": "translationChanged", + "read": "translation", + "required": false, + "scriptable": true, + "stored": true, + "type": "QVector2D", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "activeTranslation", + "notify": "translationChanged", + "read": "activeTranslation", + "required": false, + "revision": 1538, + "scriptable": true, + "stored": true, + "type": "QVector2D", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "persistentTranslation", + "notify": "translationChanged", + "read": "persistentTranslation", + "required": false, + "revision": 1538, + "scriptable": true, + "stored": true, + "type": "QVector2D", + "user": false, + "write": "setPersistentTranslation" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "snapMode", + "notify": "snapModeChanged", + "read": "snapMode", + "required": false, + "revision": 526, + "scriptable": true, + "stored": true, + "type": "SnapMode", + "user": false, + "write": "setSnapMode" + } + ], + "qualifiedClassName": "QQuickDragHandler", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "delta", + "type": "QVector2D" + } + ], + "index": 0, + "name": "translationChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "snapModeChanged", + "returnType": "void", + "revision": 526 + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickMultiPointHandler" + } + ] + } + ], + "inputFile": "qquickdraghandler_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "DragEvent" + }, + { + "name": "QML.Creatable", + "value": "false" + }, + { + "name": "QML.UncreatableReason", + "value": "DragEvent is only meant to be created by DropArea" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickDragEvent", + "lineNumber": 29, + "methods": [ + { + "access": "public", + "arguments": [ + { + "name": "format", + "type": "QString" + } + ], + "index": 0, + "name": "getDataAsString", + "returnType": "QString" + }, + { + "access": "public", + "arguments": [ + { + "name": "format", + "type": "QString" + } + ], + "index": 1, + "name": "getDataAsArrayBuffer", + "returnType": "QByteArray" + }, + { + "access": "public", + "index": 2, + "name": "acceptProposedAction", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "accept", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "action", + "type": "Qt::DropAction" + } + ], + "index": 4, + "name": "accept", + "returnType": "void" + } + ], + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "x", + "read": "x", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "y", + "read": "y", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "source", + "read": "source", + "required": false, + "scriptable": true, + "stored": true, + "type": "QObject*", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "keys", + "read": "keys", + "required": false, + "scriptable": true, + "stored": true, + "type": "QStringList", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "supportedActions", + "read": "supportedActions", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::DropActions", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "proposedAction", + "read": "proposedAction", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::DropActions", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 6, + "name": "action", + "read": "action", + "required": false, + "reset": "resetAction", + "scriptable": true, + "stored": true, + "type": "Qt::DropAction", + "user": false, + "write": "setAction" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 7, + "name": "accepted", + "read": "accepted", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setAccepted" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 8, + "name": "hasColor", + "read": "hasColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 9, + "name": "hasHtml", + "read": "hasHtml", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 10, + "name": "hasText", + "read": "hasText", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 11, + "name": "hasUrls", + "read": "hasUrls", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 12, + "name": "colorData", + "read": "colorData", + "required": false, + "scriptable": true, + "stored": true, + "type": "QVariant", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 13, + "name": "html", + "read": "html", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 14, + "name": "text", + "read": "text", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 15, + "name": "urls", + "read": "urls", + "required": false, + "scriptable": true, + "stored": true, + "type": "QList", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 16, + "name": "formats", + "read": "formats", + "required": false, + "scriptable": true, + "stored": true, + "type": "QStringList", + "user": false + } + ], + "qualifiedClassName": "QQuickDragEvent", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickDropAreaDrag", + "lineNumber": 92, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "x", + "notify": "positionChanged", + "read": "x", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "y", + "notify": "positionChanged", + "read": "y", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "source", + "notify": "sourceChanged", + "read": "source", + "required": false, + "scriptable": true, + "stored": true, + "type": "QObject*", + "user": false + } + ], + "qualifiedClassName": "QQuickDropAreaDrag", + "signals": [ + { + "access": "public", + "index": 0, + "name": "positionChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "sourceChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "DropArea" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickDropArea", + "lineNumber": 120, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "containsDrag", + "notify": "containsDragChanged", + "read": "containsDrag", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "keys", + "notify": "keysChanged", + "read": "keys", + "required": false, + "scriptable": true, + "stored": true, + "type": "QStringList", + "user": false, + "write": "setKeys" + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 2, + "name": "drag", + "read": "drag", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickDropAreaDrag*", + "user": false + } + ], + "qualifiedClassName": "QQuickDropArea", + "signals": [ + { + "access": "public", + "index": 0, + "name": "containsDragChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "keysChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "sourceChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "drag", + "type": "QQuickDragEvent*" + } + ], + "index": 3, + "name": "entered", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "exited", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "drag", + "type": "QQuickDragEvent*" + } + ], + "index": 5, + "name": "positionChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "drop", + "type": "QQuickDragEvent*" + } + ], + "index": 6, + "name": "dropped", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickItem" + } + ] + } + ], + "inputFile": "qquickdroparea_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "KeyEvent" + }, + { + "name": "QML.Creatable", + "value": "false" + }, + { + "name": "QML.UncreatableReason", + "value": "Should only be used by signal handlers in the Keys attached property" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickKeyEvent", + "lineNumber": 39, + "methods": [ + { + "access": "public", + "arguments": [ + { + "name": "key", + "type": "QKeySequence::StandardKey" + } + ], + "index": 0, + "name": "matches", + "returnType": "bool", + "revision": 514 + } + ], + "object": true, + "properties": [ + { + "constant": true, + "designable": true, + "final": true, + "index": 0, + "name": "key", + "read": "key", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 1, + "name": "text", + "read": "text", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 2, + "name": "modifiers", + "read": "modifiers", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 3, + "name": "isAutoRepeat", + "read": "isAutoRepeat", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 4, + "name": "count", + "read": "count", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 5, + "name": "nativeScanCode", + "read": "nativeScanCode", + "required": false, + "scriptable": true, + "stored": true, + "type": "quint32", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 6, + "name": "accepted", + "read": "isAccepted", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setAccepted" + } + ], + "qualifiedClassName": "QQuickKeyEvent", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "MouseEvent" + }, + { + "name": "QML.Creatable", + "value": "false" + }, + { + "name": "QML.UncreatableReason", + "value": "Should only be used by mouse event signal handlers, for example in MouseArea" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickMouseEvent", + "lineNumber": 106, + "object": true, + "properties": [ + { + "constant": true, + "designable": true, + "final": true, + "index": 0, + "name": "x", + "read": "x", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 1, + "name": "y", + "read": "y", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 2, + "name": "button", + "read": "button", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 3, + "name": "buttons", + "read": "buttons", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 4, + "name": "modifiers", + "read": "modifiers", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 5, + "name": "source", + "read": "source", + "required": false, + "revision": 519, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 6, + "name": "isClick", + "read": "isClick", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 7, + "name": "wasHeld", + "read": "wasHeld", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 8, + "name": "accepted", + "read": "isAccepted", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setAccepted" + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 9, + "name": "flags", + "read": "flags", + "required": false, + "revision": 523, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + } + ], + "qualifiedClassName": "QQuickMouseEvent", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "WheelEvent" + }, + { + "name": "QML.Creatable", + "value": "false" + }, + { + "name": "QML.UncreatableReason", + "value": "Should only be used by wheel event signal handlers, for example in MouseArea" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickWheelEvent", + "lineNumber": 182, + "object": true, + "properties": [ + { + "constant": true, + "designable": true, + "final": true, + "index": 0, + "name": "device", + "read": "pointingDevice", + "required": false, + "scriptable": true, + "stored": true, + "type": "const QPointingDevice*", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 1, + "name": "x", + "read": "x", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 2, + "name": "y", + "read": "y", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 3, + "name": "angleDelta", + "read": "angleDelta", + "required": false, + "scriptable": true, + "stored": true, + "type": "QPoint", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 4, + "name": "pixelDelta", + "read": "pixelDelta", + "required": false, + "scriptable": true, + "stored": true, + "type": "QPoint", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 5, + "name": "phase", + "read": "phase", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::ScrollPhase", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 6, + "name": "buttons", + "read": "buttons", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 7, + "name": "modifiers", + "read": "modifiers", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 8, + "name": "inverted", + "read": "inverted", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 9, + "name": "accepted", + "read": "isAccepted", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setAccepted" + } + ], + "qualifiedClassName": "QQuickWheelEvent", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "CloseEvent" + }, + { + "name": "QML.Creatable", + "value": "false" + }, + { + "name": "QML.UncreatableReason", + "value": "Should only be used by Window's closing signal" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickCloseEvent", + "lineNumber": 242, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "accepted", + "read": "isAccepted", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setAccepted" + } + ], + "qualifiedClassName": "QQuickCloseEvent", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qquickevents_p_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "DefaultProperty", + "value": "flickableData" + }, + { + "name": "QML.Element", + "value": "Flickable" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickFlickable", + "enums": [ + { + "alias": "BoundsBehaviorFlag", + "isClass": false, + "isFlag": true, + "name": "BoundsBehavior", + "values": [ + "StopAtBounds", + "DragOverBounds", + "OvershootBounds", + "DragAndOvershootBounds" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "BoundsMovement", + "values": [ + "FollowBoundsBehavior" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "FlickableDirection", + "values": [ + "AutoFlickDirection", + "HorizontalFlick", + "VerticalFlick", + "HorizontalAndVerticalFlick", + "AutoFlickIfNeeded" + ] + } + ], + "lineNumber": 25, + "methods": [ + { + "access": "public", + "arguments": [ + { + "name": "w", + "type": "qreal" + }, + { + "name": "h", + "type": "qreal" + }, + { + "name": "center", + "type": "QPointF" + } + ], + "index": 49, + "name": "resizeContent", + "returnType": "void" + }, + { + "access": "public", + "index": 50, + "name": "returnToBounds", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "xVelocity", + "type": "qreal" + }, + { + "name": "yVelocity", + "type": "qreal" + } + ], + "index": 51, + "name": "flick", + "returnType": "void" + }, + { + "access": "public", + "index": 52, + "name": "cancelFlick", + "returnType": "void" + } + ], + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "contentWidth", + "notify": "contentWidthChanged", + "read": "contentWidth", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setContentWidth" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "contentHeight", + "notify": "contentHeightChanged", + "read": "contentHeight", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setContentHeight" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "contentX", + "notify": "contentXChanged", + "read": "contentX", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setContentX" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "contentY", + "notify": "contentYChanged", + "read": "contentY", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setContentY" + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 4, + "name": "contentItem", + "read": "contentItem", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "topMargin", + "notify": "topMarginChanged", + "read": "topMargin", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setTopMargin" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "bottomMargin", + "notify": "bottomMarginChanged", + "read": "bottomMargin", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setBottomMargin" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 7, + "name": "originY", + "notify": "originYChanged", + "read": "originY", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 8, + "name": "leftMargin", + "notify": "leftMarginChanged", + "read": "leftMargin", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setLeftMargin" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 9, + "name": "rightMargin", + "notify": "rightMarginChanged", + "read": "rightMargin", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setRightMargin" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 10, + "name": "originX", + "notify": "originXChanged", + "read": "originX", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 11, + "name": "horizontalVelocity", + "notify": "horizontalVelocityChanged", + "read": "horizontalVelocity", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 12, + "name": "verticalVelocity", + "notify": "verticalVelocityChanged", + "read": "verticalVelocity", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 13, + "name": "boundsBehavior", + "notify": "boundsBehaviorChanged", + "read": "boundsBehavior", + "required": false, + "scriptable": true, + "stored": true, + "type": "BoundsBehavior", + "user": false, + "write": "setBoundsBehavior" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 14, + "name": "boundsMovement", + "notify": "boundsMovementChanged", + "read": "boundsMovement", + "required": false, + "revision": 522, + "scriptable": true, + "stored": true, + "type": "BoundsMovement", + "user": false, + "write": "setBoundsMovement" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 15, + "name": "rebound", + "notify": "reboundChanged", + "read": "rebound", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickTransition*", + "user": false, + "write": "setRebound" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 16, + "name": "maximumFlickVelocity", + "notify": "maximumFlickVelocityChanged", + "read": "maximumFlickVelocity", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setMaximumFlickVelocity" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 17, + "name": "flickDeceleration", + "notify": "flickDecelerationChanged", + "read": "flickDeceleration", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setFlickDeceleration" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 18, + "name": "moving", + "notify": "movingChanged", + "read": "isMoving", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 19, + "name": "movingHorizontally", + "notify": "movingHorizontallyChanged", + "read": "isMovingHorizontally", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 20, + "name": "movingVertically", + "notify": "movingVerticallyChanged", + "read": "isMovingVertically", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 21, + "name": "flicking", + "notify": "flickingChanged", + "read": "isFlicking", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 22, + "name": "flickingHorizontally", + "notify": "flickingHorizontallyChanged", + "read": "isFlickingHorizontally", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 23, + "name": "flickingVertically", + "notify": "flickingVerticallyChanged", + "read": "isFlickingVertically", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 24, + "name": "dragging", + "notify": "draggingChanged", + "read": "isDragging", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 25, + "name": "draggingHorizontally", + "notify": "draggingHorizontallyChanged", + "read": "isDraggingHorizontally", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 26, + "name": "draggingVertically", + "notify": "draggingVerticallyChanged", + "read": "isDraggingVertically", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 27, + "name": "flickableDirection", + "notify": "flickableDirectionChanged", + "read": "flickableDirection", + "required": false, + "scriptable": true, + "stored": true, + "type": "FlickableDirection", + "user": false, + "write": "setFlickableDirection" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 28, + "name": "interactive", + "notify": "interactiveChanged", + "read": "isInteractive", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setInteractive" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 29, + "name": "pressDelay", + "notify": "pressDelayChanged", + "read": "pressDelay", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setPressDelay" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 30, + "name": "atXEnd", + "notify": "atXEndChanged", + "read": "isAtXEnd", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 31, + "name": "atYEnd", + "notify": "atYEndChanged", + "read": "isAtYEnd", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 32, + "name": "atXBeginning", + "notify": "atXBeginningChanged", + "read": "isAtXBeginning", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 33, + "name": "atYBeginning", + "notify": "atYBeginningChanged", + "read": "isAtYBeginning", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 34, + "name": "visibleArea", + "read": "visibleArea", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickFlickableVisibleArea*", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 35, + "name": "pixelAligned", + "notify": "pixelAlignedChanged", + "read": "pixelAligned", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setPixelAligned" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 36, + "name": "synchronousDrag", + "notify": "synchronousDragChanged", + "read": "synchronousDrag", + "required": false, + "revision": 524, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setSynchronousDrag" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 37, + "name": "horizontalOvershoot", + "notify": "horizontalOvershootChanged", + "read": "horizontalOvershoot", + "required": false, + "revision": 521, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 38, + "name": "verticalOvershoot", + "notify": "verticalOvershootChanged", + "read": "verticalOvershoot", + "required": false, + "revision": 521, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 39, + "name": "flickableData", + "read": "flickableData", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlListProperty", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 40, + "name": "flickableChildren", + "read": "flickableChildren", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlListProperty", + "user": false + } + ], + "qualifiedClassName": "QQuickFlickable", + "signals": [ + { + "access": "public", + "index": 0, + "name": "contentWidthChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "contentHeightChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "contentXChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "contentYChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "topMarginChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "bottomMarginChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "leftMarginChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "rightMarginChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 8, + "name": "originYChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 9, + "name": "originXChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 10, + "name": "movingChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 11, + "name": "movingHorizontallyChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 12, + "name": "movingVerticallyChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 13, + "name": "flickingChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 14, + "name": "flickingHorizontallyChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 15, + "name": "flickingVerticallyChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 16, + "name": "draggingChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 17, + "name": "draggingHorizontallyChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 18, + "name": "draggingVerticallyChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 19, + "name": "horizontalVelocityChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 20, + "name": "verticalVelocityChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 21, + "name": "isAtBoundaryChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 22, + "name": "flickableDirectionChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 23, + "name": "interactiveChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 24, + "name": "boundsBehaviorChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 25, + "name": "boundsMovementChanged", + "returnType": "void", + "revision": 522 + }, + { + "access": "public", + "index": 26, + "name": "reboundChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 27, + "name": "maximumFlickVelocityChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 28, + "name": "flickDecelerationChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 29, + "name": "pressDelayChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 30, + "name": "movementStarted", + "returnType": "void" + }, + { + "access": "public", + "index": 31, + "name": "movementEnded", + "returnType": "void" + }, + { + "access": "public", + "index": 32, + "name": "flickStarted", + "returnType": "void" + }, + { + "access": "public", + "index": 33, + "name": "flickEnded", + "returnType": "void" + }, + { + "access": "public", + "index": 34, + "name": "dragStarted", + "returnType": "void" + }, + { + "access": "public", + "index": 35, + "name": "dragEnded", + "returnType": "void" + }, + { + "access": "public", + "index": 36, + "name": "pixelAlignedChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 37, + "name": "synchronousDragChanged", + "returnType": "void", + "revision": 524 + }, + { + "access": "public", + "index": 38, + "name": "horizontalOvershootChanged", + "returnType": "void", + "revision": 521 + }, + { + "access": "public", + "index": 39, + "name": "verticalOvershootChanged", + "returnType": "void", + "revision": 521 + }, + { + "access": "public", + "index": 40, + "name": "atXEndChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 41, + "name": "atYEndChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 42, + "name": "atXBeginningChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 43, + "name": "atYBeginningChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "protected", + "index": 44, + "name": "movementStarting", + "returnType": "void" + }, + { + "access": "protected", + "index": 45, + "name": "movementEnding", + "returnType": "void" + }, + { + "access": "protected", + "arguments": [ + { + "name": "hMovementEnding", + "type": "bool" + }, + { + "name": "vMovementEnding", + "type": "bool" + } + ], + "index": 46, + "name": "movementEnding", + "returnType": "void" + }, + { + "access": "protected", + "index": 47, + "name": "velocityTimelineCompleted", + "returnType": "void" + }, + { + "access": "protected", + "index": 48, + "name": "timelineCompleted", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickItem" + } + ] + } + ], + "inputFile": "qquickflickable_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickFlickableVisibleArea", + "lineNumber": 250, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "xPosition", + "notify": "xPositionChanged", + "read": "xPosition", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "yPosition", + "notify": "yPositionChanged", + "read": "yPosition", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "widthRatio", + "notify": "widthRatioChanged", + "read": "widthRatio", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "heightRatio", + "notify": "heightRatioChanged", + "read": "heightRatio", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + } + ], + "qualifiedClassName": "QQuickFlickableVisibleArea", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "xPosition", + "type": "qreal" + } + ], + "index": 0, + "name": "xPositionChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "yPosition", + "type": "qreal" + } + ], + "index": 1, + "name": "yPositionChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "widthRatio", + "type": "qreal" + } + ], + "index": 2, + "name": "widthRatioChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "heightRatio", + "type": "qreal" + } + ], + "index": 3, + "name": "heightRatioChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qquickflickable_p_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "Flipable" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickFlipable", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "Side", + "values": [ + "Front", + "Back" + ] + } + ], + "lineNumber": 31, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "front", + "notify": "frontChanged", + "read": "front", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false, + "write": "setFront" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "back", + "notify": "backChanged", + "read": "back", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false, + "write": "setBack" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "side", + "notify": "sideChanged", + "read": "side", + "required": false, + "scriptable": true, + "stored": true, + "type": "Side", + "user": false + } + ], + "qualifiedClassName": "QQuickFlipable", + "signals": [ + { + "access": "public", + "index": 0, + "name": "frontChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "backChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "sideChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "private", + "index": 3, + "name": "retransformBack", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickItem" + } + ] + } + ], + "inputFile": "qquickflipable_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "FocusScope" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickFocusScope", + "lineNumber": 24, + "object": true, + "qualifiedClassName": "QQuickFocusScope", + "superClasses": [ + { + "access": "public", + "name": "QQuickItem" + } + ] + } + ], + "inputFile": "qquickfocusscope_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "FontLoader" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickFontLoader", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "Status", + "values": [ + "Null", + "Ready", + "Loading", + "Error" + ] + } + ], + "lineNumber": 28, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "source", + "notify": "sourceChanged", + "read": "source", + "required": false, + "scriptable": true, + "stored": true, + "type": "QUrl", + "user": false, + "write": "setSource" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "name", + "notify": "nameChanged", + "read": "name", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "status", + "notify": "statusChanged", + "read": "status", + "required": false, + "scriptable": true, + "stored": true, + "type": "Status", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "font", + "notify": "fontChanged", + "read": "font", + "required": false, + "scriptable": true, + "stored": true, + "type": "QFont", + "user": false + } + ], + "qualifiedClassName": "QQuickFontLoader", + "signals": [ + { + "access": "public", + "index": 0, + "name": "sourceChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "nameChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "fontChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "statusChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "private", + "arguments": [ + { + "type": "int" + } + ], + "index": 4, + "name": "updateFontInfo", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qquickfontloader_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "FontMetrics" + }, + { + "name": "QML.AddedInVersion", + "value": "516" + } + ], + "className": "QQuickFontMetrics", + "lineNumber": 30, + "methods": [ + { + "access": "public", + "arguments": [ + { + "name": "text", + "type": "QString" + } + ], + "index": 1, + "name": "advanceWidth", + "returnType": "qreal" + }, + { + "access": "public", + "arguments": [ + { + "name": "text", + "type": "QString" + } + ], + "index": 2, + "name": "boundingRect", + "returnType": "QRectF" + }, + { + "access": "public", + "arguments": [ + { + "name": "text", + "type": "QString" + } + ], + "index": 3, + "name": "tightBoundingRect", + "returnType": "QRectF" + }, + { + "access": "public", + "arguments": [ + { + "name": "text", + "type": "QString" + }, + { + "name": "mode", + "type": "Qt::TextElideMode" + }, + { + "name": "width", + "type": "qreal" + }, + { + "name": "flags", + "type": "int" + } + ], + "index": 4, + "name": "elidedText", + "returnType": "QString" + }, + { + "access": "public", + "arguments": [ + { + "name": "text", + "type": "QString" + }, + { + "name": "mode", + "type": "Qt::TextElideMode" + }, + { + "name": "width", + "type": "qreal" + } + ], + "index": 5, + "isCloned": true, + "name": "elidedText", + "returnType": "QString" + } + ], + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "font", + "notify": "fontChanged", + "read": "font", + "required": false, + "scriptable": true, + "stored": true, + "type": "QFont", + "user": false, + "write": "setFont" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "ascent", + "notify": "fontChanged", + "read": "ascent", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "descent", + "notify": "fontChanged", + "read": "descent", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "height", + "notify": "fontChanged", + "read": "height", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "leading", + "notify": "fontChanged", + "read": "leading", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "lineSpacing", + "notify": "fontChanged", + "read": "lineSpacing", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "minimumLeftBearing", + "notify": "fontChanged", + "read": "minimumLeftBearing", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 7, + "name": "minimumRightBearing", + "notify": "fontChanged", + "read": "minimumRightBearing", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 8, + "name": "maximumCharacterWidth", + "notify": "fontChanged", + "read": "maximumCharacterWidth", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 9, + "name": "xHeight", + "notify": "fontChanged", + "read": "xHeight", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 10, + "name": "averageCharacterWidth", + "notify": "fontChanged", + "read": "averageCharacterWidth", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 11, + "name": "underlinePosition", + "notify": "fontChanged", + "read": "underlinePosition", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 12, + "name": "overlinePosition", + "notify": "fontChanged", + "read": "overlinePosition", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 13, + "name": "strikeOutPosition", + "notify": "fontChanged", + "read": "strikeOutPosition", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 14, + "name": "lineWidth", + "notify": "fontChanged", + "read": "lineWidth", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + } + ], + "qualifiedClassName": "QQuickFontMetrics", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "font", + "type": "QFont" + } + ], + "index": 0, + "name": "fontChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qquickfontmetrics_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Foreign", + "value": "QStyleHints" + }, + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.AddedInVersion", + "value": "1540" + } + ], + "className": "QStyleHintsForeign", + "gadget": true, + "lineNumber": 36, + "qualifiedClassName": "QStyleHintsForeign" + }, + { + "classInfos": [ + { + "name": "QML.Foreign", + "value": "QImage" + }, + { + "name": "QML.Element", + "value": "anonymous" + } + ], + "className": "QImageForeign", + "gadget": true, + "lineNumber": 44, + "qualifiedClassName": "QImageForeign" + }, + { + "classInfos": [ + { + "name": "QML.Foreign", + "value": "QValidator" + }, + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QValidatorForeign", + "gadget": true, + "lineNumber": 52, + "qualifiedClassName": "QValidatorForeign" + }, + { + "classInfos": [ + { + "name": "QML.Foreign", + "value": "QRegularExpressionValidator" + }, + { + "name": "QML.Element", + "value": "RegularExpressionValidator" + }, + { + "name": "QML.AddedInVersion", + "value": "526" + } + ], + "className": "QRegularExpressionValidatorForeign", + "gadget": true, + "lineNumber": 61, + "qualifiedClassName": "QRegularExpressionValidatorForeign" + }, + { + "classInfos": [ + { + "name": "QML.Foreign", + "value": "QInputMethod" + }, + { + "name": "QML.Element", + "value": "InputMethod" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + }, + { + "name": "QML.RemovedInVersion", + "value": "1540" + }, + { + "name": "QML.Creatable", + "value": "false" + }, + { + "name": "QML.UncreatableReason", + "value": "InputMethod is an abstract class." + } + ], + "className": "QInputMethodForeign", + "gadget": true, + "lineNumber": 73, + "qualifiedClassName": "QInputMethodForeign" + }, + { + "classInfos": [ + { + "name": "QML.Foreign", + "value": "QEventPoint" + }, + { + "name": "QML.Element", + "value": "eventPoint" + }, + { + "name": "QML.AddedInVersion", + "value": "1541" + } + ], + "className": "QEventPointForeign", + "gadget": true, + "lineNumber": 94, + "qualifiedClassName": "QEventPointForeign" + }, + { + "className": "QEventPointDerived", + "gadget": true, + "lineNumber": 105, + "qualifiedClassName": "QEventPointDerived", + "superClasses": [ + { + "access": "public", + "name": "QEventPoint" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Foreign", + "value": "QKeySequence" + }, + { + "name": "QML.ForeignIsNamespace", + "value": "true" + }, + { + "name": "QML.Element", + "value": "StandardKey" + }, + { + "name": "QML.AddedInVersion", + "value": "514" + } + ], + "className": "QKeySequenceForeign", + "lineNumber": 85, + "namespace": true, + "qualifiedClassName": "QKeySequenceForeign" + }, + { + "classInfos": [ + { + "name": "QML.Foreign", + "value": "QEventPointDerived" + }, + { + "name": "QML.ForeignIsNamespace", + "value": "true" + }, + { + "name": "QML.Element", + "value": "EventPoint" + }, + { + "name": "QML.AddedInVersion", + "value": "1542" + } + ], + "className": "QEventPointForeignNamespace", + "lineNumber": 110, + "namespace": true, + "qualifiedClassName": "QEventPointForeignNamespace" + } + ], + "inputFile": "qquickforeignutils_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "FrameAnimation" + }, + { + "name": "QML.AddedInVersion", + "value": "1540" + } + ], + "className": "QQuickFrameAnimation", + "interfaces": [ + [ + { + "className": "QQmlParserStatus", + "id": "\"org.qt-project.Qt.QQmlParserStatus\"" + } + ] + ], + "lineNumber": 26, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "running", + "notify": "runningChanged", + "read": "isRunning", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setRunning" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "paused", + "notify": "pausedChanged", + "read": "isPaused", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setPaused" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "currentFrame", + "notify": "currentFrameChanged", + "read": "currentFrame", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "frameTime", + "notify": "frameTimeChanged", + "read": "frameTime", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "smoothFrameTime", + "notify": "smoothFrameTimeChanged", + "read": "smoothFrameTime", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "elapsedTime", + "notify": "elapsedTimeChanged", + "read": "elapsedTime", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + } + ], + "qualifiedClassName": "QQuickFrameAnimation", + "signals": [ + { + "access": "public", + "index": 0, + "name": "triggered", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "runningChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "pausedChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "currentFrameChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "frameTimeChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "smoothFrameTimeChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "elapsedTimeChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "index": 7, + "name": "start", + "returnType": "void" + }, + { + "access": "public", + "index": 8, + "name": "stop", + "returnType": "void" + }, + { + "access": "public", + "index": 9, + "name": "restart", + "returnType": "void" + }, + { + "access": "public", + "index": 10, + "name": "pause", + "returnType": "void" + }, + { + "access": "public", + "index": 11, + "name": "resume", + "returnType": "void" + }, + { + "access": "public", + "index": 12, + "name": "reset", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QQmlParserStatus" + } + ] + } + ], + "inputFile": "qquickframeanimation_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQuickFramebufferObject", + "lineNumber": 15, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "textureFollowsItemSize", + "notify": "textureFollowsItemSizeChanged", + "read": "textureFollowsItemSize", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setTextureFollowsItemSize" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "mirrorVertically", + "notify": "mirrorVerticallyChanged", + "read": "mirrorVertically", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setMirrorVertically" + } + ], + "qualifiedClassName": "QQuickFramebufferObject", + "signals": [ + { + "access": "public", + "arguments": [ + { + "type": "bool" + } + ], + "index": 0, + "name": "textureFollowsItemSizeChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "bool" + } + ], + "index": 1, + "name": "mirrorVerticallyChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "private", + "index": 2, + "name": "invalidateSceneGraph", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickItem" + } + ] + } + ], + "inputFile": "qquickframebufferobject.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "GraphicsInfo" + }, + { + "name": "QML.AddedInVersion", + "value": "520" + }, + { + "name": "QML.Creatable", + "value": "false" + }, + { + "name": "QML.UncreatableReason", + "value": "GraphicsInfo is only available via attached properties." + }, + { + "name": "QML.Attached", + "value": "QQuickGraphicsInfo" + } + ], + "className": "QQuickGraphicsInfo", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "GraphicsApi", + "values": [ + "Unknown", + "Software", + "OpenVG", + "OpenGL", + "Direct3D11", + "Vulkan", + "Metal", + "Null", + "Direct3D12", + "OpenGLRhi", + "Direct3D11Rhi", + "VulkanRhi", + "MetalRhi", + "NullRhi" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "ShaderType", + "values": [ + "UnknownShadingLanguage", + "GLSL", + "HLSL", + "RhiShader" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "ShaderCompilationType", + "values": [ + "RuntimeCompilation", + "OfflineCompilation" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "ShaderSourceType", + "values": [ + "ShaderSourceString", + "ShaderSourceFile", + "ShaderByteCode" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "OpenGLContextProfile", + "values": [ + "OpenGLNoProfile", + "OpenGLCoreProfile", + "OpenGLCompatibilityProfile" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "RenderableType", + "values": [ + "SurfaceFormatUnspecified", + "SurfaceFormatOpenGL", + "SurfaceFormatOpenGLES" + ] + } + ], + "lineNumber": 30, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "api", + "notify": "apiChanged", + "read": "api", + "required": false, + "scriptable": true, + "stored": true, + "type": "GraphicsApi", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "shaderType", + "notify": "shaderTypeChanged", + "read": "shaderType", + "required": false, + "scriptable": true, + "stored": true, + "type": "ShaderType", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "shaderCompilationType", + "notify": "shaderCompilationTypeChanged", + "read": "shaderCompilationType", + "required": false, + "scriptable": true, + "stored": true, + "type": "ShaderCompilationType", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "shaderSourceType", + "notify": "shaderSourceTypeChanged", + "read": "shaderSourceType", + "required": false, + "scriptable": true, + "stored": true, + "type": "ShaderSourceType", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "majorVersion", + "notify": "majorVersionChanged", + "read": "majorVersion", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "minorVersion", + "notify": "minorVersionChanged", + "read": "minorVersion", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 6, + "name": "profile", + "notify": "profileChanged", + "read": "profile", + "required": false, + "scriptable": true, + "stored": true, + "type": "OpenGLContextProfile", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 7, + "name": "renderableType", + "notify": "renderableTypeChanged", + "read": "renderableType", + "required": false, + "scriptable": true, + "stored": true, + "type": "RenderableType", + "user": false + } + ], + "qualifiedClassName": "QQuickGraphicsInfo", + "signals": [ + { + "access": "public", + "index": 0, + "name": "apiChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "shaderTypeChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "shaderCompilationTypeChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "shaderSourceTypeChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "majorVersionChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "minorVersionChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "profileChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "renderableTypeChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "private", + "index": 8, + "name": "updateInfo", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "window", + "type": "QQuickWindow*" + } + ], + "index": 9, + "name": "setWindow", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qquickgraphicsinfo_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "DefaultProperty", + "value": "data" + }, + { + "name": "QML.Element", + "value": "GridView" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + }, + { + "name": "QML.Attached", + "value": "QQuickGridViewAttached" + } + ], + "className": "QQuickGridView", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "Flow", + "values": [ + "FlowLeftToRight", + "FlowTopToBottom" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "SnapMode", + "values": [ + "NoSnap", + "SnapToRow", + "SnapOneRow" + ] + } + ], + "lineNumber": 28, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "flow", + "notify": "flowChanged", + "read": "flow", + "required": false, + "scriptable": true, + "stored": true, + "type": "Flow", + "user": false, + "write": "setFlow" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "cellWidth", + "notify": "cellWidthChanged", + "read": "cellWidth", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setCellWidth" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "cellHeight", + "notify": "cellHeightChanged", + "read": "cellHeight", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setCellHeight" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "snapMode", + "notify": "snapModeChanged", + "read": "snapMode", + "required": false, + "scriptable": true, + "stored": true, + "type": "SnapMode", + "user": false, + "write": "setSnapMode" + } + ], + "qualifiedClassName": "QQuickGridView", + "signals": [ + { + "access": "public", + "index": 0, + "name": "cellWidthChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "cellHeightChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "highlightMoveDurationChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "flowChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "snapModeChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "index": 5, + "name": "moveCurrentIndexUp", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "moveCurrentIndexDown", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "moveCurrentIndexLeft", + "returnType": "void" + }, + { + "access": "public", + "index": 8, + "name": "moveCurrentIndexRight", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickItemView" + } + ] + }, + { + "className": "QQuickGridViewAttached", + "lineNumber": 92, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "view", + "notify": "viewChanged", + "read": "view", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickGridView*", + "user": false + } + ], + "qualifiedClassName": "QQuickGridViewAttached", + "superClasses": [ + { + "access": "public", + "name": "QQuickItemViewAttached" + } + ] + } + ], + "inputFile": "qquickgridview_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + } + ], + "className": "QQuickHandlerPoint", + "gadget": true, + "lineNumber": 25, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "id", + "read": "id", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "uniqueId", + "read": "uniqueId", + "required": false, + "scriptable": true, + "stored": true, + "type": "QPointingDeviceUniqueId", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "position", + "read": "position", + "required": false, + "scriptable": true, + "stored": true, + "type": "QPointF", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "scenePosition", + "read": "scenePosition", + "required": false, + "scriptable": true, + "stored": true, + "type": "QPointF", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "pressPosition", + "read": "pressPosition", + "required": false, + "scriptable": true, + "stored": true, + "type": "QPointF", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "scenePressPosition", + "read": "scenePressPosition", + "required": false, + "scriptable": true, + "stored": true, + "type": "QPointF", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 6, + "name": "sceneGrabPosition", + "read": "sceneGrabPosition", + "required": false, + "scriptable": true, + "stored": true, + "type": "QPointF", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 7, + "name": "pressedButtons", + "read": "pressedButtons", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::MouseButtons", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 8, + "name": "modifiers", + "read": "modifiers", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::KeyboardModifiers", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 9, + "name": "velocity", + "read": "velocity", + "required": false, + "scriptable": true, + "stored": true, + "type": "QVector2D", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 10, + "name": "rotation", + "read": "rotation", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 11, + "name": "pressure", + "read": "pressure", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 12, + "name": "ellipseDiameters", + "read": "ellipseDiameters", + "required": false, + "scriptable": true, + "stored": true, + "type": "QSizeF", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 13, + "name": "device", + "read": "device", + "required": false, + "scriptable": true, + "stored": true, + "type": "QPointingDevice*", + "user": false + } + ], + "qualifiedClassName": "QQuickHandlerPoint" + } + ], + "inputFile": "qquickhandlerpoint_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "HoverHandler" + }, + { + "name": "QML.AddedInVersion", + "value": "524" + } + ], + "className": "QQuickHoverHandler", + "lineNumber": 28, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "hovered", + "notify": "hoveredChanged", + "read": "isHovered", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "blocking", + "notify": "blockingChanged", + "read": "isBlocking", + "required": false, + "revision": 1539, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setBlocking" + } + ], + "qualifiedClassName": "QQuickHoverHandler", + "signals": [ + { + "access": "public", + "index": 0, + "name": "hoveredChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "blockingChanged", + "returnType": "void", + "revision": 1539 + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickSinglePointHandler" + } + ] + } + ], + "inputFile": "qquickhoverhandler_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "Image" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickImage", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "HAlignment", + "values": [ + "AlignLeft", + "AlignRight", + "AlignHCenter" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "VAlignment", + "values": [ + "AlignTop", + "AlignBottom", + "AlignVCenter" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "FillMode", + "values": [ + "Stretch", + "PreserveAspectFit", + "PreserveAspectCrop", + "Tile", + "TileVertically", + "TileHorizontally", + "Pad" + ] + } + ], + "lineNumber": 24, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "fillMode", + "notify": "fillModeChanged", + "read": "fillMode", + "required": false, + "scriptable": true, + "stored": true, + "type": "FillMode", + "user": false, + "write": "setFillMode" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "paintedWidth", + "notify": "paintedGeometryChanged", + "read": "paintedWidth", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "paintedHeight", + "notify": "paintedGeometryChanged", + "read": "paintedHeight", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "horizontalAlignment", + "notify": "horizontalAlignmentChanged", + "read": "horizontalAlignment", + "required": false, + "scriptable": true, + "stored": true, + "type": "HAlignment", + "user": false, + "write": "setHorizontalAlignment" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "verticalAlignment", + "notify": "verticalAlignmentChanged", + "read": "verticalAlignment", + "required": false, + "scriptable": true, + "stored": true, + "type": "VAlignment", + "user": false, + "write": "setVerticalAlignment" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "sourceSize", + "notify": "sourceSizeChanged", + "read": "sourceSize", + "required": false, + "reset": "resetSourceSize", + "scriptable": true, + "stored": true, + "type": "QSize", + "user": false, + "write": "setSourceSize" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "mipmap", + "notify": "mipmapChanged", + "read": "mipmap", + "required": false, + "revision": 515, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setMipmap" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 7, + "name": "autoTransform", + "notify": "autoTransformChanged", + "read": "autoTransform", + "required": false, + "revision": 517, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setAutoTransform" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 8, + "name": "sourceClipRect", + "notify": "sourceClipRectChanged", + "read": "sourceClipRect", + "required": false, + "reset": "resetSourceClipRect", + "revision": 527, + "scriptable": true, + "stored": true, + "type": "QRectF", + "user": false, + "write": "setSourceClipRect" + } + ], + "qualifiedClassName": "QQuickImage", + "signals": [ + { + "access": "public", + "index": 0, + "name": "fillModeChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "paintedGeometryChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "alignment", + "type": "HAlignment" + } + ], + "index": 2, + "name": "horizontalAlignmentChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "alignment", + "type": "VAlignment" + } + ], + "index": 3, + "name": "verticalAlignmentChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "bool" + } + ], + "index": 4, + "name": "mipmapChanged", + "returnType": "void", + "revision": 515 + }, + { + "access": "public", + "index": 5, + "name": "autoTransformChanged", + "returnType": "void", + "revision": 517 + } + ], + "slots": [ + { + "access": "private", + "index": 6, + "name": "invalidateSceneGraph", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickImageBase" + } + ] + } + ], + "inputFile": "qquickimage_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQuickImageTextureProvider", + "lineNumber": 24, + "object": true, + "qualifiedClassName": "QQuickImageTextureProvider", + "superClasses": [ + { + "access": "public", + "name": "QSGTextureProvider" + } + ] + } + ], + "inputFile": "qquickimage_p_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "ImageBase" + }, + { + "name": "QML.AddedInVersion", + "value": "526" + }, + { + "name": "QML.Creatable", + "value": "false" + }, + { + "name": "QML.UncreatableReason", + "value": "ImageBase is an abstract base class." + } + ], + "className": "QQuickImageBase", + "enums": [ + { + "alias": "LoadPixmapOption", + "isClass": false, + "isFlag": true, + "name": "LoadPixmapOptions", + "values": [ + "NoOption", + "HandleDPR", + "UseProviderOptions" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "Status", + "values": [ + "Null", + "Ready", + "Loading", + "Error" + ] + } + ], + "lineNumber": 25, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "status", + "notify": "statusChanged", + "read": "status", + "required": false, + "scriptable": true, + "stored": true, + "type": "Status", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "source", + "notify": "sourceChanged", + "read": "source", + "required": false, + "scriptable": true, + "stored": true, + "type": "QUrl", + "user": false, + "write": "setSource" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "progress", + "notify": "progressChanged", + "read": "progress", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "asynchronous", + "notify": "asynchronousChanged", + "read": "asynchronous", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setAsynchronous" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "cache", + "notify": "cacheChanged", + "read": "cache", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setCache" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "mirror", + "notify": "mirrorChanged", + "read": "mirror", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setMirror" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "mirrorVertically", + "notify": "mirrorVerticallyChanged", + "read": "mirrorVertically", + "required": false, + "revision": 1538, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setMirrorVertically" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 7, + "name": "retainWhileLoading", + "notify": "retainWhileLoadingChanged", + "read": "retainWhileLoading", + "required": false, + "revision": 1544, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setRetainWhileLoading" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 8, + "name": "currentFrame", + "notify": "currentFrameChanged", + "read": "currentFrame", + "required": false, + "revision": 526, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setCurrentFrame" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 9, + "name": "frameCount", + "notify": "frameCountChanged", + "read": "frameCount", + "required": false, + "revision": 526, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 10, + "name": "colorSpace", + "notify": "colorSpaceChanged", + "read": "colorSpace", + "required": false, + "revision": 527, + "scriptable": true, + "stored": true, + "type": "QColorSpace", + "user": false, + "write": "setColorSpace" + } + ], + "qualifiedClassName": "QQuickImageBase", + "signals": [ + { + "access": "public", + "arguments": [ + { + "type": "QUrl" + } + ], + "index": 0, + "name": "sourceChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "sourceSizeChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QQuickImageBase::Status" + } + ], + "index": 2, + "name": "statusChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "progress", + "type": "qreal" + } + ], + "index": 3, + "name": "progressChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "asynchronousChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "cacheChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "mirrorChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "currentFrameChanged", + "returnType": "void", + "revision": 526 + }, + { + "access": "public", + "index": 8, + "name": "frameCountChanged", + "returnType": "void", + "revision": 526 + }, + { + "access": "public", + "index": 9, + "name": "sourceClipRectChanged", + "returnType": "void", + "revision": 527 + }, + { + "access": "public", + "index": 10, + "name": "colorSpaceChanged", + "returnType": "void", + "revision": 527 + }, + { + "access": "public", + "index": 11, + "name": "mirrorVerticallyChanged", + "returnType": "void", + "revision": 1538 + }, + { + "access": "public", + "index": 12, + "name": "retainWhileLoadingChanged", + "returnType": "void", + "revision": 1544 + } + ], + "slots": [ + { + "access": "private", + "index": 13, + "name": "requestFinished", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "type": "qint64" + }, + { + "type": "qint64" + } + ], + "index": 14, + "name": "requestProgress", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickImplicitSizeItem" + } + ] + } + ], + "inputFile": "qquickimagebase_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQuickTextureFactory", + "lineNumber": 21, + "object": true, + "qualifiedClassName": "QQuickTextureFactory", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "className": "QQuickImageResponse", + "lineNumber": 38, + "object": true, + "qualifiedClassName": "QQuickImageResponse", + "signals": [ + { + "access": "public", + "index": 0, + "name": "finished", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "index": 1, + "name": "cancel", + "returnType": "void" + }, + { + "access": "private", + "index": 2, + "name": "_q_finished", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "className": "QQuickImageProvider", + "lineNumber": 61, + "object": true, + "qualifiedClassName": "QQuickImageProvider", + "superClasses": [ + { + "access": "public", + "name": "QQmlImageProviderBase" + } + ] + } + ], + "inputFile": "qquickimageprovider.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.AddedInVersion", + "value": "1538" + } + ], + "className": "QQuickImplicitSizeItem", + "lineNumber": 24, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "implicitWidth", + "notify": "implicitWidthChanged", + "read": "implicitWidth", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "implicitHeight", + "notify": "implicitHeightChanged", + "read": "implicitHeight", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + } + ], + "qualifiedClassName": "QQuickImplicitSizeItem", + "superClasses": [ + { + "access": "public", + "name": "QQuickItem" + } + ] + } + ], + "inputFile": "qquickimplicitsizeitem_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "InputMethod" + }, + { + "name": "QML.AddedInVersion", + "value": "1540" + }, + { + "name": "QML.Singleton", + "value": "true" + } + ], + "className": "QQuickInputMethod", + "lineNumber": 28, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "cursorRectangle", + "notify": "cursorRectangleChanged", + "read": "cursorRectangle", + "required": false, + "scriptable": true, + "stored": true, + "type": "QRectF", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "anchorRectangle", + "notify": "anchorRectangleChanged", + "read": "anchorRectangle", + "required": false, + "scriptable": true, + "stored": true, + "type": "QRectF", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "keyboardRectangle", + "notify": "keyboardRectangleChanged", + "read": "keyboardRectangle", + "required": false, + "scriptable": true, + "stored": true, + "type": "QRectF", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "inputItemClipRectangle", + "notify": "inputItemClipRectangleChanged", + "read": "inputItemClipRectangle", + "required": false, + "scriptable": true, + "stored": true, + "type": "QRectF", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "visible", + "notify": "visibleChanged", + "read": "isVisible", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "animating", + "notify": "animatingChanged", + "read": "isAnimating", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 6, + "name": "locale", + "notify": "localeChanged", + "read": "locale", + "required": false, + "scriptable": true, + "stored": true, + "type": "QLocale", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 7, + "name": "inputDirection", + "notify": "inputDirectionChanged", + "read": "inputDirection", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::LayoutDirection", + "user": false + } + ], + "qualifiedClassName": "QQuickInputMethod", + "signals": [ + { + "access": "public", + "index": 0, + "name": "anchorRectangleChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "animatingChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "cursorRectangleChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "newDirection", + "type": "Qt::LayoutDirection" + } + ], + "index": 3, + "name": "inputDirectionChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "inputItemClipRectangleChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "keyboardRectangleChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "localeChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "visibleChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "index": 8, + "name": "commit", + "returnType": "void" + }, + { + "access": "public", + "index": 9, + "name": "hide", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "a", + "type": "QInputMethod::Action" + }, + { + "name": "cursorPosition", + "type": "int" + } + ], + "index": 10, + "name": "invokeAction", + "returnType": "void" + }, + { + "access": "public", + "index": 11, + "name": "reset", + "returnType": "void" + }, + { + "access": "public", + "index": 12, + "name": "show", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "queries", + "type": "Qt::InputMethodQueries" + } + ], + "index": 13, + "name": "update", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qquickinputmethod_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickTransform", + "lineNumber": 22, + "object": true, + "qualifiedClassName": "QQuickTransform", + "slots": [ + { + "access": "protected", + "index": 0, + "name": "update", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "classInfos": [ + { + "name": "DefaultProperty", + "value": "data" + }, + { + "name": "ParentProperty", + "value": "parent" + }, + { + "name": "qt_QmlJSWrapperFactoryMethod", + "value": "_q_createJSWrapper(QQmlV4ExecutionEnginePtr)" + }, + { + "name": "QML.Element", + "value": "Item" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickItem", + "enums": [ + { + "alias": "Flag", + "isClass": false, + "isFlag": true, + "name": "Flags", + "values": [ + "ItemClipsChildrenToShape", + "ItemAcceptsInputMethod", + "ItemIsFocusScope", + "ItemHasContents", + "ItemAcceptsDrops", + "ItemIsViewport", + "ItemObservesViewport" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "ItemChange", + "values": [ + "ItemChildAddedChange", + "ItemChildRemovedChange", + "ItemSceneChange", + "ItemVisibleHasChanged", + "ItemParentHasChanged", + "ItemOpacityHasChanged", + "ItemActiveFocusHasChanged", + "ItemRotationHasChanged", + "ItemAntialiasingHasChanged", + "ItemDevicePixelRatioHasChanged", + "ItemEnabledHasChanged" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "TransformOrigin", + "values": [ + "TopLeft", + "Top", + "TopRight", + "Left", + "Center", + "Right", + "BottomLeft", + "Bottom", + "BottomRight" + ] + } + ], + "interfaces": [ + [ + { + "className": "QQmlParserStatus", + "id": "\"org.qt-project.Qt.QQmlParserStatus\"" + } + ] + ], + "lineNumber": 62, + "methods": [ + { + "access": "public", + "arguments": [ + { + "name": "callback", + "type": "QJSValue" + }, + { + "name": "targetSize", + "type": "QSize" + } + ], + "index": 33, + "name": "grabToImage", + "returnType": "bool", + "revision": 516 + }, + { + "access": "public", + "arguments": [ + { + "name": "callback", + "type": "QJSValue" + } + ], + "index": 34, + "isCloned": true, + "name": "grabToImage", + "returnType": "bool", + "revision": 516 + }, + { + "access": "public", + "arguments": [ + { + "name": "point", + "type": "QPointF" + } + ], + "index": 35, + "name": "contains", + "returnType": "bool" + }, + { + "access": "public", + "arguments": [ + { + "name": "item", + "type": "const QQuickItem*" + }, + { + "name": "point", + "type": "QPointF" + } + ], + "index": 36, + "name": "mapFromItem", + "returnType": "QPointF" + }, + { + "access": "public", + "arguments": [ + { + "name": "item", + "type": "const QQuickItem*" + }, + { + "name": "x", + "type": "qreal" + }, + { + "name": "y", + "type": "qreal" + } + ], + "index": 37, + "name": "mapFromItem", + "returnType": "QPointF" + }, + { + "access": "public", + "arguments": [ + { + "name": "item", + "type": "const QQuickItem*" + }, + { + "name": "rect", + "type": "QRectF" + } + ], + "index": 38, + "name": "mapFromItem", + "returnType": "QRectF" + }, + { + "access": "public", + "arguments": [ + { + "name": "item", + "type": "const QQuickItem*" + }, + { + "name": "x", + "type": "qreal" + }, + { + "name": "y", + "type": "qreal" + }, + { + "name": "width", + "type": "qreal" + }, + { + "name": "height", + "type": "qreal" + } + ], + "index": 39, + "name": "mapFromItem", + "returnType": "QRectF" + }, + { + "access": "public", + "arguments": [ + { + "name": "item", + "type": "const QQuickItem*" + }, + { + "name": "point", + "type": "QPointF" + } + ], + "index": 40, + "name": "mapToItem", + "returnType": "QPointF" + }, + { + "access": "public", + "arguments": [ + { + "name": "item", + "type": "const QQuickItem*" + }, + { + "name": "x", + "type": "qreal" + }, + { + "name": "y", + "type": "qreal" + } + ], + "index": 41, + "name": "mapToItem", + "returnType": "QPointF" + }, + { + "access": "public", + "arguments": [ + { + "name": "item", + "type": "const QQuickItem*" + }, + { + "name": "rect", + "type": "QRectF" + } + ], + "index": 42, + "name": "mapToItem", + "returnType": "QRectF" + }, + { + "access": "public", + "arguments": [ + { + "name": "item", + "type": "const QQuickItem*" + }, + { + "name": "x", + "type": "qreal" + }, + { + "name": "y", + "type": "qreal" + }, + { + "name": "width", + "type": "qreal" + }, + { + "name": "height", + "type": "qreal" + } + ], + "index": 43, + "name": "mapToItem", + "returnType": "QRectF" + }, + { + "access": "public", + "arguments": [ + { + "name": "x", + "type": "qreal" + }, + { + "name": "y", + "type": "qreal" + } + ], + "index": 44, + "name": "mapFromGlobal", + "returnType": "QPointF", + "revision": 519 + }, + { + "access": "public", + "arguments": [ + { + "name": "point", + "type": "QPointF" + } + ], + "index": 45, + "name": "mapFromGlobal", + "returnType": "QPointF", + "revision": 519 + }, + { + "access": "public", + "arguments": [ + { + "name": "x", + "type": "qreal" + }, + { + "name": "y", + "type": "qreal" + } + ], + "index": 46, + "name": "mapToGlobal", + "returnType": "QPointF", + "revision": 519 + }, + { + "access": "public", + "arguments": [ + { + "name": "point", + "type": "QPointF" + } + ], + "index": 47, + "name": "mapToGlobal", + "returnType": "QPointF", + "revision": 519 + }, + { + "access": "public", + "index": 48, + "name": "forceActiveFocus", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "reason", + "type": "Qt::FocusReason" + } + ], + "index": 49, + "name": "forceActiveFocus", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "forward", + "type": "bool" + } + ], + "index": 50, + "name": "nextItemInFocusChain", + "returnType": "QQuickItem*", + "revision": 513 + }, + { + "access": "public", + "index": 51, + "isCloned": true, + "name": "nextItemInFocusChain", + "returnType": "QQuickItem*", + "revision": 513 + }, + { + "access": "public", + "arguments": [ + { + "name": "x", + "type": "qreal" + }, + { + "name": "y", + "type": "qreal" + } + ], + "index": 52, + "name": "childAt", + "returnType": "QQuickItem*" + }, + { + "access": "public", + "index": 53, + "name": "ensurePolished", + "returnType": "void", + "revision": 1539 + }, + { + "access": "public", + "index": 54, + "name": "dumpItemTree", + "returnType": "void", + "revision": 1539 + } + ], + "object": true, + "properties": [ + { + "constant": false, + "designable": false, + "final": true, + "index": 0, + "name": "parent", + "notify": "parentChanged", + "read": "parentItem", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false, + "write": "setParentItem" + }, + { + "constant": false, + "designable": false, + "final": false, + "index": 1, + "name": "data", + "privateClass": "QQuickItem::d_func()", + "read": "data", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlListProperty", + "user": false + }, + { + "constant": false, + "designable": false, + "final": false, + "index": 2, + "name": "resources", + "privateClass": "QQuickItem::d_func()", + "read": "resources", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlListProperty", + "user": false + }, + { + "constant": false, + "designable": false, + "final": false, + "index": 3, + "name": "children", + "notify": "childrenChanged", + "privateClass": "QQuickItem::d_func()", + "read": "children", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlListProperty", + "user": false + }, + { + "bindable": "bindableX", + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "x", + "notify": "xChanged", + "read": "x", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setX" + }, + { + "bindable": "bindableY", + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "y", + "notify": "yChanged", + "read": "y", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setY" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 6, + "name": "z", + "notify": "zChanged", + "read": "z", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setZ" + }, + { + "bindable": "bindableWidth", + "constant": false, + "designable": true, + "final": true, + "index": 7, + "name": "width", + "notify": "widthChanged", + "read": "width", + "required": false, + "reset": "resetWidth", + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setWidth" + }, + { + "bindable": "bindableHeight", + "constant": false, + "designable": true, + "final": true, + "index": 8, + "name": "height", + "notify": "heightChanged", + "read": "height", + "required": false, + "reset": "resetHeight", + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setHeight" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 9, + "name": "opacity", + "notify": "opacityChanged", + "read": "opacity", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setOpacity" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 10, + "name": "enabled", + "notify": "enabledChanged", + "read": "isEnabled", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setEnabled" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 11, + "name": "visible", + "notify": "visibleChanged", + "read": "isVisible", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setVisible" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 12, + "name": "palette", + "notify": "paletteChanged", + "privateClass": "QQuickItem::d_func()", + "read": "palette", + "required": false, + "reset": "resetPalette", + "revision": 1536, + "scriptable": true, + "stored": true, + "type": "QQuickPalette*", + "user": false, + "write": "setPalette" + }, + { + "constant": false, + "designable": false, + "final": false, + "index": 13, + "name": "visibleChildren", + "notify": "visibleChildrenChanged", + "privateClass": "QQuickItem::d_func()", + "read": "visibleChildren", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlListProperty", + "user": false + }, + { + "constant": false, + "designable": false, + "final": false, + "index": 14, + "name": "states", + "privateClass": "QQuickItem::d_func()", + "read": "states", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlListProperty", + "user": false + }, + { + "constant": false, + "designable": false, + "final": false, + "index": 15, + "name": "transitions", + "privateClass": "QQuickItem::d_func()", + "read": "transitions", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlListProperty", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 16, + "name": "state", + "notify": "stateChanged", + "read": "state", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setState" + }, + { + "constant": false, + "designable": false, + "final": true, + "index": 17, + "name": "childrenRect", + "notify": "childrenRectChanged", + "read": "childrenRect", + "required": false, + "scriptable": true, + "stored": true, + "type": "QRectF", + "user": false + }, + { + "constant": true, + "designable": false, + "final": true, + "index": 18, + "name": "anchors", + "privateClass": "QQuickItem::d_func()", + "read": "anchors", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickAnchors*", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 19, + "name": "left", + "privateClass": "QQuickItem::d_func()", + "read": "left", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickAnchorLine", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 20, + "name": "right", + "privateClass": "QQuickItem::d_func()", + "read": "right", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickAnchorLine", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 21, + "name": "horizontalCenter", + "privateClass": "QQuickItem::d_func()", + "read": "horizontalCenter", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickAnchorLine", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 22, + "name": "top", + "privateClass": "QQuickItem::d_func()", + "read": "top", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickAnchorLine", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 23, + "name": "bottom", + "privateClass": "QQuickItem::d_func()", + "read": "bottom", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickAnchorLine", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 24, + "name": "verticalCenter", + "privateClass": "QQuickItem::d_func()", + "read": "verticalCenter", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickAnchorLine", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 25, + "name": "baseline", + "privateClass": "QQuickItem::d_func()", + "read": "baseline", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickAnchorLine", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 26, + "name": "baselineOffset", + "notify": "baselineOffsetChanged", + "read": "baselineOffset", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setBaselineOffset" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 27, + "name": "clip", + "notify": "clipChanged", + "read": "clip", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setClip" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 28, + "name": "focus", + "notify": "focusChanged", + "read": "hasFocus", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setFocus" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 29, + "name": "activeFocus", + "notify": "activeFocusChanged", + "read": "hasActiveFocus", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 30, + "name": "activeFocusOnTab", + "notify": "activeFocusOnTabChanged", + "read": "activeFocusOnTab", + "required": false, + "revision": 513, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setActiveFocusOnTab" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 31, + "name": "focusPolicy", + "notify": "focusPolicyChanged", + "read": "focusPolicy", + "required": false, + "revision": 1543, + "scriptable": true, + "stored": true, + "type": "Qt::FocusPolicy", + "user": false, + "write": "setFocusPolicy" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 32, + "name": "rotation", + "notify": "rotationChanged", + "read": "rotation", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setRotation" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 33, + "name": "scale", + "notify": "scaleChanged", + "read": "scale", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setScale" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 34, + "name": "transformOrigin", + "notify": "transformOriginChanged", + "read": "transformOrigin", + "required": false, + "scriptable": true, + "stored": true, + "type": "TransformOrigin", + "user": false, + "write": "setTransformOrigin" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 35, + "name": "transformOriginPoint", + "read": "transformOriginPoint", + "required": false, + "scriptable": true, + "stored": true, + "type": "QPointF", + "user": false + }, + { + "constant": false, + "designable": false, + "final": true, + "index": 36, + "name": "transform", + "read": "transform", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlListProperty", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 37, + "name": "smooth", + "notify": "smoothChanged", + "read": "smooth", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setSmooth" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 38, + "name": "antialiasing", + "notify": "antialiasingChanged", + "read": "antialiasing", + "required": false, + "reset": "resetAntialiasing", + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setAntialiasing" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 39, + "name": "implicitWidth", + "notify": "implicitWidthChanged", + "read": "implicitWidth", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setImplicitWidth" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 40, + "name": "implicitHeight", + "notify": "implicitHeightChanged", + "read": "implicitHeight", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setImplicitHeight" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 41, + "name": "containmentMask", + "notify": "containmentMaskChanged", + "read": "containmentMask", + "required": false, + "revision": 523, + "scriptable": true, + "stored": true, + "type": "QObject*", + "user": false, + "write": "setContainmentMask" + }, + { + "constant": true, + "designable": false, + "final": true, + "index": 42, + "name": "layer", + "privateClass": "QQuickItem::d_func()", + "read": "layer", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickItemLayer*", + "user": false + } + ], + "qualifiedClassName": "QQuickItem", + "signals": [ + { + "access": "public", + "arguments": [ + { + "type": "QRectF" + } + ], + "index": 0, + "name": "childrenRectChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "qreal" + } + ], + "index": 1, + "name": "baselineOffsetChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QString" + } + ], + "index": 2, + "name": "stateChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "bool" + } + ], + "index": 3, + "name": "focusChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "bool" + } + ], + "index": 4, + "name": "activeFocusChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "Qt::FocusPolicy" + } + ], + "index": 5, + "name": "focusPolicyChanged", + "returnType": "void", + "revision": 1543 + }, + { + "access": "public", + "arguments": [ + { + "type": "bool" + } + ], + "index": 6, + "name": "activeFocusOnTabChanged", + "returnType": "void", + "revision": 513 + }, + { + "access": "public", + "arguments": [ + { + "type": "QQuickItem*" + } + ], + "index": 7, + "name": "parentChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "TransformOrigin" + } + ], + "index": 8, + "name": "transformOriginChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "bool" + } + ], + "index": 9, + "name": "smoothChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "bool" + } + ], + "index": 10, + "name": "antialiasingChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "bool" + } + ], + "index": 11, + "name": "clipChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "window", + "type": "QQuickWindow*" + } + ], + "index": 12, + "name": "windowChanged", + "returnType": "void", + "revision": 513 + }, + { + "access": "public", + "index": 13, + "name": "childrenChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 14, + "name": "opacityChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 15, + "name": "enabledChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 16, + "name": "visibleChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 17, + "name": "visibleChildrenChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 18, + "name": "rotationChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 19, + "name": "scaleChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 20, + "name": "xChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 21, + "name": "yChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 22, + "name": "widthChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 23, + "name": "heightChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 24, + "name": "zChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 25, + "name": "implicitWidthChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 26, + "name": "implicitHeightChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 27, + "name": "containmentMaskChanged", + "returnType": "void", + "revision": 523 + }, + { + "access": "public", + "index": 28, + "name": "paletteChanged", + "returnType": "void", + "revision": 1536 + }, + { + "access": "public", + "index": 29, + "name": "paletteCreated", + "returnType": "void", + "revision": 1536 + } + ], + "slots": [ + { + "access": "public", + "index": 30, + "name": "update", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "type": "QObject*" + } + ], + "index": 31, + "name": "_q_resourceObjectDeleted", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "type": "QQmlV4ExecutionEnginePtr" + } + ], + "index": 32, + "name": "_q_createJSWrapper", + "returnType": "quint64" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QQmlParserStatus" + } + ] + } + ], + "inputFile": "qquickitem.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickItemLayer", + "lineNumber": 106, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "enabled", + "notify": "enabledChanged", + "read": "enabled", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setEnabled" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "textureSize", + "notify": "sizeChanged", + "read": "size", + "required": false, + "scriptable": true, + "stored": true, + "type": "QSize", + "user": false, + "write": "setSize" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "sourceRect", + "notify": "sourceRectChanged", + "read": "sourceRect", + "required": false, + "scriptable": true, + "stored": true, + "type": "QRectF", + "user": false, + "write": "setSourceRect" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "mipmap", + "notify": "mipmapChanged", + "read": "mipmap", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setMipmap" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "smooth", + "notify": "smoothChanged", + "read": "smooth", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setSmooth" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "live", + "notify": "liveChanged", + "read": "live", + "required": false, + "revision": 1541, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setLive" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 6, + "name": "wrapMode", + "notify": "wrapModeChanged", + "read": "wrapMode", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickShaderEffectSource::WrapMode", + "user": false, + "write": "setWrapMode" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 7, + "name": "format", + "notify": "formatChanged", + "read": "format", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickShaderEffectSource::Format", + "user": false, + "write": "setFormat" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 8, + "name": "samplerName", + "notify": "nameChanged", + "read": "name", + "required": false, + "scriptable": true, + "stored": true, + "type": "QByteArray", + "user": false, + "write": "setName" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 9, + "name": "effect", + "notify": "effectChanged", + "read": "effect", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlComponent*", + "user": false, + "write": "setEffect" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 10, + "name": "textureMirroring", + "notify": "textureMirroringChanged", + "read": "textureMirroring", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickShaderEffectSource::TextureMirroring", + "user": false, + "write": "setTextureMirroring" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 11, + "name": "samples", + "notify": "samplesChanged", + "read": "samples", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setSamples" + } + ], + "qualifiedClassName": "QQuickItemLayer", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "enabled", + "type": "bool" + } + ], + "index": 0, + "name": "enabledChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "size", + "type": "QSize" + } + ], + "index": 1, + "name": "sizeChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "mipmap", + "type": "bool" + } + ], + "index": 2, + "name": "mipmapChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "mode", + "type": "QQuickShaderEffectSource::WrapMode" + } + ], + "index": 3, + "name": "wrapModeChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "name", + "type": "QByteArray" + } + ], + "index": 4, + "name": "nameChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "component", + "type": "QQmlComponent*" + } + ], + "index": 5, + "name": "effectChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "smooth", + "type": "bool" + } + ], + "index": 6, + "name": "smoothChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "live", + "type": "bool" + } + ], + "index": 7, + "name": "liveChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "format", + "type": "QQuickShaderEffectSource::Format" + } + ], + "index": 8, + "name": "formatChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "sourceRect", + "type": "QRectF" + } + ], + "index": 9, + "name": "sourceRectChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "mirroring", + "type": "QQuickShaderEffectSource::TextureMirroring" + } + ], + "index": 10, + "name": "textureMirroringChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "count", + "type": "int" + } + ], + "index": 11, + "name": "samplesChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QQuickItemChangeListener" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "KeyNavigation" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + }, + { + "name": "QML.Creatable", + "value": "false" + }, + { + "name": "QML.UncreatableReason", + "value": "KeyNavigation is only available via attached properties." + }, + { + "name": "QML.Attached", + "value": "QQuickKeyNavigationAttached" + } + ], + "className": "QQuickKeyNavigationAttached", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "Priority", + "values": [ + "BeforeItem", + "AfterItem" + ] + } + ], + "lineNumber": 767, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "left", + "notify": "leftChanged", + "read": "left", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false, + "write": "setLeft" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "right", + "notify": "rightChanged", + "read": "right", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false, + "write": "setRight" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "up", + "notify": "upChanged", + "read": "up", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false, + "write": "setUp" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "down", + "notify": "downChanged", + "read": "down", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false, + "write": "setDown" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "tab", + "notify": "tabChanged", + "read": "tab", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false, + "write": "setTab" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "backtab", + "notify": "backtabChanged", + "read": "backtab", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false, + "write": "setBacktab" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 6, + "name": "priority", + "notify": "priorityChanged", + "read": "priority", + "required": false, + "scriptable": true, + "stored": true, + "type": "Priority", + "user": false, + "write": "setPriority" + } + ], + "qualifiedClassName": "QQuickKeyNavigationAttached", + "signals": [ + { + "access": "public", + "index": 0, + "name": "leftChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "rightChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "upChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "downChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "tabChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "backtabChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "priorityChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QQuickItemKeyFilter" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "LayoutMirroring" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + }, + { + "name": "QML.Creatable", + "value": "false" + }, + { + "name": "QML.UncreatableReason", + "value": "LayoutMirroring is only available via attached properties." + }, + { + "name": "QML.Attached", + "value": "QQuickLayoutMirroringAttached" + } + ], + "className": "QQuickLayoutMirroringAttached", + "lineNumber": 824, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "enabled", + "notify": "enabledChanged", + "read": "enabled", + "required": false, + "reset": "resetEnabled", + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setEnabled" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "childrenInherit", + "notify": "childrenInheritChanged", + "read": "childrenInherit", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setChildrenInherit" + } + ], + "qualifiedClassName": "QQuickLayoutMirroringAttached", + "signals": [ + { + "access": "public", + "index": 0, + "name": "enabledChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "childrenInheritChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "EnterKey" + }, + { + "name": "QML.Creatable", + "value": "false" + }, + { + "name": "QML.UncreatableReason", + "value": "EnterKey is only available via attached properties" + }, + { + "name": "QML.AddedInVersion", + "value": "518" + }, + { + "name": "QML.Attached", + "value": "QQuickEnterKeyAttached" + } + ], + "className": "QQuickEnterKeyAttached", + "lineNumber": 854, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "type", + "notify": "typeChanged", + "read": "type", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::EnterKeyType", + "user": false, + "write": "setType" + } + ], + "qualifiedClassName": "QQuickEnterKeyAttached", + "signals": [ + { + "access": "public", + "index": 0, + "name": "typeChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "Keys" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + }, + { + "name": "QML.Creatable", + "value": "false" + }, + { + "name": "QML.UncreatableReason", + "value": "Keys is only available via attached properties" + }, + { + "name": "QML.Attached", + "value": "QQuickKeysAttached" + } + ], + "className": "QQuickKeysAttached", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "Priority", + "values": [ + "BeforeItem", + "AfterItem" + ] + } + ], + "lineNumber": 900, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "enabled", + "notify": "enabledChanged", + "read": "enabled", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setEnabled" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "forwardTo", + "read": "forwardTo", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlListProperty", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "priority", + "notify": "priorityChanged", + "read": "priority", + "required": false, + "scriptable": true, + "stored": true, + "type": "Priority", + "user": false, + "write": "setPriority" + } + ], + "qualifiedClassName": "QQuickKeysAttached", + "signals": [ + { + "access": "public", + "index": 0, + "name": "enabledChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "priorityChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "event", + "type": "QQuickKeyEvent*" + } + ], + "index": 2, + "name": "pressed", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "event", + "type": "QQuickKeyEvent*" + } + ], + "index": 3, + "name": "released", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "event", + "type": "QQuickKeyEvent*" + } + ], + "index": 4, + "name": "shortcutOverride", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "event", + "type": "QQuickKeyEvent*" + } + ], + "index": 5, + "name": "digit0Pressed", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "event", + "type": "QQuickKeyEvent*" + } + ], + "index": 6, + "name": "digit1Pressed", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "event", + "type": "QQuickKeyEvent*" + } + ], + "index": 7, + "name": "digit2Pressed", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "event", + "type": "QQuickKeyEvent*" + } + ], + "index": 8, + "name": "digit3Pressed", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "event", + "type": "QQuickKeyEvent*" + } + ], + "index": 9, + "name": "digit4Pressed", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "event", + "type": "QQuickKeyEvent*" + } + ], + "index": 10, + "name": "digit5Pressed", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "event", + "type": "QQuickKeyEvent*" + } + ], + "index": 11, + "name": "digit6Pressed", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "event", + "type": "QQuickKeyEvent*" + } + ], + "index": 12, + "name": "digit7Pressed", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "event", + "type": "QQuickKeyEvent*" + } + ], + "index": 13, + "name": "digit8Pressed", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "event", + "type": "QQuickKeyEvent*" + } + ], + "index": 14, + "name": "digit9Pressed", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "event", + "type": "QQuickKeyEvent*" + } + ], + "index": 15, + "name": "leftPressed", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "event", + "type": "QQuickKeyEvent*" + } + ], + "index": 16, + "name": "rightPressed", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "event", + "type": "QQuickKeyEvent*" + } + ], + "index": 17, + "name": "upPressed", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "event", + "type": "QQuickKeyEvent*" + } + ], + "index": 18, + "name": "downPressed", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "event", + "type": "QQuickKeyEvent*" + } + ], + "index": 19, + "name": "tabPressed", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "event", + "type": "QQuickKeyEvent*" + } + ], + "index": 20, + "name": "backtabPressed", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "event", + "type": "QQuickKeyEvent*" + } + ], + "index": 21, + "name": "asteriskPressed", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "event", + "type": "QQuickKeyEvent*" + } + ], + "index": 22, + "name": "numberSignPressed", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "event", + "type": "QQuickKeyEvent*" + } + ], + "index": 23, + "name": "escapePressed", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "event", + "type": "QQuickKeyEvent*" + } + ], + "index": 24, + "name": "returnPressed", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "event", + "type": "QQuickKeyEvent*" + } + ], + "index": 25, + "name": "enterPressed", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "event", + "type": "QQuickKeyEvent*" + } + ], + "index": 26, + "name": "deletePressed", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "event", + "type": "QQuickKeyEvent*" + } + ], + "index": 27, + "name": "spacePressed", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "event", + "type": "QQuickKeyEvent*" + } + ], + "index": 28, + "name": "backPressed", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "event", + "type": "QQuickKeyEvent*" + } + ], + "index": 29, + "name": "cancelPressed", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "event", + "type": "QQuickKeyEvent*" + } + ], + "index": 30, + "name": "selectPressed", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "event", + "type": "QQuickKeyEvent*" + } + ], + "index": 31, + "name": "yesPressed", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "event", + "type": "QQuickKeyEvent*" + } + ], + "index": 32, + "name": "noPressed", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "event", + "type": "QQuickKeyEvent*" + } + ], + "index": 33, + "name": "context1Pressed", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "event", + "type": "QQuickKeyEvent*" + } + ], + "index": 34, + "name": "context2Pressed", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "event", + "type": "QQuickKeyEvent*" + } + ], + "index": 35, + "name": "context3Pressed", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "event", + "type": "QQuickKeyEvent*" + } + ], + "index": 36, + "name": "context4Pressed", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "event", + "type": "QQuickKeyEvent*" + } + ], + "index": 37, + "name": "callPressed", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "event", + "type": "QQuickKeyEvent*" + } + ], + "index": 38, + "name": "hangupPressed", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "event", + "type": "QQuickKeyEvent*" + } + ], + "index": 39, + "name": "flipPressed", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "event", + "type": "QQuickKeyEvent*" + } + ], + "index": 40, + "name": "menuPressed", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "event", + "type": "QQuickKeyEvent*" + } + ], + "index": 41, + "name": "volumeUpPressed", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "event", + "type": "QQuickKeyEvent*" + } + ], + "index": 42, + "name": "volumeDownPressed", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QQuickItemKeyFilter" + } + ] + } + ], + "inputFile": "qquickitem_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "ParentAnimation" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickParentAnimation", + "lineNumber": 25, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "target", + "notify": "targetChanged", + "read": "target", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false, + "write": "setTargetObject" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "newParent", + "notify": "newParentChanged", + "read": "newParent", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false, + "write": "setNewParent" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "via", + "notify": "viaChanged", + "read": "via", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false, + "write": "setVia" + } + ], + "qualifiedClassName": "QQuickParentAnimation", + "signals": [ + { + "access": "public", + "index": 0, + "name": "targetChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "newParentChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "viaChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickAnimationGroup" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "AnchorAnimation" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickAnchorAnimation", + "lineNumber": 61, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "targets", + "read": "targets", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlListProperty", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "duration", + "notify": "durationChanged", + "read": "duration", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setDuration" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "easing", + "notify": "easingChanged", + "read": "easing", + "required": false, + "scriptable": true, + "stored": true, + "type": "QEasingCurve", + "user": false, + "write": "setEasing" + } + ], + "qualifiedClassName": "QQuickAnchorAnimation", + "signals": [ + { + "access": "public", + "arguments": [ + { + "type": "int" + } + ], + "index": 0, + "name": "durationChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QEasingCurve" + } + ], + "index": 1, + "name": "easingChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickAbstractAnimation" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "PathAnimation" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickPathAnimation", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "Orientation", + "values": [ + "Fixed", + "RightFirst", + "LeftFirst", + "BottomFirst", + "TopFirst" + ] + } + ], + "lineNumber": 98, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "duration", + "notify": "durationChanged", + "read": "duration", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setDuration" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "easing", + "notify": "easingChanged", + "read": "easing", + "required": false, + "scriptable": true, + "stored": true, + "type": "QEasingCurve", + "user": false, + "write": "setEasing" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "path", + "notify": "pathChanged", + "read": "path", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickPath*", + "user": false, + "write": "setPath" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "target", + "notify": "targetChanged", + "read": "target", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false, + "write": "setTargetObject" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "orientation", + "notify": "orientationChanged", + "read": "orientation", + "required": false, + "scriptable": true, + "stored": true, + "type": "Orientation", + "user": false, + "write": "setOrientation" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "anchorPoint", + "notify": "anchorPointChanged", + "read": "anchorPoint", + "required": false, + "scriptable": true, + "stored": true, + "type": "QPointF", + "user": false, + "write": "setAnchorPoint" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "orientationEntryDuration", + "notify": "orientationEntryDurationChanged", + "read": "orientationEntryDuration", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setOrientationEntryDuration" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 7, + "name": "orientationExitDuration", + "notify": "orientationExitDurationChanged", + "read": "orientationExitDuration", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setOrientationExitDuration" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 8, + "name": "endRotation", + "notify": "endRotationChanged", + "read": "endRotation", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setEndRotation" + } + ], + "qualifiedClassName": "QQuickPathAnimation", + "signals": [ + { + "access": "public", + "arguments": [ + { + "type": "int" + } + ], + "index": 0, + "name": "durationChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QEasingCurve" + } + ], + "index": 1, + "name": "easingChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "pathChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "targetChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "Orientation" + } + ], + "index": 4, + "name": "orientationChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QPointF" + } + ], + "index": 5, + "name": "anchorPointChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "qreal" + } + ], + "index": 6, + "name": "orientationEntryDurationChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "qreal" + } + ], + "index": 7, + "name": "orientationExitDurationChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "qreal" + } + ], + "index": 8, + "name": "endRotationChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickAbstractAnimation" + } + ] + } + ], + "inputFile": "qquickitemanimation_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickItemGrabResult", + "lineNumber": 21, + "methods": [ + { + "access": "public", + "arguments": [ + { + "name": "fileName", + "type": "QString" + } + ], + "index": 3, + "name": "saveToFile", + "returnType": "bool" + }, + { + "access": "public", + "arguments": [ + { + "name": "fileName", + "type": "QUrl" + } + ], + "index": 4, + "name": "saveToFile", + "returnType": "bool", + "revision": 1538 + } + ], + "object": true, + "properties": [ + { + "constant": true, + "designable": true, + "final": false, + "index": 0, + "name": "image", + "read": "image", + "required": false, + "scriptable": true, + "stored": true, + "type": "QImage", + "user": false + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 1, + "name": "url", + "read": "url", + "required": false, + "scriptable": true, + "stored": true, + "type": "QUrl", + "user": false + } + ], + "qualifiedClassName": "QQuickItemGrabResult", + "signals": [ + { + "access": "public", + "index": 0, + "name": "ready", + "returnType": "void" + } + ], + "slots": [ + { + "access": "private", + "index": 1, + "name": "setup", + "returnType": "void" + }, + { + "access": "private", + "index": 2, + "name": "render", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qquickitemgrabresult.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Foreign", + "value": "QInputDevice" + }, + { + "name": "QML.Element", + "value": "InputDevice" + }, + { + "name": "QML.AddedInVersion", + "value": "1536" + }, + { + "name": "QML.Creatable", + "value": "false" + }, + { + "name": "QML.UncreatableReason", + "value": "InputDevice is only available via read-only properties." + } + ], + "className": "QInputDeviceForeign", + "gadget": true, + "lineNumber": 31, + "qualifiedClassName": "QInputDeviceForeign" + }, + { + "classInfos": [ + { + "name": "QML.Foreign", + "value": "QPointingDevice" + }, + { + "name": "QML.Element", + "value": "PointerDevice" + }, + { + "name": "QML.AddedInVersion", + "value": "524" + }, + { + "name": "QML.Creatable", + "value": "false" + }, + { + "name": "QML.UncreatableReason", + "value": "PointerDevice is only available via read-only properties." + } + ], + "className": "QPointingDeviceForeign", + "gadget": true, + "lineNumber": 40, + "qualifiedClassName": "QPointingDeviceForeign" + }, + { + "classInfos": [ + { + "name": "QML.Foreign", + "value": "QPointingDeviceUniqueId" + }, + { + "name": "QML.Element", + "value": "pointingDeviceUniqueId" + }, + { + "name": "QML.AddedInVersion", + "value": "521" + }, + { + "name": "QML.Creatable", + "value": "false" + }, + { + "name": "QML.UncreatableReason", + "value": "pointingDeviceUniqueId cannot be created in QML." + } + ], + "className": "QPointingDeviceUniqueIdForeign", + "gadget": true, + "lineNumber": 49, + "qualifiedClassName": "QPointingDeviceUniqueIdForeign" + } + ], + "inputFile": "qquickitemsmodule_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "ItemView" + }, + { + "name": "QML.Creatable", + "value": "false" + }, + { + "name": "QML.UncreatableReason", + "value": "ItemView is an abstract base class." + }, + { + "name": "QML.AddedInVersion", + "value": "513" + } + ], + "className": "QQuickItemView", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "LayoutDirection", + "values": [ + "LeftToRight", + "RightToLeft", + "VerticalTopToBottom", + "VerticalBottomToTop" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "VerticalLayoutDirection", + "values": [ + "TopToBottom", + "BottomToTop" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "HighlightRangeMode", + "values": [ + "NoHighlightRange", + "ApplyRange", + "StrictlyEnforceRange" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "PositionMode", + "values": [ + "Beginning", + "Center", + "End", + "Visible", + "Contain", + "SnapPosition" + ] + } + ], + "lineNumber": 34, + "methods": [ + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + }, + { + "name": "mode", + "type": "int" + } + ], + "index": 42, + "name": "positionViewAtIndex", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "x", + "type": "qreal" + }, + { + "name": "y", + "type": "qreal" + } + ], + "index": 43, + "name": "indexAt", + "returnType": "int" + }, + { + "access": "public", + "arguments": [ + { + "name": "x", + "type": "qreal" + }, + { + "name": "y", + "type": "qreal" + } + ], + "index": 44, + "name": "itemAt", + "returnType": "QQuickItem*" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + } + ], + "index": 45, + "name": "itemAtIndex", + "returnType": "QQuickItem*", + "revision": 525 + }, + { + "access": "public", + "index": 46, + "name": "positionViewAtBeginning", + "returnType": "void" + }, + { + "access": "public", + "index": 47, + "name": "positionViewAtEnd", + "returnType": "void" + }, + { + "access": "public", + "index": 48, + "name": "forceLayout", + "returnType": "void", + "revision": 513 + } + ], + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "model", + "notify": "modelChanged", + "read": "model", + "required": false, + "scriptable": true, + "stored": true, + "type": "QVariant", + "user": false, + "write": "setModel" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "delegate", + "notify": "delegateChanged", + "read": "delegate", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlComponent*", + "user": false, + "write": "setDelegate" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "count", + "notify": "countChanged", + "read": "count", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "currentIndex", + "notify": "currentIndexChanged", + "read": "currentIndex", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setCurrentIndex" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "currentItem", + "notify": "currentItemChanged", + "read": "currentItem", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "keyNavigationWraps", + "notify": "keyNavigationWrapsChanged", + "read": "isWrapEnabled", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setWrapEnabled" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "keyNavigationEnabled", + "notify": "keyNavigationEnabledChanged", + "read": "isKeyNavigationEnabled", + "required": false, + "revision": 519, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setKeyNavigationEnabled" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 7, + "name": "cacheBuffer", + "notify": "cacheBufferChanged", + "read": "cacheBuffer", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setCacheBuffer" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 8, + "name": "displayMarginBeginning", + "notify": "displayMarginBeginningChanged", + "read": "displayMarginBeginning", + "required": false, + "revision": 515, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setDisplayMarginBeginning" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 9, + "name": "displayMarginEnd", + "notify": "displayMarginEndChanged", + "read": "displayMarginEnd", + "required": false, + "revision": 515, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setDisplayMarginEnd" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 10, + "name": "layoutDirection", + "notify": "layoutDirectionChanged", + "read": "layoutDirection", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::LayoutDirection", + "user": false, + "write": "setLayoutDirection" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 11, + "name": "effectiveLayoutDirection", + "notify": "effectiveLayoutDirectionChanged", + "read": "effectiveLayoutDirection", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::LayoutDirection", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 12, + "name": "verticalLayoutDirection", + "notify": "verticalLayoutDirectionChanged", + "read": "verticalLayoutDirection", + "required": false, + "scriptable": true, + "stored": true, + "type": "VerticalLayoutDirection", + "user": false, + "write": "setVerticalLayoutDirection" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 13, + "name": "header", + "notify": "headerChanged", + "read": "header", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlComponent*", + "user": false, + "write": "setHeader" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 14, + "name": "headerItem", + "notify": "headerItemChanged", + "read": "headerItem", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 15, + "name": "footer", + "notify": "footerChanged", + "read": "footer", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlComponent*", + "user": false, + "write": "setFooter" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 16, + "name": "footerItem", + "notify": "footerItemChanged", + "read": "footerItem", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 17, + "name": "populate", + "notify": "populateTransitionChanged", + "read": "populateTransition", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickTransition*", + "user": false, + "write": "setPopulateTransition" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 18, + "name": "add", + "notify": "addTransitionChanged", + "read": "addTransition", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickTransition*", + "user": false, + "write": "setAddTransition" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 19, + "name": "addDisplaced", + "notify": "addDisplacedTransitionChanged", + "read": "addDisplacedTransition", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickTransition*", + "user": false, + "write": "setAddDisplacedTransition" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 20, + "name": "move", + "notify": "moveTransitionChanged", + "read": "moveTransition", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickTransition*", + "user": false, + "write": "setMoveTransition" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 21, + "name": "moveDisplaced", + "notify": "moveDisplacedTransitionChanged", + "read": "moveDisplacedTransition", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickTransition*", + "user": false, + "write": "setMoveDisplacedTransition" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 22, + "name": "remove", + "notify": "removeTransitionChanged", + "read": "removeTransition", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickTransition*", + "user": false, + "write": "setRemoveTransition" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 23, + "name": "removeDisplaced", + "notify": "removeDisplacedTransitionChanged", + "read": "removeDisplacedTransition", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickTransition*", + "user": false, + "write": "setRemoveDisplacedTransition" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 24, + "name": "displaced", + "notify": "displacedTransitionChanged", + "read": "displacedTransition", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickTransition*", + "user": false, + "write": "setDisplacedTransition" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 25, + "name": "highlight", + "notify": "highlightChanged", + "read": "highlight", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlComponent*", + "user": false, + "write": "setHighlight" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 26, + "name": "highlightItem", + "notify": "highlightItemChanged", + "read": "highlightItem", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 27, + "name": "highlightFollowsCurrentItem", + "notify": "highlightFollowsCurrentItemChanged", + "read": "highlightFollowsCurrentItem", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setHighlightFollowsCurrentItem" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 28, + "name": "highlightRangeMode", + "notify": "highlightRangeModeChanged", + "read": "highlightRangeMode", + "required": false, + "scriptable": true, + "stored": true, + "type": "HighlightRangeMode", + "user": false, + "write": "setHighlightRangeMode" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 29, + "name": "preferredHighlightBegin", + "notify": "preferredHighlightBeginChanged", + "read": "preferredHighlightBegin", + "required": false, + "reset": "resetPreferredHighlightBegin", + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setPreferredHighlightBegin" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 30, + "name": "preferredHighlightEnd", + "notify": "preferredHighlightEndChanged", + "read": "preferredHighlightEnd", + "required": false, + "reset": "resetPreferredHighlightEnd", + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setPreferredHighlightEnd" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 31, + "name": "highlightMoveDuration", + "notify": "highlightMoveDurationChanged", + "read": "highlightMoveDuration", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setHighlightMoveDuration" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 32, + "name": "reuseItems", + "notify": "reuseItemsChanged", + "read": "reuseItems", + "required": false, + "revision": 527, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setReuseItems" + } + ], + "qualifiedClassName": "QQuickItemView", + "signals": [ + { + "access": "public", + "index": 0, + "name": "modelChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "delegateChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "countChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "currentIndexChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "currentItemChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "keyNavigationWrapsChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "keyNavigationEnabledChanged", + "returnType": "void", + "revision": 519 + }, + { + "access": "public", + "index": 7, + "name": "cacheBufferChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 8, + "name": "displayMarginBeginningChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 9, + "name": "displayMarginEndChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 10, + "name": "layoutDirectionChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 11, + "name": "effectiveLayoutDirectionChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 12, + "name": "verticalLayoutDirectionChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 13, + "name": "headerChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 14, + "name": "footerChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 15, + "name": "headerItemChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 16, + "name": "footerItemChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 17, + "name": "populateTransitionChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 18, + "name": "addTransitionChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 19, + "name": "addDisplacedTransitionChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 20, + "name": "moveTransitionChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 21, + "name": "moveDisplacedTransitionChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 22, + "name": "removeTransitionChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 23, + "name": "removeDisplacedTransitionChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 24, + "name": "displacedTransitionChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 25, + "name": "highlightChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 26, + "name": "highlightItemChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 27, + "name": "highlightFollowsCurrentItemChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 28, + "name": "highlightRangeModeChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 29, + "name": "preferredHighlightBeginChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 30, + "name": "preferredHighlightEndChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 31, + "name": "highlightMoveDurationChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 32, + "name": "reuseItemsChanged", + "returnType": "void", + "revision": 527 + } + ], + "slots": [ + { + "access": "protected", + "index": 33, + "name": "destroyRemoved", + "returnType": "void" + }, + { + "access": "protected", + "arguments": [ + { + "name": "index", + "type": "int" + }, + { + "name": "item", + "type": "QObject*" + } + ], + "index": 34, + "name": "createdItem", + "returnType": "void" + }, + { + "access": "protected", + "arguments": [ + { + "name": "index", + "type": "int" + }, + { + "name": "item", + "type": "QObject*" + } + ], + "index": 35, + "name": "initItem", + "returnType": "void" + }, + { + "access": "protected", + "arguments": [ + { + "name": "changeSet", + "type": "QQmlChangeSet" + }, + { + "name": "reset", + "type": "bool" + } + ], + "index": 36, + "name": "modelUpdated", + "returnType": "void" + }, + { + "access": "protected", + "arguments": [ + { + "name": "item", + "type": "QObject*" + } + ], + "index": 37, + "name": "destroyingItem", + "returnType": "void" + }, + { + "access": "protected", + "arguments": [ + { + "name": "modelIndex", + "type": "int" + }, + { + "name": "object", + "type": "QObject*" + } + ], + "index": 38, + "name": "onItemPooled", + "returnType": "void", + "revision": 527 + }, + { + "access": "protected", + "arguments": [ + { + "name": "modelIndex", + "type": "int" + }, + { + "name": "object", + "type": "QObject*" + } + ], + "index": 39, + "name": "onItemReused", + "returnType": "void", + "revision": 527 + }, + { + "access": "protected", + "index": 40, + "name": "animStopped", + "returnType": "void" + }, + { + "access": "protected", + "index": 41, + "name": "trackedPositionChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickFlickable" + } + ] + }, + { + "className": "QQuickItemViewAttached", + "lineNumber": 286, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "isCurrentItem", + "notify": "currentItemChanged", + "read": "isCurrentItem", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "delayRemove", + "notify": "delayRemoveChanged", + "read": "delayRemove", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setDelayRemove" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "section", + "notify": "sectionChanged", + "read": "section", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "previousSection", + "notify": "prevSectionChanged", + "read": "prevSection", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "nextSection", + "notify": "nextSectionChanged", + "read": "nextSection", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + } + ], + "qualifiedClassName": "QQuickItemViewAttached", + "signals": [ + { + "access": "public", + "index": 0, + "name": "viewChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "currentItemChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "delayRemoveChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "add", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "remove", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "sectionChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "prevSectionChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "nextSectionChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 8, + "name": "pooled", + "returnType": "void" + }, + { + "access": "public", + "index": 9, + "name": "reused", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qquickitemview_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "ViewTransition" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + }, + { + "name": "QML.Creatable", + "value": "false" + }, + { + "name": "QML.UncreatableReason", + "value": "ViewTransition is only available via attached properties." + }, + { + "name": "QML.Attached", + "value": "QQuickViewTransitionAttached" + } + ], + "className": "QQuickViewTransitionAttached", + "lineNumber": 153, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "index", + "notify": "indexChanged", + "read": "index", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "item", + "notify": "itemChanged", + "read": "item", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "destination", + "notify": "destinationChanged", + "read": "destination", + "required": false, + "scriptable": true, + "stored": true, + "type": "QPointF", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "targetIndexes", + "notify": "targetIndexesChanged", + "read": "targetIndexes", + "required": false, + "scriptable": true, + "stored": true, + "type": "QList", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "targetItems", + "notify": "targetItemsChanged", + "read": "targetItems", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlListProperty", + "user": false + } + ], + "qualifiedClassName": "QQuickViewTransitionAttached", + "signals": [ + { + "access": "public", + "index": 0, + "name": "indexChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "itemChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "destinationChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "targetIndexesChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "targetItemsChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qquickitemviewtransition_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "ViewSection" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickViewSection", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "SectionCriteria", + "values": [ + "FullString", + "FirstCharacter" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "LabelPositioning", + "values": [ + "InlineLabels", + "CurrentLabelAtStart", + "NextLabelAtEnd" + ] + } + ], + "lineNumber": 32, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "property", + "notify": "propertyChanged", + "read": "property", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setProperty" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "criteria", + "notify": "criteriaChanged", + "read": "criteria", + "required": false, + "scriptable": true, + "stored": true, + "type": "SectionCriteria", + "user": false, + "write": "setCriteria" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "delegate", + "notify": "delegateChanged", + "read": "delegate", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlComponent*", + "user": false, + "write": "setDelegate" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "labelPositioning", + "notify": "labelPositioningChanged", + "read": "labelPositioning", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setLabelPositioning" + } + ], + "qualifiedClassName": "QQuickViewSection", + "signals": [ + { + "access": "public", + "index": 0, + "name": "sectionsChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "propertyChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "criteriaChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "delegateChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "labelPositioningChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "classInfos": [ + { + "name": "DefaultProperty", + "value": "data" + }, + { + "name": "QML.Element", + "value": "ListView" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + }, + { + "name": "QML.Attached", + "value": "QQuickListViewAttached" + } + ], + "className": "QQuickListView", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "Orientation", + "values": [ + "Horizontal", + "Vertical" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "SnapMode", + "values": [ + "NoSnap", + "SnapToItem", + "SnapOneItem" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "HeaderPositioning", + "values": [ + "InlineHeader", + "OverlayHeader", + "PullBackHeader" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "FooterPositioning", + "values": [ + "InlineFooter", + "OverlayFooter", + "PullBackFooter" + ] + } + ], + "lineNumber": 80, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "highlightMoveVelocity", + "notify": "highlightMoveVelocityChanged", + "read": "highlightMoveVelocity", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setHighlightMoveVelocity" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "highlightResizeVelocity", + "notify": "highlightResizeVelocityChanged", + "read": "highlightResizeVelocity", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setHighlightResizeVelocity" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "highlightResizeDuration", + "notify": "highlightResizeDurationChanged", + "read": "highlightResizeDuration", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setHighlightResizeDuration" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "spacing", + "notify": "spacingChanged", + "read": "spacing", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setSpacing" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "orientation", + "notify": "orientationChanged", + "read": "orientation", + "required": false, + "scriptable": true, + "stored": true, + "type": "Orientation", + "user": false, + "write": "setOrientation" + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 5, + "name": "section", + "read": "sectionCriteria", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickViewSection*", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "currentSection", + "notify": "currentSectionChanged", + "read": "currentSection", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 7, + "name": "snapMode", + "notify": "snapModeChanged", + "read": "snapMode", + "required": false, + "scriptable": true, + "stored": true, + "type": "SnapMode", + "user": false, + "write": "setSnapMode" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 8, + "name": "headerPositioning", + "notify": "headerPositioningChanged", + "read": "headerPositioning", + "required": false, + "revision": 516, + "scriptable": true, + "stored": true, + "type": "HeaderPositioning", + "user": false, + "write": "setHeaderPositioning" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 9, + "name": "footerPositioning", + "notify": "footerPositioningChanged", + "read": "footerPositioning", + "required": false, + "revision": 516, + "scriptable": true, + "stored": true, + "type": "FooterPositioning", + "user": false, + "write": "setFooterPositioning" + } + ], + "qualifiedClassName": "QQuickListView", + "signals": [ + { + "access": "public", + "index": 0, + "name": "spacingChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "orientationChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "currentSectionChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "highlightMoveVelocityChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "highlightResizeVelocityChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "highlightResizeDurationChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "snapModeChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "headerPositioningChanged", + "returnType": "void", + "revision": 516 + }, + { + "access": "public", + "index": 8, + "name": "footerPositioningChanged", + "returnType": "void", + "revision": 516 + } + ], + "slots": [ + { + "access": "public", + "index": 9, + "name": "incrementCurrentIndex", + "returnType": "void" + }, + { + "access": "public", + "index": 10, + "name": "decrementCurrentIndex", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickItemView" + } + ] + }, + { + "className": "QQuickListViewAttached", + "lineNumber": 174, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "view", + "notify": "viewChanged", + "read": "view", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickListView*", + "user": false + } + ], + "qualifiedClassName": "QQuickListViewAttached", + "superClasses": [ + { + "access": "public", + "name": "QQuickItemViewAttached" + } + ] + } + ], + "inputFile": "qquicklistview_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "Loader" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickLoader", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "Status", + "values": [ + "Null", + "Ready", + "Loading", + "Error" + ] + } + ], + "lineNumber": 23, + "methods": [ + { + "access": "public", + "arguments": [ + { + "name": "source", + "type": "QUrl" + }, + { + "name": "initialProperties", + "type": "QJSValue" + } + ], + "index": 10, + "name": "setSource", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "source", + "type": "QUrl" + } + ], + "index": 11, + "name": "setSource", + "returnType": "void" + } + ], + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "active", + "notify": "activeChanged", + "read": "active", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setActive" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "source", + "notify": "sourceChanged", + "read": "source", + "required": false, + "scriptable": true, + "stored": true, + "type": "QUrl", + "user": false, + "write": "setSourceWithoutResolve" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "sourceComponent", + "notify": "sourceComponentChanged", + "read": "sourceComponent", + "required": false, + "reset": "resetSourceComponent", + "scriptable": true, + "stored": true, + "type": "QQmlComponent*", + "user": false, + "write": "setSourceComponent" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "item", + "notify": "itemChanged", + "read": "item", + "required": false, + "scriptable": true, + "stored": true, + "type": "QObject*", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "status", + "notify": "statusChanged", + "read": "status", + "required": false, + "scriptable": true, + "stored": true, + "type": "Status", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "progress", + "notify": "progressChanged", + "read": "progress", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "asynchronous", + "notify": "asynchronousChanged", + "read": "asynchronous", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setAsynchronous" + } + ], + "qualifiedClassName": "QQuickLoader", + "signals": [ + { + "access": "public", + "index": 0, + "name": "itemChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "activeChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "sourceChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "sourceComponentChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "statusChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "progressChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "loaded", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "asynchronousChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "private", + "index": 8, + "name": "_q_sourceLoaded", + "returnType": "void" + }, + { + "access": "private", + "index": 9, + "name": "_q_updateSize", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickImplicitSizeItem" + } + ] + } + ], + "inputFile": "qquickloader_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "MouseArea" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickMouseArea", + "lineNumber": 29, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "mouseX", + "notify": "mouseXChanged", + "read": "mouseX", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "mouseY", + "notify": "mouseYChanged", + "read": "mouseY", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "containsMouse", + "notify": "hoveredChanged", + "read": "hovered", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "pressed", + "notify": "pressedChanged", + "read": "isPressed", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "enabled", + "notify": "enabledChanged", + "read": "isEnabled", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setEnabled" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "scrollGestureEnabled", + "notify": "scrollGestureEnabledChanged", + "read": "isScrollGestureEnabled", + "required": false, + "revision": 517, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setScrollGestureEnabled" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "pressedButtons", + "notify": "pressedButtonsChanged", + "read": "pressedButtons", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::MouseButtons", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 7, + "name": "acceptedButtons", + "notify": "acceptedButtonsChanged", + "read": "acceptedButtons", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::MouseButtons", + "user": false, + "write": "setAcceptedButtons" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 8, + "name": "hoverEnabled", + "notify": "hoverEnabledChanged", + "read": "hoverEnabled", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setHoverEnabled" + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 9, + "name": "drag", + "read": "drag", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickDrag*", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 10, + "name": "preventStealing", + "notify": "preventStealingChanged", + "read": "preventStealing", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setPreventStealing" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 11, + "name": "propagateComposedEvents", + "notify": "propagateComposedEventsChanged", + "read": "propagateComposedEvents", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setPropagateComposedEvents" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 12, + "name": "cursorShape", + "notify": "cursorShapeChanged", + "read": "cursorShape", + "required": false, + "reset": "unsetCursor", + "scriptable": true, + "stored": true, + "type": "Qt::CursorShape", + "user": false, + "write": "setCursorShape" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 13, + "name": "containsPress", + "notify": "containsPressChanged", + "read": "containsPress", + "required": false, + "revision": 516, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 14, + "name": "pressAndHoldInterval", + "notify": "pressAndHoldIntervalChanged", + "read": "pressAndHoldInterval", + "required": false, + "reset": "resetPressAndHoldInterval", + "revision": 521, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setPressAndHoldInterval" + } + ], + "qualifiedClassName": "QQuickMouseArea", + "signals": [ + { + "access": "public", + "index": 0, + "name": "hoveredChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "pressedChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "enabledChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "scrollGestureEnabledChanged", + "returnType": "void", + "revision": 517 + }, + { + "access": "public", + "index": 4, + "name": "pressedButtonsChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "acceptedButtonsChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "hoverEnabledChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "cursorShapeChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "mouse", + "type": "QQuickMouseEvent*" + } + ], + "index": 8, + "name": "positionChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "mouse", + "type": "QQuickMouseEvent*" + } + ], + "index": 9, + "name": "mouseXChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "mouse", + "type": "QQuickMouseEvent*" + } + ], + "index": 10, + "name": "mouseYChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 11, + "name": "preventStealingChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 12, + "name": "propagateComposedEventsChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "mouse", + "type": "QQuickMouseEvent*" + } + ], + "index": 13, + "name": "pressed", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "mouse", + "type": "QQuickMouseEvent*" + } + ], + "index": 14, + "name": "pressAndHold", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "mouse", + "type": "QQuickMouseEvent*" + } + ], + "index": 15, + "name": "released", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "mouse", + "type": "QQuickMouseEvent*" + } + ], + "index": 16, + "name": "clicked", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "mouse", + "type": "QQuickMouseEvent*" + } + ], + "index": 17, + "name": "doubleClicked", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "wheel", + "type": "QQuickWheelEvent*" + } + ], + "index": 18, + "name": "wheel", + "returnType": "void" + }, + { + "access": "public", + "index": 19, + "name": "entered", + "returnType": "void" + }, + { + "access": "public", + "index": 20, + "name": "exited", + "returnType": "void" + }, + { + "access": "public", + "index": 21, + "name": "canceled", + "returnType": "void" + }, + { + "access": "public", + "index": 22, + "name": "containsPressChanged", + "returnType": "void", + "revision": 516 + }, + { + "access": "public", + "index": 23, + "name": "pressAndHoldIntervalChanged", + "returnType": "void", + "revision": 521 + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickItem" + } + ] + } + ], + "inputFile": "qquickmousearea_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQuickMultiPointHandler", + "lineNumber": 28, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "minimumPointCount", + "notify": "minimumPointCountChanged", + "read": "minimumPointCount", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setMinimumPointCount" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "maximumPointCount", + "notify": "maximumPointCountChanged", + "read": "maximumPointCount", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setMaximumPointCount" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "centroid", + "notify": "centroidChanged", + "read": "centroid", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickHandlerPoint", + "user": false + } + ], + "qualifiedClassName": "QQuickMultiPointHandler", + "signals": [ + { + "access": "public", + "index": 0, + "name": "minimumPointCountChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "maximumPointCountChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "centroidChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickPointerDeviceHandler" + } + ] + } + ], + "inputFile": "qquickmultipointhandler_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "TouchPoint" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickTouchPoint", + "lineNumber": 33, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "pointId", + "notify": "pointIdChanged", + "read": "pointId", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "uniqueId", + "notify": "uniqueIdChanged", + "read": "uniqueId", + "required": false, + "revision": 521, + "scriptable": true, + "stored": true, + "type": "QPointingDeviceUniqueId", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "pressed", + "notify": "pressedChanged", + "read": "pressed", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "x", + "notify": "xChanged", + "read": "x", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "y", + "notify": "yChanged", + "read": "y", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "ellipseDiameters", + "notify": "ellipseDiametersChanged", + "read": "ellipseDiameters", + "required": false, + "revision": 521, + "scriptable": true, + "stored": true, + "type": "QSizeF", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "pressure", + "notify": "pressureChanged", + "read": "pressure", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 7, + "name": "rotation", + "notify": "rotationChanged", + "read": "rotation", + "required": false, + "revision": 521, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 8, + "name": "velocity", + "notify": "velocityChanged", + "read": "velocity", + "required": false, + "scriptable": true, + "stored": true, + "type": "QVector2D", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 9, + "name": "area", + "notify": "areaChanged", + "read": "area", + "required": false, + "scriptable": true, + "stored": true, + "type": "QRectF", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 10, + "name": "startX", + "notify": "startXChanged", + "read": "startX", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 11, + "name": "startY", + "notify": "startYChanged", + "read": "startY", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 12, + "name": "previousX", + "notify": "previousXChanged", + "read": "previousX", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 13, + "name": "previousY", + "notify": "previousYChanged", + "read": "previousY", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 14, + "name": "sceneX", + "notify": "sceneXChanged", + "read": "sceneX", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 15, + "name": "sceneY", + "notify": "sceneYChanged", + "read": "sceneY", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + } + ], + "qualifiedClassName": "QQuickTouchPoint", + "signals": [ + { + "access": "public", + "index": 0, + "name": "pressedChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "pointIdChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "uniqueIdChanged", + "returnType": "void", + "revision": 521 + }, + { + "access": "public", + "index": 3, + "name": "xChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "yChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "ellipseDiametersChanged", + "returnType": "void", + "revision": 521 + }, + { + "access": "public", + "index": 6, + "name": "pressureChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "rotationChanged", + "returnType": "void", + "revision": 521 + }, + { + "access": "public", + "index": 8, + "name": "velocityChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 9, + "name": "areaChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 10, + "name": "startXChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 11, + "name": "startYChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 12, + "name": "previousXChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 13, + "name": "previousYChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 14, + "name": "sceneXChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 15, + "name": "sceneYChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "GestureEvent" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + }, + { + "name": "QML.Creatable", + "value": "false" + }, + { + "name": "QML.UncreatableReason", + "value": "GestureEvent is only available in the context of handling the gestureStarted signal from MultiPointTouchArea." + } + ], + "className": "QQuickGrabGestureEvent", + "lineNumber": 152, + "methods": [ + { + "access": "public", + "index": 0, + "name": "grab", + "returnType": "void" + } + ], + "object": true, + "properties": [ + { + "constant": true, + "designable": true, + "final": true, + "index": 0, + "name": "touchPoints", + "read": "touchPoints", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlListProperty", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 1, + "name": "dragThreshold", + "read": "dragThreshold", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + } + ], + "qualifiedClassName": "QQuickGrabGestureEvent", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "MultiPointTouchArea" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickMultiPointTouchArea", + "lineNumber": 179, + "object": true, + "properties": [ + { + "constant": true, + "designable": true, + "final": false, + "index": 0, + "name": "touchPoints", + "read": "touchPoints", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlListProperty", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "minimumTouchPoints", + "notify": "minimumTouchPointsChanged", + "read": "minimumTouchPoints", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setMinimumTouchPoints" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "maximumTouchPoints", + "notify": "maximumTouchPointsChanged", + "read": "maximumTouchPoints", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setMaximumTouchPoints" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "mouseEnabled", + "notify": "mouseEnabledChanged", + "read": "mouseEnabled", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setMouseEnabled" + } + ], + "qualifiedClassName": "QQuickMultiPointTouchArea", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "touchPoints", + "type": "QList" + } + ], + "index": 0, + "name": "pressed", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "touchPoints", + "type": "QList" + } + ], + "index": 1, + "name": "updated", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "touchPoints", + "type": "QList" + } + ], + "index": 2, + "name": "released", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "touchPoints", + "type": "QList" + } + ], + "index": 3, + "name": "canceled", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "gesture", + "type": "QQuickGrabGestureEvent*" + } + ], + "index": 4, + "name": "gestureStarted", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "touchPoints", + "type": "QList" + } + ], + "index": 5, + "name": "touchUpdated", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "minimumTouchPointsChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "maximumTouchPointsChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 8, + "name": "mouseEnabledChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickItem" + } + ] + } + ], + "inputFile": "qquickmultipointtoucharea_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "PaintedItem" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + }, + { + "name": "QML.Creatable", + "value": "false" + }, + { + "name": "QML.UncreatableReason", + "value": "Cannot create instance of abstract class PaintedItem." + } + ], + "className": "QQuickPaintedItem", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "RenderTarget", + "values": [ + "Image", + "FramebufferObject", + "InvertedYFramebufferObject" + ] + }, + { + "alias": "PerformanceHint", + "isClass": false, + "isFlag": true, + "name": "PerformanceHints", + "values": [ + "FastFBOResizing" + ] + } + ], + "lineNumber": 13, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "contentsSize", + "notify": "contentsSizeChanged", + "read": "contentsSize", + "required": false, + "scriptable": true, + "stored": true, + "type": "QSize", + "user": false, + "write": "setContentsSize" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "fillColor", + "notify": "fillColorChanged", + "read": "fillColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false, + "write": "setFillColor" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "contentsScale", + "notify": "contentsScaleChanged", + "read": "contentsScale", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setContentsScale" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "renderTarget", + "notify": "renderTargetChanged", + "read": "renderTarget", + "required": false, + "scriptable": true, + "stored": true, + "type": "RenderTarget", + "user": false, + "write": "setRenderTarget" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "textureSize", + "notify": "textureSizeChanged", + "read": "textureSize", + "required": false, + "scriptable": true, + "stored": true, + "type": "QSize", + "user": false, + "write": "setTextureSize" + } + ], + "qualifiedClassName": "QQuickPaintedItem", + "signals": [ + { + "access": "public", + "index": 0, + "name": "fillColorChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "contentsSizeChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "contentsScaleChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "renderTargetChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "textureSizeChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "private", + "index": 5, + "name": "invalidateSceneGraph", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickItem" + } + ] + } + ], + "inputFile": "qquickpainteditem.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "Palette" + }, + { + "name": "QML.AddedInVersion", + "value": "1536" + } + ], + "className": "QQuickPalette", + "lineNumber": 27, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "active", + "notify": "activeChanged", + "read": "active", + "required": false, + "reset": "resetActive", + "scriptable": true, + "stored": true, + "type": "QQuickColorGroup*", + "user": false, + "write": "setActive" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "inactive", + "notify": "inactiveChanged", + "read": "inactive", + "required": false, + "reset": "resetInactive", + "scriptable": true, + "stored": true, + "type": "QQuickColorGroup*", + "user": false, + "write": "setInactive" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "disabled", + "notify": "disabledChanged", + "read": "disabled", + "required": false, + "reset": "resetDisabled", + "scriptable": true, + "stored": true, + "type": "QQuickColorGroup*", + "user": false, + "write": "setDisabled" + } + ], + "qualifiedClassName": "QQuickPalette", + "signals": [ + { + "access": "public", + "index": 0, + "name": "activeChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "inactiveChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "disabledChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "active", + "type": "QQuickColorGroup*" + } + ], + "index": 3, + "name": "setActive", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "inactive", + "type": "QQuickColorGroup*" + } + ], + "index": 4, + "name": "setInactive", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "disabled", + "type": "QQuickColorGroup*" + } + ], + "index": 5, + "name": "setDisabled", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickColorGroup" + } + ] + } + ], + "inputFile": "qquickpalette_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickPathElement", + "lineNumber": 44, + "object": true, + "qualifiedClassName": "QQuickPathElement", + "signals": [ + { + "access": "public", + "index": 0, + "name": "changed", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "PathAttribute" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickPathAttribute", + "lineNumber": 55, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "name", + "notify": "nameChanged", + "read": "name", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setName" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "value", + "notify": "valueChanged", + "read": "value", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setValue" + } + ], + "qualifiedClassName": "QQuickPathAttribute", + "signals": [ + { + "access": "public", + "index": 0, + "name": "nameChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "valueChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickPathElement" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickCurve", + "lineNumber": 82, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "x", + "notify": "xChanged", + "read": "x", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setX" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "y", + "notify": "yChanged", + "read": "y", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setY" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "relativeX", + "notify": "relativeXChanged", + "read": "relativeX", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setRelativeX" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "relativeY", + "notify": "relativeYChanged", + "read": "relativeY", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setRelativeY" + } + ], + "qualifiedClassName": "QQuickCurve", + "signals": [ + { + "access": "public", + "index": 0, + "name": "xChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "yChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "relativeXChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "relativeYChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickPathElement" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "PathLine" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickPathLine", + "lineNumber": 126, + "object": true, + "qualifiedClassName": "QQuickPathLine", + "superClasses": [ + { + "access": "public", + "name": "QQuickCurve" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "PathMove" + }, + { + "name": "QML.AddedInVersion", + "value": "521" + } + ], + "className": "QQuickPathMove", + "lineNumber": 137, + "object": true, + "qualifiedClassName": "QQuickPathMove", + "superClasses": [ + { + "access": "public", + "name": "QQuickCurve" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "PathQuad" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickPathQuad", + "lineNumber": 148, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "controlX", + "notify": "controlXChanged", + "read": "controlX", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setControlX" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "controlY", + "notify": "controlYChanged", + "read": "controlY", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setControlY" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "relativeControlX", + "notify": "relativeControlXChanged", + "read": "relativeControlX", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setRelativeControlX" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "relativeControlY", + "notify": "relativeControlYChanged", + "read": "relativeControlY", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setRelativeControlY" + } + ], + "qualifiedClassName": "QQuickPathQuad", + "signals": [ + { + "access": "public", + "index": 0, + "name": "controlXChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "controlYChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "relativeControlXChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "relativeControlYChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickCurve" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "PathCubic" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickPathCubic", + "lineNumber": 191, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "control1X", + "notify": "control1XChanged", + "read": "control1X", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setControl1X" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "control1Y", + "notify": "control1YChanged", + "read": "control1Y", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setControl1Y" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "control2X", + "notify": "control2XChanged", + "read": "control2X", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setControl2X" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "control2Y", + "notify": "control2YChanged", + "read": "control2Y", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setControl2Y" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "relativeControl1X", + "notify": "relativeControl1XChanged", + "read": "relativeControl1X", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setRelativeControl1X" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "relativeControl1Y", + "notify": "relativeControl1YChanged", + "read": "relativeControl1Y", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setRelativeControl1Y" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "relativeControl2X", + "notify": "relativeControl2XChanged", + "read": "relativeControl2X", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setRelativeControl2X" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 7, + "name": "relativeControl2Y", + "notify": "relativeControl2YChanged", + "read": "relativeControl2Y", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setRelativeControl2Y" + } + ], + "qualifiedClassName": "QQuickPathCubic", + "signals": [ + { + "access": "public", + "index": 0, + "name": "control1XChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "control1YChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "control2XChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "control2YChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "relativeControl1XChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "relativeControl1YChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "relativeControl2XChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "relativeControl2YChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickCurve" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "PathCurve" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickPathCatmullRomCurve", + "lineNumber": 259, + "object": true, + "qualifiedClassName": "QQuickPathCatmullRomCurve", + "superClasses": [ + { + "access": "public", + "name": "QQuickCurve" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "PathArc" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickPathArc", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "ArcDirection", + "values": [ + "Clockwise", + "Counterclockwise" + ] + } + ], + "lineNumber": 270, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "radiusX", + "notify": "radiusXChanged", + "read": "radiusX", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setRadiusX" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "radiusY", + "notify": "radiusYChanged", + "read": "radiusY", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setRadiusY" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "useLargeArc", + "notify": "useLargeArcChanged", + "read": "useLargeArc", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setUseLargeArc" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "direction", + "notify": "directionChanged", + "read": "direction", + "required": false, + "scriptable": true, + "stored": true, + "type": "ArcDirection", + "user": false, + "write": "setDirection" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "xAxisRotation", + "notify": "xAxisRotationChanged", + "read": "xAxisRotation", + "required": false, + "revision": 521, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setXAxisRotation" + } + ], + "qualifiedClassName": "QQuickPathArc", + "signals": [ + { + "access": "public", + "index": 0, + "name": "radiusXChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "radiusYChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "useLargeArcChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "directionChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "xAxisRotationChanged", + "returnType": "void", + "revision": 521 + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickCurve" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "PathAngleArc" + }, + { + "name": "QML.AddedInVersion", + "value": "523" + } + ], + "className": "QQuickPathAngleArc", + "lineNumber": 320, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "centerX", + "notify": "centerXChanged", + "read": "centerX", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setCenterX" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "centerY", + "notify": "centerYChanged", + "read": "centerY", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setCenterY" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "radiusX", + "notify": "radiusXChanged", + "read": "radiusX", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setRadiusX" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "radiusY", + "notify": "radiusYChanged", + "read": "radiusY", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setRadiusY" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "startAngle", + "notify": "startAngleChanged", + "read": "startAngle", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setStartAngle" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "sweepAngle", + "notify": "sweepAngleChanged", + "read": "sweepAngle", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setSweepAngle" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "moveToStart", + "notify": "moveToStartChanged", + "read": "moveToStart", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setMoveToStart" + } + ], + "qualifiedClassName": "QQuickPathAngleArc", + "signals": [ + { + "access": "public", + "index": 0, + "name": "centerXChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "centerYChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "radiusXChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "radiusYChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "startAngleChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "sweepAngleChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "moveToStartChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickCurve" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "PathSvg" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickPathSvg", + "lineNumber": 380, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "path", + "notify": "pathChanged", + "read": "path", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setPath" + } + ], + "qualifiedClassName": "QQuickPathSvg", + "signals": [ + { + "access": "public", + "index": 0, + "name": "pathChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickCurve" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "PathRectangle" + }, + { + "name": "QML.AddedInVersion", + "value": "1544" + } + ], + "className": "QQuickPathRectangle", + "lineNumber": 401, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "width", + "notify": "widthChanged", + "read": "width", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setWidth" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "height", + "notify": "heightChanged", + "read": "height", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setHeight" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "strokeAdjustment", + "notify": "strokeAdjustmentChanged", + "read": "strokeAdjustment", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setStrokeAdjustment" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "radius", + "notify": "radiusChanged", + "read": "radius", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setRadius" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "topLeftRadius", + "notify": "topLeftRadiusChanged", + "read": "topLeftRadius", + "required": false, + "reset": "resetTopLeftRadius", + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setTopLeftRadius" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "topRightRadius", + "notify": "topRightRadiusChanged", + "read": "topRightRadius", + "required": false, + "reset": "resetTopRightRadius", + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setTopRightRadius" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 6, + "name": "bottomLeftRadius", + "notify": "bottomLeftRadiusChanged", + "read": "bottomLeftRadius", + "required": false, + "reset": "resetBottomLeftRadius", + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setBottomLeftRadius" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 7, + "name": "bottomRightRadius", + "notify": "bottomRightRadiusChanged", + "read": "bottomRightRadius", + "required": false, + "reset": "resetBottomRightRadius", + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setBottomRightRadius" + } + ], + "qualifiedClassName": "QQuickPathRectangle", + "signals": [ + { + "access": "public", + "index": 0, + "name": "widthChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "heightChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "strokeAdjustmentChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "radiusChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "topLeftRadiusChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "topRightRadiusChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "bottomLeftRadiusChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "bottomRightRadiusChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickCurve" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "PathPercent" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickPathPercent", + "lineNumber": 478, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "value", + "notify": "valueChanged", + "read": "value", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setValue" + } + ], + "qualifiedClassName": "QQuickPathPercent", + "signals": [ + { + "access": "public", + "index": 0, + "name": "valueChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickPathElement" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "PathPolyline" + }, + { + "name": "QML.AddedInVersion", + "value": "526" + } + ], + "className": "QQuickPathPolyline", + "lineNumber": 497, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "start", + "notify": "startChanged", + "read": "start", + "required": false, + "scriptable": true, + "stored": true, + "type": "QPointF", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "path", + "notify": "pathChanged", + "read": "path", + "required": false, + "scriptable": true, + "stored": true, + "type": "QVariant", + "user": false, + "write": "setPath" + } + ], + "qualifiedClassName": "QQuickPathPolyline", + "signals": [ + { + "access": "public", + "index": 0, + "name": "pathChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "startChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickCurve" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "PathMultiline" + }, + { + "name": "QML.AddedInVersion", + "value": "526" + } + ], + "className": "QQuickPathMultiline", + "lineNumber": 521, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "start", + "notify": "startChanged", + "read": "start", + "required": false, + "scriptable": true, + "stored": true, + "type": "QPointF", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "paths", + "notify": "pathsChanged", + "read": "paths", + "required": false, + "scriptable": true, + "stored": true, + "type": "QVariant", + "user": false, + "write": "setPaths" + } + ], + "qualifiedClassName": "QQuickPathMultiline", + "signals": [ + { + "access": "public", + "index": 0, + "name": "pathsChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "startChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickCurve" + } + ] + }, + { + "classInfos": [ + { + "name": "DefaultProperty", + "value": "pathElements" + }, + { + "name": "QML.Element", + "value": "Path" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickPath", + "interfaces": [ + [ + { + "className": "QQmlParserStatus", + "id": "\"org.qt-project.Qt.QQmlParserStatus\"" + } + ] + ], + "lineNumber": 559, + "methods": [ + { + "access": "public", + "arguments": [ + { + "name": "t", + "type": "qreal" + } + ], + "index": 6, + "name": "pointAtPercent", + "returnType": "QPointF", + "revision": 526 + } + ], + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "pathElements", + "read": "pathElements", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlListProperty", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "startX", + "notify": "startXChanged", + "read": "startX", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setStartX" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "startY", + "notify": "startYChanged", + "read": "startY", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setStartY" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "closed", + "notify": "changed", + "read": "isClosed", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "simplify", + "notify": "simplifyChanged", + "read": "simplify", + "required": false, + "revision": 1542, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setSimplify" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "scale", + "notify": "scaleChanged", + "read": "scale", + "required": false, + "revision": 526, + "scriptable": true, + "stored": true, + "type": "QSizeF", + "user": false, + "write": "setScale" + } + ], + "qualifiedClassName": "QQuickPath", + "signals": [ + { + "access": "public", + "index": 0, + "name": "changed", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "startXChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "startYChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "simplifyChanged", + "returnType": "void", + "revision": 1542 + }, + { + "access": "public", + "index": 4, + "name": "scaleChanged", + "returnType": "void", + "revision": 526 + } + ], + "slots": [ + { + "access": "private", + "index": 5, + "name": "processPath", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QQmlParserStatus" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "PathText" + }, + { + "name": "QML.AddedInVersion", + "value": "527" + } + ], + "className": "QQuickPathText", + "lineNumber": 666, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "x", + "notify": "xChanged", + "read": "x", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setX" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "y", + "notify": "yChanged", + "read": "y", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setY" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "width", + "notify": "changed", + "read": "width", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "height", + "notify": "changed", + "read": "height", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "text", + "notify": "textChanged", + "read": "text", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setText" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "font", + "notify": "fontChanged", + "read": "font", + "required": false, + "scriptable": true, + "stored": true, + "type": "QFont", + "user": false, + "write": "setFont" + } + ], + "qualifiedClassName": "QQuickPathText", + "signals": [ + { + "access": "public", + "index": 0, + "name": "xChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "yChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "textChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "fontChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "private", + "index": 4, + "name": "invalidate", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickPathElement" + } + ] + } + ], + "inputFile": "qquickpath_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "PathInterpolator" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickPathInterpolator", + "lineNumber": 28, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "path", + "notify": "pathChanged", + "read": "path", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickPath*", + "user": false, + "write": "setPath" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "progress", + "notify": "progressChanged", + "read": "progress", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setProgress" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "x", + "notify": "xChanged", + "read": "x", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "y", + "notify": "yChanged", + "read": "y", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "angle", + "notify": "angleChanged", + "read": "angle", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + } + ], + "qualifiedClassName": "QQuickPathInterpolator", + "signals": [ + { + "access": "public", + "index": 0, + "name": "pathChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "progressChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "xChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "yChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "angleChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "private", + "index": 5, + "name": "_q_pathUpdated", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qquickpathinterpolator_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "PathView" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + }, + { + "name": "QML.Attached", + "value": "QQuickPathViewAttached" + } + ], + "className": "QQuickPathView", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "HighlightRangeMode", + "values": [ + "NoHighlightRange", + "ApplyRange", + "StrictlyEnforceRange" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "SnapMode", + "values": [ + "NoSnap", + "SnapToItem", + "SnapOneItem" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "MovementDirection", + "values": [ + "Shortest", + "Negative", + "Positive" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "PositionMode", + "values": [ + "Beginning", + "Center", + "End", + "Contain", + "SnapPosition" + ] + } + ], + "lineNumber": 33, + "methods": [ + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + }, + { + "name": "mode", + "type": "int" + } + ], + "index": 41, + "name": "positionViewAtIndex", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "x", + "type": "qreal" + }, + { + "name": "y", + "type": "qreal" + } + ], + "index": 42, + "name": "indexAt", + "returnType": "int" + }, + { + "access": "public", + "arguments": [ + { + "name": "x", + "type": "qreal" + }, + { + "name": "y", + "type": "qreal" + } + ], + "index": 43, + "name": "itemAt", + "returnType": "QQuickItem*" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + } + ], + "index": 44, + "name": "itemAtIndex", + "returnType": "QQuickItem*", + "revision": 525 + } + ], + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "model", + "notify": "modelChanged", + "read": "model", + "required": false, + "scriptable": true, + "stored": true, + "type": "QVariant", + "user": false, + "write": "setModel" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "path", + "notify": "pathChanged", + "read": "path", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickPath*", + "user": false, + "write": "setPath" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "currentIndex", + "notify": "currentIndexChanged", + "read": "currentIndex", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setCurrentIndex" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "currentItem", + "notify": "currentItemChanged", + "read": "currentItem", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "offset", + "notify": "offsetChanged", + "read": "offset", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setOffset" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "highlight", + "notify": "highlightChanged", + "read": "highlight", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlComponent*", + "user": false, + "write": "setHighlight" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "highlightItem", + "notify": "highlightItemChanged", + "read": "highlightItem", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 7, + "name": "preferredHighlightBegin", + "notify": "preferredHighlightBeginChanged", + "read": "preferredHighlightBegin", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setPreferredHighlightBegin" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 8, + "name": "preferredHighlightEnd", + "notify": "preferredHighlightEndChanged", + "read": "preferredHighlightEnd", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setPreferredHighlightEnd" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 9, + "name": "highlightRangeMode", + "notify": "highlightRangeModeChanged", + "read": "highlightRangeMode", + "required": false, + "scriptable": true, + "stored": true, + "type": "HighlightRangeMode", + "user": false, + "write": "setHighlightRangeMode" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 10, + "name": "highlightMoveDuration", + "notify": "highlightMoveDurationChanged", + "read": "highlightMoveDuration", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setHighlightMoveDuration" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 11, + "name": "dragMargin", + "notify": "dragMarginChanged", + "read": "dragMargin", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setDragMargin" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 12, + "name": "maximumFlickVelocity", + "notify": "maximumFlickVelocityChanged", + "read": "maximumFlickVelocity", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setMaximumFlickVelocity" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 13, + "name": "flickDeceleration", + "notify": "flickDecelerationChanged", + "read": "flickDeceleration", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setFlickDeceleration" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 14, + "name": "interactive", + "notify": "interactiveChanged", + "read": "isInteractive", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setInteractive" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 15, + "name": "moving", + "notify": "movingChanged", + "read": "isMoving", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 16, + "name": "flicking", + "notify": "flickingChanged", + "read": "isFlicking", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 17, + "name": "dragging", + "notify": "draggingChanged", + "read": "isDragging", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 18, + "name": "count", + "notify": "countChanged", + "read": "count", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 19, + "name": "delegate", + "notify": "delegateChanged", + "read": "delegate", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlComponent*", + "user": false, + "write": "setDelegate" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 20, + "name": "pathItemCount", + "notify": "pathItemCountChanged", + "read": "pathItemCount", + "required": false, + "reset": "resetPathItemCount", + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setPathItemCount" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 21, + "name": "snapMode", + "notify": "snapModeChanged", + "read": "snapMode", + "required": false, + "scriptable": true, + "stored": true, + "type": "SnapMode", + "user": false, + "write": "setSnapMode" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 22, + "name": "movementDirection", + "notify": "movementDirectionChanged", + "read": "movementDirection", + "required": false, + "revision": 519, + "scriptable": true, + "stored": true, + "type": "MovementDirection", + "user": false, + "write": "setMovementDirection" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 23, + "name": "cacheItemCount", + "notify": "cacheItemCountChanged", + "read": "cacheItemCount", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setCacheItemCount" + } + ], + "qualifiedClassName": "QQuickPathView", + "signals": [ + { + "access": "public", + "index": 0, + "name": "currentIndexChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "currentItemChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "offsetChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "modelChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "countChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "pathChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "preferredHighlightBeginChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "preferredHighlightEndChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 8, + "name": "highlightRangeModeChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 9, + "name": "dragMarginChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 10, + "name": "snapPositionChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 11, + "name": "delegateChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 12, + "name": "pathItemCountChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 13, + "name": "maximumFlickVelocityChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 14, + "name": "flickDecelerationChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 15, + "name": "interactiveChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 16, + "name": "movingChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 17, + "name": "flickingChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 18, + "name": "draggingChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 19, + "name": "highlightChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 20, + "name": "highlightItemChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 21, + "name": "highlightMoveDurationChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 22, + "name": "movementStarted", + "returnType": "void" + }, + { + "access": "public", + "index": 23, + "name": "movementEnded", + "returnType": "void" + }, + { + "access": "public", + "index": 24, + "name": "movementDirectionChanged", + "returnType": "void", + "revision": 519 + }, + { + "access": "public", + "index": 25, + "name": "flickStarted", + "returnType": "void" + }, + { + "access": "public", + "index": 26, + "name": "flickEnded", + "returnType": "void" + }, + { + "access": "public", + "index": 27, + "name": "dragStarted", + "returnType": "void" + }, + { + "access": "public", + "index": 28, + "name": "dragEnded", + "returnType": "void" + }, + { + "access": "public", + "index": 29, + "name": "snapModeChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 30, + "name": "cacheItemCountChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "index": 31, + "name": "incrementCurrentIndex", + "returnType": "void" + }, + { + "access": "public", + "index": 32, + "name": "decrementCurrentIndex", + "returnType": "void" + }, + { + "access": "private", + "index": 33, + "name": "refill", + "returnType": "void" + }, + { + "access": "private", + "index": 34, + "name": "ticked", + "returnType": "void" + }, + { + "access": "private", + "index": 35, + "name": "movementEnding", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "changeSet", + "type": "QQmlChangeSet" + }, + { + "name": "reset", + "type": "bool" + } + ], + "index": 36, + "name": "modelUpdated", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "index", + "type": "int" + }, + { + "name": "item", + "type": "QObject*" + } + ], + "index": 37, + "name": "createdItem", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "index", + "type": "int" + }, + { + "name": "item", + "type": "QObject*" + } + ], + "index": 38, + "name": "initItem", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "item", + "type": "QObject*" + } + ], + "index": 39, + "name": "destroyingItem", + "returnType": "void" + }, + { + "access": "private", + "index": 40, + "name": "pathUpdated", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickItem" + } + ] + }, + { + "className": "QQuickPathViewAttached", + "lineNumber": 217, + "object": true, + "properties": [ + { + "constant": true, + "designable": true, + "final": true, + "index": 0, + "name": "view", + "read": "view", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickPathView*", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "isCurrentItem", + "notify": "currentItemChanged", + "read": "isCurrentItem", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "onPath", + "notify": "pathChanged", + "read": "isOnPath", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + } + ], + "qualifiedClassName": "QQuickPathViewAttached", + "signals": [ + { + "access": "public", + "index": 0, + "name": "currentItemChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "pathChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qquickpathview_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "Pinch" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickPinch", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "Axis", + "values": [ + "NoDrag", + "XAxis", + "YAxis", + "XAndYAxis", + "XandYAxis" + ] + } + ], + "lineNumber": 24, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "target", + "notify": "targetChanged", + "read": "target", + "required": false, + "reset": "resetTarget", + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false, + "write": "setTarget" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "minimumScale", + "notify": "minimumScaleChanged", + "read": "minimumScale", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setMinimumScale" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "maximumScale", + "notify": "maximumScaleChanged", + "read": "maximumScale", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setMaximumScale" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "minimumRotation", + "notify": "minimumRotationChanged", + "read": "minimumRotation", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setMinimumRotation" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "maximumRotation", + "notify": "maximumRotationChanged", + "read": "maximumRotation", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setMaximumRotation" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "dragAxis", + "notify": "dragAxisChanged", + "read": "axis", + "required": false, + "scriptable": true, + "stored": true, + "type": "Axis", + "user": false, + "write": "setAxis" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "minimumX", + "notify": "minimumXChanged", + "read": "xmin", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setXmin" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 7, + "name": "maximumX", + "notify": "maximumXChanged", + "read": "xmax", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setXmax" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 8, + "name": "minimumY", + "notify": "minimumYChanged", + "read": "ymin", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setYmin" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 9, + "name": "maximumY", + "notify": "maximumYChanged", + "read": "ymax", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setYmax" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 10, + "name": "active", + "notify": "activeChanged", + "read": "active", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + } + ], + "qualifiedClassName": "QQuickPinch", + "signals": [ + { + "access": "public", + "index": 0, + "name": "targetChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "minimumScaleChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "maximumScaleChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "minimumRotationChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "maximumRotationChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "dragAxisChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "minimumXChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "maximumXChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 8, + "name": "minimumYChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 9, + "name": "maximumYChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 10, + "name": "activeChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickPinchEvent", + "lineNumber": 163, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "center", + "read": "center", + "required": false, + "scriptable": true, + "stored": true, + "type": "QPointF", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "startCenter", + "read": "startCenter", + "required": false, + "scriptable": true, + "stored": true, + "type": "QPointF", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "previousCenter", + "read": "previousCenter", + "required": false, + "scriptable": true, + "stored": true, + "type": "QPointF", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "scale", + "read": "scale", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "previousScale", + "read": "previousScale", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "angle", + "read": "angle", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 6, + "name": "previousAngle", + "read": "previousAngle", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 7, + "name": "rotation", + "read": "rotation", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 8, + "name": "point1", + "read": "point1", + "required": false, + "scriptable": true, + "stored": true, + "type": "QPointF", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 9, + "name": "startPoint1", + "read": "startPoint1", + "required": false, + "scriptable": true, + "stored": true, + "type": "QPointF", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 10, + "name": "point2", + "read": "point2", + "required": false, + "scriptable": true, + "stored": true, + "type": "QPointF", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 11, + "name": "startPoint2", + "read": "startPoint2", + "required": false, + "scriptable": true, + "stored": true, + "type": "QPointF", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 12, + "name": "pointCount", + "read": "pointCount", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 13, + "name": "accepted", + "read": "accepted", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setAccepted" + } + ], + "qualifiedClassName": "QQuickPinchEvent", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "PinchArea" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickPinchArea", + "lineNumber": 234, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "enabled", + "notify": "enabledChanged", + "read": "isEnabled", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setEnabled" + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 1, + "name": "pinch", + "read": "pinch", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickPinch*", + "user": false + } + ], + "qualifiedClassName": "QQuickPinchArea", + "signals": [ + { + "access": "public", + "index": 0, + "name": "enabledChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "pinch", + "type": "QQuickPinchEvent*" + } + ], + "index": 1, + "name": "pinchStarted", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "pinch", + "type": "QQuickPinchEvent*" + } + ], + "index": 2, + "name": "pinchUpdated", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "pinch", + "type": "QQuickPinchEvent*" + } + ], + "index": 3, + "name": "pinchFinished", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "pinch", + "type": "QQuickPinchEvent*" + } + ], + "index": 4, + "name": "smartZoom", + "returnType": "void", + "revision": 517 + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickItem" + } + ] + } + ], + "inputFile": "qquickpincharea_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "PinchHandler" + }, + { + "name": "QML.AddedInVersion", + "value": "524" + } + ], + "className": "QQuickPinchHandler", + "lineNumber": 29, + "object": true, + "properties": [ + { + "constant": true, + "designable": true, + "final": false, + "index": 0, + "name": "scaleAxis", + "read": "scaleAxis", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickDragAxis*", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "minimumScale", + "notify": "minimumScaleChanged", + "read": "minimumScale", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setMinimumScale" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "maximumScale", + "notify": "maximumScaleChanged", + "read": "maximumScale", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setMaximumScale" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "scale", + "notify": "updated", + "read": "scale", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "activeScale", + "notify": "scaleChanged", + "read": "activeScale", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "persistentScale", + "notify": "scaleChanged", + "read": "persistentScale", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setPersistentScale" + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 6, + "name": "rotationAxis", + "read": "rotationAxis", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickDragAxis*", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 7, + "name": "minimumRotation", + "notify": "minimumRotationChanged", + "read": "minimumRotation", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setMinimumRotation" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 8, + "name": "maximumRotation", + "notify": "maximumRotationChanged", + "read": "maximumRotation", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setMaximumRotation" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 9, + "name": "rotation", + "notify": "updated", + "read": "rotation", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 10, + "name": "activeRotation", + "notify": "rotationChanged", + "read": "activeRotation", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 11, + "name": "persistentRotation", + "notify": "rotationChanged", + "read": "persistentRotation", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setPersistentRotation" + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 12, + "name": "xAxis", + "read": "xAxis", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickDragAxis*", + "user": false + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 13, + "name": "yAxis", + "read": "yAxis", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickDragAxis*", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 14, + "name": "translation", + "notify": "updated", + "read": "translation", + "required": false, + "scriptable": true, + "stored": true, + "type": "QVector2D", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 15, + "name": "activeTranslation", + "notify": "translationChanged", + "read": "activeTranslation", + "required": false, + "revision": 1541, + "scriptable": true, + "stored": true, + "type": "QPointF", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 16, + "name": "persistentTranslation", + "notify": "translationChanged", + "read": "persistentTranslation", + "required": false, + "revision": 1541, + "scriptable": true, + "stored": true, + "type": "QPointF", + "user": false, + "write": "setPersistentTranslation" + } + ], + "qualifiedClassName": "QQuickPinchHandler", + "signals": [ + { + "access": "public", + "index": 0, + "name": "minimumScaleChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "maximumScaleChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "minimumRotationChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "maximumRotationChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "updated", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "delta", + "type": "qreal" + } + ], + "index": 5, + "name": "scaleChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "delta", + "type": "qreal" + } + ], + "index": 6, + "name": "rotationChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "delta", + "type": "QVector2D" + } + ], + "index": 7, + "name": "translationChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickMultiPointHandler" + } + ] + } + ], + "inputFile": "qquickpinchhandler_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQuickPixmapCache", + "lineNumber": 44, + "object": true, + "qualifiedClassName": "QQuickPixmapCache", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qquickpixmapcache_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQuickPointerDeviceHandler", + "lineNumber": 23, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "acceptedDevices", + "notify": "acceptedDevicesChanged", + "read": "acceptedDevices", + "required": false, + "scriptable": true, + "stored": true, + "type": "QInputDevice::DeviceTypes", + "user": false, + "write": "setAcceptedDevices" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "acceptedPointerTypes", + "notify": "acceptedPointerTypesChanged", + "read": "acceptedPointerTypes", + "required": false, + "scriptable": true, + "stored": true, + "type": "QPointingDevice::PointerTypes", + "user": false, + "write": "setAcceptedPointerTypes" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "acceptedButtons", + "notify": "acceptedButtonsChanged", + "read": "acceptedButtons", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::MouseButtons", + "user": false, + "write": "setAcceptedButtons" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "acceptedModifiers", + "notify": "acceptedModifiersChanged", + "read": "acceptedModifiers", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::KeyboardModifiers", + "user": false, + "write": "setAcceptedModifiers" + } + ], + "qualifiedClassName": "QQuickPointerDeviceHandler", + "signals": [ + { + "access": "public", + "index": 0, + "name": "acceptedDevicesChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "acceptedPointerTypesChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "acceptedButtonsChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "acceptedModifiersChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "acceptedDevices", + "type": "QInputDevice::DeviceTypes" + } + ], + "index": 4, + "name": "setAcceptedDevices", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "acceptedPointerTypes", + "type": "QPointingDevice::PointerTypes" + } + ], + "index": 5, + "name": "setAcceptedPointerTypes", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "buttons", + "type": "Qt::MouseButtons" + } + ], + "index": 6, + "name": "setAcceptedButtons", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "acceptedModifiers", + "type": "Qt::KeyboardModifiers" + } + ], + "index": 7, + "name": "setAcceptedModifiers", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickPointerHandler" + } + ] + } + ], + "inputFile": "qquickpointerdevicehandler_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "ParentProperty", + "value": "parent" + }, + { + "name": "QML.Element", + "value": "PointerHandler" + }, + { + "name": "QML.Creatable", + "value": "false" + }, + { + "name": "QML.UncreatableReason", + "value": "PointerHandler is an abstract base class." + }, + { + "name": "QML.AddedInVersion", + "value": "524" + } + ], + "className": "QQuickPointerHandler", + "enums": [ + { + "alias": "GrabPermission", + "isClass": false, + "isFlag": true, + "name": "GrabPermissions", + "values": [ + "TakeOverForbidden", + "CanTakeOverFromHandlersOfSameType", + "CanTakeOverFromHandlersOfDifferentType", + "CanTakeOverFromItems", + "CanTakeOverFromAnything", + "ApprovesTakeOverByHandlersOfSameType", + "ApprovesTakeOverByHandlersOfDifferentType", + "ApprovesTakeOverByItems", + "ApprovesCancellation", + "ApprovesTakeOverByAnything" + ] + } + ], + "interfaces": [ + [ + { + "className": "QQmlParserStatus", + "id": "\"org.qt-project.Qt.QQmlParserStatus\"" + } + ] + ], + "lineNumber": 36, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "enabled", + "notify": "enabledChanged", + "read": "enabled", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setEnabled" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "active", + "notify": "activeChanged", + "read": "active", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "target", + "notify": "targetChanged", + "read": "target", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false, + "write": "setTarget" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "parent", + "notify": "parentChanged", + "read": "parentItem", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false, + "write": "setParentItem" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "grabPermissions", + "notify": "grabPermissionChanged", + "read": "grabPermissions", + "required": false, + "scriptable": true, + "stored": true, + "type": "GrabPermissions", + "user": false, + "write": "setGrabPermissions" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "margin", + "notify": "marginChanged", + "read": "margin", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setMargin" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "dragThreshold", + "notify": "dragThresholdChanged", + "read": "dragThreshold", + "required": false, + "reset": "resetDragThreshold", + "revision": 527, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setDragThreshold" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 7, + "name": "cursorShape", + "notify": "cursorShapeChanged", + "read": "cursorShape", + "required": false, + "reset": "resetCursorShape", + "revision": 527, + "scriptable": true, + "stored": true, + "type": "Qt::CursorShape", + "user": false, + "write": "setCursorShape" + } + ], + "qualifiedClassName": "QQuickPointerHandler", + "signals": [ + { + "access": "public", + "index": 0, + "name": "enabledChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "activeChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "targetChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "marginChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "dragThresholdChanged", + "returnType": "void", + "revision": 527 + }, + { + "access": "public", + "arguments": [ + { + "name": "transition", + "type": "QPointingDevice::GrabTransition" + }, + { + "name": "point", + "type": "QEventPoint" + } + ], + "index": 5, + "name": "grabChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "grabPermissionChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "point", + "type": "QEventPoint" + } + ], + "index": 7, + "name": "canceled", + "returnType": "void" + }, + { + "access": "public", + "index": 8, + "name": "cursorShapeChanged", + "returnType": "void", + "revision": 527 + }, + { + "access": "public", + "index": 9, + "name": "parentChanged", + "returnType": "void", + "revision": 1539 + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QQmlParserStatus" + } + ] + } + ], + "inputFile": "qquickpointerhandler_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "PointHandler" + }, + { + "name": "QML.AddedInVersion", + "value": "524" + } + ], + "className": "QQuickPointHandler", + "lineNumber": 22, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "translation", + "notify": "translationChanged", + "read": "translation", + "required": false, + "scriptable": true, + "stored": true, + "type": "QVector2D", + "user": false + } + ], + "qualifiedClassName": "QQuickPointHandler", + "signals": [ + { + "access": "public", + "index": 0, + "name": "translationChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickSinglePointHandler" + } + ] + } + ], + "inputFile": "qquickpointhandler_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQuickPositionerAttached", + "lineNumber": 36, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "index", + "notify": "indexChanged", + "read": "index", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "isFirstItem", + "notify": "isFirstItemChanged", + "read": "isFirstItem", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "isLastItem", + "notify": "isLastItemChanged", + "read": "isLastItem", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + } + ], + "qualifiedClassName": "QQuickPositionerAttached", + "signals": [ + { + "access": "public", + "index": 0, + "name": "indexChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "isFirstItemChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "isLastItemChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "Positioner" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + }, + { + "name": "QML.Creatable", + "value": "false" + }, + { + "name": "QML.UncreatableReason", + "value": "Positioner is an abstract type that is only available as an attached property." + }, + { + "name": "QML.Attached", + "value": "QQuickPositionerAttached" + } + ], + "className": "QQuickBasePositioner", + "lineNumber": 67, + "methods": [ + { + "access": "public", + "index": 11, + "name": "forceLayout", + "returnType": "void", + "revision": 521 + } + ], + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "spacing", + "notify": "spacingChanged", + "read": "spacing", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setSpacing" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "populate", + "notify": "populateChanged", + "read": "populate", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickTransition*", + "user": false, + "write": "setPopulate" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "move", + "notify": "moveChanged", + "read": "move", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickTransition*", + "user": false, + "write": "setMove" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "add", + "notify": "addChanged", + "read": "add", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickTransition*", + "user": false, + "write": "setAdd" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "padding", + "notify": "paddingChanged", + "read": "padding", + "required": false, + "reset": "resetPadding", + "revision": 518, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setPadding" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "topPadding", + "notify": "topPaddingChanged", + "read": "topPadding", + "required": false, + "reset": "resetTopPadding", + "revision": 518, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setTopPadding" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "leftPadding", + "notify": "leftPaddingChanged", + "read": "leftPadding", + "required": false, + "reset": "resetLeftPadding", + "revision": 518, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setLeftPadding" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 7, + "name": "rightPadding", + "notify": "rightPaddingChanged", + "read": "rightPadding", + "required": false, + "reset": "resetRightPadding", + "revision": 518, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setRightPadding" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 8, + "name": "bottomPadding", + "notify": "bottomPaddingChanged", + "read": "bottomPadding", + "required": false, + "reset": "resetBottomPadding", + "revision": 518, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setBottomPadding" + } + ], + "qualifiedClassName": "QQuickBasePositioner", + "signals": [ + { + "access": "public", + "index": 0, + "name": "spacingChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "populateChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "moveChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "addChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "paddingChanged", + "returnType": "void", + "revision": 518 + }, + { + "access": "public", + "index": 5, + "name": "topPaddingChanged", + "returnType": "void", + "revision": 518 + }, + { + "access": "public", + "index": 6, + "name": "leftPaddingChanged", + "returnType": "void", + "revision": 518 + }, + { + "access": "public", + "index": 7, + "name": "rightPaddingChanged", + "returnType": "void", + "revision": 518 + }, + { + "access": "public", + "index": 8, + "name": "bottomPaddingChanged", + "returnType": "void", + "revision": 518 + }, + { + "access": "public", + "index": 9, + "name": "positioningComplete", + "returnType": "void", + "revision": 521 + } + ], + "slots": [ + { + "access": "protected", + "index": 10, + "name": "prePositioning", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickImplicitSizeItem" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "Column" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickColumn", + "lineNumber": 210, + "object": true, + "qualifiedClassName": "QQuickColumn", + "superClasses": [ + { + "access": "public", + "name": "QQuickBasePositioner" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "Row" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickRow", + "lineNumber": 224, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "layoutDirection", + "notify": "layoutDirectionChanged", + "read": "layoutDirection", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::LayoutDirection", + "user": false, + "write": "setLayoutDirection" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "effectiveLayoutDirection", + "notify": "effectiveLayoutDirectionChanged", + "read": "effectiveLayoutDirection", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::LayoutDirection", + "user": false + } + ], + "qualifiedClassName": "QQuickRow", + "signals": [ + { + "access": "public", + "index": 0, + "name": "layoutDirectionChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "effectiveLayoutDirectionChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickBasePositioner" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "Grid" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickGrid", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "Flow", + "values": [ + "LeftToRight", + "TopToBottom" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "HAlignment", + "values": [ + "AlignLeft", + "AlignRight", + "AlignHCenter" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "VAlignment", + "values": [ + "AlignTop", + "AlignBottom", + "AlignVCenter" + ] + } + ], + "lineNumber": 251, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "rows", + "notify": "rowsChanged", + "read": "rows", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setRows" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "columns", + "notify": "columnsChanged", + "read": "columns", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setColumns" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "rowSpacing", + "notify": "rowSpacingChanged", + "read": "rowSpacing", + "required": false, + "reset": "resetRowSpacing", + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setRowSpacing" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "columnSpacing", + "notify": "columnSpacingChanged", + "read": "columnSpacing", + "required": false, + "reset": "resetColumnSpacing", + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setColumnSpacing" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "flow", + "notify": "flowChanged", + "read": "flow", + "required": false, + "scriptable": true, + "stored": true, + "type": "Flow", + "user": false, + "write": "setFlow" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "layoutDirection", + "notify": "layoutDirectionChanged", + "read": "layoutDirection", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::LayoutDirection", + "user": false, + "write": "setLayoutDirection" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "effectiveLayoutDirection", + "notify": "effectiveLayoutDirectionChanged", + "read": "effectiveLayoutDirection", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::LayoutDirection", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 7, + "name": "horizontalItemAlignment", + "notify": "horizontalAlignmentChanged", + "read": "hItemAlign", + "required": false, + "revision": 513, + "scriptable": true, + "stored": true, + "type": "HAlignment", + "user": false, + "write": "setHItemAlign" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 8, + "name": "effectiveHorizontalItemAlignment", + "notify": "effectiveHorizontalAlignmentChanged", + "read": "effectiveHAlign", + "required": false, + "revision": 513, + "scriptable": true, + "stored": true, + "type": "HAlignment", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 9, + "name": "verticalItemAlignment", + "notify": "verticalAlignmentChanged", + "read": "vItemAlign", + "required": false, + "revision": 513, + "scriptable": true, + "stored": true, + "type": "VAlignment", + "user": false, + "write": "setVItemAlign" + } + ], + "qualifiedClassName": "QQuickGrid", + "signals": [ + { + "access": "public", + "index": 0, + "name": "rowsChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "columnsChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "flowChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "layoutDirectionChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "effectiveLayoutDirectionChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "rowSpacingChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "columnSpacingChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "alignment", + "type": "HAlignment" + } + ], + "index": 7, + "name": "horizontalAlignmentChanged", + "returnType": "void", + "revision": 513 + }, + { + "access": "public", + "arguments": [ + { + "name": "alignment", + "type": "HAlignment" + } + ], + "index": 8, + "name": "effectiveHorizontalAlignmentChanged", + "returnType": "void", + "revision": 513 + }, + { + "access": "public", + "arguments": [ + { + "name": "alignment", + "type": "VAlignment" + } + ], + "index": 9, + "name": "verticalAlignmentChanged", + "returnType": "void", + "revision": 513 + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickBasePositioner" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "Flow" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickFlow", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "Flow", + "values": [ + "LeftToRight", + "TopToBottom" + ] + } + ], + "lineNumber": 339, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "flow", + "notify": "flowChanged", + "read": "flow", + "required": false, + "scriptable": true, + "stored": true, + "type": "Flow", + "user": false, + "write": "setFlow" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "layoutDirection", + "notify": "layoutDirectionChanged", + "read": "layoutDirection", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::LayoutDirection", + "user": false, + "write": "setLayoutDirection" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "effectiveLayoutDirection", + "notify": "effectiveLayoutDirectionChanged", + "read": "effectiveLayoutDirection", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::LayoutDirection", + "user": false + } + ], + "qualifiedClassName": "QQuickFlow", + "signals": [ + { + "access": "public", + "index": 0, + "name": "flowChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "layoutDirectionChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "effectiveLayoutDirectionChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickBasePositioner" + } + ] + } + ], + "inputFile": "qquickpositioners_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQuickProfiler", + "lineNumber": 138, + "object": true, + "qualifiedClassName": "QQuickProfiler", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "data", + "type": "QList" + } + ], + "index": 0, + "name": "dataReady", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QQmlProfilerDefinitions" + } + ] + } + ], + "inputFile": "qquickprofiler_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "PropertyChanges" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + }, + { + "name": "QML.HasCustomParser", + "value": "true" + }, + { + "name": "ImmediatePropertyNames", + "value": "target,restoreEntryValues,explicit,objectName" + } + ], + "className": "QQuickPropertyChanges", + "lineNumber": 24, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "target", + "notify": "objectChanged", + "read": "object", + "required": false, + "scriptable": true, + "stored": true, + "type": "QObject*", + "user": false, + "write": "setObject" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "restoreEntryValues", + "notify": "restoreEntryValuesChanged", + "read": "restoreEntryValues", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setRestoreEntryValues" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "explicit", + "notify": "isExplicitChanged", + "read": "isExplicit", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setIsExplicit" + } + ], + "qualifiedClassName": "QQuickPropertyChanges", + "signals": [ + { + "access": "public", + "index": 0, + "name": "objectChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "restoreEntryValuesChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "isExplicitChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickStateOperation" + } + ] + } + ], + "inputFile": "qquickpropertychanges_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickPen", + "lineNumber": 26, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "width", + "notify": "widthChanged", + "read": "width", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setWidth" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "color", + "notify": "colorChanged", + "read": "color", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false, + "write": "setColor" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "pixelAligned", + "notify": "pixelAlignedChanged", + "read": "pixelAligned", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setPixelAligned" + } + ], + "qualifiedClassName": "QQuickPen", + "signals": [ + { + "access": "public", + "index": 0, + "name": "widthChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "colorChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "pixelAlignedChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "GradientStop" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickGradientStop", + "lineNumber": 61, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "position", + "read": "position", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setPosition" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "color", + "read": "color", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false, + "write": "setColor" + } + ], + "qualifiedClassName": "QQuickGradientStop", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "classInfos": [ + { + "name": "DefaultProperty", + "value": "stops" + }, + { + "name": "QML.Element", + "value": "Gradient" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + }, + { + "name": "QML.Extended", + "value": "QGradient" + }, + { + "name": "QML.ExtensionIsNamespace", + "value": "true" + } + ], + "className": "QQuickGradient", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "Orientation", + "values": [ + "Vertical", + "Horizontal" + ] + } + ], + "lineNumber": 87, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "stops", + "read": "stops", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlListProperty", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "orientation", + "notify": "orientationChanged", + "read": "orientation", + "required": false, + "revision": 524, + "scriptable": true, + "stored": true, + "type": "Orientation", + "user": false, + "write": "setOrientation" + } + ], + "qualifiedClassName": "QQuickGradient", + "signals": [ + { + "access": "public", + "index": 0, + "name": "updated", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "orientationChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "Rectangle" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickRectangle", + "lineNumber": 128, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "color", + "notify": "colorChanged", + "read": "color", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false, + "write": "setColor" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "gradient", + "read": "gradient", + "required": false, + "reset": "resetGradient", + "scriptable": true, + "stored": true, + "type": "QJSValue", + "user": false, + "write": "setGradient" + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 2, + "name": "border", + "read": "border", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickPen*", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "radius", + "notify": "radiusChanged", + "read": "radius", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setRadius" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "topLeftRadius", + "notify": "topLeftRadiusChanged", + "read": "topLeftRadius", + "required": false, + "reset": "resetTopLeftRadius", + "revision": 1543, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setTopLeftRadius" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "topRightRadius", + "notify": "topRightRadiusChanged", + "read": "topRightRadius", + "required": false, + "reset": "resetTopRightRadius", + "revision": 1543, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setTopRightRadius" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 6, + "name": "bottomLeftRadius", + "notify": "bottomLeftRadiusChanged", + "read": "bottomLeftRadius", + "required": false, + "reset": "resetBottomLeftRadius", + "revision": 1543, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setBottomLeftRadius" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 7, + "name": "bottomRightRadius", + "notify": "bottomRightRadiusChanged", + "read": "bottomRightRadius", + "required": false, + "reset": "resetBottomRightRadius", + "revision": 1543, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setBottomRightRadius" + } + ], + "qualifiedClassName": "QQuickRectangle", + "signals": [ + { + "access": "public", + "index": 0, + "name": "colorChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "radiusChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "topLeftRadiusChanged", + "returnType": "void", + "revision": 1543 + }, + { + "access": "public", + "index": 3, + "name": "topRightRadiusChanged", + "returnType": "void", + "revision": 1543 + }, + { + "access": "public", + "index": 4, + "name": "bottomLeftRadiusChanged", + "returnType": "void", + "revision": 1543 + }, + { + "access": "public", + "index": 5, + "name": "bottomRightRadiusChanged", + "returnType": "void", + "revision": 1543 + } + ], + "slots": [ + { + "access": "private", + "index": 6, + "name": "doUpdate", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickItem" + } + ] + } + ], + "inputFile": "qquickrectangle_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQuickRenderControl", + "lineNumber": 20, + "object": true, + "qualifiedClassName": "QQuickRenderControl", + "signals": [ + { + "access": "public", + "index": 0, + "name": "renderRequested", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "sceneChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qquickrendercontrol.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "DefaultProperty", + "value": "delegate" + }, + { + "name": "QML.Element", + "value": "Repeater" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickRepeater", + "lineNumber": 29, + "methods": [ + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + } + ], + "index": 8, + "name": "itemAt", + "returnType": "QQuickItem*" + } + ], + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "model", + "notify": "modelChanged", + "read": "model", + "required": false, + "scriptable": true, + "stored": true, + "type": "QVariant", + "user": false, + "write": "setModel" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "delegate", + "notify": "delegateChanged", + "read": "delegate", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlComponent*", + "user": false, + "write": "setDelegate" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "count", + "notify": "countChanged", + "read": "count", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + } + ], + "qualifiedClassName": "QQuickRepeater", + "signals": [ + { + "access": "public", + "index": 0, + "name": "modelChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "delegateChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "countChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + }, + { + "name": "item", + "type": "QQuickItem*" + } + ], + "index": 3, + "name": "itemAdded", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + }, + { + "name": "item", + "type": "QQuickItem*" + } + ], + "index": 4, + "name": "itemRemoved", + "returnType": "void" + } + ], + "slots": [ + { + "access": "private", + "arguments": [ + { + "name": "index", + "type": "int" + }, + { + "name": "item", + "type": "QObject*" + } + ], + "index": 5, + "name": "createdItem", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "type": "int" + }, + { + "name": "item", + "type": "QObject*" + } + ], + "index": 6, + "name": "initItem", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "changeSet", + "type": "QQmlChangeSet" + }, + { + "name": "reset", + "type": "bool" + } + ], + "index": 7, + "name": "modelUpdated", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickItem" + } + ] + } + ], + "inputFile": "qquickrepeater_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickScaleGrid", + "lineNumber": 28, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "left", + "notify": "leftBorderChanged", + "read": "left", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setLeft" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "top", + "notify": "topBorderChanged", + "read": "top", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setTop" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "right", + "notify": "rightBorderChanged", + "read": "right", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setRight" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "bottom", + "notify": "bottomBorderChanged", + "read": "bottom", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setBottom" + } + ], + "qualifiedClassName": "QQuickScaleGrid", + "signals": [ + { + "access": "public", + "index": 0, + "name": "borderChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "leftBorderChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "topBorderChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "rightBorderChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "bottomBorderChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qquickscalegrid_p_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "ScreenInfo" + }, + { + "name": "QML.AddedInVersion", + "value": "515" + }, + { + "name": "QML.Creatable", + "value": "false" + }, + { + "name": "QML.UncreatableReason", + "value": "ScreenInfo can only be used via the attached property." + } + ], + "className": "QQuickScreenInfo", + "lineNumber": 31, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "name", + "notify": "nameChanged", + "read": "name", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "manufacturer", + "notify": "manufacturerChanged", + "read": "manufacturer", + "required": false, + "revision": 522, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "model", + "notify": "modelChanged", + "read": "model", + "required": false, + "revision": 522, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "serialNumber", + "notify": "serialNumberChanged", + "read": "serialNumber", + "required": false, + "revision": 522, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "width", + "notify": "widthChanged", + "read": "width", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "height", + "notify": "heightChanged", + "read": "height", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 6, + "name": "desktopAvailableWidth", + "notify": "desktopGeometryChanged", + "read": "desktopAvailableWidth", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 7, + "name": "desktopAvailableHeight", + "notify": "desktopGeometryChanged", + "read": "desktopAvailableHeight", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 8, + "name": "logicalPixelDensity", + "notify": "logicalPixelDensityChanged", + "read": "logicalPixelDensity", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 9, + "name": "pixelDensity", + "notify": "pixelDensityChanged", + "read": "pixelDensity", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 10, + "name": "devicePixelRatio", + "notify": "devicePixelRatioChanged", + "read": "devicePixelRatio", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 11, + "name": "primaryOrientation", + "notify": "primaryOrientationChanged", + "read": "primaryOrientation", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::ScreenOrientation", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 12, + "name": "orientation", + "notify": "orientationChanged", + "read": "orientation", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::ScreenOrientation", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 13, + "name": "virtualX", + "notify": "virtualXChanged", + "read": "virtualX", + "required": false, + "revision": 515, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 14, + "name": "virtualY", + "notify": "virtualYChanged", + "read": "virtualY", + "required": false, + "revision": 515, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + } + ], + "qualifiedClassName": "QQuickScreenInfo", + "signals": [ + { + "access": "public", + "index": 0, + "name": "nameChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "manufacturerChanged", + "returnType": "void", + "revision": 522 + }, + { + "access": "public", + "index": 2, + "name": "modelChanged", + "returnType": "void", + "revision": 522 + }, + { + "access": "public", + "index": 3, + "name": "serialNumberChanged", + "returnType": "void", + "revision": 522 + }, + { + "access": "public", + "index": 4, + "name": "widthChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "heightChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "desktopGeometryChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "logicalPixelDensityChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 8, + "name": "pixelDensityChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 9, + "name": "devicePixelRatioChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 10, + "name": "primaryOrientationChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 11, + "name": "orientationChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 12, + "name": "virtualXChanged", + "returnType": "void", + "revision": 515 + }, + { + "access": "public", + "index": 13, + "name": "virtualYChanged", + "returnType": "void", + "revision": 515 + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickScreenAttached", + "lineNumber": 96, + "methods": [ + { + "access": "public", + "arguments": [ + { + "name": "a", + "type": "int" + }, + { + "name": "b", + "type": "int" + } + ], + "index": 1, + "name": "angleBetween", + "returnType": "int" + } + ], + "object": true, + "qualifiedClassName": "QQuickScreenAttached", + "slots": [ + { + "access": "protected", + "arguments": [ + { + "type": "QScreen*" + } + ], + "index": 0, + "name": "screenChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickScreenInfo" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Attached", + "value": "QQuickScreenAttached" + }, + { + "name": "QML.Element", + "value": "Screen" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + }, + { + "name": "QML.Creatable", + "value": "false" + }, + { + "name": "QML.UncreatableReason", + "value": "Screen can only be used via the attached property." + } + ], + "className": "QQuickScreen", + "lineNumber": 119, + "object": true, + "qualifiedClassName": "QQuickScreen", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qquickscreen_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "ShaderEffect" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickShaderEffect", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "CullMode", + "values": [ + "NoCulling", + "BackFaceCulling", + "FrontFaceCulling" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "Status", + "values": [ + "Compiled", + "Uncompiled", + "Error" + ] + } + ], + "lineNumber": 30, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "fragmentShader", + "notify": "fragmentShaderChanged", + "read": "fragmentShader", + "required": false, + "scriptable": true, + "stored": true, + "type": "QUrl", + "user": false, + "write": "setFragmentShader" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "vertexShader", + "notify": "vertexShaderChanged", + "read": "vertexShader", + "required": false, + "scriptable": true, + "stored": true, + "type": "QUrl", + "user": false, + "write": "setVertexShader" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "blending", + "notify": "blendingChanged", + "read": "blending", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setBlending" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "mesh", + "notify": "meshChanged", + "read": "mesh", + "required": false, + "scriptable": true, + "stored": true, + "type": "QVariant", + "user": false, + "write": "setMesh" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "cullMode", + "notify": "cullModeChanged", + "read": "cullMode", + "required": false, + "scriptable": true, + "stored": true, + "type": "CullMode", + "user": false, + "write": "setCullMode" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "log", + "notify": "logChanged", + "read": "log", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "status", + "notify": "statusChanged", + "read": "status", + "required": false, + "scriptable": true, + "stored": true, + "type": "Status", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 7, + "name": "supportsAtlasTextures", + "notify": "supportsAtlasTexturesChanged", + "read": "supportsAtlasTextures", + "required": false, + "revision": 516, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setSupportsAtlasTextures" + } + ], + "qualifiedClassName": "QQuickShaderEffect", + "signals": [ + { + "access": "public", + "index": 0, + "name": "fragmentShaderChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "vertexShaderChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "blendingChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "meshChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "cullModeChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "logChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "statusChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "supportsAtlasTexturesChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickItem" + } + ] + } + ], + "inputFile": "qquickshadereffect_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "ShaderEffectMesh" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + }, + { + "name": "QML.Creatable", + "value": "false" + }, + { + "name": "QML.UncreatableReason", + "value": "Cannot create instance of abstract class ShaderEffectMesh." + } + ], + "className": "QQuickShaderEffectMesh", + "lineNumber": 40, + "object": true, + "qualifiedClassName": "QQuickShaderEffectMesh", + "signals": [ + { + "access": "public", + "index": 0, + "name": "geometryChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "GridMesh" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickGridMesh", + "lineNumber": 65, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "resolution", + "notify": "resolutionChanged", + "read": "resolution", + "required": false, + "scriptable": true, + "stored": true, + "type": "QSize", + "user": false, + "write": "setResolution" + } + ], + "qualifiedClassName": "QQuickGridMesh", + "signals": [ + { + "access": "public", + "index": 0, + "name": "resolutionChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickShaderEffectMesh" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "BorderImageMesh" + }, + { + "name": "QML.AddedInVersion", + "value": "520" + } + ], + "className": "QQuickBorderImageMesh", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "TileMode", + "values": [ + "Stretch", + "Repeat", + "Round" + ] + } + ], + "lineNumber": 90, + "object": true, + "properties": [ + { + "constant": true, + "designable": true, + "final": false, + "index": 0, + "name": "border", + "read": "border", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickScaleGrid*", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "size", + "notify": "sizeChanged", + "read": "size", + "required": false, + "scriptable": true, + "stored": true, + "type": "QSize", + "user": false, + "write": "setSize" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "horizontalTileMode", + "notify": "horizontalTileModeChanged", + "read": "horizontalTileMode", + "required": false, + "scriptable": true, + "stored": true, + "type": "TileMode", + "user": false, + "write": "setHorizontalTileMode" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "verticalTileMode", + "notify": "verticalTileModeChanged", + "read": "verticalTileMode", + "required": false, + "scriptable": true, + "stored": true, + "type": "TileMode", + "user": false, + "write": "setVerticalTileMode" + } + ], + "qualifiedClassName": "QQuickBorderImageMesh", + "signals": [ + { + "access": "public", + "index": 0, + "name": "sizeChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "horizontalTileModeChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "verticalTileModeChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickShaderEffectMesh" + } + ] + } + ], + "inputFile": "qquickshadereffectmesh_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "ShaderEffectSource" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickShaderEffectSource", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "WrapMode", + "values": [ + "ClampToEdge", + "RepeatHorizontally", + "RepeatVertically", + "Repeat" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "Format", + "values": [ + "RGBA8", + "RGBA16F", + "RGBA32F", + "Alpha", + "RGB", + "RGBA" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "TextureMirroring", + "values": [ + "NoMirroring", + "MirrorHorizontally", + "MirrorVertically" + ] + } + ], + "lineNumber": 42, + "methods": [ + { + "access": "public", + "index": 14, + "name": "scheduleUpdate", + "returnType": "void" + } + ], + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "wrapMode", + "notify": "wrapModeChanged", + "read": "wrapMode", + "required": false, + "scriptable": true, + "stored": true, + "type": "WrapMode", + "user": false, + "write": "setWrapMode" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "sourceItem", + "notify": "sourceItemChanged", + "read": "sourceItem", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false, + "write": "setSourceItem" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "sourceRect", + "notify": "sourceRectChanged", + "read": "sourceRect", + "required": false, + "scriptable": true, + "stored": true, + "type": "QRectF", + "user": false, + "write": "setSourceRect" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "textureSize", + "notify": "textureSizeChanged", + "read": "textureSize", + "required": false, + "scriptable": true, + "stored": true, + "type": "QSize", + "user": false, + "write": "setTextureSize" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "format", + "notify": "formatChanged", + "read": "format", + "required": false, + "scriptable": true, + "stored": true, + "type": "Format", + "user": false, + "write": "setFormat" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "live", + "notify": "liveChanged", + "read": "live", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setLive" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "hideSource", + "notify": "hideSourceChanged", + "read": "hideSource", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setHideSource" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 7, + "name": "mipmap", + "notify": "mipmapChanged", + "read": "mipmap", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setMipmap" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 8, + "name": "recursive", + "notify": "recursiveChanged", + "read": "recursive", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setRecursive" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 9, + "name": "textureMirroring", + "notify": "textureMirroringChanged", + "read": "textureMirroring", + "required": false, + "revision": 518, + "scriptable": true, + "stored": true, + "type": "TextureMirroring", + "user": false, + "write": "setTextureMirroring" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 10, + "name": "samples", + "notify": "samplesChanged", + "read": "samples", + "required": false, + "revision": 521, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setSamples" + } + ], + "qualifiedClassName": "QQuickShaderEffectSource", + "signals": [ + { + "access": "public", + "index": 0, + "name": "wrapModeChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "sourceItemChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "sourceRectChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "textureSizeChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "formatChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "liveChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "hideSourceChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "mipmapChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 8, + "name": "recursiveChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 9, + "name": "textureMirroringChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 10, + "name": "samplesChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 11, + "name": "scheduledUpdateCompleted", + "returnType": "void" + } + ], + "slots": [ + { + "access": "private", + "arguments": [ + { + "name": "item", + "type": "QObject*" + } + ], + "index": 12, + "name": "sourceItemDestroyed", + "returnType": "void" + }, + { + "access": "private", + "index": 13, + "name": "invalidateSceneGraph", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickItem" + }, + { + "access": "public", + "name": "QQuickItemChangeListener" + } + ] + } + ], + "inputFile": "qquickshadereffectsource_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "Shortcut" + }, + { + "name": "QML.AddedInVersion", + "value": "517" + } + ], + "className": "QQuickShortcut", + "interfaces": [ + [ + { + "className": "QQmlParserStatus", + "id": "\"org.qt-project.Qt.QQmlParserStatus\"" + } + ] + ], + "lineNumber": 31, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "sequence", + "notify": "sequenceChanged", + "read": "sequence", + "required": false, + "scriptable": true, + "stored": true, + "type": "QVariant", + "user": false, + "write": "setSequence" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "sequences", + "notify": "sequencesChanged", + "read": "sequences", + "required": false, + "revision": 521, + "scriptable": true, + "stored": true, + "type": "QVariantList", + "user": false, + "write": "setSequences" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "nativeText", + "notify": "sequenceChanged", + "read": "nativeText", + "required": false, + "revision": 518, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "portableText", + "notify": "sequenceChanged", + "read": "portableText", + "required": false, + "revision": 518, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "enabled", + "notify": "enabledChanged", + "read": "isEnabled", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setEnabled" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "autoRepeat", + "notify": "autoRepeatChanged", + "read": "autoRepeat", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setAutoRepeat" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 6, + "name": "context", + "notify": "contextChanged", + "read": "context", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::ShortcutContext", + "user": false, + "write": "setContext" + } + ], + "qualifiedClassName": "QQuickShortcut", + "signals": [ + { + "access": "public", + "index": 0, + "name": "sequenceChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "sequencesChanged", + "returnType": "void", + "revision": 521 + }, + { + "access": "public", + "index": 2, + "name": "enabledChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "autoRepeatChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "contextChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "activated", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "activatedAmbiguously", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QQmlParserStatus" + } + ] + } + ], + "inputFile": "qquickshortcut_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQuickSinglePointHandler", + "lineNumber": 25, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "point", + "notify": "pointChanged", + "read": "point", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickHandlerPoint", + "user": false + } + ], + "qualifiedClassName": "QQuickSinglePointHandler", + "signals": [ + { + "access": "public", + "index": 0, + "name": "pointChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickPointerDeviceHandler" + } + ] + } + ], + "inputFile": "qquicksinglepointhandler_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "SmoothedAnimation" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickSmoothedAnimation", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "ReversingMode", + "values": [ + "Eased", + "Immediate", + "Sync" + ] + } + ], + "lineNumber": 27, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "velocity", + "notify": "velocityChanged", + "read": "velocity", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setVelocity" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "reversingMode", + "notify": "reversingModeChanged", + "read": "reversingMode", + "required": false, + "scriptable": true, + "stored": true, + "type": "ReversingMode", + "user": false, + "write": "setReversingMode" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "maximumEasingTime", + "notify": "maximumEasingTimeChanged", + "read": "maximumEasingTime", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setMaximumEasingTime" + } + ], + "qualifiedClassName": "QQuickSmoothedAnimation", + "signals": [ + { + "access": "public", + "index": 0, + "name": "velocityChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "reversingModeChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "maximumEasingTimeChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickNumberAnimation" + } + ] + } + ], + "inputFile": "qquicksmoothedanimation_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QSmoothedAnimationTimer", + "lineNumber": 28, + "object": true, + "qualifiedClassName": "QSmoothedAnimationTimer", + "slots": [ + { + "access": "public", + "index": 0, + "name": "stopAnimation", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QTimer" + } + ] + } + ], + "inputFile": "qquicksmoothedanimation_p_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "SpringAnimation" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickSpringAnimation", + "interfaces": [ + [ + { + "className": "QQmlPropertyValueSource", + "id": "\"org.qt-project.Qt.QQmlPropertyValueSource\"" + } + ] + ], + "lineNumber": 26, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "velocity", + "read": "velocity", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setVelocity" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "spring", + "read": "spring", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setSpring" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "damping", + "read": "damping", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setDamping" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "epsilon", + "read": "epsilon", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setEpsilon" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "modulus", + "notify": "modulusChanged", + "read": "modulus", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setModulus" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "mass", + "notify": "massChanged", + "read": "mass", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setMass" + } + ], + "qualifiedClassName": "QQuickSpringAnimation", + "signals": [ + { + "access": "public", + "index": 0, + "name": "modulusChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "massChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "syncChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickNumberAnimation" + } + ] + } + ], + "inputFile": "qquickspringanimation_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "Sprite" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickSprite", + "lineNumber": 33, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "source", + "notify": "sourceChanged", + "read": "source", + "required": false, + "scriptable": true, + "stored": true, + "type": "QUrl", + "user": false, + "write": "setSource" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "reverse", + "notify": "reverseChanged", + "read": "reverse", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setReverse" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "frameSync", + "notify": "frameSyncChanged", + "read": "frameSync", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setFrameSync" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "frames", + "notify": "frameCountChanged", + "read": "frames", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setFrames" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "frameCount", + "notify": "frameCountChanged", + "read": "frameCount", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setFrameCount" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "frameHeight", + "notify": "frameHeightChanged", + "read": "frameHeight", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setFrameHeight" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "frameWidth", + "notify": "frameWidthChanged", + "read": "frameWidth", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setFrameWidth" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 7, + "name": "frameX", + "notify": "frameXChanged", + "read": "frameX", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setFrameX" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 8, + "name": "frameY", + "notify": "frameYChanged", + "read": "frameY", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setFrameY" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 9, + "name": "frameRate", + "notify": "frameRateChanged", + "read": "frameRate", + "required": false, + "reset": "resetFrameRate", + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setFrameRate" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 10, + "name": "frameRateVariation", + "notify": "frameRateVariationChanged", + "read": "frameRateVariation", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setFrameRateVariation" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 11, + "name": "frameDuration", + "notify": "frameDurationChanged", + "read": "frameDuration", + "required": false, + "reset": "resetFrameDuration", + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setFrameDuration" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 12, + "name": "frameDurationVariation", + "notify": "frameDurationVariationChanged", + "read": "frameDurationVariation", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setFrameDurationVariation" + } + ], + "qualifiedClassName": "QQuickSprite", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "QUrl" + } + ], + "index": 0, + "name": "sourceChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "int" + } + ], + "index": 1, + "name": "frameHeightChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "int" + } + ], + "index": 2, + "name": "frameWidthChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "bool" + } + ], + "index": 3, + "name": "reverseChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "int" + } + ], + "index": 4, + "name": "frameCountChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "int" + } + ], + "index": 5, + "name": "frameXChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "int" + } + ], + "index": 6, + "name": "frameYChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 7, + "name": "frameRateChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 8, + "name": "frameRateVariationChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "int" + } + ], + "index": 9, + "name": "frameDurationChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "int" + } + ], + "index": 10, + "name": "frameDurationVariationChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "bool" + } + ], + "index": 11, + "name": "frameSyncChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "QUrl" + } + ], + "index": 12, + "name": "setSource", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "int" + } + ], + "index": 13, + "name": "setFrameHeight", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "int" + } + ], + "index": 14, + "name": "setFrameWidth", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "bool" + } + ], + "index": 15, + "name": "setReverse", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "int" + } + ], + "index": 16, + "name": "setFrames", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "int" + } + ], + "index": 17, + "name": "setFrameCount", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "int" + } + ], + "index": 18, + "name": "setFrameX", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "int" + } + ], + "index": 19, + "name": "setFrameY", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 20, + "name": "setFrameRate", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 21, + "name": "setFrameRateVariation", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "int" + } + ], + "index": 22, + "name": "setFrameDuration", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "int" + } + ], + "index": 23, + "name": "setFrameDurationVariation", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "bool" + } + ], + "index": 24, + "name": "setFrameSync", + "returnType": "void" + }, + { + "access": "private", + "index": 25, + "name": "startImageLoading", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickStochasticState" + } + ] + } + ], + "inputFile": "qquicksprite_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQuickStochasticState", + "lineNumber": 37, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "duration", + "notify": "durationChanged", + "read": "duration", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setDuration" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "durationVariation", + "notify": "durationVariationChanged", + "read": "durationVariation", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setDurationVariation" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "randomStart", + "notify": "randomStartChanged", + "read": "randomStart", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setRandomStart" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "to", + "notify": "toChanged", + "read": "to", + "required": false, + "scriptable": true, + "stored": true, + "type": "QVariantMap", + "user": false, + "write": "setTo" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "name", + "notify": "nameChanged", + "read": "name", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setName" + } + ], + "qualifiedClassName": "QQuickStochasticState", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "int" + } + ], + "index": 0, + "name": "durationChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "QString" + } + ], + "index": 1, + "name": "nameChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "QVariantMap" + } + ], + "index": 2, + "name": "toChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "int" + } + ], + "index": 3, + "name": "durationVariationChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "entered", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "bool" + } + ], + "index": 5, + "name": "randomStartChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "int" + } + ], + "index": 6, + "name": "setDuration", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "QString" + } + ], + "index": 7, + "name": "setName", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "QVariantMap" + } + ], + "index": 8, + "name": "setTo", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "int" + } + ], + "index": 9, + "name": "setDurationVariation", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "bool" + } + ], + "index": 10, + "name": "setRandomStart", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "className": "QQuickStochasticEngine", + "lineNumber": 150, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "globalGoal", + "notify": "globalGoalChanged", + "read": "globalGoal", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setGlobalGoal" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "states", + "read": "states", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlListProperty", + "user": false + } + ], + "qualifiedClassName": "QQuickStochasticEngine", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "QString" + } + ], + "index": 0, + "name": "globalGoalChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "idx", + "type": "int" + } + ], + "index": 1, + "name": "stateChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "QString" + } + ], + "index": 2, + "name": "setGlobalGoal", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "time", + "type": "uint" + } + ], + "index": 3, + "name": "updateSprites", + "returnType": "uint" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "className": "QQuickSpriteEngine", + "lineNumber": 229, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "sprites", + "read": "sprites", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlListProperty", + "user": false + } + ], + "qualifiedClassName": "QQuickSpriteEngine", + "superClasses": [ + { + "access": "public", + "name": "QQuickStochasticEngine" + } + ] + } + ], + "inputFile": "qquickspriteengine_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "DefaultProperty", + "value": "sprites" + }, + { + "name": "QML.Element", + "value": "SpriteSequence" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickSpriteSequence", + "lineNumber": 31, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "running", + "notify": "runningChanged", + "read": "running", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setRunning" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "interpolate", + "notify": "interpolateChanged", + "read": "interpolate", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setInterpolate" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "goalSprite", + "notify": "goalSpriteChanged", + "read": "goalSprite", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setGoalSprite" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "currentSprite", + "notify": "currentSpriteChanged", + "read": "currentSprite", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "sprites", + "read": "sprites", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlListProperty", + "user": false + } + ], + "qualifiedClassName": "QQuickSpriteSequence", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "bool" + } + ], + "index": 0, + "name": "runningChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "bool" + } + ], + "index": 1, + "name": "interpolateChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "QString" + } + ], + "index": 2, + "name": "goalSpriteChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "QString" + } + ], + "index": 3, + "name": "currentSpriteChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "sprite", + "type": "QString" + } + ], + "index": 4, + "name": "jumpTo", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "sprite", + "type": "QString" + } + ], + "index": 5, + "name": "setGoalSprite", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "bool" + } + ], + "index": 6, + "name": "setRunning", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "bool" + } + ], + "index": 7, + "name": "setInterpolate", + "returnType": "void" + }, + { + "access": "private", + "index": 8, + "name": "createEngine", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickItem" + } + ] + } + ], + "inputFile": "qquickspritesequence_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickStateOperation", + "lineNumber": 92, + "object": true, + "qualifiedClassName": "QQuickStateOperation", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "classInfos": [ + { + "name": "DefaultProperty", + "value": "changes" + }, + { + "name": "DeferredPropertyNames", + "value": "changes" + }, + { + "name": "QML.Element", + "value": "State" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickState", + "lineNumber": 119, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "name", + "read": "name", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setName" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "when", + "read": "when", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setWhen" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "extend", + "read": "extends", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setExtends" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "changes", + "read": "changes", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlListProperty", + "user": false + } + ], + "qualifiedClassName": "QQuickState", + "signals": [ + { + "access": "public", + "index": 0, + "name": "completed", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qquickstate_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "StateChangeScript" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickStateChangeScript", + "lineNumber": 24, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "script", + "read": "script", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlScriptString", + "user": false, + "write": "setScript" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "name", + "read": "name", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setName" + } + ], + "qualifiedClassName": "QQuickStateChangeScript", + "superClasses": [ + { + "access": "public", + "name": "QQuickStateOperation" + }, + { + "access": "public", + "name": "QQuickStateActionEvent" + } + ] + } + ], + "inputFile": "qquickstatechangescript_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "StateGroup" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickStateGroup", + "interfaces": [ + [ + { + "className": "QQmlParserStatus", + "id": "\"org.qt-project.Qt.QQmlParserStatus\"" + } + ] + ], + "lineNumber": 23, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "state", + "notify": "stateChanged", + "read": "state", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setState" + }, + { + "constant": false, + "designable": false, + "final": false, + "index": 1, + "name": "states", + "read": "statesProperty", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlListProperty", + "user": false + }, + { + "constant": false, + "designable": false, + "final": false, + "index": 2, + "name": "transitions", + "read": "transitionsProperty", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlListProperty", + "user": false + } + ], + "qualifiedClassName": "QQuickStateGroup", + "signals": [ + { + "access": "public", + "arguments": [ + { + "type": "QString" + } + ], + "index": 0, + "name": "stateChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QQmlParserStatus" + } + ] + } + ], + "inputFile": "qquickstategroup_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "ParentProperty", + "value": "parent" + }, + { + "name": "QML.Element", + "value": "ParentChange" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickParentChange", + "lineNumber": 28, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "target", + "read": "object", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false, + "write": "setObject" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "parent", + "read": "parent", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false, + "write": "setParent" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "x", + "read": "x", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlScriptString", + "user": false, + "write": "setX" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "y", + "read": "y", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlScriptString", + "user": false, + "write": "setY" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "width", + "read": "width", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlScriptString", + "user": false, + "write": "setWidth" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "height", + "read": "height", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlScriptString", + "user": false, + "write": "setHeight" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "scale", + "read": "scale", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlScriptString", + "user": false, + "write": "setScale" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 7, + "name": "rotation", + "read": "rotation", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlScriptString", + "user": false, + "write": "setRotation" + } + ], + "qualifiedClassName": "QQuickParentChange", + "superClasses": [ + { + "access": "public", + "name": "QQuickStateOperation" + }, + { + "access": "public", + "name": "QQuickStateActionEvent" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickAnchorSet", + "lineNumber": 94, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "left", + "read": "left", + "required": false, + "reset": "resetLeft", + "scriptable": true, + "stored": true, + "type": "QQmlScriptString", + "user": false, + "write": "setLeft" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "right", + "read": "right", + "required": false, + "reset": "resetRight", + "scriptable": true, + "stored": true, + "type": "QQmlScriptString", + "user": false, + "write": "setRight" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "horizontalCenter", + "read": "horizontalCenter", + "required": false, + "reset": "resetHorizontalCenter", + "scriptable": true, + "stored": true, + "type": "QQmlScriptString", + "user": false, + "write": "setHorizontalCenter" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "top", + "read": "top", + "required": false, + "reset": "resetTop", + "scriptable": true, + "stored": true, + "type": "QQmlScriptString", + "user": false, + "write": "setTop" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "bottom", + "read": "bottom", + "required": false, + "reset": "resetBottom", + "scriptable": true, + "stored": true, + "type": "QQmlScriptString", + "user": false, + "write": "setBottom" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "verticalCenter", + "read": "verticalCenter", + "required": false, + "reset": "resetVerticalCenter", + "scriptable": true, + "stored": true, + "type": "QQmlScriptString", + "user": false, + "write": "setVerticalCenter" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 6, + "name": "baseline", + "read": "baseline", + "required": false, + "reset": "resetBaseline", + "scriptable": true, + "stored": true, + "type": "QQmlScriptString", + "user": false, + "write": "setBaseline" + } + ], + "qualifiedClassName": "QQuickAnchorSet", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "AnchorChanges" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickAnchorChanges", + "lineNumber": 149, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "target", + "read": "object", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false, + "write": "setObject" + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 1, + "name": "anchors", + "read": "anchors", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickAnchorSet*", + "user": false + } + ], + "qualifiedClassName": "QQuickAnchorChanges", + "superClasses": [ + { + "access": "public", + "name": "QQuickStateOperation" + }, + { + "access": "public", + "name": "QQuickStateActionEvent" + } + ] + } + ], + "inputFile": "qquickstateoperations_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "SystemPalette" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickSystemPalette", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "ColorGroup", + "values": [ + "Active", + "Inactive", + "Disabled" + ] + } + ], + "lineNumber": 29, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "colorGroup", + "notify": "paletteChanged", + "read": "colorGroup", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickSystemPalette::ColorGroup", + "user": false, + "write": "setColorGroup" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "window", + "notify": "paletteChanged", + "read": "window", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "windowText", + "notify": "paletteChanged", + "read": "windowText", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "base", + "notify": "paletteChanged", + "read": "base", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "text", + "notify": "paletteChanged", + "read": "text", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "alternateBase", + "notify": "paletteChanged", + "read": "alternateBase", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "button", + "notify": "paletteChanged", + "read": "button", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 7, + "name": "buttonText", + "notify": "paletteChanged", + "read": "buttonText", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 8, + "name": "light", + "notify": "paletteChanged", + "read": "light", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 9, + "name": "midlight", + "notify": "paletteChanged", + "read": "midlight", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 10, + "name": "dark", + "notify": "paletteChanged", + "read": "dark", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 11, + "name": "mid", + "notify": "paletteChanged", + "read": "mid", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 12, + "name": "shadow", + "notify": "paletteChanged", + "read": "shadow", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 13, + "name": "highlight", + "notify": "paletteChanged", + "read": "highlight", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 14, + "name": "highlightedText", + "notify": "paletteChanged", + "read": "highlightedText", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 15, + "name": "placeholderText", + "notify": "paletteChanged", + "read": "placeholderText", + "required": false, + "revision": 1538, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 16, + "name": "accent", + "notify": "paletteChanged", + "read": "accent", + "required": false, + "revision": 1543, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + } + ], + "qualifiedClassName": "QQuickSystemPalette", + "signals": [ + { + "access": "public", + "index": 0, + "name": "paletteChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qquicksystempalette_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "TableView" + }, + { + "name": "QML.AddedInVersion", + "value": "524" + }, + { + "name": "QML.Attached", + "value": "QQuickTableViewAttached" + } + ], + "className": "QQuickTableView", + "enums": [ + { + "alias": "PositionModeFlag", + "isClass": false, + "isFlag": true, + "name": "PositionMode", + "values": [ + "AlignLeft", + "AlignRight", + "AlignHCenter", + "AlignTop", + "AlignBottom", + "AlignVCenter", + "AlignCenter", + "Visible", + "Contain" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "SelectionBehavior", + "values": [ + "SelectionDisabled", + "SelectCells", + "SelectRows", + "SelectColumns" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "SelectionMode", + "values": [ + "SingleSelection", + "ContiguousSelection", + "ExtendedSelection" + ] + }, + { + "alias": "EditTrigger", + "isClass": false, + "isFlag": true, + "name": "EditTriggers", + "values": [ + "NoEditTriggers", + "SingleTapped", + "DoubleTapped", + "SelectedTapped", + "EditKeyPressed", + "AnyKeyPressed" + ] + } + ], + "interfaces": [ + [ + { + "className": "QQmlFinalizerHook", + "id": "\"org.qt-project.Qt.QQmlFinalizerHook\"" + } + ] + ], + "lineNumber": 34, + "methods": [ + { + "access": "public", + "index": 30, + "name": "forceLayout", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "cell", + "type": "QPoint" + }, + { + "name": "mode", + "type": "PositionMode" + }, + { + "name": "offset", + "type": "QPointF" + }, + { + "name": "subRect", + "type": "QRectF" + } + ], + "index": 31, + "name": "positionViewAtCell", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "cell", + "type": "QPoint" + }, + { + "name": "mode", + "type": "PositionMode" + }, + { + "name": "offset", + "type": "QPointF" + } + ], + "index": 32, + "isCloned": true, + "name": "positionViewAtCell", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "cell", + "type": "QPoint" + }, + { + "name": "mode", + "type": "PositionMode" + } + ], + "index": 33, + "isCloned": true, + "name": "positionViewAtCell", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "QModelIndex" + }, + { + "name": "mode", + "type": "PositionMode" + }, + { + "name": "offset", + "type": "QPointF" + }, + { + "name": "subRect", + "type": "QRectF" + } + ], + "index": 34, + "name": "positionViewAtIndex", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "QModelIndex" + }, + { + "name": "mode", + "type": "PositionMode" + }, + { + "name": "offset", + "type": "QPointF" + } + ], + "index": 35, + "isCloned": true, + "name": "positionViewAtIndex", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "QModelIndex" + }, + { + "name": "mode", + "type": "PositionMode" + } + ], + "index": 36, + "isCloned": true, + "name": "positionViewAtIndex", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "row", + "type": "int" + }, + { + "name": "mode", + "type": "PositionMode" + }, + { + "name": "offset", + "type": "qreal" + }, + { + "name": "subRect", + "type": "QRectF" + } + ], + "index": 37, + "name": "positionViewAtRow", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "row", + "type": "int" + }, + { + "name": "mode", + "type": "PositionMode" + }, + { + "name": "offset", + "type": "qreal" + } + ], + "index": 38, + "isCloned": true, + "name": "positionViewAtRow", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "row", + "type": "int" + }, + { + "name": "mode", + "type": "PositionMode" + } + ], + "index": 39, + "isCloned": true, + "name": "positionViewAtRow", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "column", + "type": "int" + }, + { + "name": "mode", + "type": "PositionMode" + }, + { + "name": "offset", + "type": "qreal" + }, + { + "name": "subRect", + "type": "QRectF" + } + ], + "index": 40, + "name": "positionViewAtColumn", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "column", + "type": "int" + }, + { + "name": "mode", + "type": "PositionMode" + }, + { + "name": "offset", + "type": "qreal" + } + ], + "index": 41, + "isCloned": true, + "name": "positionViewAtColumn", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "column", + "type": "int" + }, + { + "name": "mode", + "type": "PositionMode" + } + ], + "index": 42, + "isCloned": true, + "name": "positionViewAtColumn", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "cell", + "type": "QPoint" + } + ], + "index": 43, + "name": "itemAtCell", + "returnType": "QQuickItem*" + }, + { + "access": "public", + "arguments": [ + { + "name": "position", + "type": "QPointF" + }, + { + "name": "includeSpacing", + "type": "bool" + } + ], + "index": 44, + "name": "cellAtPosition", + "returnType": "QPoint", + "revision": 1540 + }, + { + "access": "public", + "arguments": [ + { + "name": "position", + "type": "QPointF" + } + ], + "index": 45, + "isCloned": true, + "name": "cellAtPosition", + "returnType": "QPoint", + "revision": 1540 + }, + { + "access": "public", + "arguments": [ + { + "name": "x", + "type": "qreal" + }, + { + "name": "y", + "type": "qreal" + }, + { + "name": "includeSpacing", + "type": "bool" + } + ], + "index": 46, + "name": "cellAtPosition", + "returnType": "QPoint", + "revision": 1540 + }, + { + "access": "public", + "arguments": [ + { + "name": "x", + "type": "qreal" + }, + { + "name": "y", + "type": "qreal" + } + ], + "index": 47, + "isCloned": true, + "name": "cellAtPosition", + "returnType": "QPoint", + "revision": 1540 + }, + { + "access": "public", + "arguments": [ + { + "name": "row", + "type": "int" + }, + { + "name": "column", + "type": "int" + } + ], + "index": 48, + "name": "modelIndex", + "returnType": "QModelIndex", + "revision": 1540 + }, + { + "access": "public", + "arguments": [ + { + "name": "position", + "type": "QPointF" + }, + { + "name": "includeSpacing", + "type": "bool" + } + ], + "index": 49, + "name": "cellAtPos", + "returnType": "QPoint" + }, + { + "access": "public", + "arguments": [ + { + "name": "position", + "type": "QPointF" + } + ], + "index": 50, + "isCloned": true, + "name": "cellAtPos", + "returnType": "QPoint" + }, + { + "access": "public", + "arguments": [ + { + "name": "x", + "type": "qreal" + }, + { + "name": "y", + "type": "qreal" + }, + { + "name": "includeSpacing", + "type": "bool" + } + ], + "index": 51, + "name": "cellAtPos", + "returnType": "QPoint" + }, + { + "access": "public", + "arguments": [ + { + "name": "x", + "type": "qreal" + }, + { + "name": "y", + "type": "qreal" + } + ], + "index": 52, + "isCloned": true, + "name": "cellAtPos", + "returnType": "QPoint" + }, + { + "access": "public", + "arguments": [ + { + "name": "column", + "type": "int" + } + ], + "index": 53, + "name": "isColumnLoaded", + "returnType": "bool", + "revision": 1538 + }, + { + "access": "public", + "arguments": [ + { + "name": "row", + "type": "int" + } + ], + "index": 54, + "name": "isRowLoaded", + "returnType": "bool", + "revision": 1538 + }, + { + "access": "public", + "arguments": [ + { + "name": "column", + "type": "int" + } + ], + "index": 55, + "name": "columnWidth", + "returnType": "qreal", + "revision": 1538 + }, + { + "access": "public", + "arguments": [ + { + "name": "row", + "type": "int" + } + ], + "index": 56, + "name": "rowHeight", + "returnType": "qreal", + "revision": 1538 + }, + { + "access": "public", + "arguments": [ + { + "name": "column", + "type": "int" + } + ], + "index": 57, + "name": "implicitColumnWidth", + "returnType": "qreal", + "revision": 1538 + }, + { + "access": "public", + "arguments": [ + { + "name": "row", + "type": "int" + } + ], + "index": 58, + "name": "implicitRowHeight", + "returnType": "qreal", + "revision": 1538 + }, + { + "access": "public", + "arguments": [ + { + "name": "row", + "type": "int" + }, + { + "name": "column", + "type": "int" + } + ], + "index": 59, + "name": "index", + "returnType": "QModelIndex", + "revision": 1540 + }, + { + "access": "public", + "arguments": [ + { + "name": "cell", + "type": "QPoint" + } + ], + "index": 60, + "name": "modelIndex", + "returnType": "QModelIndex", + "revision": 1540 + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "QModelIndex" + } + ], + "index": 61, + "name": "cellAtIndex", + "returnType": "QPoint", + "revision": 1540 + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "QModelIndex" + } + ], + "index": 62, + "name": "rowAtIndex", + "returnType": "int", + "revision": 1540 + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "QModelIndex" + } + ], + "index": 63, + "name": "columnAtIndex", + "returnType": "int", + "revision": 1540 + }, + { + "access": "public", + "arguments": [ + { + "name": "column", + "type": "int" + }, + { + "name": "size", + "type": "qreal" + } + ], + "index": 64, + "name": "setColumnWidth", + "returnType": "void", + "revision": 1541 + }, + { + "access": "public", + "index": 65, + "name": "clearColumnWidths", + "returnType": "void", + "revision": 1541 + }, + { + "access": "public", + "arguments": [ + { + "name": "column", + "type": "int" + } + ], + "index": 66, + "name": "explicitColumnWidth", + "returnType": "qreal", + "revision": 1541 + }, + { + "access": "public", + "arguments": [ + { + "name": "row", + "type": "int" + }, + { + "name": "size", + "type": "qreal" + } + ], + "index": 67, + "name": "setRowHeight", + "returnType": "void", + "revision": 1541 + }, + { + "access": "public", + "index": 68, + "name": "clearRowHeights", + "returnType": "void", + "revision": 1541 + }, + { + "access": "public", + "arguments": [ + { + "name": "row", + "type": "int" + } + ], + "index": 69, + "name": "explicitRowHeight", + "returnType": "qreal", + "revision": 1541 + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "QModelIndex" + } + ], + "index": 70, + "name": "edit", + "returnType": "void", + "revision": 1541 + }, + { + "access": "public", + "index": 71, + "name": "closeEditor", + "returnType": "void", + "revision": 1541 + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "QModelIndex" + } + ], + "index": 72, + "name": "itemAtIndex", + "returnType": "QQuickItem*", + "revision": 1541 + }, + { + "access": "public", + "arguments": [ + { + "name": "column", + "type": "int" + }, + { + "name": "row", + "type": "int" + } + ], + "index": 73, + "name": "itemAtCell", + "returnType": "QQuickItem*" + }, + { + "access": "public", + "arguments": [ + { + "name": "column", + "type": "int" + }, + { + "name": "row", + "type": "int" + }, + { + "name": "mode", + "type": "PositionMode" + }, + { + "name": "offset", + "type": "QPointF" + }, + { + "name": "subRect", + "type": "QRectF" + } + ], + "index": 74, + "name": "positionViewAtCell", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "column", + "type": "int" + }, + { + "name": "row", + "type": "int" + }, + { + "name": "mode", + "type": "PositionMode" + }, + { + "name": "offset", + "type": "QPointF" + } + ], + "index": 75, + "isCloned": true, + "name": "positionViewAtCell", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "column", + "type": "int" + }, + { + "name": "row", + "type": "int" + }, + { + "name": "mode", + "type": "PositionMode" + } + ], + "index": 76, + "isCloned": true, + "name": "positionViewAtCell", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "source", + "type": "int" + }, + { + "name": "destination", + "type": "int" + } + ], + "index": 77, + "name": "moveColumn", + "returnType": "void", + "revision": 1544 + }, + { + "access": "public", + "arguments": [ + { + "name": "source", + "type": "int" + }, + { + "name": "destination", + "type": "int" + } + ], + "index": 78, + "name": "moveRow", + "returnType": "void", + "revision": 1544 + }, + { + "access": "public", + "index": 79, + "name": "clearColumnReordering", + "returnType": "void", + "revision": 1544 + }, + { + "access": "public", + "index": 80, + "name": "clearRowReordering", + "returnType": "void", + "revision": 1544 + } + ], + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "rows", + "notify": "rowsChanged", + "read": "rows", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "columns", + "notify": "columnsChanged", + "read": "columns", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "rowSpacing", + "notify": "rowSpacingChanged", + "read": "rowSpacing", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setRowSpacing" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "columnSpacing", + "notify": "columnSpacingChanged", + "read": "columnSpacing", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setColumnSpacing" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "rowHeightProvider", + "notify": "rowHeightProviderChanged", + "read": "rowHeightProvider", + "required": false, + "scriptable": true, + "stored": true, + "type": "QJSValue", + "user": false, + "write": "setRowHeightProvider" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "columnWidthProvider", + "notify": "columnWidthProviderChanged", + "read": "columnWidthProvider", + "required": false, + "scriptable": true, + "stored": true, + "type": "QJSValue", + "user": false, + "write": "setColumnWidthProvider" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "model", + "notify": "modelChanged", + "read": "model", + "required": false, + "scriptable": true, + "stored": true, + "type": "QVariant", + "user": false, + "write": "setModel" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 7, + "name": "delegate", + "notify": "delegateChanged", + "read": "delegate", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlComponent*", + "user": false, + "write": "setDelegate" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 8, + "name": "reuseItems", + "notify": "reuseItemsChanged", + "read": "reuseItems", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setReuseItems" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 9, + "name": "contentWidth", + "notify": "contentWidthChanged", + "read": "contentWidth", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setContentWidth" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 10, + "name": "contentHeight", + "notify": "contentHeightChanged", + "read": "contentHeight", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setContentHeight" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 11, + "name": "syncView", + "notify": "syncViewChanged", + "read": "syncView", + "required": false, + "revision": 526, + "scriptable": true, + "stored": true, + "type": "QQuickTableView*", + "user": false, + "write": "setSyncView" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 12, + "name": "syncDirection", + "notify": "syncDirectionChanged", + "read": "syncDirection", + "required": false, + "revision": 526, + "scriptable": true, + "stored": true, + "type": "Qt::Orientations", + "user": false, + "write": "setSyncDirection" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 13, + "name": "leftColumn", + "notify": "leftColumnChanged", + "read": "leftColumn", + "required": false, + "revision": 1536, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 14, + "name": "rightColumn", + "notify": "rightColumnChanged", + "read": "rightColumn", + "required": false, + "revision": 1536, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 15, + "name": "topRow", + "notify": "topRowChanged", + "read": "topRow", + "required": false, + "revision": 1536, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 16, + "name": "bottomRow", + "notify": "bottomRowChanged", + "read": "bottomRow", + "required": false, + "revision": 1536, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 17, + "name": "selectionModel", + "notify": "selectionModelChanged", + "read": "selectionModel", + "required": false, + "revision": 1538, + "scriptable": true, + "stored": true, + "type": "QItemSelectionModel*", + "user": false, + "write": "setSelectionModel" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 18, + "name": "animate", + "notify": "animateChanged", + "read": "animate", + "required": false, + "revision": 1540, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setAnimate" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 19, + "name": "keyNavigationEnabled", + "notify": "keyNavigationEnabledChanged", + "read": "keyNavigationEnabled", + "required": false, + "revision": 1540, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setKeyNavigationEnabled" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 20, + "name": "pointerNavigationEnabled", + "notify": "pointerNavigationEnabledChanged", + "read": "pointerNavigationEnabled", + "required": false, + "revision": 1540, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setPointerNavigationEnabled" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 21, + "name": "currentRow", + "notify": "currentRowChanged", + "read": "currentRow", + "required": false, + "revision": 1540, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 22, + "name": "currentColumn", + "notify": "currentColumnChanged", + "read": "currentColumn", + "required": false, + "revision": 1540, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 23, + "name": "alternatingRows", + "notify": "alternatingRowsChanged", + "read": "alternatingRows", + "required": false, + "revision": 1540, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setAlternatingRows" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 24, + "name": "selectionBehavior", + "notify": "selectionBehaviorChanged", + "read": "selectionBehavior", + "required": false, + "revision": 1540, + "scriptable": true, + "stored": true, + "type": "SelectionBehavior", + "user": false, + "write": "setSelectionBehavior" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 25, + "name": "resizableColumns", + "notify": "resizableColumnsChanged", + "read": "resizableColumns", + "required": false, + "revision": 1541, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setResizableColumns" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 26, + "name": "resizableRows", + "notify": "resizableRowsChanged", + "read": "resizableRows", + "required": false, + "revision": 1541, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setResizableRows" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 27, + "name": "editTriggers", + "notify": "editTriggersChanged", + "read": "editTriggers", + "required": false, + "revision": 1541, + "scriptable": true, + "stored": true, + "type": "EditTriggers", + "user": false, + "write": "setEditTriggers" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 28, + "name": "selectionMode", + "notify": "selectionModeChanged", + "read": "selectionMode", + "required": false, + "revision": 1542, + "scriptable": true, + "stored": true, + "type": "SelectionMode", + "user": false, + "write": "setSelectionMode" + } + ], + "qualifiedClassName": "QQuickTableView", + "signals": [ + { + "access": "public", + "index": 0, + "name": "rowsChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "columnsChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "rowSpacingChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "columnSpacingChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "rowHeightProviderChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "columnWidthProviderChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "modelChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "delegateChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 8, + "name": "reuseItemsChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 9, + "name": "syncViewChanged", + "returnType": "void", + "revision": 526 + }, + { + "access": "public", + "index": 10, + "name": "syncDirectionChanged", + "returnType": "void", + "revision": 526 + }, + { + "access": "public", + "index": 11, + "name": "leftColumnChanged", + "returnType": "void", + "revision": 1536 + }, + { + "access": "public", + "index": 12, + "name": "rightColumnChanged", + "returnType": "void", + "revision": 1536 + }, + { + "access": "public", + "index": 13, + "name": "topRowChanged", + "returnType": "void", + "revision": 1536 + }, + { + "access": "public", + "index": 14, + "name": "bottomRowChanged", + "returnType": "void", + "revision": 1536 + }, + { + "access": "public", + "index": 15, + "name": "selectionModelChanged", + "returnType": "void", + "revision": 1538 + }, + { + "access": "public", + "index": 16, + "name": "animateChanged", + "returnType": "void", + "revision": 1540 + }, + { + "access": "public", + "index": 17, + "name": "keyNavigationEnabledChanged", + "returnType": "void", + "revision": 1540 + }, + { + "access": "public", + "index": 18, + "name": "pointerNavigationEnabledChanged", + "returnType": "void", + "revision": 1540 + }, + { + "access": "public", + "index": 19, + "name": "currentRowChanged", + "returnType": "void", + "revision": 1540 + }, + { + "access": "public", + "index": 20, + "name": "currentColumnChanged", + "returnType": "void", + "revision": 1540 + }, + { + "access": "public", + "index": 21, + "name": "alternatingRowsChanged", + "returnType": "void", + "revision": 1540 + }, + { + "access": "public", + "index": 22, + "name": "selectionBehaviorChanged", + "returnType": "void", + "revision": 1540 + }, + { + "access": "public", + "index": 23, + "name": "resizableColumnsChanged", + "returnType": "void", + "revision": 1541 + }, + { + "access": "public", + "index": 24, + "name": "resizableRowsChanged", + "returnType": "void", + "revision": 1541 + }, + { + "access": "public", + "index": 25, + "name": "editTriggersChanged", + "returnType": "void", + "revision": 1541 + }, + { + "access": "public", + "index": 26, + "name": "layoutChanged", + "returnType": "void", + "revision": 1541 + }, + { + "access": "public", + "index": 27, + "name": "selectionModeChanged", + "returnType": "void", + "revision": 1542 + }, + { + "access": "public", + "arguments": [ + { + "name": "logicalIndex", + "type": "int" + }, + { + "name": "oldVisualIndex", + "type": "int" + }, + { + "name": "newVisualIndex", + "type": "int" + } + ], + "index": 28, + "name": "rowMoved", + "returnType": "void", + "revision": 1544 + }, + { + "access": "public", + "arguments": [ + { + "name": "logicalIndex", + "type": "int" + }, + { + "name": "oldVisualIndex", + "type": "int" + }, + { + "name": "newVisualIndex", + "type": "int" + } + ], + "index": 29, + "name": "columnMoved", + "returnType": "void", + "revision": 1544 + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickFlickable" + }, + { + "access": "public", + "name": "QQmlFinalizerHook" + } + ] + }, + { + "className": "QQuickTableViewAttached", + "lineNumber": 297, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "view", + "notify": "viewChanged", + "read": "view", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickTableView*", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "editDelegate", + "notify": "editDelegateChanged", + "read": "editDelegate", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlComponent*", + "user": false, + "write": "setEditDelegate" + } + ], + "qualifiedClassName": "QQuickTableViewAttached", + "signals": [ + { + "access": "public", + "index": 0, + "name": "viewChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "pooled", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "reused", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "editDelegateChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "commit", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qquicktableview_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQuickTableViewHoverHandler", + "lineNumber": 56, + "object": true, + "qualifiedClassName": "QQuickTableViewHoverHandler", + "superClasses": [ + { + "access": "public", + "name": "QQuickHoverHandler" + } + ] + }, + { + "className": "QQuickTableViewPointerHandler", + "lineNumber": 73, + "object": true, + "qualifiedClassName": "QQuickTableViewPointerHandler", + "superClasses": [ + { + "access": "public", + "name": "QQuickSinglePointHandler" + } + ] + }, + { + "className": "QQuickTableViewResizeHandler", + "lineNumber": 102, + "object": true, + "qualifiedClassName": "QQuickTableViewResizeHandler", + "superClasses": [ + { + "access": "public", + "name": "QQuickTableViewPointerHandler" + } + ] + }, + { + "className": "QQuickTableViewSectionDragHandler", + "lineNumber": 128, + "object": true, + "qualifiedClassName": "QQuickTableViewSectionDragHandler", + "superClasses": [ + { + "access": "public", + "name": "QQuickTableViewPointerHandler" + } + ] + }, + { + "className": "QQuickTableViewTapHandler", + "lineNumber": 168, + "object": true, + "qualifiedClassName": "QQuickTableViewTapHandler", + "superClasses": [ + { + "access": "public", + "name": "QQuickTapHandler" + } + ] + } + ], + "inputFile": "qquicktableview_p_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "TapHandler" + }, + { + "name": "QML.AddedInVersion", + "value": "524" + } + ], + "className": "QQuickTapHandler", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "GesturePolicy", + "values": [ + "DragThreshold", + "WithinBounds", + "ReleaseWithinBounds", + "DragWithinBounds" + ] + }, + { + "alias": "ExclusiveSignal", + "isClass": false, + "isFlag": true, + "name": "ExclusiveSignals", + "values": [ + "NotExclusive", + "SingleTap", + "DoubleTap" + ] + } + ], + "lineNumber": 27, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "pressed", + "notify": "pressedChanged", + "read": "isPressed", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "tapCount", + "notify": "tapCountChanged", + "read": "tapCount", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "timeHeld", + "notify": "timeHeldChanged", + "read": "timeHeld", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "longPressThreshold", + "notify": "longPressThresholdChanged", + "read": "longPressThreshold", + "required": false, + "reset": "resetLongPressThreshold", + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setLongPressThreshold" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "gesturePolicy", + "notify": "gesturePolicyChanged", + "read": "gesturePolicy", + "required": false, + "scriptable": true, + "stored": true, + "type": "GesturePolicy", + "user": false, + "write": "setGesturePolicy" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "exclusiveSignals", + "notify": "exclusiveSignalsChanged", + "read": "exclusiveSignals", + "required": false, + "revision": 1541, + "scriptable": true, + "stored": true, + "type": "QQuickTapHandler::ExclusiveSignals", + "user": false, + "write": "setExclusiveSignals" + } + ], + "qualifiedClassName": "QQuickTapHandler", + "signals": [ + { + "access": "public", + "index": 0, + "name": "pressedChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "tapCountChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "timeHeldChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "longPressThresholdChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "gesturePolicyChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "exclusiveSignalsChanged", + "returnType": "void", + "revision": 1541 + }, + { + "access": "public", + "arguments": [ + { + "name": "eventPoint", + "type": "QEventPoint" + }, + { + "type": "Qt::MouseButton" + } + ], + "index": 6, + "name": "tapped", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "eventPoint", + "type": "QEventPoint" + }, + { + "type": "Qt::MouseButton" + } + ], + "index": 7, + "name": "singleTapped", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "eventPoint", + "type": "QEventPoint" + }, + { + "type": "Qt::MouseButton" + } + ], + "index": 8, + "name": "doubleTapped", + "returnType": "void" + }, + { + "access": "public", + "index": 9, + "name": "longPressed", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickSinglePointHandler" + } + ] + } + ], + "inputFile": "qquicktaphandler_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "Text" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickText", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "HAlignment", + "values": [ + "AlignLeft", + "AlignRight", + "AlignHCenter", + "AlignJustify" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "VAlignment", + "values": [ + "AlignTop", + "AlignBottom", + "AlignVCenter" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "TextStyle", + "values": [ + "Normal", + "Outline", + "Raised", + "Sunken" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "TextFormat", + "values": [ + "PlainText", + "RichText", + "MarkdownText", + "AutoText", + "StyledText" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "TextElideMode", + "values": [ + "ElideLeft", + "ElideRight", + "ElideMiddle", + "ElideNone" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "WrapMode", + "values": [ + "NoWrap", + "WordWrap", + "WrapAnywhere", + "WrapAtWordBoundaryOrAnywhere", + "Wrap" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "RenderType", + "values": [ + "QtRendering", + "NativeRendering", + "CurveRendering" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "RenderTypeQuality", + "values": [ + "DefaultRenderTypeQuality", + "LowRenderTypeQuality", + "NormalRenderTypeQuality", + "HighRenderTypeQuality", + "VeryHighRenderTypeQuality" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "LineHeightMode", + "values": [ + "ProportionalHeight", + "FixedHeight" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "FontSizeMode", + "values": [ + "FixedSize", + "HorizontalFit", + "VerticalFit", + "Fit" + ] + } + ], + "interfaces": [ + [ + { + "className": "QQuickTextInterface", + "id": "\"org.qt-project.Qt.QQuickTextInterface\"" + } + ] + ], + "lineNumber": 27, + "methods": [ + { + "access": "public", + "index": 40, + "name": "forceLayout", + "returnType": "void", + "revision": 521 + }, + { + "access": "public", + "arguments": [ + { + "name": "x", + "type": "qreal" + }, + { + "name": "y", + "type": "qreal" + } + ], + "index": 41, + "name": "linkAt", + "returnType": "QString", + "revision": 515 + } + ], + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "text", + "notify": "textChanged", + "read": "text", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setText" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "font", + "notify": "fontChanged", + "read": "font", + "required": false, + "scriptable": true, + "stored": true, + "type": "QFont", + "user": false, + "write": "setFont" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "color", + "notify": "colorChanged", + "read": "color", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false, + "write": "setColor" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "linkColor", + "notify": "linkColorChanged", + "read": "linkColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false, + "write": "setLinkColor" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "style", + "notify": "styleChanged", + "read": "style", + "required": false, + "scriptable": true, + "stored": true, + "type": "TextStyle", + "user": false, + "write": "setStyle" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "styleColor", + "notify": "styleColorChanged", + "read": "styleColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false, + "write": "setStyleColor" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "horizontalAlignment", + "notify": "horizontalAlignmentChanged", + "read": "hAlign", + "required": false, + "reset": "resetHAlign", + "scriptable": true, + "stored": true, + "type": "HAlignment", + "user": false, + "write": "setHAlign" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 7, + "name": "effectiveHorizontalAlignment", + "notify": "effectiveHorizontalAlignmentChanged", + "read": "effectiveHAlign", + "required": false, + "scriptable": true, + "stored": true, + "type": "HAlignment", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 8, + "name": "verticalAlignment", + "notify": "verticalAlignmentChanged", + "read": "vAlign", + "required": false, + "scriptable": true, + "stored": true, + "type": "VAlignment", + "user": false, + "write": "setVAlign" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 9, + "name": "wrapMode", + "notify": "wrapModeChanged", + "read": "wrapMode", + "required": false, + "scriptable": true, + "stored": true, + "type": "WrapMode", + "user": false, + "write": "setWrapMode" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 10, + "name": "lineCount", + "notify": "lineCountChanged", + "read": "lineCount", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 11, + "name": "truncated", + "notify": "truncatedChanged", + "read": "truncated", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 12, + "name": "maximumLineCount", + "notify": "maximumLineCountChanged", + "read": "maximumLineCount", + "required": false, + "reset": "resetMaximumLineCount", + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setMaximumLineCount" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 13, + "name": "textFormat", + "notify": "textFormatChanged", + "read": "textFormat", + "required": false, + "scriptable": true, + "stored": true, + "type": "TextFormat", + "user": false, + "write": "setTextFormat" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 14, + "name": "elide", + "notify": "elideModeChanged", + "read": "elideMode", + "required": false, + "scriptable": true, + "stored": true, + "type": "TextElideMode", + "user": false, + "write": "setElideMode" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 15, + "name": "contentWidth", + "notify": "contentWidthChanged", + "read": "contentWidth", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 16, + "name": "contentHeight", + "notify": "contentHeightChanged", + "read": "contentHeight", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 17, + "name": "paintedWidth", + "notify": "contentWidthChanged", + "read": "contentWidth", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 18, + "name": "paintedHeight", + "notify": "contentHeightChanged", + "read": "contentHeight", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 19, + "name": "lineHeight", + "notify": "lineHeightChanged", + "read": "lineHeight", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setLineHeight" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 20, + "name": "lineHeightMode", + "notify": "lineHeightModeChanged", + "read": "lineHeightMode", + "required": false, + "scriptable": true, + "stored": true, + "type": "LineHeightMode", + "user": false, + "write": "setLineHeightMode" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 21, + "name": "baseUrl", + "notify": "baseUrlChanged", + "read": "baseUrl", + "required": false, + "reset": "resetBaseUrl", + "scriptable": true, + "stored": true, + "type": "QUrl", + "user": false, + "write": "setBaseUrl" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 22, + "name": "minimumPixelSize", + "notify": "minimumPixelSizeChanged", + "read": "minimumPixelSize", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setMinimumPixelSize" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 23, + "name": "minimumPointSize", + "notify": "minimumPointSizeChanged", + "read": "minimumPointSize", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setMinimumPointSize" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 24, + "name": "fontSizeMode", + "notify": "fontSizeModeChanged", + "read": "fontSizeMode", + "required": false, + "scriptable": true, + "stored": true, + "type": "FontSizeMode", + "user": false, + "write": "setFontSizeMode" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 25, + "name": "renderType", + "notify": "renderTypeChanged", + "read": "renderType", + "required": false, + "scriptable": true, + "stored": true, + "type": "RenderType", + "user": false, + "write": "setRenderType" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 26, + "name": "hoveredLink", + "notify": "linkHovered", + "read": "hoveredLink", + "required": false, + "revision": 514, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 27, + "name": "renderTypeQuality", + "notify": "renderTypeQualityChanged", + "read": "renderTypeQuality", + "required": false, + "revision": 1536, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setRenderTypeQuality" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 28, + "name": "padding", + "notify": "paddingChanged", + "read": "padding", + "required": false, + "reset": "resetPadding", + "revision": 518, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setPadding" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 29, + "name": "topPadding", + "notify": "topPaddingChanged", + "read": "topPadding", + "required": false, + "reset": "resetTopPadding", + "revision": 518, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setTopPadding" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 30, + "name": "leftPadding", + "notify": "leftPaddingChanged", + "read": "leftPadding", + "required": false, + "reset": "resetLeftPadding", + "revision": 518, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setLeftPadding" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 31, + "name": "rightPadding", + "notify": "rightPaddingChanged", + "read": "rightPadding", + "required": false, + "reset": "resetRightPadding", + "revision": 518, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setRightPadding" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 32, + "name": "bottomPadding", + "notify": "bottomPaddingChanged", + "read": "bottomPadding", + "required": false, + "reset": "resetBottomPadding", + "revision": 518, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setBottomPadding" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 33, + "name": "fontInfo", + "notify": "fontInfoChanged", + "read": "fontInfo", + "required": false, + "revision": 521, + "scriptable": true, + "stored": true, + "type": "QJSValue", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 34, + "name": "advance", + "notify": "contentSizeChanged", + "read": "advance", + "required": false, + "revision": 522, + "scriptable": true, + "stored": true, + "type": "QSizeF", + "user": false + } + ], + "qualifiedClassName": "QQuickText", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "text", + "type": "QString" + } + ], + "index": 0, + "name": "textChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "link", + "type": "QString" + } + ], + "index": 1, + "name": "linkActivated", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "link", + "type": "QString" + } + ], + "index": 2, + "name": "linkHovered", + "returnType": "void", + "revision": 514 + }, + { + "access": "public", + "arguments": [ + { + "name": "font", + "type": "QFont" + } + ], + "index": 3, + "name": "fontChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "colorChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "linkColorChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "style", + "type": "QQuickText::TextStyle" + } + ], + "index": 6, + "name": "styleChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "styleColorChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "alignment", + "type": "QQuickText::HAlignment" + } + ], + "index": 8, + "name": "horizontalAlignmentChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "alignment", + "type": "QQuickText::VAlignment" + } + ], + "index": 9, + "name": "verticalAlignmentChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 10, + "name": "wrapModeChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 11, + "name": "lineCountChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 12, + "name": "truncatedChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 13, + "name": "maximumLineCountChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "textFormat", + "type": "QQuickText::TextFormat" + } + ], + "index": 14, + "name": "textFormatChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "mode", + "type": "QQuickText::TextElideMode" + } + ], + "index": 15, + "name": "elideModeChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 16, + "name": "contentSizeChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "contentWidth", + "type": "qreal" + } + ], + "index": 17, + "name": "contentWidthChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "contentHeight", + "type": "qreal" + } + ], + "index": 18, + "name": "contentHeightChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "lineHeight", + "type": "qreal" + } + ], + "index": 19, + "name": "lineHeightChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "mode", + "type": "LineHeightMode" + } + ], + "index": 20, + "name": "lineHeightModeChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 21, + "name": "fontSizeModeChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 22, + "name": "minimumPixelSizeChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 23, + "name": "minimumPointSizeChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 24, + "name": "effectiveHorizontalAlignmentChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "line", + "type": "QQuickTextLine*" + } + ], + "index": 25, + "name": "lineLaidOut", + "returnType": "void" + }, + { + "access": "public", + "index": 26, + "name": "baseUrlChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 27, + "name": "renderTypeChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 28, + "name": "paddingChanged", + "returnType": "void", + "revision": 518 + }, + { + "access": "public", + "index": 29, + "name": "topPaddingChanged", + "returnType": "void", + "revision": 518 + }, + { + "access": "public", + "index": 30, + "name": "leftPaddingChanged", + "returnType": "void", + "revision": 518 + }, + { + "access": "public", + "index": 31, + "name": "rightPaddingChanged", + "returnType": "void", + "revision": 518 + }, + { + "access": "public", + "index": 32, + "name": "bottomPaddingChanged", + "returnType": "void", + "revision": 518 + }, + { + "access": "public", + "index": 33, + "name": "fontInfoChanged", + "returnType": "void", + "revision": 521 + }, + { + "access": "public", + "index": 34, + "name": "renderTypeQualityChanged", + "returnType": "void", + "revision": 1536 + } + ], + "slots": [ + { + "access": "private", + "index": 35, + "name": "q_updateLayout", + "returnType": "void" + }, + { + "access": "private", + "index": 36, + "name": "triggerPreprocess", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "type", + "type": "int" + }, + { + "name": "source", + "type": "QUrl" + } + ], + "index": 37, + "name": "loadResource", + "returnType": "QVariant", + "revision": 1543 + }, + { + "access": "private", + "index": 38, + "name": "resourceRequestFinished", + "returnType": "void" + }, + { + "access": "private", + "index": 39, + "name": "imageDownloadFinished", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickImplicitSizeItem" + }, + { + "access": "public", + "name": "QQuickTextInterface" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickTextLine", + "lineNumber": 316, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "number", + "read": "number", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "width", + "read": "width", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setWidth" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "height", + "read": "height", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setHeight" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "x", + "read": "x", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setX" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "y", + "read": "y", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setY" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "implicitWidth", + "read": "implicitWidth", + "required": false, + "revision": 527, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 6, + "name": "isLast", + "read": "isLast", + "required": false, + "revision": 527, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + } + ], + "qualifiedClassName": "QQuickTextLine", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qquicktext_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQuickTextControl", + "lineNumber": 40, + "methods": [ + { + "access": "public", + "arguments": [ + { + "name": "query", + "type": "Qt::InputMethodQuery" + }, + { + "name": "argument", + "type": "QVariant" + } + ], + "index": 30, + "name": "inputMethodQuery", + "returnType": "QVariant" + } + ], + "object": true, + "qualifiedClassName": "QQuickTextControl", + "signals": [ + { + "access": "public", + "index": 0, + "name": "textChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "preeditTextChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "from", + "type": "int" + }, + { + "name": "charsRemoved", + "type": "int" + }, + { + "name": "charsAdded", + "type": "int" + } + ], + "index": 2, + "name": "contentsChange", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "b", + "type": "bool" + } + ], + "index": 3, + "name": "undoAvailable", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "b", + "type": "bool" + } + ], + "index": 4, + "name": "redoAvailable", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "format", + "type": "QTextCharFormat" + } + ], + "index": 5, + "name": "currentCharFormatChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "b", + "type": "bool" + } + ], + "index": 6, + "name": "copyAvailable", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "selectionChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 8, + "name": "cursorPositionChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "overwriteMode", + "type": "bool" + } + ], + "index": 9, + "name": "overwriteModeChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 10, + "name": "updateCursorRequest", + "returnType": "void" + }, + { + "access": "public", + "index": 11, + "name": "updateRequest", + "returnType": "void" + }, + { + "access": "public", + "index": 12, + "name": "cursorRectangleChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "link", + "type": "QString" + } + ], + "index": 13, + "name": "linkActivated", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "link", + "type": "QString" + } + ], + "index": 14, + "name": "linkHovered", + "returnType": "void" + }, + { + "access": "public", + "index": 15, + "name": "markerClicked", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "marker", + "type": "bool" + } + ], + "index": 16, + "name": "markerHovered", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "text", + "type": "QString" + } + ], + "index": 17, + "name": "setPlainText", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "text", + "type": "QString" + } + ], + "index": 18, + "name": "setMarkdownText", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "text", + "type": "QString" + } + ], + "index": 19, + "name": "setHtml", + "returnType": "void" + }, + { + "access": "public", + "index": 20, + "name": "cut", + "returnType": "void" + }, + { + "access": "public", + "index": 21, + "name": "copy", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "mode", + "type": "QClipboard::Mode" + } + ], + "index": 22, + "name": "paste", + "returnType": "void" + }, + { + "access": "public", + "index": 23, + "isCloned": true, + "name": "paste", + "returnType": "void" + }, + { + "access": "public", + "index": 24, + "name": "undo", + "returnType": "void" + }, + { + "access": "public", + "index": 25, + "name": "redo", + "returnType": "void" + }, + { + "access": "public", + "index": 26, + "name": "clear", + "returnType": "void" + }, + { + "access": "public", + "index": 27, + "name": "selectAll", + "returnType": "void" + }, + { + "access": "private", + "index": 28, + "name": "_q_updateCurrentCharFormatAndSelection", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "type": "QTextCursor" + } + ], + "index": 29, + "name": "_q_updateCursorPosChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QInputControl" + } + ] + } + ], + "inputFile": "qquicktextcontrol_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "TextDocument" + }, + { + "name": "QML.Creatable", + "value": "false" + }, + { + "name": "QML.UncreatableReason", + "value": "TextDocument is only available as a property of TextEdit or TextArea." + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickTextDocument", + "enums": [ + { + "isClass": true, + "isFlag": false, + "name": "Status", + "type": "quint8", + "values": [ + "Null", + "Loading", + "Loaded", + "Saving", + "Saved", + "ReadError", + "WriteError", + "NonLocalFileError" + ] + } + ], + "lineNumber": 13, + "methods": [ + { + "access": "public", + "index": 5, + "name": "save", + "returnType": "void", + "revision": 1543 + }, + { + "access": "public", + "arguments": [ + { + "name": "url", + "type": "QUrl" + } + ], + "index": 6, + "name": "saveAs", + "returnType": "void", + "revision": 1543 + } + ], + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "source", + "notify": "sourceChanged", + "read": "source", + "required": false, + "revision": 1543, + "scriptable": true, + "stored": true, + "type": "QUrl", + "user": false, + "write": "setSource" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "modified", + "notify": "modifiedChanged", + "read": "isModified", + "required": false, + "revision": 1543, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setModified" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "status", + "notify": "statusChanged", + "read": "status", + "required": false, + "revision": 1543, + "scriptable": true, + "stored": true, + "type": "Status", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "errorString", + "notify": "errorStringChanged", + "read": "errorString", + "required": false, + "revision": 1543, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + } + ], + "qualifiedClassName": "QQuickTextDocument", + "signals": [ + { + "access": "public", + "index": 0, + "name": "textDocumentChanged", + "returnType": "void", + "revision": 1543 + }, + { + "access": "public", + "index": 1, + "name": "sourceChanged", + "returnType": "void", + "revision": 1543 + }, + { + "access": "public", + "index": 2, + "name": "modifiedChanged", + "returnType": "void", + "revision": 1543 + }, + { + "access": "public", + "index": 3, + "name": "statusChanged", + "returnType": "void", + "revision": 1543 + }, + { + "access": "public", + "index": 4, + "name": "errorStringChanged", + "returnType": "void", + "revision": 1543 + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qquicktextdocument.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQuickTextImageHandler", + "interfaces": [ + [ + { + "className": "QTextObjectInterface", + "id": "\"org.qt-project.Qt.QTextObjectInterface\"" + } + ] + ], + "lineNumber": 44, + "object": true, + "qualifiedClassName": "QQuickTextImageHandler", + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QTextObjectInterface" + } + ] + } + ], + "inputFile": "qquicktextdocument_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.Foreign", + "value": "QTextBlock" + }, + { + "name": "QML.Extended", + "value": "QQuickTextBlockForeign" + } + ], + "className": "QQuickTextBlockForeign", + "gadget": true, + "lineNumber": 31, + "qualifiedClassName": "QQuickTextBlockForeign" + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "TextEdit" + }, + { + "name": "QML.AddedInVersion", + "value": "1540" + } + ], + "className": "QQuickTextEdit", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "HAlignment", + "values": [ + "AlignLeft", + "AlignRight", + "AlignHCenter", + "AlignJustify" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "VAlignment", + "values": [ + "AlignTop", + "AlignBottom", + "AlignVCenter" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "TextFormat", + "values": [ + "PlainText", + "RichText", + "AutoText", + "MarkdownText" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "WrapMode", + "values": [ + "NoWrap", + "WordWrap", + "WrapAnywhere", + "WrapAtWordBoundaryOrAnywhere", + "Wrap" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "SelectionMode", + "values": [ + "SelectCharacters", + "SelectWords" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "RenderType", + "values": [ + "QtRendering", + "NativeRendering", + "CurveRendering" + ] + } + ], + "interfaces": [ + [ + { + "className": "QQuickTextInterface", + "id": "\"org.qt-project.Qt.QQuickTextInterface\"" + } + ] + ], + "lineNumber": 39, + "methods": [ + { + "access": "public", + "arguments": [ + { + "name": "query", + "type": "Qt::InputMethodQuery" + }, + { + "name": "argument", + "type": "QVariant" + } + ], + "index": 75, + "name": "inputMethodQuery", + "returnType": "QVariant", + "revision": 516 + }, + { + "access": "public", + "arguments": [ + { + "type": "int" + } + ], + "index": 76, + "name": "positionToRectangle", + "returnType": "QRectF" + }, + { + "access": "public", + "arguments": [ + { + "name": "x", + "type": "qreal" + }, + { + "name": "y", + "type": "qreal" + } + ], + "index": 77, + "name": "positionAt", + "returnType": "int" + }, + { + "access": "public", + "arguments": [ + { + "name": "pos", + "type": "int" + } + ], + "index": 78, + "name": "moveCursorSelection", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "pos", + "type": "int" + }, + { + "name": "mode", + "type": "SelectionMode" + } + ], + "index": 79, + "name": "moveCursorSelection", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "start", + "type": "int" + }, + { + "name": "end", + "type": "int" + } + ], + "index": 80, + "name": "getText", + "returnType": "QString" + }, + { + "access": "public", + "arguments": [ + { + "name": "start", + "type": "int" + }, + { + "name": "end", + "type": "int" + } + ], + "index": 81, + "name": "getFormattedText", + "returnType": "QString" + }, + { + "access": "public", + "arguments": [ + { + "name": "x", + "type": "qreal" + }, + { + "name": "y", + "type": "qreal" + } + ], + "index": 82, + "name": "linkAt", + "returnType": "QString", + "revision": 515 + } + ], + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "text", + "notify": "textChanged", + "read": "text", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setText" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "color", + "notify": "colorChanged", + "read": "color", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false, + "write": "setColor" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "selectionColor", + "notify": "selectionColorChanged", + "read": "selectionColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false, + "write": "setSelectionColor" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "selectedTextColor", + "notify": "selectedTextColorChanged", + "read": "selectedTextColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false, + "write": "setSelectedTextColor" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "font", + "notify": "fontChanged", + "read": "font", + "required": false, + "scriptable": true, + "stored": true, + "type": "QFont", + "user": false, + "write": "setFont" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "horizontalAlignment", + "notify": "horizontalAlignmentChanged", + "read": "hAlign", + "required": false, + "reset": "resetHAlign", + "scriptable": true, + "stored": true, + "type": "HAlignment", + "user": false, + "write": "setHAlign" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "effectiveHorizontalAlignment", + "notify": "effectiveHorizontalAlignmentChanged", + "read": "effectiveHAlign", + "required": false, + "scriptable": true, + "stored": true, + "type": "HAlignment", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 7, + "name": "verticalAlignment", + "notify": "verticalAlignmentChanged", + "read": "vAlign", + "required": false, + "scriptable": true, + "stored": true, + "type": "VAlignment", + "user": false, + "write": "setVAlign" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 8, + "name": "wrapMode", + "notify": "wrapModeChanged", + "read": "wrapMode", + "required": false, + "scriptable": true, + "stored": true, + "type": "WrapMode", + "user": false, + "write": "setWrapMode" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 9, + "name": "lineCount", + "notify": "lineCountChanged", + "read": "lineCount", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 10, + "name": "length", + "notify": "textChanged", + "read": "length", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 11, + "name": "contentWidth", + "notify": "contentSizeChanged", + "read": "contentWidth", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 12, + "name": "contentHeight", + "notify": "contentSizeChanged", + "read": "contentHeight", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 13, + "name": "paintedWidth", + "notify": "contentSizeChanged", + "read": "contentWidth", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 14, + "name": "paintedHeight", + "notify": "contentSizeChanged", + "read": "contentHeight", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 15, + "name": "textFormat", + "notify": "textFormatChanged", + "read": "textFormat", + "required": false, + "scriptable": true, + "stored": true, + "type": "TextFormat", + "user": false, + "write": "setTextFormat" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 16, + "name": "readOnly", + "notify": "readOnlyChanged", + "read": "isReadOnly", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setReadOnly" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 17, + "name": "cursorVisible", + "notify": "cursorVisibleChanged", + "read": "isCursorVisible", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setCursorVisible" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 18, + "name": "cursorPosition", + "notify": "cursorPositionChanged", + "read": "cursorPosition", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setCursorPosition" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 19, + "name": "cursorRectangle", + "notify": "cursorRectangleChanged", + "read": "cursorRectangle", + "required": false, + "scriptable": true, + "stored": true, + "type": "QRectF", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 20, + "name": "cursorDelegate", + "notify": "cursorDelegateChanged", + "read": "cursorDelegate", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlComponent*", + "user": false, + "write": "setCursorDelegate" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 21, + "name": "overwriteMode", + "notify": "overwriteModeChanged", + "read": "overwriteMode", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setOverwriteMode" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 22, + "name": "selectionStart", + "notify": "selectionStartChanged", + "read": "selectionStart", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 23, + "name": "selectionEnd", + "notify": "selectionEndChanged", + "read": "selectionEnd", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 24, + "name": "selectedText", + "notify": "selectedTextChanged", + "read": "selectedText", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 25, + "name": "activeFocusOnPress", + "notify": "activeFocusOnPressChanged", + "read": "focusOnPress", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setFocusOnPress" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 26, + "name": "persistentSelection", + "notify": "persistentSelectionChanged", + "read": "persistentSelection", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setPersistentSelection" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 27, + "name": "textMargin", + "notify": "textMarginChanged", + "read": "textMargin", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setTextMargin" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 28, + "name": "inputMethodHints", + "notify": "inputMethodHintsChanged", + "read": "inputMethodHints", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::InputMethodHints", + "user": false, + "write": "setInputMethodHints" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 29, + "name": "selectByKeyboard", + "notify": "selectByKeyboardChanged", + "read": "selectByKeyboard", + "required": false, + "revision": 513, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setSelectByKeyboard" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 30, + "name": "selectByMouse", + "notify": "selectByMouseChanged", + "read": "selectByMouse", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setSelectByMouse" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 31, + "name": "mouseSelectionMode", + "notify": "mouseSelectionModeChanged", + "read": "mouseSelectionMode", + "required": false, + "scriptable": true, + "stored": true, + "type": "SelectionMode", + "user": false, + "write": "setMouseSelectionMode" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 32, + "name": "canPaste", + "notify": "canPasteChanged", + "read": "canPaste", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 33, + "name": "canUndo", + "notify": "canUndoChanged", + "read": "canUndo", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 34, + "name": "canRedo", + "notify": "canRedoChanged", + "read": "canRedo", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 35, + "name": "inputMethodComposing", + "notify": "inputMethodComposingChanged", + "read": "isInputMethodComposing", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 36, + "name": "baseUrl", + "notify": "baseUrlChanged", + "read": "baseUrl", + "required": false, + "reset": "resetBaseUrl", + "scriptable": true, + "stored": true, + "type": "QUrl", + "user": false, + "write": "setBaseUrl" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 37, + "name": "renderType", + "notify": "renderTypeChanged", + "read": "renderType", + "required": false, + "scriptable": true, + "stored": true, + "type": "RenderType", + "user": false, + "write": "setRenderType" + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 38, + "name": "textDocument", + "read": "textDocument", + "required": false, + "revision": 513, + "scriptable": true, + "stored": true, + "type": "QQuickTextDocument*", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 39, + "name": "hoveredLink", + "notify": "linkHovered", + "read": "hoveredLink", + "required": false, + "revision": 514, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 40, + "name": "padding", + "notify": "paddingChanged", + "read": "padding", + "required": false, + "reset": "resetPadding", + "revision": 518, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setPadding" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 41, + "name": "topPadding", + "notify": "topPaddingChanged", + "read": "topPadding", + "required": false, + "reset": "resetTopPadding", + "revision": 518, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setTopPadding" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 42, + "name": "leftPadding", + "notify": "leftPaddingChanged", + "read": "leftPadding", + "required": false, + "reset": "resetLeftPadding", + "revision": 518, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setLeftPadding" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 43, + "name": "rightPadding", + "notify": "rightPaddingChanged", + "read": "rightPadding", + "required": false, + "reset": "resetRightPadding", + "revision": 518, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setRightPadding" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 44, + "name": "bottomPadding", + "notify": "bottomPaddingChanged", + "read": "bottomPadding", + "required": false, + "reset": "resetBottomPadding", + "revision": 518, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setBottomPadding" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 45, + "name": "preeditText", + "notify": "preeditTextChanged", + "read": "preeditText", + "required": false, + "revision": 519, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 46, + "name": "tabStopDistance", + "notify": "tabStopDistanceChanged", + "read": "tabStopDistance", + "required": false, + "revision": 522, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setTabStopDistance" + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 47, + "name": "cursorSelection", + "read": "cursorSelection", + "required": false, + "revision": 1543, + "scriptable": true, + "stored": true, + "type": "QQuickTextSelection*", + "user": false + } + ], + "qualifiedClassName": "QQuickTextEdit", + "signals": [ + { + "access": "public", + "index": 0, + "name": "textChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "preeditTextChanged", + "returnType": "void", + "revision": 519 + }, + { + "access": "public", + "index": 2, + "name": "contentSizeChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "cursorPositionChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "cursorRectangleChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "selectionStartChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "selectionEndChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "selectedTextChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "color", + "type": "QColor" + } + ], + "index": 8, + "name": "colorChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "color", + "type": "QColor" + } + ], + "index": 9, + "name": "selectionColorChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "color", + "type": "QColor" + } + ], + "index": 10, + "name": "selectedTextColorChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "font", + "type": "QFont" + } + ], + "index": 11, + "name": "fontChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "alignment", + "type": "QQuickTextEdit::HAlignment" + } + ], + "index": 12, + "name": "horizontalAlignmentChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "alignment", + "type": "QQuickTextEdit::VAlignment" + } + ], + "index": 13, + "name": "verticalAlignmentChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 14, + "name": "wrapModeChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 15, + "name": "lineCountChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "textFormat", + "type": "QQuickTextEdit::TextFormat" + } + ], + "index": 16, + "name": "textFormatChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "isReadOnly", + "type": "bool" + } + ], + "index": 17, + "name": "readOnlyChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "isCursorVisible", + "type": "bool" + } + ], + "index": 18, + "name": "cursorVisibleChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 19, + "name": "cursorDelegateChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "overwriteMode", + "type": "bool" + } + ], + "index": 20, + "name": "overwriteModeChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "activeFocusOnPressed", + "type": "bool" + } + ], + "index": 21, + "name": "activeFocusOnPressChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "isPersistentSelection", + "type": "bool" + } + ], + "index": 22, + "name": "persistentSelectionChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "textMargin", + "type": "qreal" + } + ], + "index": 23, + "name": "textMarginChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "selectByKeyboard", + "type": "bool" + } + ], + "index": 24, + "name": "selectByKeyboardChanged", + "returnType": "void", + "revision": 513 + }, + { + "access": "public", + "arguments": [ + { + "name": "selectByMouse", + "type": "bool" + } + ], + "index": 25, + "name": "selectByMouseChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "mode", + "type": "QQuickTextEdit::SelectionMode" + } + ], + "index": 26, + "name": "mouseSelectionModeChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "link", + "type": "QString" + } + ], + "index": 27, + "name": "linkActivated", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "link", + "type": "QString" + } + ], + "index": 28, + "name": "linkHovered", + "returnType": "void", + "revision": 514 + }, + { + "access": "public", + "index": 29, + "name": "canPasteChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 30, + "name": "canUndoChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 31, + "name": "canRedoChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 32, + "name": "inputMethodComposingChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 33, + "name": "effectiveHorizontalAlignmentChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 34, + "name": "baseUrlChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 35, + "name": "inputMethodHintsChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 36, + "name": "renderTypeChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 37, + "name": "editingFinished", + "returnType": "void", + "revision": 518 + }, + { + "access": "public", + "index": 38, + "name": "paddingChanged", + "returnType": "void", + "revision": 518 + }, + { + "access": "public", + "index": 39, + "name": "topPaddingChanged", + "returnType": "void", + "revision": 518 + }, + { + "access": "public", + "index": 40, + "name": "leftPaddingChanged", + "returnType": "void", + "revision": 518 + }, + { + "access": "public", + "index": 41, + "name": "rightPaddingChanged", + "returnType": "void", + "revision": 518 + }, + { + "access": "public", + "index": 42, + "name": "bottomPaddingChanged", + "returnType": "void", + "revision": 518 + }, + { + "access": "public", + "arguments": [ + { + "name": "distance", + "type": "qreal" + } + ], + "index": 43, + "name": "tabStopDistanceChanged", + "returnType": "void", + "revision": 522 + } + ], + "slots": [ + { + "access": "public", + "index": 44, + "name": "selectAll", + "returnType": "void" + }, + { + "access": "public", + "index": 45, + "name": "selectWord", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "start", + "type": "int" + }, + { + "name": "end", + "type": "int" + } + ], + "index": 46, + "name": "select", + "returnType": "void" + }, + { + "access": "public", + "index": 47, + "name": "deselect", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "start", + "type": "int" + }, + { + "name": "end", + "type": "int" + } + ], + "index": 48, + "name": "isRightToLeft", + "returnType": "bool" + }, + { + "access": "public", + "index": 49, + "name": "cut", + "returnType": "void" + }, + { + "access": "public", + "index": 50, + "name": "copy", + "returnType": "void" + }, + { + "access": "public", + "index": 51, + "name": "paste", + "returnType": "void" + }, + { + "access": "public", + "index": 52, + "name": "undo", + "returnType": "void" + }, + { + "access": "public", + "index": 53, + "name": "redo", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "position", + "type": "int" + }, + { + "name": "text", + "type": "QString" + } + ], + "index": 54, + "name": "insert", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "start", + "type": "int" + }, + { + "name": "end", + "type": "int" + } + ], + "index": 55, + "name": "remove", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "text", + "type": "QString" + } + ], + "index": 56, + "name": "append", + "returnType": "void", + "revision": 514 + }, + { + "access": "public", + "index": 57, + "name": "clear", + "returnType": "void", + "revision": 519 + }, + { + "access": "private", + "index": 58, + "name": "q_invalidate", + "returnType": "void" + }, + { + "access": "private", + "index": 59, + "name": "q_textChanged", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "type": "int" + }, + { + "type": "int" + }, + { + "type": "int" + } + ], + "index": 60, + "name": "q_contentsChange", + "returnType": "void" + }, + { + "access": "private", + "index": 61, + "name": "updateSelection", + "returnType": "void" + }, + { + "access": "private", + "index": 62, + "name": "moveCursorDelegate", + "returnType": "void" + }, + { + "access": "private", + "index": 63, + "name": "createCursor", + "returnType": "void" + }, + { + "access": "private", + "index": 64, + "name": "q_canPasteChanged", + "returnType": "void" + }, + { + "access": "private", + "index": 65, + "name": "updateWholeDocument", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "block", + "type": "QTextBlock" + } + ], + "index": 66, + "name": "invalidateBlock", + "returnType": "void" + }, + { + "access": "private", + "index": 67, + "name": "updateCursor", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "link", + "type": "QString" + } + ], + "index": 68, + "name": "q_linkHovered", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "hovered", + "type": "bool" + } + ], + "index": 69, + "name": "q_markerHovered", + "returnType": "void" + }, + { + "access": "private", + "index": 70, + "name": "q_updateAlignment", + "returnType": "void" + }, + { + "access": "private", + "index": 71, + "name": "updateSize", + "returnType": "void" + }, + { + "access": "private", + "index": 72, + "name": "triggerPreprocess", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "type", + "type": "int" + }, + { + "name": "source", + "type": "QUrl" + } + ], + "index": 73, + "name": "loadResource", + "returnType": "QVariant", + "revision": 1543 + }, + { + "access": "private", + "index": 74, + "name": "resourceRequestFinished", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickImplicitSizeItem" + }, + { + "access": "public", + "name": "QQuickTextInterface" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "TextEdit" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + }, + { + "name": "QML.RemovedInVersion", + "value": "1540" + } + ], + "className": "QQuickPre64TextEdit", + "lineNumber": 422, + "object": true, + "qualifiedClassName": "QQuickPre64TextEdit", + "superClasses": [ + { + "access": "public", + "name": "QQuickTextEdit" + } + ] + } + ], + "inputFile": "qquicktextedit_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "TextInput" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + }, + { + "name": "QML.AddedInVersion", + "value": "1540" + } + ], + "className": "QQuickTextInput", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "EchoMode", + "values": [ + "Normal", + "NoEcho", + "Password", + "PasswordEchoOnEdit" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "HAlignment", + "values": [ + "AlignLeft", + "AlignRight", + "AlignHCenter" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "VAlignment", + "values": [ + "AlignTop", + "AlignBottom", + "AlignVCenter" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "WrapMode", + "values": [ + "NoWrap", + "WordWrap", + "WrapAnywhere", + "WrapAtWordBoundaryOrAnywhere", + "Wrap" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "SelectionMode", + "values": [ + "SelectCharacters", + "SelectWords" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "CursorPosition", + "values": [ + "CursorBetweenCharacters", + "CursorOnCharacter" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "RenderType", + "values": [ + "QtRendering", + "NativeRendering", + "CurveRendering" + ] + } + ], + "interfaces": [ + [ + { + "className": "QQuickTextInterface", + "id": "\"org.qt-project.Qt.QQuickTextInterface\"" + } + ] + ], + "lineNumber": 28, + "methods": [ + { + "access": "public", + "arguments": [ + { + "name": "args", + "type": "QQmlV4FunctionPtr" + } + ], + "index": 69, + "name": "positionAt", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "pos", + "type": "int" + } + ], + "index": 70, + "name": "positionToRectangle", + "returnType": "QRectF" + }, + { + "access": "public", + "arguments": [ + { + "name": "pos", + "type": "int" + } + ], + "index": 71, + "name": "moveCursorSelection", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "pos", + "type": "int" + }, + { + "name": "mode", + "type": "SelectionMode" + } + ], + "index": 72, + "name": "moveCursorSelection", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "query", + "type": "Qt::InputMethodQuery" + }, + { + "name": "argument", + "type": "QVariant" + } + ], + "index": 73, + "name": "inputMethodQuery", + "returnType": "QVariant", + "revision": 516 + }, + { + "access": "public", + "arguments": [ + { + "name": "start", + "type": "int" + }, + { + "name": "end", + "type": "int" + } + ], + "index": 74, + "name": "getText", + "returnType": "QString" + } + ], + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "text", + "notify": "textChanged", + "read": "text", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setText" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "length", + "notify": "textChanged", + "read": "length", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "color", + "notify": "colorChanged", + "read": "color", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false, + "write": "setColor" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "selectionColor", + "notify": "selectionColorChanged", + "read": "selectionColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false, + "write": "setSelectionColor" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "selectedTextColor", + "notify": "selectedTextColorChanged", + "read": "selectedTextColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false, + "write": "setSelectedTextColor" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "font", + "notify": "fontChanged", + "read": "font", + "required": false, + "scriptable": true, + "stored": true, + "type": "QFont", + "user": false, + "write": "setFont" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "horizontalAlignment", + "notify": "horizontalAlignmentChanged", + "read": "hAlign", + "required": false, + "reset": "resetHAlign", + "scriptable": true, + "stored": true, + "type": "HAlignment", + "user": false, + "write": "setHAlign" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 7, + "name": "effectiveHorizontalAlignment", + "notify": "effectiveHorizontalAlignmentChanged", + "read": "effectiveHAlign", + "required": false, + "scriptable": true, + "stored": true, + "type": "HAlignment", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 8, + "name": "verticalAlignment", + "notify": "verticalAlignmentChanged", + "read": "vAlign", + "required": false, + "scriptable": true, + "stored": true, + "type": "VAlignment", + "user": false, + "write": "setVAlign" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 9, + "name": "wrapMode", + "notify": "wrapModeChanged", + "read": "wrapMode", + "required": false, + "scriptable": true, + "stored": true, + "type": "WrapMode", + "user": false, + "write": "setWrapMode" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 10, + "name": "readOnly", + "notify": "readOnlyChanged", + "read": "isReadOnly", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setReadOnly" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 11, + "name": "cursorVisible", + "notify": "cursorVisibleChanged", + "read": "isCursorVisible", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setCursorVisible" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 12, + "name": "cursorPosition", + "notify": "cursorPositionChanged", + "read": "cursorPosition", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setCursorPosition" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 13, + "name": "cursorRectangle", + "notify": "cursorRectangleChanged", + "read": "cursorRectangle", + "required": false, + "scriptable": true, + "stored": true, + "type": "QRectF", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 14, + "name": "cursorDelegate", + "notify": "cursorDelegateChanged", + "read": "cursorDelegate", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlComponent*", + "user": false, + "write": "setCursorDelegate" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 15, + "name": "overwriteMode", + "notify": "overwriteModeChanged", + "read": "overwriteMode", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setOverwriteMode" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 16, + "name": "selectionStart", + "notify": "selectionStartChanged", + "read": "selectionStart", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 17, + "name": "selectionEnd", + "notify": "selectionEndChanged", + "read": "selectionEnd", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 18, + "name": "selectedText", + "notify": "selectedTextChanged", + "read": "selectedText", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 19, + "name": "maximumLength", + "notify": "maximumLengthChanged", + "read": "maxLength", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setMaxLength" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 20, + "name": "validator", + "notify": "validatorChanged", + "read": "validator", + "required": false, + "scriptable": true, + "stored": true, + "type": "QValidator*", + "user": false, + "write": "setValidator" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 21, + "name": "inputMask", + "notify": "inputMaskChanged", + "read": "inputMask", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setInputMask" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 22, + "name": "inputMethodHints", + "notify": "inputMethodHintsChanged", + "read": "inputMethodHints", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::InputMethodHints", + "user": false, + "write": "setInputMethodHints" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 23, + "name": "acceptableInput", + "notify": "acceptableInputChanged", + "read": "hasAcceptableInput", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 24, + "name": "echoMode", + "notify": "echoModeChanged", + "read": "echoMode", + "required": false, + "scriptable": true, + "stored": true, + "type": "EchoMode", + "user": false, + "write": "setEchoMode" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 25, + "name": "activeFocusOnPress", + "notify": "activeFocusOnPressChanged", + "read": "focusOnPress", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setFocusOnPress" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 26, + "name": "passwordCharacter", + "notify": "passwordCharacterChanged", + "read": "passwordCharacter", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setPasswordCharacter" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 27, + "name": "passwordMaskDelay", + "notify": "passwordMaskDelayChanged", + "read": "passwordMaskDelay", + "required": false, + "reset": "resetPasswordMaskDelay", + "revision": 516, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setPasswordMaskDelay" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 28, + "name": "displayText", + "notify": "displayTextChanged", + "read": "displayText", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 29, + "name": "preeditText", + "notify": "preeditTextChanged", + "read": "preeditText", + "required": false, + "revision": 519, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 30, + "name": "autoScroll", + "notify": "autoScrollChanged", + "read": "autoScroll", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setAutoScroll" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 31, + "name": "selectByMouse", + "notify": "selectByMouseChanged", + "read": "selectByMouse", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setSelectByMouse" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 32, + "name": "mouseSelectionMode", + "notify": "mouseSelectionModeChanged", + "read": "mouseSelectionMode", + "required": false, + "scriptable": true, + "stored": true, + "type": "SelectionMode", + "user": false, + "write": "setMouseSelectionMode" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 33, + "name": "persistentSelection", + "notify": "persistentSelectionChanged", + "read": "persistentSelection", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setPersistentSelection" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 34, + "name": "canPaste", + "notify": "canPasteChanged", + "read": "canPaste", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 35, + "name": "canUndo", + "notify": "canUndoChanged", + "read": "canUndo", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 36, + "name": "canRedo", + "notify": "canRedoChanged", + "read": "canRedo", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 37, + "name": "inputMethodComposing", + "notify": "inputMethodComposingChanged", + "read": "isInputMethodComposing", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 38, + "name": "contentWidth", + "notify": "contentSizeChanged", + "read": "contentWidth", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 39, + "name": "contentHeight", + "notify": "contentSizeChanged", + "read": "contentHeight", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 40, + "name": "renderType", + "notify": "renderTypeChanged", + "read": "renderType", + "required": false, + "scriptable": true, + "stored": true, + "type": "RenderType", + "user": false, + "write": "setRenderType" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 41, + "name": "padding", + "notify": "paddingChanged", + "read": "padding", + "required": false, + "reset": "resetPadding", + "revision": 518, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setPadding" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 42, + "name": "topPadding", + "notify": "topPaddingChanged", + "read": "topPadding", + "required": false, + "reset": "resetTopPadding", + "revision": 518, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setTopPadding" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 43, + "name": "leftPadding", + "notify": "leftPaddingChanged", + "read": "leftPadding", + "required": false, + "reset": "resetLeftPadding", + "revision": 518, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setLeftPadding" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 44, + "name": "rightPadding", + "notify": "rightPaddingChanged", + "read": "rightPadding", + "required": false, + "reset": "resetRightPadding", + "revision": 518, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setRightPadding" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 45, + "name": "bottomPadding", + "notify": "bottomPaddingChanged", + "read": "bottomPadding", + "required": false, + "reset": "resetBottomPadding", + "revision": 518, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setBottomPadding" + } + ], + "qualifiedClassName": "QQuickTextInput", + "signals": [ + { + "access": "public", + "index": 0, + "name": "textChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "cursorPositionChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "cursorRectangleChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "selectionStartChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "selectionEndChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "selectedTextChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "accepted", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "acceptableInputChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 8, + "name": "editingFinished", + "returnType": "void", + "revision": 514 + }, + { + "access": "public", + "index": 9, + "name": "textEdited", + "returnType": "void", + "revision": 521 + }, + { + "access": "public", + "index": 10, + "name": "colorChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 11, + "name": "selectionColorChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 12, + "name": "selectedTextColorChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "font", + "type": "QFont" + } + ], + "index": 13, + "name": "fontChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "alignment", + "type": "QQuickTextInput::HAlignment" + } + ], + "index": 14, + "name": "horizontalAlignmentChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "alignment", + "type": "QQuickTextInput::VAlignment" + } + ], + "index": 15, + "name": "verticalAlignmentChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 16, + "name": "wrapModeChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "isReadOnly", + "type": "bool" + } + ], + "index": 17, + "name": "readOnlyChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "isCursorVisible", + "type": "bool" + } + ], + "index": 18, + "name": "cursorVisibleChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 19, + "name": "cursorDelegateChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "overwriteMode", + "type": "bool" + } + ], + "index": 20, + "name": "overwriteModeChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "maximumLength", + "type": "int" + } + ], + "index": 21, + "name": "maximumLengthChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 22, + "name": "validatorChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "inputMask", + "type": "QString" + } + ], + "index": 23, + "name": "inputMaskChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "echoMode", + "type": "QQuickTextInput::EchoMode" + } + ], + "index": 24, + "name": "echoModeChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 25, + "name": "passwordCharacterChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "delay", + "type": "int" + } + ], + "index": 26, + "name": "passwordMaskDelayChanged", + "returnType": "void", + "revision": 516 + }, + { + "access": "public", + "index": 27, + "name": "displayTextChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 28, + "name": "preeditTextChanged", + "returnType": "void", + "revision": 519 + }, + { + "access": "public", + "arguments": [ + { + "name": "activeFocusOnPress", + "type": "bool" + } + ], + "index": 29, + "name": "activeFocusOnPressChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "autoScroll", + "type": "bool" + } + ], + "index": 30, + "name": "autoScrollChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "selectByMouse", + "type": "bool" + } + ], + "index": 31, + "name": "selectByMouseChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "mode", + "type": "QQuickTextInput::SelectionMode" + } + ], + "index": 32, + "name": "mouseSelectionModeChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 33, + "name": "persistentSelectionChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 34, + "name": "canPasteChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 35, + "name": "canUndoChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 36, + "name": "canRedoChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 37, + "name": "inputMethodComposingChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 38, + "name": "effectiveHorizontalAlignmentChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 39, + "name": "contentSizeChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 40, + "name": "inputMethodHintsChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 41, + "name": "renderTypeChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 42, + "name": "paddingChanged", + "returnType": "void", + "revision": 518 + }, + { + "access": "public", + "index": 43, + "name": "topPaddingChanged", + "returnType": "void", + "revision": 518 + }, + { + "access": "public", + "index": 44, + "name": "leftPaddingChanged", + "returnType": "void", + "revision": 518 + }, + { + "access": "public", + "index": 45, + "name": "rightPaddingChanged", + "returnType": "void", + "revision": 518 + }, + { + "access": "public", + "index": 46, + "name": "bottomPaddingChanged", + "returnType": "void", + "revision": 518 + } + ], + "slots": [ + { + "access": "public", + "index": 47, + "name": "selectAll", + "returnType": "void" + }, + { + "access": "public", + "index": 48, + "name": "selectWord", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "start", + "type": "int" + }, + { + "name": "end", + "type": "int" + } + ], + "index": 49, + "name": "select", + "returnType": "void" + }, + { + "access": "public", + "index": 50, + "name": "deselect", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "start", + "type": "int" + }, + { + "name": "end", + "type": "int" + } + ], + "index": 51, + "name": "isRightToLeft", + "returnType": "bool" + }, + { + "access": "public", + "index": 52, + "name": "cut", + "returnType": "void" + }, + { + "access": "public", + "index": 53, + "name": "copy", + "returnType": "void" + }, + { + "access": "public", + "index": 54, + "name": "paste", + "returnType": "void" + }, + { + "access": "public", + "index": 55, + "name": "undo", + "returnType": "void" + }, + { + "access": "public", + "index": 56, + "name": "redo", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "position", + "type": "int" + }, + { + "name": "text", + "type": "QString" + } + ], + "index": 57, + "name": "insert", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "start", + "type": "int" + }, + { + "name": "end", + "type": "int" + } + ], + "index": 58, + "name": "remove", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "position", + "type": "int" + } + ], + "index": 59, + "name": "ensureVisible", + "returnType": "void", + "revision": 516 + }, + { + "access": "public", + "index": 60, + "name": "clear", + "returnType": "void", + "revision": 519 + }, + { + "access": "private", + "index": 61, + "name": "selectionChanged", + "returnType": "void" + }, + { + "access": "private", + "index": 62, + "name": "createCursor", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "scroll", + "type": "bool" + } + ], + "index": 63, + "name": "updateCursorRectangle", + "returnType": "void" + }, + { + "access": "private", + "index": 64, + "isCloned": true, + "name": "updateCursorRectangle", + "returnType": "void" + }, + { + "access": "private", + "index": 65, + "name": "q_canPasteChanged", + "returnType": "void" + }, + { + "access": "private", + "index": 66, + "name": "q_updateAlignment", + "returnType": "void" + }, + { + "access": "private", + "index": 67, + "name": "triggerPreprocess", + "returnType": "void" + }, + { + "access": "private", + "index": 68, + "name": "q_validatorChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickImplicitSizeItem" + }, + { + "access": "public", + "name": "QQuickTextInterface" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "TextInput" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + }, + { + "name": "QML.RemovedInVersion", + "value": "1540" + } + ], + "className": "QQuickPre64TextInput", + "lineNumber": 408, + "object": true, + "qualifiedClassName": "QQuickPre64TextInput", + "superClasses": [ + { + "access": "public", + "name": "QQuickTextInput" + } + ] + } + ], + "inputFile": "qquicktextinput_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "TextMetrics" + }, + { + "name": "QML.AddedInVersion", + "value": "516" + } + ], + "className": "QQuickTextMetrics", + "lineNumber": 31, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "font", + "notify": "fontChanged", + "read": "font", + "required": false, + "scriptable": true, + "stored": true, + "type": "QFont", + "user": false, + "write": "setFont" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "text", + "notify": "textChanged", + "read": "text", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setText" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "advanceWidth", + "notify": "metricsChanged", + "read": "advanceWidth", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "boundingRect", + "notify": "metricsChanged", + "read": "boundingRect", + "required": false, + "scriptable": true, + "stored": true, + "type": "QRectF", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "width", + "notify": "metricsChanged", + "read": "width", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "height", + "notify": "metricsChanged", + "read": "height", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 6, + "name": "tightBoundingRect", + "notify": "metricsChanged", + "read": "tightBoundingRect", + "required": false, + "scriptable": true, + "stored": true, + "type": "QRectF", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 7, + "name": "elidedText", + "notify": "metricsChanged", + "read": "elidedText", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 8, + "name": "elide", + "notify": "elideChanged", + "read": "elide", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::TextElideMode", + "user": false, + "write": "setElide" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 9, + "name": "elideWidth", + "notify": "elideWidthChanged", + "read": "elideWidth", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setElideWidth" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 10, + "name": "renderType", + "notify": "renderTypeChanged", + "read": "renderType", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickText::RenderType", + "user": false, + "write": "setRenderType" + } + ], + "qualifiedClassName": "QQuickTextMetrics", + "signals": [ + { + "access": "public", + "index": 0, + "name": "fontChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "textChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "elideChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "elideWidthChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "metricsChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "renderTypeChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qquicktextmetrics_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.AddedInVersion", + "value": "1543" + } + ], + "className": "QQuickTextSelection", + "lineNumber": 31, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "text", + "notify": "textChanged", + "read": "text", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setText" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "font", + "notify": "fontChanged", + "read": "font", + "required": false, + "scriptable": true, + "stored": true, + "type": "QFont", + "user": false, + "write": "setFont" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "color", + "notify": "colorChanged", + "read": "color", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false, + "write": "setColor" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "alignment", + "notify": "alignmentChanged", + "read": "alignment", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::Alignment", + "user": false, + "write": "setAlignment" + } + ], + "qualifiedClassName": "QQuickTextSelection", + "signals": [ + { + "access": "public", + "index": 0, + "name": "textChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "fontChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "colorChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "alignmentChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qquicktextselection_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQuickTextUtil", + "lineNumber": 26, + "object": true, + "qualifiedClassName": "QQuickTextUtil", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qquicktextutil_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQuickTimeLine", + "lineNumber": 29, + "object": true, + "qualifiedClassName": "QQuickTimeLine", + "signals": [ + { + "access": "public", + "index": 0, + "name": "updated", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "completed", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QAbstractAnimationJob" + } + ] + } + ], + "inputFile": "qquicktimeline_p_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "DefaultProperty", + "value": "animations" + }, + { + "name": "DeferredPropertyNames", + "value": "animations" + }, + { + "name": "QML.Element", + "value": "Transition" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickTransition", + "lineNumber": 58, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "from", + "notify": "fromChanged", + "read": "fromState", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setFromState" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "to", + "notify": "toChanged", + "read": "toState", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setToState" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "reversible", + "notify": "reversibleChanged", + "read": "reversible", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setReversible" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "running", + "notify": "runningChanged", + "read": "running", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "animations", + "read": "animations", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlListProperty", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "enabled", + "notify": "enabledChanged", + "read": "enabled", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setEnabled" + } + ], + "qualifiedClassName": "QQuickTransition", + "signals": [ + { + "access": "public", + "index": 0, + "name": "fromChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "toChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "reversibleChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "enabledChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "runningChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qquicktransition_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "Translate" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickTranslate", + "lineNumber": 27, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "x", + "notify": "xChanged", + "read": "x", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setX" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "y", + "notify": "yChanged", + "read": "y", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setY" + } + ], + "qualifiedClassName": "QQuickTranslate", + "signals": [ + { + "access": "public", + "index": 0, + "name": "xChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "yChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickTransform" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "Scale" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickScale", + "lineNumber": 56, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "origin", + "notify": "originChanged", + "read": "origin", + "required": false, + "scriptable": true, + "stored": true, + "type": "QVector3D", + "user": false, + "write": "setOrigin" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "xScale", + "notify": "xScaleChanged", + "read": "xScale", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setXScale" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "yScale", + "notify": "yScaleChanged", + "read": "yScale", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setYScale" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "zScale", + "notify": "zScaleChanged", + "read": "zScale", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setZScale" + } + ], + "qualifiedClassName": "QQuickScale", + "signals": [ + { + "access": "public", + "index": 0, + "name": "originChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "xScaleChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "yScaleChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "zScaleChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "scaleChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickTransform" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "Rotation" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickRotation", + "lineNumber": 95, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "origin", + "notify": "originChanged", + "read": "origin", + "required": false, + "scriptable": true, + "stored": true, + "type": "QVector3D", + "user": false, + "write": "setOrigin" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "angle", + "notify": "angleChanged", + "read": "angle", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setAngle" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "axis", + "notify": "axisChanged", + "read": "axis", + "required": false, + "scriptable": true, + "stored": true, + "type": "QVector3D", + "user": false, + "write": "setAxis" + } + ], + "qualifiedClassName": "QQuickRotation", + "signals": [ + { + "access": "public", + "index": 0, + "name": "originChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "angleChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "axisChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickTransform" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "Matrix4x4" + }, + { + "name": "QML.AddedInVersion", + "value": "515" + } + ], + "className": "QQuickMatrix4x4", + "lineNumber": 129, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "matrix", + "notify": "matrixChanged", + "read": "matrix", + "required": false, + "scriptable": true, + "stored": true, + "type": "QMatrix4x4", + "user": false, + "write": "setMatrix" + } + ], + "qualifiedClassName": "QQuickMatrix4x4", + "signals": [ + { + "access": "public", + "index": 0, + "name": "matrixChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickTransform" + } + ] + } + ], + "inputFile": "qquicktranslate_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "TreeView" + }, + { + "name": "QML.AddedInVersion", + "value": "1539" + } + ], + "className": "QQuickTreeView", + "lineNumber": 25, + "methods": [ + { + "access": "public", + "arguments": [ + { + "name": "row", + "type": "int" + } + ], + "index": 3, + "name": "depth", + "returnType": "int" + }, + { + "access": "public", + "arguments": [ + { + "name": "row", + "type": "int" + } + ], + "index": 4, + "name": "isExpanded", + "returnType": "bool" + }, + { + "access": "public", + "arguments": [ + { + "name": "row", + "type": "int" + } + ], + "index": 5, + "name": "expand", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "row", + "type": "int" + } + ], + "index": 6, + "name": "collapse", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "row", + "type": "int" + } + ], + "index": 7, + "name": "toggleExpanded", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "row", + "type": "int" + }, + { + "name": "depth", + "type": "int" + } + ], + "index": 8, + "name": "expandRecursively", + "returnType": "void", + "revision": 1540 + }, + { + "access": "public", + "arguments": [ + { + "name": "row", + "type": "int" + } + ], + "index": 9, + "isCloned": true, + "name": "expandRecursively", + "returnType": "void", + "revision": 1540 + }, + { + "access": "public", + "index": 10, + "isCloned": true, + "name": "expandRecursively", + "returnType": "void", + "revision": 1540 + }, + { + "access": "public", + "arguments": [ + { + "name": "row", + "type": "int" + } + ], + "index": 11, + "name": "collapseRecursively", + "returnType": "void", + "revision": 1540 + }, + { + "access": "public", + "index": 12, + "isCloned": true, + "name": "collapseRecursively", + "returnType": "void", + "revision": 1540 + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "QModelIndex" + } + ], + "index": 13, + "name": "expandToIndex", + "returnType": "void", + "revision": 1540 + }, + { + "access": "public", + "arguments": [ + { + "name": "cell", + "type": "QPoint" + } + ], + "index": 14, + "name": "modelIndex", + "returnType": "QModelIndex" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "QModelIndex" + } + ], + "index": 15, + "name": "cellAtIndex", + "returnType": "QPoint" + }, + { + "access": "public", + "arguments": [ + { + "name": "row", + "type": "int" + }, + { + "name": "column", + "type": "int" + } + ], + "index": 16, + "name": "modelIndex", + "returnType": "QModelIndex", + "revision": 1540 + } + ], + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "rootIndex", + "notify": "rootIndexChanged", + "read": "rootIndex", + "required": false, + "reset": "resetRootIndex", + "revision": 1542, + "scriptable": true, + "stored": true, + "type": "QModelIndex", + "user": false, + "write": "setRootIndex" + } + ], + "qualifiedClassName": "QQuickTreeView", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "row", + "type": "int" + }, + { + "name": "depth", + "type": "int" + } + ], + "index": 0, + "name": "expanded", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "row", + "type": "int" + }, + { + "name": "recursively", + "type": "bool" + } + ], + "index": 1, + "name": "collapsed", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "rootIndexChanged", + "returnType": "void", + "revision": 1542 + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickTableView" + } + ] + } + ], + "inputFile": "qquicktreeview_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "IntValidator" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickIntValidator", + "lineNumber": 27, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "locale", + "notify": "localeNameChanged", + "read": "localeName", + "required": false, + "reset": "resetLocaleName", + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setLocaleName" + } + ], + "qualifiedClassName": "QQuickIntValidator", + "signals": [ + { + "access": "public", + "index": 0, + "name": "localeNameChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QIntValidator" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "DoubleValidator" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickDoubleValidator", + "lineNumber": 44, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "locale", + "notify": "localeNameChanged", + "read": "localeName", + "required": false, + "reset": "resetLocaleName", + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setLocaleName" + } + ], + "qualifiedClassName": "QQuickDoubleValidator", + "signals": [ + { + "access": "public", + "index": 0, + "name": "localeNameChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QDoubleValidator" + } + ] + } + ], + "inputFile": "qquickvalidator_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.AddedInVersion", + "value": "512" + }, + { + "name": "QML.Foreign", + "value": "QColor" + }, + { + "name": "QML.Element", + "value": "color" + }, + { + "name": "QML.Extended", + "value": "QQuickColorValueType" + }, + { + "name": "QML.Creatable", + "value": "true" + }, + { + "name": "QML.CreationMethod", + "value": "structured" + } + ], + "className": "QQuickColorValueType", + "constructors": [ + { + "access": "public", + "index": 0, + "name": "QQuickColorValueType", + "returnType": "" + }, + { + "access": "public", + "arguments": [ + { + "name": "string", + "type": "QString" + } + ], + "index": 1, + "name": "QQuickColorValueType", + "returnType": "" + } + ], + "gadget": true, + "lineNumber": 33, + "methods": [ + { + "access": "public", + "index": 0, + "name": "toString", + "returnType": "QString" + }, + { + "access": "public", + "arguments": [ + { + "name": "value", + "type": "qreal" + } + ], + "index": 1, + "name": "alpha", + "returnType": "QVariant" + }, + { + "access": "public", + "arguments": [ + { + "name": "factor", + "type": "qreal" + } + ], + "index": 2, + "name": "lighter", + "returnType": "QVariant" + }, + { + "access": "public", + "index": 3, + "isCloned": true, + "name": "lighter", + "returnType": "QVariant" + }, + { + "access": "public", + "arguments": [ + { + "name": "factor", + "type": "qreal" + } + ], + "index": 4, + "name": "darker", + "returnType": "QVariant" + }, + { + "access": "public", + "index": 5, + "isCloned": true, + "name": "darker", + "returnType": "QVariant" + }, + { + "access": "public", + "arguments": [ + { + "name": "factor", + "type": "QVariant" + } + ], + "index": 6, + "name": "tint", + "returnType": "QVariant" + } + ], + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "r", + "read": "r", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setR" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "g", + "read": "g", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setG" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "b", + "read": "b", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setB" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "a", + "read": "a", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setA" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "hsvHue", + "read": "hsvHue", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setHsvHue" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "hsvSaturation", + "read": "hsvSaturation", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setHsvSaturation" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 6, + "name": "hsvValue", + "read": "hsvValue", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setHsvValue" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 7, + "name": "hslHue", + "read": "hslHue", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setHslHue" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 8, + "name": "hslSaturation", + "read": "hslSaturation", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setHslSaturation" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 9, + "name": "hslLightness", + "read": "hslLightness", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setHslLightness" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 10, + "name": "valid", + "read": "isValid", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + } + ], + "qualifiedClassName": "QQuickColorValueType" + }, + { + "classInfos": [ + { + "name": "QML.AddedInVersion", + "value": "512" + }, + { + "name": "QML.Foreign", + "value": "QVector2D" + }, + { + "name": "QML.Element", + "value": "vector2d" + }, + { + "name": "QML.Extended", + "value": "QQuickVector2DValueType" + }, + { + "name": "QML.Creatable", + "value": "true" + }, + { + "name": "QML.CreationMethod", + "value": "structured" + } + ], + "className": "QQuickVector2DValueType", + "constructors": [ + { + "access": "public", + "index": 0, + "name": "QQuickVector2DValueType", + "returnType": "" + } + ], + "gadget": true, + "lineNumber": 91, + "methods": [ + { + "access": "public", + "index": 0, + "name": "toString", + "returnType": "QString" + }, + { + "access": "public", + "arguments": [ + { + "name": "vec", + "type": "QVector2D" + } + ], + "index": 1, + "name": "dotProduct", + "returnType": "qreal" + }, + { + "access": "public", + "arguments": [ + { + "name": "vec", + "type": "QVector2D" + } + ], + "index": 2, + "name": "times", + "returnType": "QVector2D" + }, + { + "access": "public", + "arguments": [ + { + "name": "scalar", + "type": "qreal" + } + ], + "index": 3, + "name": "times", + "returnType": "QVector2D" + }, + { + "access": "public", + "arguments": [ + { + "name": "vec", + "type": "QVector2D" + } + ], + "index": 4, + "name": "plus", + "returnType": "QVector2D" + }, + { + "access": "public", + "arguments": [ + { + "name": "vec", + "type": "QVector2D" + } + ], + "index": 5, + "name": "minus", + "returnType": "QVector2D" + }, + { + "access": "public", + "index": 6, + "name": "normalized", + "returnType": "QVector2D" + }, + { + "access": "public", + "index": 7, + "name": "length", + "returnType": "qreal" + }, + { + "access": "public", + "index": 8, + "name": "toVector3d", + "returnType": "QVector3D" + }, + { + "access": "public", + "index": 9, + "name": "toVector4d", + "returnType": "QVector4D" + }, + { + "access": "public", + "arguments": [ + { + "name": "vec", + "type": "QVector2D" + }, + { + "name": "epsilon", + "type": "qreal" + } + ], + "index": 10, + "name": "fuzzyEquals", + "returnType": "bool" + }, + { + "access": "public", + "arguments": [ + { + "name": "vec", + "type": "QVector2D" + } + ], + "index": 11, + "name": "fuzzyEquals", + "returnType": "bool" + } + ], + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "x", + "read": "x", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setX" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "y", + "read": "y", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setY" + } + ], + "qualifiedClassName": "QQuickVector2DValueType" + }, + { + "classInfos": [ + { + "name": "QML.AddedInVersion", + "value": "512" + }, + { + "name": "QML.Foreign", + "value": "QVector3D" + }, + { + "name": "QML.Element", + "value": "vector3d" + }, + { + "name": "QML.Extended", + "value": "QQuickVector3DValueType" + }, + { + "name": "QML.Creatable", + "value": "true" + }, + { + "name": "QML.CreationMethod", + "value": "structured" + } + ], + "className": "QQuickVector3DValueType", + "constructors": [ + { + "access": "public", + "index": 0, + "name": "QQuickVector3DValueType", + "returnType": "" + } + ], + "gadget": true, + "lineNumber": 129, + "methods": [ + { + "access": "public", + "index": 0, + "name": "toString", + "returnType": "QString" + }, + { + "access": "public", + "arguments": [ + { + "name": "vec", + "type": "QVector3D" + } + ], + "index": 1, + "name": "crossProduct", + "returnType": "QVector3D" + }, + { + "access": "public", + "arguments": [ + { + "name": "vec", + "type": "QVector3D" + } + ], + "index": 2, + "name": "dotProduct", + "returnType": "qreal" + }, + { + "access": "public", + "arguments": [ + { + "name": "m", + "type": "QMatrix4x4" + } + ], + "index": 3, + "name": "times", + "returnType": "QVector3D" + }, + { + "access": "public", + "arguments": [ + { + "name": "vec", + "type": "QVector3D" + } + ], + "index": 4, + "name": "times", + "returnType": "QVector3D" + }, + { + "access": "public", + "arguments": [ + { + "name": "scalar", + "type": "qreal" + } + ], + "index": 5, + "name": "times", + "returnType": "QVector3D" + }, + { + "access": "public", + "arguments": [ + { + "name": "vec", + "type": "QVector3D" + } + ], + "index": 6, + "name": "plus", + "returnType": "QVector3D" + }, + { + "access": "public", + "arguments": [ + { + "name": "vec", + "type": "QVector3D" + } + ], + "index": 7, + "name": "minus", + "returnType": "QVector3D" + }, + { + "access": "public", + "index": 8, + "name": "normalized", + "returnType": "QVector3D" + }, + { + "access": "public", + "index": 9, + "name": "length", + "returnType": "qreal" + }, + { + "access": "public", + "index": 10, + "name": "toVector2d", + "returnType": "QVector2D" + }, + { + "access": "public", + "index": 11, + "name": "toVector4d", + "returnType": "QVector4D" + }, + { + "access": "public", + "arguments": [ + { + "name": "vec", + "type": "QVector3D" + }, + { + "name": "epsilon", + "type": "qreal" + } + ], + "index": 12, + "name": "fuzzyEquals", + "returnType": "bool" + }, + { + "access": "public", + "arguments": [ + { + "name": "vec", + "type": "QVector3D" + } + ], + "index": 13, + "name": "fuzzyEquals", + "returnType": "bool" + } + ], + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "x", + "read": "x", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setX" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "y", + "read": "y", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setY" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "z", + "read": "z", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setZ" + } + ], + "qualifiedClassName": "QQuickVector3DValueType" + }, + { + "classInfos": [ + { + "name": "QML.AddedInVersion", + "value": "512" + }, + { + "name": "QML.Foreign", + "value": "QVector4D" + }, + { + "name": "QML.Element", + "value": "vector4d" + }, + { + "name": "QML.Extended", + "value": "QQuickVector4DValueType" + }, + { + "name": "QML.Creatable", + "value": "true" + }, + { + "name": "QML.CreationMethod", + "value": "structured" + } + ], + "className": "QQuickVector4DValueType", + "constructors": [ + { + "access": "public", + "index": 0, + "name": "QQuickVector4DValueType", + "returnType": "" + } + ], + "gadget": true, + "lineNumber": 172, + "methods": [ + { + "access": "public", + "index": 0, + "name": "toString", + "returnType": "QString" + }, + { + "access": "public", + "arguments": [ + { + "name": "vec", + "type": "QVector4D" + } + ], + "index": 1, + "name": "dotProduct", + "returnType": "qreal" + }, + { + "access": "public", + "arguments": [ + { + "name": "vec", + "type": "QVector4D" + } + ], + "index": 2, + "name": "times", + "returnType": "QVector4D" + }, + { + "access": "public", + "arguments": [ + { + "name": "m", + "type": "QMatrix4x4" + } + ], + "index": 3, + "name": "times", + "returnType": "QVector4D" + }, + { + "access": "public", + "arguments": [ + { + "name": "scalar", + "type": "qreal" + } + ], + "index": 4, + "name": "times", + "returnType": "QVector4D" + }, + { + "access": "public", + "arguments": [ + { + "name": "vec", + "type": "QVector4D" + } + ], + "index": 5, + "name": "plus", + "returnType": "QVector4D" + }, + { + "access": "public", + "arguments": [ + { + "name": "vec", + "type": "QVector4D" + } + ], + "index": 6, + "name": "minus", + "returnType": "QVector4D" + }, + { + "access": "public", + "index": 7, + "name": "normalized", + "returnType": "QVector4D" + }, + { + "access": "public", + "index": 8, + "name": "length", + "returnType": "qreal" + }, + { + "access": "public", + "index": 9, + "name": "toVector2d", + "returnType": "QVector2D" + }, + { + "access": "public", + "index": 10, + "name": "toVector3d", + "returnType": "QVector3D" + }, + { + "access": "public", + "arguments": [ + { + "name": "vec", + "type": "QVector4D" + }, + { + "name": "epsilon", + "type": "qreal" + } + ], + "index": 11, + "name": "fuzzyEquals", + "returnType": "bool" + }, + { + "access": "public", + "arguments": [ + { + "name": "vec", + "type": "QVector4D" + } + ], + "index": 12, + "name": "fuzzyEquals", + "returnType": "bool" + } + ], + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "x", + "read": "x", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setX" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "y", + "read": "y", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setY" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "z", + "read": "z", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setZ" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "w", + "read": "w", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setW" + } + ], + "qualifiedClassName": "QQuickVector4DValueType" + }, + { + "classInfos": [ + { + "name": "QML.AddedInVersion", + "value": "512" + }, + { + "name": "QML.Foreign", + "value": "QQuaternion" + }, + { + "name": "QML.Element", + "value": "quaternion" + }, + { + "name": "QML.Extended", + "value": "QQuickQuaternionValueType" + }, + { + "name": "QML.Creatable", + "value": "true" + }, + { + "name": "QML.CreationMethod", + "value": "structured" + } + ], + "className": "QQuickQuaternionValueType", + "constructors": [ + { + "access": "public", + "index": 0, + "name": "QQuickQuaternionValueType", + "returnType": "" + } + ], + "gadget": true, + "lineNumber": 217, + "methods": [ + { + "access": "public", + "index": 0, + "name": "toString", + "returnType": "QString" + }, + { + "access": "public", + "arguments": [ + { + "name": "q", + "type": "QQuaternion" + } + ], + "index": 1, + "name": "dotProduct", + "returnType": "qreal" + }, + { + "access": "public", + "arguments": [ + { + "name": "q", + "type": "QQuaternion" + } + ], + "index": 2, + "name": "times", + "returnType": "QQuaternion" + }, + { + "access": "public", + "arguments": [ + { + "name": "vec", + "type": "QVector3D" + } + ], + "index": 3, + "name": "times", + "returnType": "QVector3D" + }, + { + "access": "public", + "arguments": [ + { + "name": "factor", + "type": "qreal" + } + ], + "index": 4, + "name": "times", + "returnType": "QQuaternion" + }, + { + "access": "public", + "arguments": [ + { + "name": "q", + "type": "QQuaternion" + } + ], + "index": 5, + "name": "plus", + "returnType": "QQuaternion" + }, + { + "access": "public", + "arguments": [ + { + "name": "q", + "type": "QQuaternion" + } + ], + "index": 6, + "name": "minus", + "returnType": "QQuaternion" + }, + { + "access": "public", + "index": 7, + "name": "normalized", + "returnType": "QQuaternion" + }, + { + "access": "public", + "index": 8, + "name": "inverted", + "returnType": "QQuaternion" + }, + { + "access": "public", + "index": 9, + "name": "conjugated", + "returnType": "QQuaternion" + }, + { + "access": "public", + "index": 10, + "name": "length", + "returnType": "qreal" + }, + { + "access": "public", + "index": 11, + "name": "toEulerAngles", + "returnType": "QVector3D" + }, + { + "access": "public", + "index": 12, + "name": "toVector4d", + "returnType": "QVector4D" + }, + { + "access": "public", + "arguments": [ + { + "name": "q", + "type": "QQuaternion" + }, + { + "name": "epsilon", + "type": "qreal" + } + ], + "index": 13, + "name": "fuzzyEquals", + "returnType": "bool" + }, + { + "access": "public", + "arguments": [ + { + "name": "q", + "type": "QQuaternion" + } + ], + "index": 14, + "name": "fuzzyEquals", + "returnType": "bool" + } + ], + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "scalar", + "read": "scalar", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setScalar" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "x", + "read": "x", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setX" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "y", + "read": "y", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setY" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "z", + "read": "z", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setZ" + } + ], + "qualifiedClassName": "QQuickQuaternionValueType" + }, + { + "classInfos": [ + { + "name": "QML.AddedInVersion", + "value": "512" + }, + { + "name": "QML.Foreign", + "value": "QMatrix4x4" + }, + { + "name": "QML.Element", + "value": "matrix4x4" + }, + { + "name": "QML.Extended", + "value": "QQuickMatrix4x4ValueType" + }, + { + "name": "QML.Creatable", + "value": "true" + }, + { + "name": "QML.CreationMethod", + "value": "structured" + } + ], + "className": "QQuickMatrix4x4ValueType", + "constructors": [ + { + "access": "public", + "index": 0, + "name": "QQuickMatrix4x4ValueType", + "returnType": "" + } + ], + "gadget": true, + "lineNumber": 267, + "methods": [ + { + "access": "public", + "arguments": [ + { + "name": "t", + "type": "QVector3D" + } + ], + "index": 0, + "name": "translate", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "angle", + "type": "float" + }, + { + "name": "axis", + "type": "QVector3D" + } + ], + "index": 1, + "name": "rotate", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "q", + "type": "QQuaternion" + } + ], + "index": 2, + "name": "rotate", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "s", + "type": "float" + } + ], + "index": 3, + "name": "scale", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "sx", + "type": "float" + }, + { + "name": "sy", + "type": "float" + }, + { + "name": "sz", + "type": "float" + } + ], + "index": 4, + "name": "scale", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "s", + "type": "QVector3D" + } + ], + "index": 5, + "name": "scale", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "eye", + "type": "QVector3D" + }, + { + "name": "center", + "type": "QVector3D" + }, + { + "name": "up", + "type": "QVector3D" + } + ], + "index": 6, + "name": "lookAt", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "m", + "type": "QMatrix4x4" + } + ], + "index": 7, + "name": "times", + "returnType": "QMatrix4x4" + }, + { + "access": "public", + "arguments": [ + { + "name": "vec", + "type": "QVector4D" + } + ], + "index": 8, + "name": "times", + "returnType": "QVector4D" + }, + { + "access": "public", + "arguments": [ + { + "name": "vec", + "type": "QVector3D" + } + ], + "index": 9, + "name": "times", + "returnType": "QVector3D" + }, + { + "access": "public", + "arguments": [ + { + "name": "factor", + "type": "qreal" + } + ], + "index": 10, + "name": "times", + "returnType": "QMatrix4x4" + }, + { + "access": "public", + "arguments": [ + { + "name": "m", + "type": "QMatrix4x4" + } + ], + "index": 11, + "name": "plus", + "returnType": "QMatrix4x4" + }, + { + "access": "public", + "arguments": [ + { + "name": "m", + "type": "QMatrix4x4" + } + ], + "index": 12, + "name": "minus", + "returnType": "QMatrix4x4" + }, + { + "access": "public", + "arguments": [ + { + "name": "n", + "type": "int" + } + ], + "index": 13, + "name": "row", + "returnType": "QVector4D" + }, + { + "access": "public", + "arguments": [ + { + "name": "m", + "type": "int" + } + ], + "index": 14, + "name": "column", + "returnType": "QVector4D" + }, + { + "access": "public", + "index": 15, + "name": "determinant", + "returnType": "qreal" + }, + { + "access": "public", + "index": 16, + "name": "inverted", + "returnType": "QMatrix4x4" + }, + { + "access": "public", + "index": 17, + "name": "transposed", + "returnType": "QMatrix4x4" + }, + { + "access": "public", + "arguments": [ + { + "name": "p", + "type": "QPointF" + } + ], + "index": 18, + "name": "map", + "returnType": "QPointF" + }, + { + "access": "public", + "arguments": [ + { + "name": "r", + "type": "QRectF" + } + ], + "index": 19, + "name": "mapRect", + "returnType": "QRectF" + }, + { + "access": "public", + "arguments": [ + { + "name": "m", + "type": "QMatrix4x4" + }, + { + "name": "epsilon", + "type": "qreal" + } + ], + "index": 20, + "name": "fuzzyEquals", + "returnType": "bool" + }, + { + "access": "public", + "arguments": [ + { + "name": "m", + "type": "QMatrix4x4" + } + ], + "index": 21, + "name": "fuzzyEquals", + "returnType": "bool" + } + ], + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "m11", + "read": "m11", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setM11" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "m12", + "read": "m12", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setM12" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "m13", + "read": "m13", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setM13" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "m14", + "read": "m14", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setM14" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "m21", + "read": "m21", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setM21" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "m22", + "read": "m22", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setM22" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 6, + "name": "m23", + "read": "m23", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setM23" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 7, + "name": "m24", + "read": "m24", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setM24" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 8, + "name": "m31", + "read": "m31", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setM31" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 9, + "name": "m32", + "read": "m32", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setM32" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 10, + "name": "m33", + "read": "m33", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setM33" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 11, + "name": "m34", + "read": "m34", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setM34" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 12, + "name": "m41", + "read": "m41", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setM41" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 13, + "name": "m42", + "read": "m42", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setM42" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 14, + "name": "m43", + "read": "m43", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setM43" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 15, + "name": "m44", + "read": "m44", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setM44" + } + ], + "qualifiedClassName": "QQuickMatrix4x4ValueType" + }, + { + "classInfos": [ + { + "name": "QML.Singleton", + "value": "true" + }, + { + "name": "QML.Element", + "value": "PlanarTransform" + }, + { + "name": "QML.AddedInVersion", + "value": "1544" + } + ], + "className": "QQuickPlanarTransform", + "lineNumber": 363, + "methods": [ + { + "access": "public", + "index": 0, + "name": "identity", + "returnType": "QMatrix4x4" + }, + { + "access": "public", + "arguments": [ + { + "name": "scaleX", + "type": "float" + }, + { + "name": "shearY", + "type": "float" + }, + { + "name": "shearX", + "type": "float" + }, + { + "name": "scaleY", + "type": "float" + }, + { + "name": "translateX", + "type": "float" + }, + { + "name": "translateY", + "type": "float" + } + ], + "index": 1, + "name": "fromAffineMatrix", + "returnType": "QMatrix4x4" + }, + { + "access": "public", + "arguments": [ + { + "name": "translateX", + "type": "float" + }, + { + "name": "translateY", + "type": "float" + } + ], + "index": 2, + "name": "fromTranslate", + "returnType": "QMatrix4x4" + }, + { + "access": "public", + "arguments": [ + { + "name": "scaleX", + "type": "float" + }, + { + "name": "scaleY", + "type": "float" + }, + { + "name": "originX", + "type": "float" + }, + { + "name": "originY", + "type": "float" + } + ], + "index": 3, + "name": "fromScale", + "returnType": "QMatrix4x4" + }, + { + "access": "public", + "arguments": [ + { + "name": "scaleX", + "type": "float" + }, + { + "name": "scaleY", + "type": "float" + }, + { + "name": "originX", + "type": "float" + } + ], + "index": 4, + "isCloned": true, + "name": "fromScale", + "returnType": "QMatrix4x4" + }, + { + "access": "public", + "arguments": [ + { + "name": "scaleX", + "type": "float" + }, + { + "name": "scaleY", + "type": "float" + } + ], + "index": 5, + "isCloned": true, + "name": "fromScale", + "returnType": "QMatrix4x4" + }, + { + "access": "public", + "arguments": [ + { + "name": "angle", + "type": "float" + }, + { + "name": "originX", + "type": "float" + }, + { + "name": "originY", + "type": "float" + } + ], + "index": 6, + "name": "fromRotate", + "returnType": "QMatrix4x4" + }, + { + "access": "public", + "arguments": [ + { + "name": "angle", + "type": "float" + }, + { + "name": "originX", + "type": "float" + } + ], + "index": 7, + "isCloned": true, + "name": "fromRotate", + "returnType": "QMatrix4x4" + }, + { + "access": "public", + "arguments": [ + { + "name": "angle", + "type": "float" + } + ], + "index": 8, + "isCloned": true, + "name": "fromRotate", + "returnType": "QMatrix4x4" + }, + { + "access": "public", + "arguments": [ + { + "name": "shearX", + "type": "float" + }, + { + "name": "shearY", + "type": "float" + }, + { + "name": "originX", + "type": "float" + }, + { + "name": "originY", + "type": "float" + } + ], + "index": 9, + "name": "fromShear", + "returnType": "QMatrix4x4" + }, + { + "access": "public", + "arguments": [ + { + "name": "shearX", + "type": "float" + }, + { + "name": "shearY", + "type": "float" + }, + { + "name": "originX", + "type": "float" + } + ], + "index": 10, + "isCloned": true, + "name": "fromShear", + "returnType": "QMatrix4x4" + }, + { + "access": "public", + "arguments": [ + { + "name": "shearX", + "type": "float" + }, + { + "name": "shearY", + "type": "float" + } + ], + "index": 11, + "isCloned": true, + "name": "fromShear", + "returnType": "QMatrix4x4" + } + ], + "object": true, + "qualifiedClassName": "QQuickPlanarTransform", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "font" + }, + { + "name": "QML.Foreign", + "value": "QFont" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + }, + { + "name": "QML.Extended", + "value": "QQuickFontValueType" + }, + { + "name": "QML.Creatable", + "value": "true" + }, + { + "name": "QML.CreationMethod", + "value": "structured" + } + ], + "className": "QQuickFontValueType", + "constructors": [ + { + "access": "public", + "index": 0, + "name": "QQuickFontValueType", + "returnType": "" + } + ], + "gadget": true, + "lineNumber": 418, + "methods": [ + { + "access": "public", + "index": 0, + "name": "toString", + "returnType": "QString" + } + ], + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "family", + "read": "family", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setFamily" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "styleName", + "read": "styleName", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setStyleName" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "bold", + "read": "bold", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setBold" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "weight", + "read": "weight", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setWeight" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "italic", + "read": "italic", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setItalic" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "underline", + "read": "underline", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setUnderline" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 6, + "name": "overline", + "read": "overline", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setOverline" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 7, + "name": "strikeout", + "read": "strikeout", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setStrikeout" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 8, + "name": "pointSize", + "read": "pointSize", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setPointSize" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 9, + "name": "pixelSize", + "read": "pixelSize", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setPixelSize" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 10, + "name": "capitalization", + "read": "capitalization", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickFontEnums::Capitalization", + "user": false, + "write": "setCapitalization" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 11, + "name": "letterSpacing", + "read": "letterSpacing", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setLetterSpacing" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 12, + "name": "wordSpacing", + "read": "wordSpacing", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setWordSpacing" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 13, + "name": "hintingPreference", + "read": "hintingPreference", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickFontEnums::HintingPreference", + "user": false, + "write": "setHintingPreference" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 14, + "name": "kerning", + "read": "kerning", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setKerning" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 15, + "name": "preferShaping", + "read": "preferShaping", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setPreferShaping" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 16, + "name": "features", + "read": "features", + "required": false, + "scriptable": true, + "stored": true, + "type": "QVariantMap", + "user": false, + "write": "setFeatures" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 17, + "name": "variableAxes", + "read": "variableAxes", + "required": false, + "scriptable": true, + "stored": true, + "type": "QVariantMap", + "user": false, + "write": "setVariableAxes" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 18, + "name": "contextFontMerging", + "read": "contextFontMerging", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setContextFontMerging" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 19, + "name": "preferTypoLineMetrics", + "read": "preferTypoLineMetrics", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setPreferTypoLineMetrics" + } + ], + "qualifiedClassName": "QQuickFontValueType" + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.Foreign", + "value": "QColorSpace" + }, + { + "name": "QML.AddedInVersion", + "value": "527" + }, + { + "name": "QML.Extended", + "value": "QQuickColorSpaceValueType" + }, + { + "name": "QML.Creatable", + "value": "true" + }, + { + "name": "QML.CreationMethod", + "value": "structured" + } + ], + "className": "QQuickColorSpaceValueType", + "gadget": true, + "lineNumber": 554, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "namedColorSpace", + "read": "namedColorSpace", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickColorSpaceEnums::NamedColorSpace", + "user": false, + "write": "setNamedColorSpace" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "primaries", + "read": "primaries", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickColorSpaceEnums::Primaries", + "user": false, + "write": "setPrimaries" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "transferFunction", + "read": "transferFunction", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickColorSpaceEnums::TransferFunction", + "user": false, + "write": "setTransferFunction" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "gamma", + "read": "gamma", + "required": false, + "scriptable": true, + "stored": true, + "type": "float", + "user": false, + "write": "setGamma" + } + ], + "qualifiedClassName": "QQuickColorSpaceValueType" + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "Font" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickFontEnums", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "FontWeight", + "values": [ + "Thin", + "ExtraLight", + "Light", + "Normal", + "Medium", + "DemiBold", + "Bold", + "ExtraBold", + "Black" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "Capitalization", + "values": [ + "MixedCase", + "AllUppercase", + "AllLowercase", + "SmallCaps", + "Capitalize" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "HintingPreference", + "values": [ + "PreferDefaultHinting", + "PreferNoHinting", + "PreferVerticalHinting", + "PreferFullHinting" + ] + } + ], + "lineNumber": 385, + "namespace": true, + "qualifiedClassName": "QQuickFontEnums" + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "ColorSpace" + }, + { + "name": "QML.AddedInVersion", + "value": "527" + }, + { + "name": "RegisterEnumClassesUnscoped", + "value": "false" + } + ], + "className": "QQuickColorSpaceEnums", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "NamedColorSpace", + "values": [ + "Unknown", + "SRgb", + "SRgbLinear", + "AdobeRgb", + "DisplayP3", + "ProPhotoRgb" + ] + }, + { + "isClass": true, + "isFlag": false, + "name": "Primaries", + "values": [ + "Custom", + "SRgb", + "AdobeRgb", + "DciP3D65", + "ProPhotoRgb" + ] + }, + { + "isClass": true, + "isFlag": false, + "name": "TransferFunction", + "values": [ + "Custom", + "Linear", + "Gamma", + "SRgb", + "ProPhotoRgb" + ] + } + ], + "lineNumber": 519, + "namespace": true, + "qualifiedClassName": "QQuickColorSpaceEnums" + } + ], + "inputFile": "qquickvaluetypes_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQuickView", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "ResizeMode", + "values": [ + "SizeViewToRootObject", + "SizeRootObjectToView" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "Status", + "values": [ + "Null", + "Ready", + "Loading", + "Error" + ] + } + ], + "lineNumber": 19, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "resizeMode", + "read": "resizeMode", + "required": false, + "scriptable": true, + "stored": true, + "type": "ResizeMode", + "user": false, + "write": "setResizeMode" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "status", + "notify": "statusChanged", + "read": "status", + "required": false, + "scriptable": true, + "stored": true, + "type": "Status", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "source", + "read": "source", + "required": false, + "scriptable": true, + "stored": true, + "type": "QUrl", + "user": false, + "write": "setSource" + } + ], + "qualifiedClassName": "QQuickView", + "signals": [ + { + "access": "public", + "arguments": [ + { + "type": "QQuickView::Status" + } + ], + "index": 0, + "name": "statusChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "type": "QUrl" + } + ], + "index": 1, + "name": "setSource", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "uri", + "type": "QAnyStringView" + }, + { + "name": "typeName", + "type": "QAnyStringView" + } + ], + "index": 2, + "name": "loadFromModule", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "initialProperties", + "type": "QVariantMap" + } + ], + "index": 3, + "name": "setInitialProperties", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "url", + "type": "QUrl" + }, + { + "name": "component", + "type": "QQmlComponent*" + }, + { + "name": "item", + "type": "QObject*" + } + ], + "index": 4, + "name": "setContent", + "returnType": "void" + }, + { + "access": "private", + "index": 5, + "name": "continueExecute", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickWindow" + } + ] + } + ], + "inputFile": "qquickview.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "WheelHandler" + }, + { + "name": "QML.AddedInVersion", + "value": "526" + } + ], + "className": "QQuickWheelHandler", + "lineNumber": 28, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "orientation", + "notify": "orientationChanged", + "read": "orientation", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::Orientation", + "user": false, + "write": "setOrientation" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "invertible", + "notify": "invertibleChanged", + "read": "isInvertible", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setInvertible" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "activeTimeout", + "notify": "activeTimeoutChanged", + "read": "activeTimeout", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setActiveTimeout" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "rotation", + "notify": "rotationChanged", + "read": "rotation", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setRotation" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "rotationScale", + "notify": "rotationScaleChanged", + "read": "rotationScale", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setRotationScale" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "property", + "notify": "propertyChanged", + "read": "property", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setProperty" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "targetScaleMultiplier", + "notify": "targetScaleMultiplierChanged", + "read": "targetScaleMultiplier", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setTargetScaleMultiplier" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 7, + "name": "targetTransformAroundCursor", + "notify": "targetTransformAroundCursorChanged", + "read": "isTargetTransformAroundCursor", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setTargetTransformAroundCursor" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 8, + "name": "blocking", + "notify": "blockingChanged", + "read": "isBlocking", + "required": false, + "revision": 1539, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setBlocking" + } + ], + "qualifiedClassName": "QQuickWheelHandler", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "event", + "type": "QQuickWheelEvent*" + } + ], + "index": 0, + "name": "wheel", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "orientationChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "invertibleChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "activeTimeoutChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "rotationChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "rotationScaleChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "propertyChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "targetScaleMultiplierChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 8, + "name": "targetTransformAroundCursorChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 9, + "name": "blockingChanged", + "returnType": "void", + "revision": 1539 + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickSinglePointHandler" + } + ] + } + ], + "inputFile": "qquickwheelhandler_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "DefaultProperty", + "value": "data" + }, + { + "name": "QML.Element", + "value": "Window" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + }, + { + "name": "QML.RemovedInVersion", + "value": "513" + } + ], + "className": "QQuickWindow", + "enums": [ + { + "alias": "CreateTextureOption", + "isClass": false, + "isFlag": true, + "name": "CreateTextureOptions", + "values": [ + "TextureHasAlphaChannel", + "TextureHasMipmaps", + "TextureOwnsGLTexture", + "TextureCanUseAtlas", + "TextureIsOpaque" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "SceneGraphError", + "values": [ + "ContextNotAvailable" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "TextRenderType", + "values": [ + "QtTextRendering", + "NativeTextRendering", + "CurveTextRendering" + ] + } + ], + "lineNumber": 41, + "object": true, + "properties": [ + { + "constant": false, + "designable": false, + "final": false, + "index": 0, + "name": "data", + "privateClass": "QQuickWindow::d_func()", + "read": "data", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlListProperty", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "color", + "notify": "colorChanged", + "read": "color", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false, + "write": "setColor" + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 2, + "name": "contentItem", + "read": "contentItem", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "activeFocusItem", + "notify": "activeFocusItemChanged", + "read": "activeFocusItem", + "required": false, + "revision": 513, + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "palette", + "notify": "paletteChanged", + "privateClass": "QQuickWindow::d_func()", + "read": "palette", + "required": false, + "reset": "resetPalette", + "revision": 1538, + "scriptable": true, + "stored": true, + "type": "QQuickPalette*", + "user": false, + "write": "setPalette" + } + ], + "qualifiedClassName": "QQuickWindow", + "signals": [ + { + "access": "public", + "index": 0, + "name": "frameSwapped", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "sceneGraphInitialized", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "sceneGraphInvalidated", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "beforeSynchronizing", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "afterSynchronizing", + "returnType": "void", + "revision": 514 + }, + { + "access": "public", + "index": 5, + "name": "beforeRendering", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "afterRendering", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "afterAnimating", + "returnType": "void", + "revision": 514 + }, + { + "access": "public", + "index": 8, + "name": "sceneGraphAboutToStop", + "returnType": "void", + "revision": 514 + }, + { + "access": "public", + "arguments": [ + { + "name": "close", + "type": "QQuickCloseEvent*" + } + ], + "index": 9, + "name": "closing", + "returnType": "void", + "revision": 513 + }, + { + "access": "public", + "arguments": [ + { + "type": "QColor" + } + ], + "index": 10, + "name": "colorChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 11, + "name": "activeFocusItemChanged", + "returnType": "void", + "revision": 513 + }, + { + "access": "public", + "arguments": [ + { + "name": "error", + "type": "QQuickWindow::SceneGraphError" + }, + { + "name": "message", + "type": "QString" + } + ], + "index": 12, + "name": "sceneGraphError", + "returnType": "void", + "revision": 514 + }, + { + "access": "public", + "index": 13, + "name": "beforeRenderPassRecording", + "returnType": "void", + "revision": 526 + }, + { + "access": "public", + "index": 14, + "name": "afterRenderPassRecording", + "returnType": "void", + "revision": 526 + }, + { + "access": "public", + "index": 15, + "name": "paletteChanged", + "returnType": "void", + "revision": 1536 + }, + { + "access": "public", + "index": 16, + "name": "paletteCreated", + "returnType": "void", + "revision": 1536 + }, + { + "access": "public", + "index": 17, + "name": "beforeFrameBegin", + "returnType": "void", + "revision": 1536 + }, + { + "access": "public", + "index": 18, + "name": "afterFrameEnd", + "returnType": "void", + "revision": 1536 + } + ], + "slots": [ + { + "access": "public", + "index": 19, + "name": "update", + "returnType": "void" + }, + { + "access": "public", + "index": 20, + "name": "releaseResources", + "returnType": "void" + }, + { + "access": "private", + "index": 21, + "name": "maybeUpdate", + "returnType": "void" + }, + { + "access": "private", + "index": 22, + "name": "cleanupSceneGraph", + "returnType": "void" + }, + { + "access": "private", + "index": 23, + "name": "physicalDpiChanged", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "screen", + "type": "QScreen*" + } + ], + "index": 24, + "name": "handleScreenChanged", + "returnType": "void" + }, + { + "access": "private", + "index": 25, + "name": "runJobsAfterSwap", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "state", + "type": "Qt::ApplicationState" + } + ], + "index": 26, + "name": "handleApplicationStateChanged", + "returnType": "void" + }, + { + "access": "private", + "index": 27, + "name": "handleFontDatabaseChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWindow" + } + ] + } + ], + "inputFile": "qquickwindow.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickRootItem", + "lineNumber": 62, + "object": true, + "qualifiedClassName": "QQuickRootItem", + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "w", + "type": "int" + } + ], + "index": 0, + "name": "setWidth", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "h", + "type": "int" + } + ], + "index": 1, + "name": "setHeight", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickItem" + } + ] + } + ], + "inputFile": "qquickwindow_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickWindowAttached", + "lineNumber": 27, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "visibility", + "notify": "visibilityChanged", + "read": "visibility", + "required": false, + "scriptable": true, + "stored": true, + "type": "QWindow::Visibility", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "active", + "notify": "activeChanged", + "read": "isActive", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "activeFocusItem", + "notify": "activeFocusItemChanged", + "read": "activeFocusItem", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "contentItem", + "notify": "contentItemChanged", + "read": "contentItem", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "width", + "notify": "widthChanged", + "read": "width", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "height", + "notify": "heightChanged", + "read": "height", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 6, + "name": "window", + "notify": "windowChanged", + "read": "window", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickWindow*", + "user": false + } + ], + "qualifiedClassName": "QQuickWindowAttached", + "signals": [ + { + "access": "public", + "index": 0, + "name": "visibilityChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "activeChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "activeFocusItemChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "contentItemChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "widthChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "heightChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "windowChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "protected", + "arguments": [ + { + "type": "QQuickWindow*" + } + ], + "index": 7, + "name": "windowChange", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qquickwindowattached_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Foreign", + "value": "QWindow" + }, + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.AddedInVersion", + "value": "513" + } + ], + "className": "QWindowForeign", + "gadget": true, + "lineNumber": 27, + "qualifiedClassName": "QWindowForeign" + }, + { + "classInfos": [ + { + "name": "QML.Attached", + "value": "QQuickWindowAttached" + }, + { + "name": "QML.Element", + "value": "Window" + }, + { + "name": "QML.AddedInVersion", + "value": "513" + } + ], + "className": "QQuickWindowQmlImpl", + "interfaces": [ + [ + { + "className": "QQmlParserStatus", + "id": "\"org.qt-project.Qt.QQmlParserStatus\"" + } + ] + ], + "lineNumber": 35, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "visible", + "notify": "visibleChanged", + "read": "isVisible", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setVisible" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "visibility", + "notify": "visibilityChanged", + "read": "visibility", + "required": false, + "scriptable": true, + "stored": true, + "type": "QWindow::Visibility", + "user": false, + "write": "setVisibility" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "screen", + "notify": "screenChanged", + "read": "screen", + "required": false, + "revision": 515, + "scriptable": true, + "stored": true, + "type": "QObject*", + "user": false, + "write": "setScreen" + } + ], + "qualifiedClassName": "QQuickWindowQmlImpl", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "bool" + } + ], + "index": 0, + "name": "visibleChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "visibility", + "type": "QWindow::Visibility" + } + ], + "index": 1, + "name": "visibilityChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "screenChanged", + "returnType": "void", + "revision": 515 + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "int" + } + ], + "index": 3, + "name": "xChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "int" + } + ], + "index": 4, + "name": "yChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "private", + "index": 5, + "name": "applyWindowVisibility", + "returnType": "void", + "revision": 1543 + }, + { + "access": "private", + "index": 6, + "name": "updateTransientParent", + "returnType": "void", + "revision": 1543 + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickWindow" + }, + { + "access": "public", + "name": "QQmlParserStatus" + } + ] + } + ], + "inputFile": "qquickwindowmodule_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QSGAbstractRenderer", + "enums": [ + { + "alias": "MatrixTransformFlag", + "isClass": false, + "isFlag": true, + "name": "MatrixTransformFlags", + "values": [ + "MatrixTransformFlipY" + ] + } + ], + "lineNumber": 30, + "object": true, + "qualifiedClassName": "QSGAbstractRenderer", + "signals": [ + { + "access": "public", + "index": 0, + "name": "sceneGraphChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qsgabstractrenderer_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QSGLayer", + "lineNumber": 175, + "object": true, + "qualifiedClassName": "QSGLayer", + "signals": [ + { + "access": "public", + "index": 0, + "name": "updateRequested", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "scheduledUpdateCompleted", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "index": 2, + "name": "markDirtyTexture", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "invalidated", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QSGDynamicTexture" + } + ] + }, + { + "className": "QSGGuiThreadShaderEffectManager", + "lineNumber": 233, + "object": true, + "qualifiedClassName": "QSGGuiThreadShaderEffectManager", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "ok", + "type": "bool" + }, + { + "name": "typeHint", + "type": "ShaderInfo::Type" + }, + { + "name": "src", + "type": "QUrl" + }, + { + "name": "result", + "type": "ShaderInfo*" + } + ], + "index": 0, + "name": "shaderCodePrepared", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "logAndStatusChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "className": "QSGShaderEffectNode", + "lineNumber": 292, + "object": true, + "qualifiedClassName": "QSGShaderEffectNode", + "signals": [ + { + "access": "public", + "index": 0, + "name": "textureChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QSGVisitableNode" + } + ] + } + ], + "inputFile": "qsgadaptationlayer_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "ShaderManager", + "lineNumber": 668, + "object": true, + "qualifiedClassName": "QSGBatchRenderer::ShaderManager", + "slots": [ + { + "access": "public", + "index": 0, + "name": "invalidated", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qsgbatchrenderer_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "Texture", + "lineNumber": 50, + "object": true, + "qualifiedClassName": "QSGCompressedAtlasTexture::Texture", + "superClasses": [ + { + "access": "public", + "name": "QSGRhiAtlasTexture::TextureBase" + } + ] + } + ], + "inputFile": "qsgcompressedatlastexture_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QSGCompressedTexture", + "lineNumber": 29, + "object": true, + "qualifiedClassName": "QSGCompressedTexture", + "superClasses": [ + { + "access": "public", + "name": "QSGTexture" + } + ] + } + ], + "inputFile": "qsgcompressedtexture_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QSGContext", + "lineNumber": 81, + "object": true, + "qualifiedClassName": "QSGContext", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "className": "QSGRenderContext", + "lineNumber": 133, + "object": true, + "qualifiedClassName": "QSGRenderContext", + "signals": [ + { + "access": "public", + "index": 0, + "name": "initialized", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "invalidated", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "releaseCachedResourcesRequested", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "o", + "type": "QObject*" + } + ], + "index": 3, + "name": "textureFactoryDestroyed", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qsgcontext_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QSGContextPlugin", + "interfaces": [ + [ + { + "className": "QSGContextFactoryInterface", + "id": "\"org.qt-project.Qt.QSGContextFactoryInterface\"" + }, + { + "className": "QFactoryInterface", + "id": "\"org.qt-project.Qt.QFactoryInterface\"" + } + ] + ], + "lineNumber": 49, + "object": true, + "qualifiedClassName": "QSGContextPlugin", + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QSGContextFactoryInterface" + } + ] + } + ], + "inputFile": "qsgcontextplugin_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QSGDefaultRenderContext", + "lineNumber": 35, + "object": true, + "qualifiedClassName": "QSGDefaultRenderContext", + "superClasses": [ + { + "access": "public", + "name": "QSGRenderContext" + } + ] + } + ], + "inputFile": "qsgdefaultrendercontext_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QSGPlainTexture", + "lineNumber": 26, + "object": true, + "qualifiedClassName": "QSGPlainTexture", + "superClasses": [ + { + "access": "public", + "name": "QSGTexture" + } + ] + } + ], + "inputFile": "qsgplaintexture_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QSGRenderLoop", + "lineNumber": 33, + "object": true, + "qualifiedClassName": "QSGRenderLoop", + "signals": [ + { + "access": "public", + "index": 0, + "name": "timeToIncubate", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qsgrenderloop_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "Manager", + "lineNumber": 40, + "object": true, + "qualifiedClassName": "QSGRhiAtlasTexture::Manager", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "className": "AtlasBase", + "lineNumber": 63, + "object": true, + "qualifiedClassName": "QSGRhiAtlasTexture::AtlasBase", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "className": "TextureBase", + "lineNumber": 117, + "object": true, + "qualifiedClassName": "QSGRhiAtlasTexture::TextureBase", + "superClasses": [ + { + "access": "public", + "name": "QSGTexture" + } + ] + }, + { + "className": "Texture", + "lineNumber": 136, + "object": true, + "qualifiedClassName": "QSGRhiAtlasTexture::Texture", + "superClasses": [ + { + "access": "public", + "fullyQualifiedName": "QSGRhiAtlasTexture::TextureBase", + "name": "TextureBase" + } + ] + } + ], + "inputFile": "qsgrhiatlastexture_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QSGRhiLayer", + "lineNumber": 26, + "object": true, + "qualifiedClassName": "QSGRhiLayer", + "slots": [ + { + "access": "public", + "index": 0, + "name": "markDirtyTexture", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "invalidated", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QSGLayer" + } + ] + } + ], + "inputFile": "qsgrhilayer_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QSGRhiShaderEffectNode", + "lineNumber": 91, + "object": true, + "qualifiedClassName": "QSGRhiShaderEffectNode", + "slots": [ + { + "access": "private", + "index": 0, + "name": "handleTextureChange", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "object", + "type": "QObject*" + } + ], + "index": 1, + "name": "handleTextureProviderDestroyed", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QSGShaderEffectNode" + } + ] + } + ], + "inputFile": "qsgrhishadereffectnode_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QSGSoftwareRenderContext", + "lineNumber": 32, + "object": true, + "qualifiedClassName": "QSGSoftwareRenderContext", + "superClasses": [ + { + "access": "public", + "name": "QSGRenderContext" + } + ] + }, + { + "className": "QSGSoftwareContext", + "lineNumber": 48, + "object": true, + "qualifiedClassName": "QSGSoftwareContext", + "superClasses": [ + { + "access": "public", + "name": "QSGContext" + }, + { + "access": "public", + "name": "QSGRendererInterface" + } + ] + } + ], + "inputFile": "qsgsoftwarecontext_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QSGSoftwareLayer", + "lineNumber": 26, + "object": true, + "qualifiedClassName": "QSGSoftwareLayer", + "slots": [ + { + "access": "public", + "index": 0, + "name": "markDirtyTexture", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "invalidated", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QSGLayer" + } + ] + } + ], + "inputFile": "qsgsoftwarelayer_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QSGSoftwarePixmapTexture", + "lineNumber": 23, + "object": true, + "qualifiedClassName": "QSGSoftwarePixmapTexture", + "superClasses": [ + { + "access": "public", + "name": "QSGTexture" + } + ] + } + ], + "inputFile": "qsgsoftwarepixmaptexture_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QSGSoftwareRenderLoop", + "lineNumber": 24, + "object": true, + "qualifiedClassName": "QSGSoftwareRenderLoop", + "superClasses": [ + { + "access": "public", + "name": "QSGRenderLoop" + } + ] + } + ], + "inputFile": "qsgsoftwarerenderloop_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QSGSoftwareThreadedRenderLoop", + "lineNumber": 25, + "object": true, + "qualifiedClassName": "QSGSoftwareThreadedRenderLoop", + "slots": [ + { + "access": "public", + "index": 0, + "name": "onAnimationStarted", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "onAnimationStopped", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QSGRenderLoop" + } + ] + } + ], + "inputFile": "qsgsoftwarethreadedrenderloop_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QSGTexture", + "lineNumber": 19, + "object": true, + "qualifiedClassName": "QSGTexture", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "className": "QSGDynamicTexture", + "lineNumber": 99, + "object": true, + "qualifiedClassName": "QSGDynamicTexture", + "superClasses": [ + { + "access": "public", + "name": "QSGTexture" + } + ] + } + ], + "inputFile": "qsgtexture.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QSGTextureProvider", + "lineNumber": 12, + "object": true, + "qualifiedClassName": "QSGTextureProvider", + "signals": [ + { + "access": "public", + "index": 0, + "name": "textureChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qsgtextureprovider.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QSGThreadedRenderLoop", + "lineNumber": 28, + "object": true, + "qualifiedClassName": "QSGThreadedRenderLoop", + "slots": [ + { + "access": "public", + "index": 0, + "name": "animationStarted", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "animationStopped", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QSGRenderLoop" + } + ] + } + ], + "inputFile": "qsgthreadedrenderloop_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQuickLocalTransform", + "lineNumber": 16, + "object": true, + "qualifiedClassName": "QQuickLocalTransform", + "superClasses": [ + { + "access": "public", + "name": "QQuickTransform" + } + ] + } + ], + "inputFile": "qquickflipable.cpp", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQuickFontObject", + "lineNumber": 31, + "object": true, + "qualifiedClassName": "QQuickFontObject", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "id", + "type": "int" + } + ], + "index": 0, + "name": "fontDownloaded", + "returnType": "void" + } + ], + "slots": [ + { + "access": "private", + "index": 1, + "name": "replyFinished", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qquickfontloader.cpp", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QSGFramebufferObjectNode", + "lineNumber": 163, + "object": true, + "qualifiedClassName": "QSGFramebufferObjectNode", + "slots": [ + { + "access": "public", + "index": 0, + "name": "render", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "handleScreenChange", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QSGTextureProvider" + }, + { + "access": "public", + "name": "QSGSimpleTextureNode" + } + ] + } + ], + "inputFile": "qquickframebufferobject.cpp", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQuickPixmapReply", + "lineNumber": 142, + "object": true, + "qualifiedClassName": "QQuickPixmapReply", + "signals": [ + { + "access": "public", + "index": 0, + "name": "finished", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "qint64" + }, + { + "type": "qint64" + } + ], + "index": 1, + "name": "downloadProgress", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "className": "ReaderThreadExecutionEnforcer", + "lineNumber": 192, + "object": true, + "qualifiedClassName": "ReaderThreadExecutionEnforcer", + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "response", + "type": "QQuickImageResponse*" + } + ], + "index": 0, + "name": "asyncResponseFinished", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "asyncResponseFinished", + "returnType": "void" + }, + { + "access": "private", + "index": 2, + "name": "networkRequestDone", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "className": "QQuickPixmapReader", + "lineNumber": 220, + "object": true, + "qualifiedClassName": "QQuickPixmapReader", + "superClasses": [ + { + "access": "public", + "name": "QThread" + } + ] + } + ], + "inputFile": "qquickpixmapcache.cpp", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "CallbackRegistrationHelper", + "lineNumber": 35, + "object": true, + "qualifiedClassName": "CallbackRegistrationHelper", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qquickprofiler.cpp", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQuickShaderEffectSourceTextureProvider", + "lineNumber": 18, + "object": true, + "qualifiedClassName": "QQuickShaderEffectSourceTextureProvider", + "superClasses": [ + { + "access": "public", + "name": "QSGTextureProvider" + } + ] + }, + { + "className": "QQuickShaderSourceAttachedNode", + "lineNumber": 629, + "object": true, + "qualifiedClassName": "QQuickShaderSourceAttachedNode", + "slots": [ + { + "access": "public", + "index": 0, + "name": "markTextureDirty", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QSGNode" + } + ] + } + ], + "inputFile": "qquickshadereffectsource.cpp", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQuickWindowIncubationController", + "lineNumber": 79, + "object": true, + "qualifiedClassName": "QQuickWindowIncubationController", + "slots": [ + { + "access": "public", + "index": 0, + "name": "incubate", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "animationStopped", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QQmlIncubationController" + } + ] + } + ], + "inputFile": "qquickwindow.cpp", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QSGDefaultAnimationDriver", + "lineNumber": 113, + "object": true, + "qualifiedClassName": "QSGDefaultAnimationDriver", + "superClasses": [ + { + "access": "public", + "name": "QSGAnimationDriver" + } + ] + } + ], + "inputFile": "qsgcontext.cpp", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QSGGuiThreadRenderLoop", + "lineNumber": 112, + "object": true, + "qualifiedClassName": "QSGGuiThreadRenderLoop", + "superClasses": [ + { + "access": "public", + "name": "QSGRenderLoop" + } + ] + } + ], + "inputFile": "qsgrenderloop.cpp", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QSGSoftwareRenderThread", + "lineNumber": 121, + "object": true, + "qualifiedClassName": "QSGSoftwareRenderThread", + "slots": [ + { + "access": "public", + "index": 0, + "name": "onSceneGraphChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QThread" + } + ] + } + ], + "inputFile": "qsgsoftwarethreadedrenderloop.cpp", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QSGRenderThread", + "lineNumber": 220, + "object": true, + "qualifiedClassName": "QSGRenderThread", + "slots": [ + { + "access": "public", + "index": 0, + "name": "sceneGraphChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QThread" + } + ] + } + ], + "inputFile": "qsgthreadedrenderloop.cpp", + "outputRevision": 68 + } +] diff --git a/qt/6.8.1/msvc2022_64/metatypes/qt6quickcontrols2_metatypes.json b/qt/6.8.1/msvc2022_64/metatypes/qt6quickcontrols2_metatypes.json new file mode 100644 index 0000000000000000000000000000000000000000..d981c9d0d9e93fbd1df301d4bcd085b3ede65ddc --- /dev/null +++ b/qt/6.8.1/msvc2022_64/metatypes/qt6quickcontrols2_metatypes.json @@ -0,0 +1,38 @@ +[ + { + "classes": [ + { + "className": "QQuickAttachedPropertyPropagator", + "lineNumber": 14, + "object": true, + "qualifiedClassName": "QQuickAttachedPropertyPropagator", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qquickattachedpropertypropagator.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQuickStylePlugin", + "lineNumber": 25, + "object": true, + "qualifiedClassName": "QQuickStylePlugin", + "superClasses": [ + { + "access": "public", + "name": "QQmlExtensionPlugin" + } + ] + } + ], + "inputFile": "qquickstyleplugin_p.h", + "outputRevision": 68 + } +] diff --git a/qt/6.8.1/msvc2022_64/metatypes/qt6quickcontrols2basic_metatypes.json b/qt/6.8.1/msvc2022_64/metatypes/qt6quickcontrols2basic_metatypes.json new file mode 100644 index 0000000000000000000000000000000000000000..8b98e1eb08a05607ff91e7c0b4cb05e8fe5e1bf6 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/metatypes/qt6quickcontrols2basic_metatypes.json @@ -0,0 +1,618 @@ +[ + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "Basic" + }, + { + "name": "QML.Singleton", + "value": "true" + }, + { + "name": "QML.AddedInVersion", + "value": "513" + } + ], + "className": "QQuickBasicStyle", + "lineNumber": 25, + "object": true, + "properties": [ + { + "constant": true, + "designable": true, + "final": true, + "index": 0, + "name": "backgroundColor", + "read": "backgroundColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 1, + "name": "overlayModalColor", + "read": "overlayModalColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 2, + "name": "overlayDimColor", + "read": "overlayDimColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 3, + "name": "textColor", + "read": "textColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 4, + "name": "textDarkColor", + "read": "textDarkColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 5, + "name": "textLightColor", + "read": "textLightColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 6, + "name": "textLinkColor", + "read": "textLinkColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 7, + "name": "textSelectionColor", + "read": "textSelectionColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 8, + "name": "textDisabledColor", + "read": "textDisabledColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 9, + "name": "textDisabledLightColor", + "read": "textDisabledLightColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 10, + "name": "textPlaceholderColor", + "read": "textPlaceholderColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 11, + "name": "focusColor", + "read": "focusColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 12, + "name": "focusLightColor", + "read": "focusLightColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 13, + "name": "focusPressedColor", + "read": "focusPressedColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 14, + "name": "buttonColor", + "read": "buttonColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 15, + "name": "buttonPressedColor", + "read": "buttonPressedColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 16, + "name": "buttonCheckedColor", + "read": "buttonCheckedColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 17, + "name": "buttonCheckedPressedColor", + "read": "buttonCheckedPressedColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 18, + "name": "buttonCheckedFocusColor", + "read": "buttonCheckedFocusColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 19, + "name": "toolButtonColor", + "read": "toolButtonColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 20, + "name": "tabButtonColor", + "read": "tabButtonColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 21, + "name": "tabButtonPressedColor", + "read": "tabButtonPressedColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 22, + "name": "tabButtonCheckedPressedColor", + "read": "tabButtonCheckedPressedColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 23, + "name": "delegateColor", + "read": "delegateColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 24, + "name": "delegatePressedColor", + "read": "delegatePressedColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 25, + "name": "delegateFocusColor", + "read": "delegateFocusColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 26, + "name": "indicatorPressedColor", + "read": "indicatorPressedColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 27, + "name": "indicatorDisabledColor", + "read": "indicatorDisabledColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 28, + "name": "indicatorFrameColor", + "read": "indicatorFrameColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 29, + "name": "indicatorFramePressedColor", + "read": "indicatorFramePressedColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 30, + "name": "indicatorFrameDisabledColor", + "read": "indicatorFrameDisabledColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 31, + "name": "frameDarkColor", + "read": "frameDarkColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 32, + "name": "frameLightColor", + "read": "frameLightColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 33, + "name": "scrollBarColor", + "read": "scrollBarColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 34, + "name": "scrollBarPressedColor", + "read": "scrollBarPressedColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 35, + "name": "progressBarColor", + "read": "progressBarColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 36, + "name": "pageIndicatorColor", + "read": "pageIndicatorColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 37, + "name": "separatorColor", + "read": "separatorColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 38, + "name": "disabledDarkColor", + "read": "disabledDarkColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 39, + "name": "disabledLightColor", + "read": "disabledLightColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + } + ], + "qualifiedClassName": "QQuickBasicStyle", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qquickbasicstyle_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "Overlay" + }, + { + "name": "QML.Foreign", + "value": "QQuickOverlay" + }, + { + "name": "QML.Creatable", + "value": "false" + }, + { + "name": "QML.UncreatableReason", + "value": "" + }, + { + "name": "QML.AddedInVersion", + "value": "515" + } + ], + "className": "QQuickOverlayAttachedForeign", + "gadget": true, + "lineNumber": 29, + "qualifiedClassName": "QQuickOverlayAttachedForeign" + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "SplitHandle" + }, + { + "name": "QML.Foreign", + "value": "QQuickSplitHandleAttached" + }, + { + "name": "QML.Creatable", + "value": "false" + }, + { + "name": "QML.UncreatableReason", + "value": "" + }, + { + "name": "QML.AddedInVersion", + "value": "525" + } + ], + "className": "QQuickSplitHandleAttachedForeign", + "gadget": true, + "lineNumber": 39, + "qualifiedClassName": "QQuickSplitHandleAttachedForeign" + } + ], + "inputFile": "qtquickcontrols2basicforeign_p.h", + "outputRevision": 68 + } +] diff --git a/qt/6.8.1/msvc2022_64/metatypes/qt6quickcontrols2basicstyleimpl_metatypes.json b/qt/6.8.1/msvc2022_64/metatypes/qt6quickcontrols2basicstyleimpl_metatypes.json new file mode 100644 index 0000000000000000000000000000000000000000..85650a8406b4fb6a7fc7a656fc8cc04c33bdc2d3 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/metatypes/qt6quickcontrols2basicstyleimpl_metatypes.json @@ -0,0 +1,232 @@ +[ + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "BusyIndicatorImpl" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickBasicBusyIndicator", + "lineNumber": 24, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "pen", + "read": "pen", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false, + "write": "setPen" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "fill", + "read": "fill", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false, + "write": "setFill" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "running", + "read": "isRunning", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setRunning" + } + ], + "qualifiedClassName": "QQuickBasicBusyIndicator", + "superClasses": [ + { + "access": "public", + "name": "QQuickItem" + } + ] + } + ], + "inputFile": "qquickbasicbusyindicator_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "DialImpl" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickBasicDial", + "lineNumber": 24, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "progress", + "read": "progress", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setProgress" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "startAngle", + "read": "startAngle", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setStartAngle" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "endAngle", + "read": "endAngle", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setEndAngle" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "color", + "read": "color", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false, + "write": "setColor" + } + ], + "qualifiedClassName": "QQuickBasicDial", + "superClasses": [ + { + "access": "public", + "name": "QQuickPaintedItem" + } + ] + } + ], + "inputFile": "qquickbasicdial_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "ProgressBarImpl" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickBasicProgressBar", + "lineNumber": 24, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "indeterminate", + "read": "isIndeterminate", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setIndeterminate" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "progress", + "read": "progress", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setProgress" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "color", + "read": "color", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false, + "write": "setColor" + } + ], + "qualifiedClassName": "QQuickBasicProgressBar", + "superClasses": [ + { + "access": "public", + "name": "QQuickItem" + } + ] + } + ], + "inputFile": "qquickbasicprogressbar_p.h", + "outputRevision": 68 + } +] diff --git a/qt/6.8.1/msvc2022_64/metatypes/qt6quickcontrols2fluentwinui3styleimpl_metatypes.json b/qt/6.8.1/msvc2022_64/metatypes/qt6quickcontrols2fluentwinui3styleimpl_metatypes.json new file mode 100644 index 0000000000000000000000000000000000000000..e194510f2520388da661e3cb876fd5910c39b8f2 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/metatypes/qt6quickcontrols2fluentwinui3styleimpl_metatypes.json @@ -0,0 +1,60 @@ +[ + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "FocusStroke" + }, + { + "name": "QML.AddedInVersion", + "value": "1544" + } + ], + "className": "QQuickFluentWinUI3FocusStroke", + "lineNumber": 20, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "color", + "read": "color", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false, + "write": "setColor" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "radius", + "read": "radius", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setRadius" + } + ], + "qualifiedClassName": "QQuickFluentWinUI3FocusStroke", + "superClasses": [ + { + "access": "public", + "name": "QQuickPaintedItem" + } + ] + } + ], + "inputFile": "qquickfluentwinui3focusstroke_p.h", + "outputRevision": 68 + } +] diff --git a/qt/6.8.1/msvc2022_64/metatypes/qt6quickcontrols2fusion_metatypes.json b/qt/6.8.1/msvc2022_64/metatypes/qt6quickcontrols2fusion_metatypes.json new file mode 100644 index 0000000000000000000000000000000000000000..ea01c22e326138da2b16bb15d11ffd49acb7d773 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/metatypes/qt6quickcontrols2fusion_metatypes.json @@ -0,0 +1,348 @@ +[ + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "Fusion" + }, + { + "name": "QML.Singleton", + "value": "true" + }, + { + "name": "QML.AddedInVersion", + "value": "515" + } + ], + "className": "QQuickFusionStyle", + "lineNumber": 27, + "methods": [ + { + "access": "public", + "arguments": [ + { + "name": "palette", + "type": "QQuickPalette*" + } + ], + "index": 0, + "name": "highlight", + "returnType": "QColor" + }, + { + "access": "public", + "arguments": [ + { + "name": "palette", + "type": "QQuickPalette*" + } + ], + "index": 1, + "name": "highlightedText", + "returnType": "QColor" + }, + { + "access": "public", + "arguments": [ + { + "name": "palette", + "type": "QQuickPalette*" + } + ], + "index": 2, + "name": "outline", + "returnType": "QColor" + }, + { + "access": "public", + "arguments": [ + { + "name": "palette", + "type": "QQuickPalette*" + } + ], + "index": 3, + "name": "highlightedOutline", + "returnType": "QColor" + }, + { + "access": "public", + "arguments": [ + { + "name": "palette", + "type": "QQuickPalette*" + } + ], + "index": 4, + "name": "tabFrameColor", + "returnType": "QColor" + }, + { + "access": "public", + "arguments": [ + { + "name": "palette", + "type": "QQuickPalette*" + }, + { + "name": "highlighted", + "type": "bool" + }, + { + "name": "down", + "type": "bool" + }, + { + "name": "hovered", + "type": "bool" + } + ], + "index": 5, + "name": "buttonColor", + "returnType": "QColor" + }, + { + "access": "public", + "arguments": [ + { + "name": "palette", + "type": "QQuickPalette*" + }, + { + "name": "highlighted", + "type": "bool" + }, + { + "name": "down", + "type": "bool" + } + ], + "index": 6, + "isCloned": true, + "name": "buttonColor", + "returnType": "QColor" + }, + { + "access": "public", + "arguments": [ + { + "name": "palette", + "type": "QQuickPalette*" + }, + { + "name": "highlighted", + "type": "bool" + } + ], + "index": 7, + "isCloned": true, + "name": "buttonColor", + "returnType": "QColor" + }, + { + "access": "public", + "arguments": [ + { + "name": "palette", + "type": "QQuickPalette*" + } + ], + "index": 8, + "isCloned": true, + "name": "buttonColor", + "returnType": "QColor" + }, + { + "access": "public", + "arguments": [ + { + "name": "palette", + "type": "QQuickPalette*" + }, + { + "name": "highlighted", + "type": "bool" + }, + { + "name": "enabled", + "type": "bool" + } + ], + "index": 9, + "name": "buttonOutline", + "returnType": "QColor" + }, + { + "access": "public", + "arguments": [ + { + "name": "palette", + "type": "QQuickPalette*" + }, + { + "name": "highlighted", + "type": "bool" + } + ], + "index": 10, + "isCloned": true, + "name": "buttonOutline", + "returnType": "QColor" + }, + { + "access": "public", + "arguments": [ + { + "name": "palette", + "type": "QQuickPalette*" + } + ], + "index": 11, + "isCloned": true, + "name": "buttonOutline", + "returnType": "QColor" + }, + { + "access": "public", + "arguments": [ + { + "name": "baseColor", + "type": "QColor" + } + ], + "index": 12, + "name": "gradientStart", + "returnType": "QColor" + }, + { + "access": "public", + "arguments": [ + { + "name": "baseColor", + "type": "QColor" + } + ], + "index": 13, + "name": "gradientStop", + "returnType": "QColor" + }, + { + "access": "public", + "arguments": [ + { + "name": "colorA", + "type": "QColor" + }, + { + "name": "colorB", + "type": "QColor" + }, + { + "name": "factor", + "type": "int" + } + ], + "index": 14, + "name": "mergedColors", + "returnType": "QColor" + }, + { + "access": "public", + "arguments": [ + { + "name": "colorA", + "type": "QColor" + }, + { + "name": "colorB", + "type": "QColor" + } + ], + "index": 15, + "isCloned": true, + "name": "mergedColors", + "returnType": "QColor" + }, + { + "access": "public", + "arguments": [ + { + "name": "palette", + "type": "QQuickPalette*" + } + ], + "index": 16, + "name": "grooveColor", + "returnType": "QColor" + } + ], + "object": true, + "properties": [ + { + "constant": true, + "designable": true, + "final": true, + "index": 0, + "name": "lightShade", + "read": "lightShade", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 1, + "name": "darkShade", + "read": "darkShade", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 2, + "name": "topShadow", + "read": "topShadow", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 3, + "name": "innerContrastLine", + "read": "innerContrastLine", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + } + ], + "qualifiedClassName": "QQuickFusionStyle", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qquickfusionstyle_p.h", + "outputRevision": 68 + } +] diff --git a/qt/6.8.1/msvc2022_64/metatypes/qt6quickcontrols2fusionstyleimpl_metatypes.json b/qt/6.8.1/msvc2022_64/metatypes/qt6quickcontrols2fusionstyleimpl_metatypes.json new file mode 100644 index 0000000000000000000000000000000000000000..6df78dabf36c38a6c8c1f780a047909be261c827 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/metatypes/qt6quickcontrols2fusionstyleimpl_metatypes.json @@ -0,0 +1,132 @@ +[ + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "BusyIndicatorImpl" + }, + { + "name": "QML.AddedInVersion", + "value": "515" + } + ], + "className": "QQuickFusionBusyIndicator", + "lineNumber": 24, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "color", + "read": "color", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false, + "write": "setColor" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "running", + "read": "isRunning", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setRunning" + } + ], + "qualifiedClassName": "QQuickFusionBusyIndicator", + "superClasses": [ + { + "access": "public", + "name": "QQuickPaintedItem" + } + ] + } + ], + "inputFile": "qquickfusionbusyindicator_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "DialImpl" + }, + { + "name": "QML.AddedInVersion", + "value": "515" + } + ], + "className": "QQuickFusionDial", + "lineNumber": 23, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "highlight", + "read": "highlight", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setHighlight" + } + ], + "qualifiedClassName": "QQuickFusionDial", + "superClasses": [ + { + "access": "public", + "name": "QQuickPaintedItem" + } + ] + } + ], + "inputFile": "qquickfusiondial_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "KnobImpl" + }, + { + "name": "QML.AddedInVersion", + "value": "515" + } + ], + "className": "QQuickFusionKnob", + "lineNumber": 23, + "object": true, + "qualifiedClassName": "QQuickFusionKnob", + "superClasses": [ + { + "access": "public", + "name": "QQuickPaintedItem" + } + ] + } + ], + "inputFile": "qquickfusionknob_p.h", + "outputRevision": 68 + } +] diff --git a/qt/6.8.1/msvc2022_64/metatypes/qt6quickcontrols2imagine_metatypes.json b/qt/6.8.1/msvc2022_64/metatypes/qt6quickcontrols2imagine_metatypes.json new file mode 100644 index 0000000000000000000000000000000000000000..655a7f7ba665071c847850d170d2914083cb4b4a --- /dev/null +++ b/qt/6.8.1/msvc2022_64/metatypes/qt6quickcontrols2imagine_metatypes.json @@ -0,0 +1,82 @@ +[ + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "Imagine" + }, + { + "name": "QML.Attached", + "value": "QQuickImagineStyle" + }, + { + "name": "QML.Creatable", + "value": "false" + }, + { + "name": "QML.UncreatableReason", + "value": "" + }, + { + "name": "QML.AddedInVersion", + "value": "515" + } + ], + "className": "QQuickImagineStyle", + "lineNumber": 25, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "path", + "notify": "pathChanged", + "read": "path", + "required": false, + "reset": "resetPath", + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setPath" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "url", + "notify": "pathChanged", + "read": "url", + "required": false, + "scriptable": true, + "stored": true, + "type": "QUrl", + "user": false + } + ], + "qualifiedClassName": "QQuickImagineStyle", + "signals": [ + { + "access": "public", + "index": 0, + "name": "pathChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickAttachedPropertyPropagator" + } + ] + } + ], + "inputFile": "qquickimaginestyle_p.h", + "outputRevision": 68 + } +] diff --git a/qt/6.8.1/msvc2022_64/metatypes/qt6quickcontrols2imaginestyleimpl_metatypes.json b/qt/6.8.1/msvc2022_64/metatypes/qt6quickcontrols2imaginestyleimpl_metatypes.json new file mode 100644 index 0000000000000000000000000000000000000000..0d4f101c7a37a4c875e6999bee1a287fdb733380 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/metatypes/qt6quickcontrols2imaginestyleimpl_metatypes.json @@ -0,0 +1,2 @@ +[ +] diff --git a/qt/6.8.1/msvc2022_64/metatypes/qt6quickcontrols2impl_metatypes.json b/qt/6.8.1/msvc2022_64/metatypes/qt6quickcontrols2impl_metatypes.json new file mode 100644 index 0000000000000000000000000000000000000000..b6f8482adefa7f501a6bf758f4bc5af8adbea850 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/metatypes/qt6quickcontrols2impl_metatypes.json @@ -0,0 +1,1418 @@ +[ + { + "classes": [ + { + "className": "QQuickAnimatedNode", + "lineNumber": 28, + "object": true, + "qualifiedClassName": "QQuickAnimatedNode", + "signals": [ + { + "access": "public", + "index": 0, + "name": "started", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "stopped", + "returnType": "void" + } + ], + "slots": [ + { + "access": "private", + "index": 2, + "name": "advance", + "returnType": "void" + }, + { + "access": "private", + "index": 3, + "name": "update", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QSGTransformNode" + } + ] + } + ], + "inputFile": "qquickanimatednode_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "CheckLabel" + }, + { + "name": "QML.AddedInVersion", + "value": "515" + } + ], + "className": "QQuickCheckLabel", + "lineNumber": 23, + "object": true, + "qualifiedClassName": "QQuickCheckLabel", + "superClasses": [ + { + "access": "public", + "name": "QQuickText" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.Foreign", + "value": "QQuickText" + }, + { + "name": "QML.AddedInVersion", + "value": "515" + } + ], + "className": "QQuickTextForeign", + "gadget": true, + "lineNumber": 33, + "qualifiedClassName": "QQuickTextForeign" + } + ], + "inputFile": "qquickchecklabel_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "ClippedText" + }, + { + "name": "QML.AddedInVersion", + "value": "514" + } + ], + "className": "QQuickClippedText", + "lineNumber": 23, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "clipX", + "read": "clipX", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setClipX" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "clipY", + "read": "clipY", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setClipY" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "clipWidth", + "read": "clipWidth", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setClipWidth" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "clipHeight", + "read": "clipHeight", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setClipHeight" + } + ], + "qualifiedClassName": "QQuickClippedText", + "superClasses": [ + { + "access": "public", + "name": "QQuickText" + } + ] + } + ], + "inputFile": "qquickclippedtext_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "Color" + }, + { + "name": "QML.Singleton", + "value": "true" + }, + { + "name": "QML.AddedInVersion", + "value": "515" + } + ], + "className": "QQuickColor", + "lineNumber": 25, + "methods": [ + { + "access": "public", + "arguments": [ + { + "name": "color", + "type": "QColor" + }, + { + "name": "opacity", + "type": "qreal" + } + ], + "index": 0, + "name": "transparent", + "returnType": "QColor" + }, + { + "access": "public", + "arguments": [ + { + "name": "a", + "type": "QColor" + }, + { + "name": "b", + "type": "QColor" + }, + { + "name": "factor", + "type": "qreal" + } + ], + "index": 1, + "name": "blend", + "returnType": "QColor" + } + ], + "object": true, + "qualifiedClassName": "QQuickColor", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qquickcolor_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "ColorImage" + }, + { + "name": "QML.AddedInVersion", + "value": "515" + } + ], + "className": "QQuickColorImage", + "lineNumber": 24, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "color", + "notify": "colorChanged", + "read": "color", + "required": false, + "reset": "resetColor", + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false, + "write": "setColor" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "defaultColor", + "notify": "defaultColorChanged", + "read": "defaultColor", + "required": false, + "reset": "resetDefaultColor", + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false, + "write": "setDefaultColor" + } + ], + "qualifiedClassName": "QQuickColorImage", + "signals": [ + { + "access": "public", + "index": 0, + "name": "colorChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "defaultColorChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickImage" + } + ] + } + ], + "inputFile": "qquickcolorimage_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "IconImage" + }, + { + "name": "QML.AddedInVersion", + "value": "515" + } + ], + "className": "QQuickIconImage", + "lineNumber": 25, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "name", + "notify": "nameChanged", + "read": "name", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setName" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "color", + "notify": "colorChanged", + "read": "color", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false, + "write": "setColor" + } + ], + "qualifiedClassName": "QQuickIconImage", + "signals": [ + { + "access": "public", + "index": 0, + "name": "nameChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "colorChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickImage" + } + ] + } + ], + "inputFile": "qquickiconimage_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "IconLabel" + }, + { + "name": "QML.AddedInVersion", + "value": "515" + } + ], + "className": "QQuickIconLabel", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "Display", + "values": [ + "IconOnly", + "TextOnly", + "TextBesideIcon", + "TextUnderIcon" + ] + } + ], + "lineNumber": 26, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "icon", + "read": "icon", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickIcon", + "user": false, + "write": "setIcon" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "text", + "read": "text", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setText" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "font", + "read": "font", + "required": false, + "scriptable": true, + "stored": true, + "type": "QFont", + "user": false, + "write": "setFont" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "color", + "read": "color", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false, + "write": "setColor" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "display", + "read": "display", + "required": false, + "scriptable": true, + "stored": true, + "type": "Display", + "user": false, + "write": "setDisplay" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "spacing", + "read": "spacing", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setSpacing" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 6, + "name": "mirrored", + "read": "isMirrored", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setMirrored" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 7, + "name": "alignment", + "read": "alignment", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::Alignment", + "user": false, + "write": "setAlignment" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 8, + "name": "topPadding", + "read": "topPadding", + "required": false, + "reset": "resetTopPadding", + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setTopPadding" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 9, + "name": "leftPadding", + "read": "leftPadding", + "required": false, + "reset": "resetLeftPadding", + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setLeftPadding" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 10, + "name": "rightPadding", + "read": "rightPadding", + "required": false, + "reset": "resetRightPadding", + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setRightPadding" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 11, + "name": "bottomPadding", + "read": "bottomPadding", + "required": false, + "reset": "resetBottomPadding", + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setBottomPadding" + } + ], + "qualifiedClassName": "QQuickIconLabel", + "superClasses": [ + { + "access": "public", + "name": "QQuickItem" + } + ] + } + ], + "inputFile": "qquickiconlabel_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "ImageSelector" + }, + { + "name": "QML.AddedInVersion", + "value": "515" + } + ], + "className": "QQuickImageSelector", + "interfaces": [ + [ + { + "className": "QQmlParserStatus", + "id": "\"org.qt-project.Qt.QQmlParserStatus\"" + } + ], + [ + { + "className": "QQmlPropertyValueInterceptor", + "id": "\"org.qt-project.Qt.QQmlPropertyValueInterceptor\"" + } + ] + ], + "lineNumber": 29, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "source", + "notify": "sourceChanged", + "read": "source", + "required": false, + "scriptable": true, + "stored": true, + "type": "QUrl", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "name", + "read": "name", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setName" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "path", + "read": "path", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setPath" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "states", + "read": "states", + "required": false, + "scriptable": true, + "stored": true, + "type": "QVariantList", + "user": false, + "write": "setStates" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "separator", + "read": "separator", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setSeparator" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "cache", + "read": "cache", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setCache" + } + ], + "qualifiedClassName": "QQuickImageSelector", + "signals": [ + { + "access": "public", + "index": 0, + "name": "sourceChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QQmlParserStatus" + }, + { + "access": "public", + "name": "QQmlPropertyValueInterceptor" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "NinePatchImageSelector" + }, + { + "name": "QML.AddedInVersion", + "value": "515" + } + ], + "className": "QQuickNinePatchImageSelector", + "lineNumber": 93, + "object": true, + "qualifiedClassName": "QQuickNinePatchImageSelector", + "superClasses": [ + { + "access": "public", + "name": "QQuickImageSelector" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "AnimatedImageSelector" + }, + { + "name": "QML.AddedInVersion", + "value": "515" + } + ], + "className": "QQuickAnimatedImageSelector", + "lineNumber": 106, + "object": true, + "qualifiedClassName": "QQuickAnimatedImageSelector", + "superClasses": [ + { + "access": "public", + "name": "QQuickImageSelector" + } + ] + } + ], + "inputFile": "qquickimageselector_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "ItemGroup" + }, + { + "name": "QML.AddedInVersion", + "value": "514" + } + ], + "className": "QQuickItemGroup", + "lineNumber": 24, + "object": true, + "qualifiedClassName": "QQuickItemGroup", + "superClasses": [ + { + "access": "public", + "name": "QQuickImplicitSizeItem" + }, + { + "access": "protected", + "name": "QQuickItemChangeListener" + } + ] + } + ], + "inputFile": "qquickitemgroup_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "MnemonicLabel" + }, + { + "name": "QML.AddedInVersion", + "value": "515" + } + ], + "className": "QQuickMnemonicLabel", + "lineNumber": 23, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "text", + "read": "text", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setText" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "mnemonicVisible", + "read": "isMnemonicVisible", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setMnemonicVisible" + } + ], + "qualifiedClassName": "QQuickMnemonicLabel", + "superClasses": [ + { + "access": "public", + "name": "QQuickText" + } + ] + } + ], + "inputFile": "qquickmnemoniclabel_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "NinePatchImage" + }, + { + "name": "QML.AddedInVersion", + "value": "515" + } + ], + "className": "QQuickNinePatchImage", + "lineNumber": 24, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "topPadding", + "notify": "topPaddingChanged", + "read": "topPadding", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "leftPadding", + "notify": "leftPaddingChanged", + "read": "leftPadding", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "rightPadding", + "notify": "rightPaddingChanged", + "read": "rightPadding", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "bottomPadding", + "notify": "bottomPaddingChanged", + "read": "bottomPadding", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "topInset", + "notify": "topInsetChanged", + "read": "topInset", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "leftInset", + "notify": "leftInsetChanged", + "read": "leftInset", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 6, + "name": "rightInset", + "notify": "rightInsetChanged", + "read": "rightInset", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 7, + "name": "bottomInset", + "notify": "bottomInsetChanged", + "read": "bottomInset", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + } + ], + "qualifiedClassName": "QQuickNinePatchImage", + "signals": [ + { + "access": "public", + "index": 0, + "name": "topPaddingChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "leftPaddingChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "rightPaddingChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "bottomPaddingChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "topInsetChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "leftInsetChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "rightInsetChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "bottomInsetChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickImage" + } + ] + } + ], + "inputFile": "qquickninepatchimage_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "PaddedRectangle" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickPaddedRectangle", + "lineNumber": 23, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "padding", + "notify": "paddingChanged", + "read": "padding", + "required": false, + "reset": "resetPadding", + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setPadding" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "topPadding", + "notify": "topPaddingChanged", + "read": "topPadding", + "required": false, + "reset": "resetTopPadding", + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setTopPadding" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "leftPadding", + "notify": "leftPaddingChanged", + "read": "leftPadding", + "required": false, + "reset": "resetLeftPadding", + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setLeftPadding" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "rightPadding", + "notify": "rightPaddingChanged", + "read": "rightPadding", + "required": false, + "reset": "resetRightPadding", + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setRightPadding" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "bottomPadding", + "notify": "bottomPaddingChanged", + "read": "bottomPadding", + "required": false, + "reset": "resetBottomPadding", + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setBottomPadding" + } + ], + "qualifiedClassName": "QQuickPaddedRectangle", + "signals": [ + { + "access": "public", + "index": 0, + "name": "paddingChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "topPaddingChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "leftPaddingChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "rightPaddingChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "bottomPaddingChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickRectangle" + } + ] + } + ], + "inputFile": "qquickpaddedrectangle_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "PlaceholderText" + }, + { + "name": "QML.AddedInVersion", + "value": "514" + } + ], + "className": "QQuickPlaceholderText", + "lineNumber": 23, + "object": true, + "qualifiedClassName": "QQuickPlaceholderText", + "slots": [ + { + "access": "private", + "index": 0, + "name": "updateAlignment", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickText" + } + ] + } + ], + "inputFile": "qquickplaceholdertext_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Extended", + "value": "QPlatformTheme" + }, + { + "name": "QML.ExtensionIsNamespace", + "value": "true" + }, + { + "name": "QML.Element", + "value": "PlatformTheme" + }, + { + "name": "QML.Singleton", + "value": "true" + }, + { + "name": "QML.AddedInVersion", + "value": "1539" + } + ], + "className": "QQuickPlatformTheme", + "lineNumber": 25, + "methods": [ + { + "access": "public", + "arguments": [ + { + "name": "themeHint", + "type": "QPlatformTheme::ThemeHint" + } + ], + "index": 0, + "name": "themeHint", + "returnType": "QVariant" + } + ], + "object": true, + "qualifiedClassName": "QQuickPlatformTheme", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qquickplatformtheme_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "TumblerView" + }, + { + "name": "QML.AddedInVersion", + "value": "513" + } + ], + "className": "QQuickTumblerView", + "lineNumber": 29, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "model", + "notify": "modelChanged", + "read": "model", + "required": false, + "scriptable": true, + "stored": true, + "type": "QVariant", + "user": false, + "write": "setModel" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "delegate", + "notify": "delegateChanged", + "read": "delegate", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlComponent*", + "user": false, + "write": "setDelegate" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "path", + "notify": "pathChanged", + "read": "path", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickPath*", + "user": false, + "write": "setPath" + } + ], + "qualifiedClassName": "QQuickTumblerView", + "signals": [ + { + "access": "public", + "index": 0, + "name": "modelChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "delegateChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "pathChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickItem" + } + ] + } + ], + "inputFile": "qquicktumblerview_p.h", + "outputRevision": 68 + } +] diff --git a/qt/6.8.1/msvc2022_64/metatypes/qt6quickcontrols2material_metatypes.json b/qt/6.8.1/msvc2022_64/metatypes/qt6quickcontrols2material_metatypes.json new file mode 100644 index 0000000000000000000000000000000000000000..89ec47b056c0640b71c957554de8d4ef66a60e90 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/metatypes/qt6quickcontrols2material_metatypes.json @@ -0,0 +1,1274 @@ +[ + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "Material" + }, + { + "name": "QML.Attached", + "value": "QQuickMaterialStyle" + }, + { + "name": "QML.Creatable", + "value": "false" + }, + { + "name": "QML.UncreatableReason", + "value": "" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickMaterialStyle", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "Theme", + "values": [ + "Light", + "Dark", + "System" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "Variant", + "values": [ + "Normal", + "Dense" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "Color", + "values": [ + "Red", + "Pink", + "Purple", + "DeepPurple", + "Indigo", + "Blue", + "LightBlue", + "Cyan", + "Teal", + "Green", + "LightGreen", + "Lime", + "Yellow", + "Amber", + "Orange", + "DeepOrange", + "Brown", + "Grey", + "BlueGrey" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "Shade", + "values": [ + "Shade50", + "Shade100", + "Shade200", + "Shade300", + "Shade400", + "Shade500", + "Shade600", + "Shade700", + "Shade800", + "Shade900", + "ShadeA100", + "ShadeA200", + "ShadeA400", + "ShadeA700" + ] + }, + { + "isClass": true, + "isFlag": false, + "name": "RoundedScale", + "values": [ + "NotRounded", + "ExtraSmallScale", + "SmallScale", + "MediumScale", + "LargeScale", + "ExtraLargeScale", + "FullScale" + ] + }, + { + "isClass": true, + "isFlag": false, + "name": "ContainerStyle", + "values": [ + "Filled", + "Outlined" + ] + } + ], + "lineNumber": 25, + "methods": [ + { + "access": "public", + "arguments": [ + { + "name": "theme", + "type": "Theme" + }, + { + "name": "background", + "type": "QVariant" + }, + { + "name": "accent", + "type": "QVariant" + }, + { + "name": "enabled", + "type": "bool" + }, + { + "name": "flat", + "type": "bool" + }, + { + "name": "highlighted", + "type": "bool" + }, + { + "name": "checked", + "type": "bool" + } + ], + "index": 14, + "name": "buttonColor", + "returnType": "QColor" + }, + { + "access": "public", + "arguments": [ + { + "name": "color", + "type": "Color" + }, + { + "name": "shade", + "type": "Shade" + } + ], + "index": 15, + "name": "color", + "returnType": "QColor" + }, + { + "access": "public", + "arguments": [ + { + "name": "color", + "type": "Color" + } + ], + "index": 16, + "isCloned": true, + "name": "color", + "returnType": "QColor" + }, + { + "access": "public", + "arguments": [ + { + "name": "color", + "type": "QColor" + }, + { + "name": "shade", + "type": "Shade" + } + ], + "index": 17, + "name": "shade", + "returnType": "QColor" + }, + { + "access": "public", + "arguments": [ + { + "name": "flat", + "type": "bool" + }, + { + "name": "hasIcon", + "type": "bool" + } + ], + "index": 18, + "name": "buttonLeftPadding", + "returnType": "int" + }, + { + "access": "public", + "arguments": [ + { + "name": "flat", + "type": "bool" + }, + { + "name": "hasIcon", + "type": "bool" + }, + { + "name": "hasText", + "type": "bool" + } + ], + "index": 19, + "name": "buttonRightPadding", + "returnType": "int" + } + ], + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "theme", + "notify": "themeChanged", + "read": "theme", + "required": false, + "reset": "resetTheme", + "scriptable": true, + "stored": true, + "type": "Theme", + "user": false, + "write": "setTheme" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "primary", + "notify": "primaryChanged", + "read": "primary", + "required": false, + "reset": "resetPrimary", + "scriptable": true, + "stored": true, + "type": "QVariant", + "user": false, + "write": "setPrimary" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "accent", + "notify": "accentChanged", + "read": "accent", + "required": false, + "reset": "resetAccent", + "scriptable": true, + "stored": true, + "type": "QVariant", + "user": false, + "write": "setAccent" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "foreground", + "notify": "foregroundChanged", + "read": "foreground", + "required": false, + "reset": "resetForeground", + "scriptable": true, + "stored": true, + "type": "QVariant", + "user": false, + "write": "setForeground" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "background", + "notify": "backgroundChanged", + "read": "background", + "required": false, + "reset": "resetBackground", + "scriptable": true, + "stored": true, + "type": "QVariant", + "user": false, + "write": "setBackground" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "elevation", + "notify": "elevationChanged", + "read": "elevation", + "required": false, + "reset": "resetElevation", + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setElevation" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 6, + "name": "roundedScale", + "notify": "roundedScaleChanged", + "read": "roundedScale", + "required": false, + "reset": "resetRoundedScale", + "scriptable": true, + "stored": true, + "type": "RoundedScale", + "user": false, + "write": "setRoundedScale" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 7, + "name": "containerStyle", + "notify": "containerStyleChanged", + "read": "containerStyle", + "required": false, + "reset": "resetContainerStyle", + "scriptable": true, + "stored": true, + "type": "ContainerStyle", + "user": false, + "write": "setContainerStyle" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 8, + "name": "primaryColor", + "notify": "primaryChanged", + "read": "primaryColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 9, + "name": "accentColor", + "notify": "accentChanged", + "read": "accentColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 10, + "name": "backgroundColor", + "notify": "backgroundChanged", + "read": "backgroundColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 11, + "name": "primaryTextColor", + "notify": "themeChanged", + "read": "primaryTextColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 12, + "name": "primaryHighlightedTextColor", + "notify": "primaryHighlightedTextColorChanged", + "read": "primaryHighlightedTextColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 13, + "name": "secondaryTextColor", + "notify": "themeChanged", + "read": "secondaryTextColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 14, + "name": "hintTextColor", + "notify": "themeChanged", + "read": "hintTextColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 15, + "name": "textSelectionColor", + "notify": "themeOrAccentChanged", + "read": "textSelectionColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 16, + "name": "dropShadowColor", + "read": "dropShadowColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 17, + "name": "dividerColor", + "notify": "themeChanged", + "read": "dividerColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 18, + "name": "iconColor", + "notify": "themeChanged", + "read": "iconColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 19, + "name": "iconDisabledColor", + "notify": "themeChanged", + "read": "iconDisabledColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 20, + "name": "frameColor", + "notify": "themeChanged", + "read": "frameColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 21, + "name": "rippleColor", + "notify": "themeChanged", + "read": "rippleColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 22, + "name": "highlightedRippleColor", + "notify": "themeOrAccentChanged", + "read": "highlightedRippleColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 23, + "name": "switchUncheckedTrackColor", + "notify": "themeChanged", + "read": "switchUncheckedTrackColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 24, + "name": "switchCheckedTrackColor", + "notify": "themeOrAccentChanged", + "read": "switchCheckedTrackColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 25, + "name": "switchUncheckedHandleColor", + "notify": "themeChanged", + "read": "switchUncheckedHandleColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 26, + "name": "switchUncheckedHoveredHandleColor", + "notify": "themeChanged", + "read": "switchUncheckedHoveredHandleColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 27, + "name": "switchDisabledUncheckedTrackColor", + "notify": "themeChanged", + "read": "switchDisabledUncheckedTrackColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 28, + "name": "switchDisabledCheckedTrackColor", + "notify": "themeChanged", + "read": "switchDisabledCheckedTrackColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 29, + "name": "switchDisabledUncheckedTrackBorderColor", + "notify": "themeChanged", + "read": "switchDisabledUncheckedTrackBorderColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 30, + "name": "switchCheckedHandleColor", + "notify": "themeOrAccentChanged", + "read": "switchCheckedHandleColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 31, + "name": "switchDisabledUncheckedHandleColor", + "notify": "themeChanged", + "read": "switchDisabledUncheckedHandleColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 32, + "name": "switchDisabledCheckedHandleColor", + "notify": "themeChanged", + "read": "switchDisabledCheckedHandleColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 33, + "name": "switchDisabledCheckedIconColor", + "notify": "themeChanged", + "read": "switchDisabledCheckedIconColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 34, + "name": "switchDisabledUncheckedIconColor", + "notify": "themeChanged", + "read": "switchDisabledUncheckedIconColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 35, + "name": "scrollBarColor", + "notify": "themeChanged", + "read": "scrollBarColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 36, + "name": "scrollBarHoveredColor", + "notify": "themeChanged", + "read": "scrollBarHoveredColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 37, + "name": "scrollBarPressedColor", + "notify": "themeChanged", + "read": "scrollBarPressedColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 38, + "name": "dialogColor", + "notify": "dialogColorChanged", + "read": "dialogColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 39, + "name": "backgroundDimColor", + "notify": "themeChanged", + "read": "backgroundDimColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 40, + "name": "listHighlightColor", + "notify": "themeChanged", + "read": "listHighlightColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 41, + "name": "tooltipColor", + "notify": "tooltipColorChanged", + "read": "tooltipColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 42, + "name": "toolBarColor", + "notify": "toolBarColorChanged", + "read": "toolBarColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 43, + "name": "toolTextColor", + "notify": "toolTextColorChanged", + "read": "toolTextColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 44, + "name": "spinBoxDisabledIconColor", + "notify": "themeChanged", + "read": "spinBoxDisabledIconColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 45, + "name": "sliderDisabledColor", + "notify": "themeChanged", + "read": "sliderDisabledColor", + "required": false, + "revision": 527, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 46, + "name": "textFieldFilledContainerColor", + "notify": "themeChanged", + "read": "textFieldFilledContainerColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 47, + "name": "touchTarget", + "read": "touchTarget", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 48, + "name": "buttonVerticalPadding", + "read": "buttonVerticalPadding", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 49, + "name": "buttonHeight", + "read": "buttonHeight", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 50, + "name": "delegateHeight", + "read": "delegateHeight", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 51, + "name": "dialogButtonBoxHeight", + "read": "dialogButtonBoxHeight", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 52, + "name": "dialogTitleFontPixelSize", + "read": "dialogTitleFontPixelSize", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 53, + "name": "dialogRoundedScale", + "read": "dialogRoundedScale", + "required": false, + "scriptable": true, + "stored": true, + "type": "RoundedScale", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 54, + "name": "frameVerticalPadding", + "read": "frameVerticalPadding", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 55, + "name": "menuItemHeight", + "read": "menuItemHeight", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 56, + "name": "menuItemVerticalPadding", + "read": "menuItemVerticalPadding", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 57, + "name": "switchIndicatorWidth", + "read": "switchIndicatorWidth", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 58, + "name": "switchIndicatorHeight", + "read": "switchIndicatorHeight", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 59, + "name": "switchNormalHandleHeight", + "read": "switchNormalHandleHeight", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 60, + "name": "switchCheckedHandleHeight", + "read": "switchCheckedHandleHeight", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 61, + "name": "switchLargestHandleHeight", + "read": "switchLargestHandleHeight", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 62, + "name": "switchDelegateVerticalPadding", + "read": "switchDelegateVerticalPadding", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 63, + "name": "textFieldHeight", + "read": "textFieldHeight", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 64, + "name": "textFieldHorizontalPadding", + "read": "textFieldHorizontalPadding", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 65, + "name": "textFieldVerticalPadding", + "read": "textFieldVerticalPadding", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 66, + "name": "tooltipHeight", + "read": "tooltipHeight", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + } + ], + "qualifiedClassName": "QQuickMaterialStyle", + "signals": [ + { + "access": "public", + "index": 0, + "name": "themeChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "primaryChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "accentChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "foregroundChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "backgroundChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "elevationChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "themeOrAccentChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "primaryHighlightedTextColorChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 8, + "name": "dialogColorChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 9, + "name": "tooltipColorChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 10, + "name": "toolBarColorChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 11, + "name": "toolTextColorChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 12, + "name": "roundedScaleChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 13, + "name": "containerStyleChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickAttachedPropertyPropagator" + } + ] + } + ], + "inputFile": "qquickmaterialstyle_p.h", + "outputRevision": 68 + } +] diff --git a/qt/6.8.1/msvc2022_64/metatypes/qt6quickcontrols2materialstyleimpl_metatypes.json b/qt/6.8.1/msvc2022_64/metatypes/qt6quickcontrols2materialstyleimpl_metatypes.json new file mode 100644 index 0000000000000000000000000000000000000000..0cbc620e2ef5cb0a79724b3368285e3b7bdaa113 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/metatypes/qt6quickcontrols2materialstyleimpl_metatypes.json @@ -0,0 +1,687 @@ +[ + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "FloatingPlaceholderText" + }, + { + "name": "QML.AddedInVersion", + "value": "1541" + } + ], + "className": "QQuickMaterialPlaceholderText", + "lineNumber": 28, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "filled", + "notify": "filledChanged", + "read": "isFilled", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setFilled" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "controlHasActiveFocus", + "notify": "controlHasActiveFocusChanged", + "read": "controlHasActiveFocus", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setControlHasActiveFocus" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "controlHasText", + "notify": "controlHasTextChanged", + "read": "controlHasText", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setControlHasText" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "largestHeight", + "notify": "largestHeightChanged", + "read": "largestHeight", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "verticalPadding", + "notify": "verticalPaddingChanged", + "read": "verticalPadding", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setVerticalPadding" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "controlImplicitBackgroundHeight", + "notify": "controlImplicitBackgroundHeightChanged", + "read": "controlImplicitBackgroundHeight", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setControlImplicitBackgroundHeight" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 6, + "name": "controlHeight", + "read": "controlHeight", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setControlHeight" + } + ], + "qualifiedClassName": "QQuickMaterialPlaceholderText", + "signals": [ + { + "access": "public", + "index": 0, + "name": "filledChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "largestHeightChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "controlHasActiveFocusChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "controlHasTextChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "controlImplicitBackgroundHeightChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "verticalPaddingChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "private", + "index": 6, + "name": "adjustTransformOrigin", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickPlaceholderText" + } + ] + } + ], + "inputFile": "qquickmaterialplaceholdertext_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "MaterialTextContainer" + }, + { + "name": "QML.AddedInVersion", + "value": "1541" + } + ], + "className": "QQuickMaterialTextContainer", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "PlaceHolderHAlignment", + "values": [ + "AlignLeft", + "AlignRight", + "AlignHCenter", + "AlignJustify" + ] + } + ], + "lineNumber": 24, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "filled", + "read": "isFilled", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setFilled" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "controlHasActiveFocus", + "notify": "controlHasActiveFocusChanged", + "read": "controlHasActiveFocus", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setControlHasActiveFocus" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "fillColor", + "read": "fillColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false, + "write": "setFillColor" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "outlineColor", + "read": "outlineColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false, + "write": "setOutlineColor" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "focusedOutlineColor", + "read": "focusedOutlineColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false, + "write": "setFocusedOutlineColor" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "focusAnimationProgress", + "read": "focusAnimationProgress", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setFocusAnimationProgress" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 6, + "name": "placeholderTextWidth", + "read": "placeholderTextWidth", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setPlaceholderTextWidth" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 7, + "name": "placeholderTextHAlign", + "read": "placeholderTextHAlign", + "required": false, + "scriptable": true, + "stored": true, + "type": "PlaceHolderHAlignment", + "user": false, + "write": "setPlaceholderTextHAlign" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 8, + "name": "controlHasText", + "notify": "controlHasTextChanged", + "read": "controlHasText", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setControlHasText" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 9, + "name": "placeholderHasText", + "notify": "placeholderHasTextChanged", + "read": "placeholderHasText", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setPlaceholderHasText" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 10, + "name": "horizontalPadding", + "notify": "horizontalPaddingChanged", + "read": "horizontalPadding", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setHorizontalPadding" + } + ], + "qualifiedClassName": "QQuickMaterialTextContainer", + "signals": [ + { + "access": "public", + "index": 0, + "name": "animateChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "controlHasActiveFocusChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "controlHasTextChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "placeholderHasTextChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "horizontalPaddingChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickPaintedItem" + } + ] + } + ], + "inputFile": "qquickmaterialtextcontainer_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "BusyIndicatorImpl" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickMaterialBusyIndicator", + "lineNumber": 24, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "color", + "read": "color", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false, + "write": "setColor" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "running", + "read": "isRunning", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setRunning" + } + ], + "qualifiedClassName": "QQuickMaterialBusyIndicator", + "superClasses": [ + { + "access": "public", + "name": "QQuickItem" + } + ] + } + ], + "inputFile": "qquickmaterialbusyindicator_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "ProgressBarImpl" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickMaterialProgressBar", + "lineNumber": 24, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "color", + "read": "color", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false, + "write": "setColor" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "progress", + "read": "progress", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setProgress" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "indeterminate", + "read": "isIndeterminate", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setIndeterminate" + } + ], + "qualifiedClassName": "QQuickMaterialProgressBar", + "superClasses": [ + { + "access": "public", + "name": "QQuickItem" + } + ] + } + ], + "inputFile": "qquickmaterialprogressbar_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "Ripple" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickMaterialRipple", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "Trigger", + "values": [ + "Press", + "Release" + ] + } + ], + "lineNumber": 24, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "color", + "read": "color", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false, + "write": "setColor" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "clipRadius", + "read": "clipRadius", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setClipRadius" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "pressed", + "read": "isPressed", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setPressed" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "active", + "read": "isActive", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setActive" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "anchor", + "read": "anchor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false, + "write": "setAnchor" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "trigger", + "read": "trigger", + "required": false, + "scriptable": true, + "stored": true, + "type": "Trigger", + "user": false, + "write": "setTrigger" + } + ], + "qualifiedClassName": "QQuickMaterialRipple", + "superClasses": [ + { + "access": "public", + "name": "QQuickItem" + } + ] + } + ], + "inputFile": "qquickmaterialripple_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQuickMaterialRippleBackgroundNode", + "lineNumber": 113, + "object": true, + "qualifiedClassName": "QQuickMaterialRippleBackgroundNode", + "superClasses": [ + { + "access": "public", + "name": "QQuickAnimatedNode" + } + ] + } + ], + "inputFile": "qquickmaterialripple.cpp", + "outputRevision": 68 + } +] diff --git a/qt/6.8.1/msvc2022_64/metatypes/qt6quickcontrols2universal_metatypes.json b/qt/6.8.1/msvc2022_64/metatypes/qt6quickcontrols2universal_metatypes.json new file mode 100644 index 0000000000000000000000000000000000000000..78e9f2c9a9c848cebd632cd9d1f7038c67420243 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/metatypes/qt6quickcontrols2universal_metatypes.json @@ -0,0 +1,529 @@ +[ + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "Universal" + }, + { + "name": "QML.Attached", + "value": "QQuickUniversalStyle" + }, + { + "name": "QML.Creatable", + "value": "false" + }, + { + "name": "QML.UncreatableReason", + "value": "" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickUniversalStyle", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "Theme", + "values": [ + "Light", + "Dark", + "System" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "Color", + "values": [ + "Lime", + "Green", + "Emerald", + "Teal", + "Cyan", + "Cobalt", + "Indigo", + "Violet", + "Pink", + "Magenta", + "Crimson", + "Red", + "Orange", + "Amber", + "Yellow", + "Brown", + "Olive", + "Steel", + "Mauve", + "Taupe" + ] + } + ], + "lineNumber": 27, + "methods": [ + { + "access": "public", + "arguments": [ + { + "name": "color", + "type": "Color" + } + ], + "index": 5, + "name": "color", + "returnType": "QColor" + } + ], + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "theme", + "notify": "themeChanged", + "read": "theme", + "required": false, + "reset": "resetTheme", + "scriptable": true, + "stored": true, + "type": "Theme", + "user": false, + "write": "setTheme" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "accent", + "notify": "accentChanged", + "read": "accent", + "required": false, + "reset": "resetAccent", + "scriptable": true, + "stored": true, + "type": "QVariant", + "user": false, + "write": "setAccent" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "foreground", + "notify": "foregroundChanged", + "read": "foreground", + "required": false, + "reset": "resetForeground", + "scriptable": true, + "stored": true, + "type": "QVariant", + "user": false, + "write": "setForeground" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "background", + "notify": "backgroundChanged", + "read": "background", + "required": false, + "reset": "resetBackground", + "scriptable": true, + "stored": true, + "type": "QVariant", + "user": false, + "write": "setBackground" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "altHighColor", + "notify": "paletteChanged", + "read": "altHighColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "altLowColor", + "notify": "paletteChanged", + "read": "altLowColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 6, + "name": "altMediumColor", + "notify": "paletteChanged", + "read": "altMediumColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 7, + "name": "altMediumHighColor", + "notify": "paletteChanged", + "read": "altMediumHighColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 8, + "name": "altMediumLowColor", + "notify": "paletteChanged", + "read": "altMediumLowColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 9, + "name": "baseHighColor", + "notify": "paletteChanged", + "read": "baseHighColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 10, + "name": "baseLowColor", + "notify": "paletteChanged", + "read": "baseLowColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 11, + "name": "baseMediumColor", + "notify": "paletteChanged", + "read": "baseMediumColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 12, + "name": "baseMediumHighColor", + "notify": "paletteChanged", + "read": "baseMediumHighColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 13, + "name": "baseMediumLowColor", + "notify": "paletteChanged", + "read": "baseMediumLowColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 14, + "name": "chromeAltLowColor", + "notify": "paletteChanged", + "read": "chromeAltLowColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 15, + "name": "chromeBlackHighColor", + "notify": "paletteChanged", + "read": "chromeBlackHighColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 16, + "name": "chromeBlackLowColor", + "notify": "paletteChanged", + "read": "chromeBlackLowColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 17, + "name": "chromeBlackMediumLowColor", + "notify": "paletteChanged", + "read": "chromeBlackMediumLowColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 18, + "name": "chromeBlackMediumColor", + "notify": "paletteChanged", + "read": "chromeBlackMediumColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 19, + "name": "chromeDisabledHighColor", + "notify": "paletteChanged", + "read": "chromeDisabledHighColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 20, + "name": "chromeDisabledLowColor", + "notify": "paletteChanged", + "read": "chromeDisabledLowColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 21, + "name": "chromeHighColor", + "notify": "paletteChanged", + "read": "chromeHighColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 22, + "name": "chromeLowColor", + "notify": "paletteChanged", + "read": "chromeLowColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 23, + "name": "chromeMediumColor", + "notify": "paletteChanged", + "read": "chromeMediumColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 24, + "name": "chromeMediumLowColor", + "notify": "paletteChanged", + "read": "chromeMediumLowColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 25, + "name": "chromeWhiteColor", + "notify": "paletteChanged", + "read": "chromeWhiteColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 26, + "name": "listLowColor", + "notify": "paletteChanged", + "read": "listLowColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 27, + "name": "listMediumColor", + "notify": "paletteChanged", + "read": "listMediumColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false + } + ], + "qualifiedClassName": "QQuickUniversalStyle", + "signals": [ + { + "access": "public", + "index": 0, + "name": "themeChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "accentChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "foregroundChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "backgroundChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "paletteChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickAttachedPropertyPropagator" + } + ] + } + ], + "inputFile": "qquickuniversalstyle_p.h", + "outputRevision": 68 + } +] diff --git a/qt/6.8.1/msvc2022_64/metatypes/qt6quickcontrols2universalstyleimpl_metatypes.json b/qt/6.8.1/msvc2022_64/metatypes/qt6quickcontrols2universalstyleimpl_metatypes.json new file mode 100644 index 0000000000000000000000000000000000000000..5257860756c81983a9c35f12a36c2f57c28e7364 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/metatypes/qt6quickcontrols2universalstyleimpl_metatypes.json @@ -0,0 +1,160 @@ +[ + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "BusyIndicatorImpl" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickUniversalBusyIndicator", + "lineNumber": 24, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "count", + "read": "count", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setCount" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "color", + "read": "color", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false, + "write": "setColor" + } + ], + "qualifiedClassName": "QQuickUniversalBusyIndicator", + "superClasses": [ + { + "access": "public", + "name": "QQuickItem" + } + ] + } + ], + "inputFile": "qquickuniversalbusyindicator_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "FocusRectangle" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickUniversalFocusRectangle", + "lineNumber": 23, + "object": true, + "qualifiedClassName": "QQuickUniversalFocusRectangle", + "superClasses": [ + { + "access": "public", + "name": "QQuickPaintedItem" + } + ] + } + ], + "inputFile": "qquickuniversalfocusrectangle_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "ProgressBarImpl" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickUniversalProgressBar", + "lineNumber": 24, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "color", + "read": "color", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false, + "write": "setColor" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "progress", + "read": "progress", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setProgress" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "indeterminate", + "read": "isIndeterminate", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setIndeterminate" + } + ], + "qualifiedClassName": "QQuickUniversalProgressBar", + "superClasses": [ + { + "access": "public", + "name": "QQuickItem" + } + ] + } + ], + "inputFile": "qquickuniversalprogressbar_p.h", + "outputRevision": 68 + } +] diff --git a/qt/6.8.1/msvc2022_64/metatypes/qt6quickcontrols2windowsstyleimpl_metatypes.json b/qt/6.8.1/msvc2022_64/metatypes/qt6quickcontrols2windowsstyleimpl_metatypes.json new file mode 100644 index 0000000000000000000000000000000000000000..0d4f101c7a37a4c875e6999bee1a287fdb733380 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/metatypes/qt6quickcontrols2windowsstyleimpl_metatypes.json @@ -0,0 +1,2 @@ +[ +] diff --git a/qt/6.8.1/msvc2022_64/metatypes/qt6quickcontrolstestutilsprivate_metatypes.json b/qt/6.8.1/msvc2022_64/metatypes/qt6quickcontrolstestutilsprivate_metatypes.json new file mode 100644 index 0000000000000000000000000000000000000000..0131ca00a0de8f260014d07817adaef164d16042 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/metatypes/qt6quickcontrolstestutilsprivate_metatypes.json @@ -0,0 +1,81 @@ +[ + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "auto" + }, + { + "name": "QML.Singleton", + "value": "true" + } + ], + "className": "ComponentCreator", + "lineNumber": 59, + "methods": [ + { + "access": "public", + "arguments": [ + { + "name": "data", + "type": "QByteArray" + } + ], + "index": 0, + "name": "createComponent", + "returnType": "QQmlComponent*" + } + ], + "object": true, + "qualifiedClassName": "QQuickControlsTestUtils::ComponentCreator", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "auto" + }, + { + "name": "QML.Singleton", + "value": "true" + } + ], + "className": "StyleInfo", + "lineNumber": 70, + "object": true, + "properties": [ + { + "constant": true, + "designable": true, + "final": true, + "index": 0, + "name": "styleName", + "read": "styleName", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + } + ], + "qualifiedClassName": "QQuickControlsTestUtils::StyleInfo", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "controlstestutils_p.h", + "outputRevision": 68 + } +] diff --git a/qt/6.8.1/msvc2022_64/metatypes/qt6quickdialogs2_metatypes.json b/qt/6.8.1/msvc2022_64/metatypes/qt6quickdialogs2_metatypes.json new file mode 100644 index 0000000000000000000000000000000000000000..9210c6ebb16460796f61d2b86ad0efdf88e7a26e --- /dev/null +++ b/qt/6.8.1/msvc2022_64/metatypes/qt6quickdialogs2_metatypes.json @@ -0,0 +1,1038 @@ +[ + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "ColorDialog" + }, + { + "name": "QML.AddedInVersion", + "value": "1540" + } + ], + "className": "QQuickColorDialog", + "lineNumber": 24, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "selectedColor", + "notify": "selectedColorChanged", + "read": "selectedColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false, + "write": "setSelectedColor" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "options", + "notify": "optionsChanged", + "read": "options", + "required": false, + "reset": "resetOptions", + "scriptable": true, + "stored": true, + "type": "QColorDialogOptions::ColorDialogOptions", + "user": false, + "write": "setOptions" + } + ], + "qualifiedClassName": "QQuickColorDialog", + "signals": [ + { + "access": "public", + "index": 0, + "name": "selectedColorChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "optionsChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickAbstractDialog" + } + ] + } + ], + "inputFile": "qquickcolordialog_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "DefaultProperty", + "value": "data" + }, + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.AddedInVersion", + "value": "1538" + } + ], + "className": "QQuickAbstractDialog", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "StandardCode", + "values": [ + "Rejected", + "Accepted" + ] + } + ], + "interfaces": [ + [ + { + "className": "QQmlParserStatus", + "id": "\"org.qt-project.Qt.QQmlParserStatus\"" + } + ] + ], + "lineNumber": 35, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "data", + "read": "data", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlListProperty", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "parentWindow", + "notify": "parentWindowChanged", + "read": "parentWindow", + "required": false, + "reset": "resetParentWindow", + "scriptable": true, + "stored": true, + "type": "QWindow*", + "user": false, + "write": "setParentWindow" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "title", + "notify": "titleChanged", + "read": "title", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setTitle" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "flags", + "notify": "flagsChanged", + "read": "flags", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::WindowFlags", + "user": false, + "write": "setFlags" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "modality", + "notify": "modalityChanged", + "read": "modality", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::WindowModality", + "user": false, + "write": "setModality" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "visible", + "notify": "visibleChanged", + "read": "isVisible", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setVisible" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 6, + "name": "result", + "notify": "resultChanged", + "read": "result", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setResult" + } + ], + "qualifiedClassName": "QQuickAbstractDialog", + "signals": [ + { + "access": "public", + "index": 0, + "name": "accepted", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "rejected", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "parentWindowChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "titleChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "flagsChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "modalityChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "visibleChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "resultChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "index": 8, + "name": "open", + "returnType": "void" + }, + { + "access": "public", + "index": 9, + "name": "close", + "returnType": "void" + }, + { + "access": "public", + "index": 10, + "name": "accept", + "returnType": "void" + }, + { + "access": "public", + "index": 11, + "name": "reject", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "result", + "type": "int" + } + ], + "index": 12, + "name": "done", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QQmlParserStatus" + } + ] + } + ], + "inputFile": "qquickabstractdialog_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "FileDialog" + }, + { + "name": "QML.AddedInVersion", + "value": "1538" + } + ], + "className": "QQuickFileDialog", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "FileMode", + "values": [ + "OpenFile", + "OpenFiles", + "SaveFile" + ] + } + ], + "lineNumber": 27, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "fileMode", + "notify": "fileModeChanged", + "read": "fileMode", + "required": false, + "scriptable": true, + "stored": true, + "type": "FileMode", + "user": false, + "write": "setFileMode" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "selectedFile", + "notify": "selectedFileChanged", + "read": "selectedFile", + "required": false, + "scriptable": true, + "stored": true, + "type": "QUrl", + "user": false, + "write": "setSelectedFile" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "selectedFiles", + "notify": "selectedFilesChanged", + "read": "selectedFiles", + "required": false, + "scriptable": true, + "stored": true, + "type": "QList", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "currentFile", + "notify": "currentFileChanged", + "read": "currentFile", + "required": false, + "scriptable": true, + "stored": true, + "type": "QUrl", + "user": false, + "write": "setCurrentFile" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "currentFiles", + "notify": "currentFilesChanged", + "read": "currentFiles", + "required": false, + "scriptable": true, + "stored": true, + "type": "QList", + "user": false, + "write": "setCurrentFiles" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "currentFolder", + "notify": "currentFolderChanged", + "read": "currentFolder", + "required": false, + "scriptable": true, + "stored": true, + "type": "QUrl", + "user": false, + "write": "setCurrentFolder" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 6, + "name": "options", + "notify": "optionsChanged", + "read": "options", + "required": false, + "reset": "resetOptions", + "scriptable": true, + "stored": true, + "type": "QFileDialogOptions::FileDialogOptions", + "user": false, + "write": "setOptions" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 7, + "name": "nameFilters", + "notify": "nameFiltersChanged", + "read": "nameFilters", + "required": false, + "reset": "resetNameFilters", + "scriptable": true, + "stored": true, + "type": "QStringList", + "user": false, + "write": "setNameFilters" + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 8, + "name": "selectedNameFilter", + "read": "selectedNameFilter", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickFileNameFilter*", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 9, + "name": "defaultSuffix", + "notify": "defaultSuffixChanged", + "read": "defaultSuffix", + "required": false, + "reset": "resetDefaultSuffix", + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setDefaultSuffix" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 10, + "name": "acceptLabel", + "notify": "acceptLabelChanged", + "read": "acceptLabel", + "required": false, + "reset": "resetAcceptLabel", + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setAcceptLabel" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 11, + "name": "rejectLabel", + "notify": "rejectLabelChanged", + "read": "rejectLabel", + "required": false, + "reset": "resetRejectLabel", + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setRejectLabel" + } + ], + "qualifiedClassName": "QQuickFileDialog", + "signals": [ + { + "access": "public", + "index": 0, + "name": "fileModeChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "selectedFileChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "selectedFilesChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "currentFileChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "currentFilesChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "currentFolderChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "optionsChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "nameFiltersChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 8, + "name": "defaultSuffixChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 9, + "name": "acceptLabelChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 10, + "name": "rejectLabelChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickAbstractDialog" + } + ] + } + ], + "inputFile": "qquickfiledialog_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "FolderDialog" + }, + { + "name": "QML.AddedInVersion", + "value": "1539" + } + ], + "className": "QQuickFolderDialog", + "lineNumber": 27, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "currentFolder", + "notify": "currentFolderChanged", + "read": "currentFolder", + "required": false, + "scriptable": true, + "stored": true, + "type": "QUrl", + "user": false, + "write": "setCurrentFolder" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "selectedFolder", + "notify": "selectedFolderChanged", + "read": "selectedFolder", + "required": false, + "scriptable": true, + "stored": true, + "type": "QUrl", + "user": false, + "write": "setSelectedFolder" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "options", + "notify": "optionsChanged", + "read": "options", + "required": false, + "reset": "resetOptions", + "scriptable": true, + "stored": true, + "type": "QFileDialogOptions::FileDialogOptions", + "user": false, + "write": "setOptions" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "acceptLabel", + "notify": "acceptLabelChanged", + "read": "acceptLabel", + "required": false, + "reset": "resetAcceptLabel", + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setAcceptLabel" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "rejectLabel", + "notify": "rejectLabelChanged", + "read": "rejectLabel", + "required": false, + "reset": "resetRejectLabel", + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setRejectLabel" + } + ], + "qualifiedClassName": "QQuickFolderDialog", + "signals": [ + { + "access": "public", + "index": 0, + "name": "currentFolderChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "selectedFolderChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "optionsChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "acceptLabelChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "rejectLabelChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickAbstractDialog" + } + ] + } + ], + "inputFile": "qquickfolderdialog_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "FontDialog" + }, + { + "name": "QML.AddedInVersion", + "value": "1538" + } + ], + "className": "QQuickFontDialog", + "lineNumber": 24, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "selectedFont", + "notify": "selectedFontChanged", + "read": "selectedFont", + "required": false, + "scriptable": true, + "stored": true, + "type": "QFont", + "user": false, + "write": "setSelectedFont" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "currentFont", + "notify": "currentFontChanged", + "read": "currentFont", + "required": false, + "scriptable": true, + "stored": true, + "type": "QFont", + "user": false, + "write": "setCurrentFont" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "options", + "notify": "optionsChanged", + "read": "options", + "required": false, + "reset": "resetOptions", + "scriptable": true, + "stored": true, + "type": "QFontDialogOptions::FontDialogOptions", + "user": false, + "write": "setOptions" + } + ], + "qualifiedClassName": "QQuickFontDialog", + "signals": [ + { + "access": "public", + "index": 0, + "name": "selectedFontChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "currentFontChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "optionsChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickAbstractDialog" + } + ] + } + ], + "inputFile": "qquickfontdialog_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Extended", + "value": "QPlatformDialogHelper" + }, + { + "name": "QML.ExtensionIsNamespace", + "value": "true" + }, + { + "name": "QML.Element", + "value": "MessageDialog" + }, + { + "name": "QML.AddedInVersion", + "value": "1539" + } + ], + "className": "QQuickMessageDialog", + "lineNumber": 22, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "text", + "notify": "textChanged", + "read": "text", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setText" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "informativeText", + "notify": "informativeTextChanged", + "read": "informativeText", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setInformativeText" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "detailedText", + "notify": "detailedTextChanged", + "read": "detailedText", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setDetailedText" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "buttons", + "notify": "buttonsChanged", + "read": "buttons", + "required": false, + "scriptable": true, + "stored": true, + "type": "QPlatformDialogHelper::StandardButtons", + "user": false, + "write": "setButtons" + } + ], + "qualifiedClassName": "QQuickMessageDialog", + "signals": [ + { + "access": "public", + "index": 0, + "name": "textChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "informativeTextChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "detailedTextChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "buttonsChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "button", + "type": "QPlatformDialogHelper::StandardButton" + }, + { + "name": "role", + "type": "QPlatformDialogHelper::ButtonRole" + } + ], + "index": 4, + "name": "buttonClicked", + "returnType": "void" + } + ], + "slots": [ + { + "access": "private", + "arguments": [ + { + "name": "button", + "type": "QPlatformDialogHelper::StandardButton" + }, + { + "name": "role", + "type": "QPlatformDialogHelper::ButtonRole" + } + ], + "index": 5, + "name": "handleClick", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickAbstractDialog" + } + ] + } + ], + "inputFile": "qquickmessagedialog_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.Foreign", + "value": "QQuickFileNameFilter" + }, + { + "name": "QML.AddedInVersion", + "value": "1538" + } + ], + "className": "QQuickFileNameFilterQuickDialogs2Foreign", + "gadget": true, + "lineNumber": 24, + "qualifiedClassName": "QQuickFileNameFilterQuickDialogs2Foreign" + } + ], + "inputFile": "qtquickdialogs2foreign_p.h", + "outputRevision": 68 + } +] diff --git a/qt/6.8.1/msvc2022_64/metatypes/qt6quickdialogs2quickimpl_metatypes.json b/qt/6.8.1/msvc2022_64/metatypes/qt6quickdialogs2quickimpl_metatypes.json new file mode 100644 index 0000000000000000000000000000000000000000..4b2158dcd01b5f83280e9fc437e478edd8b75ce2 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/metatypes/qt6quickdialogs2quickimpl_metatypes.json @@ -0,0 +1,2554 @@ +[ + { + "classes": [ + { + "classInfos": [ + { + "name": "DeferredPropertyNames", + "value": "background,contentItem,handle" + }, + { + "name": "QML.Element", + "value": "AbstractColorPicker" + }, + { + "name": "QML.AddedInVersion", + "value": "1540" + }, + { + "name": "QML.Creatable", + "value": "false" + }, + { + "name": "QML.UncreatableReason", + "value": "AbstractColorPicker is abstract." + } + ], + "className": "QQuickAbstractColorPicker", + "lineNumber": 27, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "color", + "notify": "colorChanged", + "read": "color", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false, + "write": "setColor" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "hue", + "notify": "colorChanged", + "read": "hue", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setHue" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "saturation", + "notify": "colorChanged", + "read": "saturation", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setSaturation" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "value", + "notify": "colorChanged", + "read": "value", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setValue" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "lightness", + "notify": "colorChanged", + "read": "lightness", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setLightness" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "alpha", + "notify": "colorChanged", + "read": "alpha", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setAlpha" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 6, + "name": "pressed", + "notify": "pressedChanged", + "read": "isPressed", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setPressed" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 7, + "name": "handle", + "notify": "handleChanged", + "read": "handle", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false, + "write": "setHandle" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 8, + "name": "implicitHandleWidth", + "notify": "implicitHandleWidthChanged", + "read": "implicitHandleWidth", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 9, + "name": "implicitHandleHeight", + "notify": "implicitHandleHeightChanged", + "read": "implicitHandleHeight", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + } + ], + "qualifiedClassName": "QQuickAbstractColorPicker", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "color", + "type": "QColor" + } + ], + "index": 0, + "name": "colorChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "pressedChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "handleChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "implicitHandleWidthChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "implicitHandleHeightChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "color", + "type": "QColor" + } + ], + "index": 5, + "name": "colorPicked", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickControl" + } + ] + } + ], + "inputFile": "qquickabstractcolorpicker_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "ColorDialogImpl" + }, + { + "name": "QML.Attached", + "value": "QQuickColorDialogImplAttached" + }, + { + "name": "QML.AddedInVersion", + "value": "1540" + } + ], + "className": "QQuickColorDialogImpl", + "lineNumber": 33, + "methods": [ + { + "access": "public", + "index": 2, + "name": "invokeEyeDropper", + "returnType": "void" + } + ], + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "color", + "notify": "colorChanged", + "read": "color", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false, + "write": "setColor" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "hue", + "notify": "colorChanged", + "read": "hue", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setHue" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "saturation", + "notify": "colorChanged", + "read": "saturation", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setSaturation" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "value", + "notify": "colorChanged", + "read": "value", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setValue" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "lightness", + "notify": "colorChanged", + "read": "lightness", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setLightness" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "alpha", + "notify": "colorChanged", + "read": "alpha", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setAlpha" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 6, + "name": "red", + "notify": "colorChanged", + "read": "red", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setRed" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 7, + "name": "green", + "notify": "colorChanged", + "read": "green", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setGreen" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 8, + "name": "blue", + "notify": "colorChanged", + "read": "blue", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setBlue" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 9, + "name": "isHsl", + "notify": "specChanged", + "read": "isHsl", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setHsl" + } + ], + "qualifiedClassName": "QQuickColorDialogImpl", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "color", + "type": "QColor" + } + ], + "index": 0, + "name": "colorChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "specChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickDialog" + } + ] + }, + { + "className": "QQuickColorDialogImplAttached", + "lineNumber": 99, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "buttonBox", + "notify": "buttonBoxChanged", + "read": "buttonBox", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickDialogButtonBox*", + "user": false, + "write": "setButtonBox" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "eyeDropperButton", + "notify": "eyeDropperButtonChanged", + "read": "eyeDropperButton", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickAbstractButton*", + "user": false, + "write": "setEyeDropperButton" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "colorPicker", + "notify": "colorPickerChanged", + "read": "colorPicker", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickAbstractColorPicker*", + "user": false, + "write": "setColorPicker" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "colorInputs", + "notify": "colorInputsChanged", + "read": "colorInputs", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickColorInputs*", + "user": false, + "write": "setColorInputs" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "alphaSlider", + "notify": "alphaSliderChanged", + "read": "alphaSlider", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickSlider*", + "user": false, + "write": "setAlphaSlider" + } + ], + "qualifiedClassName": "QQuickColorDialogImplAttached", + "signals": [ + { + "access": "public", + "index": 0, + "name": "buttonBoxChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "eyeDropperButtonChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "colorPickerChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "colorInputsChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "alphaSliderChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qquickcolordialogimpl_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "ColorInputsImpl" + } + ], + "className": "QQuickColorInputs", + "lineNumber": 30, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "color", + "notify": "colorChanged", + "read": "color", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false, + "write": "setColor" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "red", + "notify": "colorChanged", + "read": "red", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "green", + "notify": "colorChanged", + "read": "green", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "blue", + "notify": "colorChanged", + "read": "blue", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "hue", + "notify": "colorChanged", + "read": "hue", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "hslSaturation", + "notify": "colorChanged", + "read": "hslSaturation", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "hsvSaturation", + "notify": "colorChanged", + "read": "hsvSaturation", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 7, + "name": "value", + "notify": "colorChanged", + "read": "value", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 8, + "name": "lightness", + "notify": "colorChanged", + "read": "lightness", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 9, + "name": "alpha", + "notify": "colorChanged", + "read": "alpha", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 10, + "name": "showAlpha", + "notify": "showAlphaChanged", + "read": "showAlpha", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setShowAlpha" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 11, + "name": "hexInput", + "notify": "hexInputChanged", + "read": "hexInput", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickTextInput*", + "user": false, + "write": "setHexInput" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 12, + "name": "redInput", + "notify": "redInputChanged", + "read": "redInput", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickTextInput*", + "user": false, + "write": "setRedInput" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 13, + "name": "greenInput", + "notify": "greenInputChanged", + "read": "greenInput", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickTextInput*", + "user": false, + "write": "setGreenInput" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 14, + "name": "blueInput", + "notify": "blueInputChanged", + "read": "blueInput", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickTextInput*", + "user": false, + "write": "setBlueInput" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 15, + "name": "hsvHueInput", + "notify": "hsvHueInputChanged", + "read": "hsvHueInput", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickTextInput*", + "user": false, + "write": "setHsvHueInput" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 16, + "name": "hslHueInput", + "notify": "hslHueInputChanged", + "read": "hslHueInput", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickTextInput*", + "user": false, + "write": "setHslHueInput" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 17, + "name": "hsvSaturationInput", + "notify": "hsvSaturationInputChanged", + "read": "hsvSaturationInput", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickTextInput*", + "user": false, + "write": "setHsvSaturationInput" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 18, + "name": "hslSaturationInput", + "notify": "hslSaturationInputChanged", + "read": "hslSaturationInput", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickTextInput*", + "user": false, + "write": "setHslSaturationInput" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 19, + "name": "valueInput", + "notify": "valueInputChanged", + "read": "valueInput", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickTextInput*", + "user": false, + "write": "setValueInput" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 20, + "name": "lightnessInput", + "notify": "lightnessInputChanged", + "read": "lightnessInput", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickTextInput*", + "user": false, + "write": "setLightnessInput" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 21, + "name": "rgbAlphaInput", + "notify": "rgbAlphaInputChanged", + "read": "rgbAlphaInput", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickTextInput*", + "user": false, + "write": "setRgbAlphaInput" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 22, + "name": "hsvAlphaInput", + "notify": "hsvAlphaInputChanged", + "read": "hsvAlphaInput", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickTextInput*", + "user": false, + "write": "setHsvAlphaInput" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 23, + "name": "hslAlphaInput", + "notify": "hslAlphaInputChanged", + "read": "hslAlphaInput", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickTextInput*", + "user": false, + "write": "setHslAlphaInput" + } + ], + "qualifiedClassName": "QQuickColorInputs", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "c", + "type": "QColor" + } + ], + "index": 0, + "name": "colorChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "c", + "type": "QColor" + } + ], + "index": 1, + "name": "colorModified", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "hslChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "bool" + } + ], + "index": 3, + "name": "showAlphaChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "hexInputChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "redInputChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "greenInputChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "blueInputChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 8, + "name": "hsvHueInputChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 9, + "name": "hslHueInputChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 10, + "name": "hsvSaturationInputChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 11, + "name": "hslSaturationInputChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 12, + "name": "valueInputChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 13, + "name": "lightnessInputChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 14, + "name": "rgbAlphaInputChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 15, + "name": "hsvAlphaInputChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 16, + "name": "hslAlphaInputChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickItem" + } + ] + } + ], + "inputFile": "qquickcolorinputs_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQuickPlatformColorDialog", + "lineNumber": 27, + "object": true, + "qualifiedClassName": "QQuickPlatformColorDialog", + "superClasses": [ + { + "access": "public", + "name": "QPlatformColorDialogHelper" + } + ] + } + ], + "inputFile": "qquickplatformcolordialog_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "SaturationLightnessPickerImpl" + } + ], + "className": "QQuickSaturationLightnessPicker", + "lineNumber": 25, + "object": true, + "qualifiedClassName": "QQuickSaturationLightnessPicker", + "superClasses": [ + { + "access": "public", + "name": "QQuickAbstractColorPicker" + } + ] + } + ], + "inputFile": "qquicksaturationlightnesspicker_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "FileDialogDelegate" + }, + { + "name": "QML.AddedInVersion", + "value": "1538" + } + ], + "className": "QQuickFileDialogDelegate", + "lineNumber": 27, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "dialog", + "notify": "dialogChanged", + "read": "dialog", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickDialog*", + "user": false, + "write": "setDialog" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "file", + "notify": "fileChanged", + "read": "file", + "required": false, + "scriptable": true, + "stored": true, + "type": "QUrl", + "user": false, + "write": "setFile" + } + ], + "qualifiedClassName": "QQuickFileDialogDelegate", + "signals": [ + { + "access": "public", + "index": 0, + "name": "dialogChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "fileChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickItemDelegate" + } + ] + } + ], + "inputFile": "qquickfiledialogdelegate_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "FileDialogImpl" + }, + { + "name": "QML.Attached", + "value": "QQuickFileDialogImplAttached" + }, + { + "name": "QML.AddedInVersion", + "value": "1538" + } + ], + "className": "QQuickFileDialogImpl", + "lineNumber": 36, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "currentFolder", + "notify": "currentFolderChanged", + "read": "currentFolder", + "required": false, + "scriptable": true, + "stored": true, + "type": "QUrl", + "user": false, + "write": "setCurrentFolder" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "selectedFile", + "notify": "selectedFileChanged", + "read": "selectedFile", + "required": false, + "scriptable": true, + "stored": true, + "type": "QUrl", + "user": false, + "write": "setSelectedFile" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "nameFilters", + "notify": "nameFiltersChanged", + "read": "nameFilters", + "required": false, + "scriptable": true, + "stored": true, + "type": "QStringList", + "user": false + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 3, + "name": "selectedNameFilter", + "read": "selectedNameFilter", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickFileNameFilter*", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "fileName", + "notify": "selectedFileChanged", + "read": "fileName", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setFileName" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "currentFolderName", + "notify": "selectedFileChanged", + "read": "currentFolderName", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + } + ], + "qualifiedClassName": "QQuickFileDialogImpl", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "folderUrl", + "type": "QUrl" + } + ], + "index": 0, + "name": "currentFolderChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "selectedFileUrl", + "type": "QUrl" + } + ], + "index": 1, + "name": "selectedFileChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "nameFiltersChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "fileUrl", + "type": "QUrl" + } + ], + "index": 3, + "name": "fileSelected", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "filter", + "type": "QString" + } + ], + "index": 4, + "name": "filterSelected", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "filter", + "type": "QString" + } + ], + "index": 5, + "name": "selectNameFilter", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickDialog" + } + ] + }, + { + "className": "QQuickFileDialogImplAttached", + "lineNumber": 104, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "buttonBox", + "notify": "buttonBoxChanged", + "read": "buttonBox", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickDialogButtonBox*", + "user": false, + "write": "setButtonBox" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "nameFiltersComboBox", + "notify": "nameFiltersComboBoxChanged", + "read": "nameFiltersComboBox", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickComboBox*", + "user": false, + "write": "setNameFiltersComboBox" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "fileDialogListView", + "notify": "fileDialogListViewChanged", + "read": "fileDialogListView", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickListView*", + "user": false, + "write": "setFileDialogListView" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "breadcrumbBar", + "notify": "breadcrumbBarChanged", + "read": "breadcrumbBar", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickFolderBreadcrumbBar*", + "user": false, + "write": "setBreadcrumbBar" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "fileNameLabel", + "notify": "fileNameLabelChanged", + "read": "fileNameLabel", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickLabel*", + "user": false, + "write": "setFileNameLabel" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "fileNameTextField", + "notify": "fileNameTextFieldChanged", + "read": "fileNameTextField", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickTextField*", + "user": false, + "write": "setFileNameTextField" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 6, + "name": "overwriteConfirmationDialog", + "notify": "overwriteConfirmationDialogChanged", + "read": "overwriteConfirmationDialog", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickDialog*", + "user": false, + "write": "setOverwriteConfirmationDialog" + } + ], + "qualifiedClassName": "QQuickFileDialogImplAttached", + "signals": [ + { + "access": "public", + "index": 0, + "name": "buttonBoxChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "nameFiltersComboBoxChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "fileDialogListViewChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "breadcrumbBarChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "fileNameLabelChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "fileNameTextFieldChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "overwriteConfirmationDialogChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qquickfiledialogimpl_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "FolderBreadcrumbBar" + }, + { + "name": "QML.AddedInVersion", + "value": "1538" + } + ], + "className": "QQuickFolderBreadcrumbBar", + "lineNumber": 28, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "dialog", + "notify": "dialogChanged", + "read": "dialog", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickDialog*", + "user": false, + "write": "setDialog" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "buttonDelegate", + "notify": "buttonDelegateChanged", + "read": "buttonDelegate", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlComponent*", + "user": false, + "write": "setButtonDelegate" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "separatorDelegate", + "notify": "separatorDelegateChanged", + "read": "separatorDelegate", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlComponent*", + "user": false, + "write": "setSeparatorDelegate" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "upButton", + "notify": "upButtonChanged", + "read": "upButton", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickAbstractButton*", + "user": false, + "write": "setUpButton" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "textField", + "notify": "textFieldChanged", + "read": "textField", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickTextField*", + "user": false, + "write": "setTextField" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "upButtonSpacing", + "notify": "upButtonSpacingChanged", + "read": "upButtonSpacing", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setUpButtonSpacing" + } + ], + "qualifiedClassName": "QQuickFolderBreadcrumbBar", + "signals": [ + { + "access": "public", + "index": 0, + "name": "dialogChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "buttonDelegateChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "separatorDelegateChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "upButtonChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "upButtonSpacingChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "textFieldChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickContainer" + } + ] + } + ], + "inputFile": "qquickfolderbreadcrumbbar_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "FolderDialogImpl" + }, + { + "name": "QML.Attached", + "value": "QQuickFolderDialogImplAttached" + }, + { + "name": "QML.AddedInVersion", + "value": "1539" + } + ], + "className": "QQuickFolderDialogImpl", + "lineNumber": 32, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "currentFolder", + "notify": "currentFolderChanged", + "read": "currentFolder", + "required": false, + "scriptable": true, + "stored": true, + "type": "QUrl", + "user": false, + "write": "setCurrentFolder" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "selectedFolder", + "notify": "selectedFolderChanged", + "read": "selectedFolder", + "required": false, + "scriptable": true, + "stored": true, + "type": "QUrl", + "user": false, + "write": "setSelectedFolder" + } + ], + "qualifiedClassName": "QQuickFolderDialogImpl", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "folderUrl", + "type": "QUrl" + } + ], + "index": 0, + "name": "currentFolderChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "folderUrl", + "type": "QUrl" + } + ], + "index": 1, + "name": "selectedFolderChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "nameFiltersChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickDialog" + } + ] + }, + { + "className": "QQuickFolderDialogImplAttached", + "lineNumber": 71, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "folderDialogListView", + "notify": "folderDialogListViewChanged", + "read": "folderDialogListView", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickListView*", + "user": false, + "write": "setFolderDialogListView" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "breadcrumbBar", + "notify": "breadcrumbBarChanged", + "read": "breadcrumbBar", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickFolderBreadcrumbBar*", + "user": false, + "write": "setBreadcrumbBar" + } + ], + "qualifiedClassName": "QQuickFolderDialogImplAttached", + "signals": [ + { + "access": "public", + "index": 0, + "name": "folderDialogListViewChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "breadcrumbBarChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qquickfolderdialogimpl_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "FontDialogImpl" + }, + { + "name": "QML.Attached", + "value": "QQuickFontDialogImplAttached" + }, + { + "name": "QML.AddedInVersion", + "value": "1538" + } + ], + "className": "QQuickFontDialogImpl", + "lineNumber": 35, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "currentFont", + "notify": "currentFontChanged", + "read": "currentFont", + "required": false, + "scriptable": true, + "stored": true, + "type": "QFont", + "user": false, + "write": "setCurrentFont" + } + ], + "qualifiedClassName": "QQuickFontDialogImpl", + "signals": [ + { + "access": "public", + "index": 0, + "name": "optionsChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "font", + "type": "QFont" + } + ], + "index": 1, + "name": "currentFontChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickDialog" + } + ] + }, + { + "className": "QQuickFontDialogImplAttached", + "lineNumber": 68, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "familyListView", + "notify": "familyListViewChanged", + "read": "familyListView", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickListView*", + "user": false, + "write": "setFamilyListView" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "styleListView", + "notify": "styleListViewChanged", + "read": "styleListView", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickListView*", + "user": false, + "write": "setStyleListView" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "sizeListView", + "notify": "sizeListViewChanged", + "read": "sizeListView", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickListView*", + "user": false, + "write": "setSizeListView" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "sampleEdit", + "notify": "sampleEditChanged", + "read": "sampleEdit", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickTextEdit*", + "user": false, + "write": "setSampleEdit" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "buttonBox", + "notify": "buttonBoxChanged", + "read": "buttonBox", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickDialogButtonBox*", + "user": false, + "write": "setButtonBox" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "writingSystemComboBox", + "notify": "writingSystemComboBoxChanged", + "read": "writingSystemComboBox", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickComboBox*", + "user": false, + "write": "setWritingSystemComboBox" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "underlineCheckBox", + "notify": "underlineCheckBoxChanged", + "read": "underlineCheckBox", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickCheckBox*", + "user": false, + "write": "setUnderlineCheckBox" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 7, + "name": "strikeoutCheckBox", + "notify": "strikeoutCheckBoxChanged", + "read": "strikeoutCheckBox", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickCheckBox*", + "user": false, + "write": "setStrikeoutCheckBox" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 8, + "name": "familyEdit", + "notify": "familyEditChanged", + "read": "familyEdit", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickTextField*", + "user": false, + "write": "setFamilyEdit" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 9, + "name": "styleEdit", + "notify": "styleEditChanged", + "read": "styleEdit", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickTextField*", + "user": false, + "write": "setStyleEdit" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 10, + "name": "sizeEdit", + "notify": "sizeEditChanged", + "read": "sizeEdit", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickTextField*", + "user": false, + "write": "setSizeEdit" + } + ], + "qualifiedClassName": "QQuickFontDialogImplAttached", + "signals": [ + { + "access": "public", + "index": 0, + "name": "buttonBoxChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "familyListViewChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "styleListViewChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "sizeListViewChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "sampleEditChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "writingSystemComboBoxChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "underlineCheckBoxChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "strikeoutCheckBoxChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 8, + "name": "familyEditChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 9, + "name": "styleEditChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 10, + "name": "sizeEditChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qquickfontdialogimpl_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "MessageDialogImpl" + }, + { + "name": "QML.Attached", + "value": "QQuickMessageDialogImplAttached" + }, + { + "name": "QML.AddedInVersion", + "value": "1539" + } + ], + "className": "QQuickMessageDialogImpl", + "lineNumber": 32, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "text", + "notify": "optionsChanged", + "read": "text", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "informativeText", + "notify": "optionsChanged", + "read": "informativeText", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "detailedText", + "notify": "optionsChanged", + "read": "detailedText", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "showDetailedText", + "notify": "showDetailedTextChanged", + "read": "showDetailedText", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + } + ], + "qualifiedClassName": "QQuickMessageDialogImpl", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "button", + "type": "QPlatformDialogHelper::StandardButton" + }, + { + "name": "role", + "type": "QPlatformDialogHelper::ButtonRole" + } + ], + "index": 0, + "name": "buttonClicked", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "showDetailedTextChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "optionsChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "index": 3, + "name": "toggleShowDetailedText", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickDialog" + } + ] + }, + { + "className": "QQuickMessageDialogImplAttached", + "lineNumber": 69, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "buttonBox", + "notify": "buttonBoxChanged", + "read": "buttonBox", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickDialogButtonBox*", + "user": false, + "write": "setButtonBox" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "detailedTextButton", + "notify": "detailedTextButtonChanged", + "read": "detailedTextButton", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickButton*", + "user": false, + "write": "setDetailedTextButton" + } + ], + "qualifiedClassName": "QQuickMessageDialogImplAttached", + "signals": [ + { + "access": "public", + "index": 0, + "name": "buttonBoxChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "detailedTextButtonChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qquickmessagedialogimpl_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQuickPlatformFileDialog", + "lineNumber": 27, + "object": true, + "qualifiedClassName": "QQuickPlatformFileDialog", + "superClasses": [ + { + "access": "public", + "name": "QPlatformFileDialogHelper" + } + ] + } + ], + "inputFile": "qquickplatformfiledialog_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQuickPlatformFolderDialog", + "lineNumber": 28, + "object": true, + "qualifiedClassName": "QQuickPlatformFolderDialog", + "superClasses": [ + { + "access": "public", + "name": "QPlatformFileDialogHelper" + } + ] + } + ], + "inputFile": "qquickplatformfolderdialog_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQuickPlatformFontDialog", + "lineNumber": 27, + "object": true, + "qualifiedClassName": "QQuickPlatformFontDialog", + "superClasses": [ + { + "access": "public", + "name": "QPlatformFontDialogHelper" + } + ] + } + ], + "inputFile": "qquickplatformfontdialog_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQuickPlatformMessageDialog", + "lineNumber": 25, + "object": true, + "qualifiedClassName": "QQuickPlatformMessageDialog", + "superClasses": [ + { + "access": "public", + "name": "QPlatformMessageDialogHelper" + } + ] + } + ], + "inputFile": "qquickplatformmessagedialog_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.Foreign", + "value": "QQuickFileNameFilter" + }, + { + "name": "QML.AddedInVersion", + "value": "1538" + } + ], + "className": "QQuickFileNameFilterQuickDialogs2QuickImplForeign", + "gadget": true, + "lineNumber": 28, + "qualifiedClassName": "QQuickFileNameFilterQuickDialogs2QuickImplForeign" + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.Foreign", + "value": "QQuickControl" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickControlForeign", + "gadget": true, + "lineNumber": 39, + "qualifiedClassName": "QQuickControlForeign" + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.Foreign", + "value": "QQuickAbstractButton" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickAbstractButtonForeign", + "gadget": true, + "lineNumber": 47, + "qualifiedClassName": "QQuickAbstractButtonForeign" + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.Foreign", + "value": "QQuickIcon" + }, + { + "name": "QML.AddedInVersion", + "value": "1538" + } + ], + "className": "QQuickIconForeign", + "gadget": true, + "lineNumber": 55, + "qualifiedClassName": "QQuickIconForeign" + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.Foreign", + "value": "QQuickPopup" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickPopupForeign", + "gadget": true, + "lineNumber": 64, + "qualifiedClassName": "QQuickPopupForeign" + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.Foreign", + "value": "QQuickDialog" + }, + { + "name": "QML.AddedInVersion", + "value": "513" + } + ], + "className": "QQuickDialogForeign", + "gadget": true, + "lineNumber": 72, + "qualifiedClassName": "QQuickDialogForeign" + } + ], + "inputFile": "qtquickdialogs2quickimplforeign_p.h", + "outputRevision": 68 + } +] diff --git a/qt/6.8.1/msvc2022_64/metatypes/qt6quickdialogs2utils_metatypes.json b/qt/6.8.1/msvc2022_64/metatypes/qt6quickdialogs2utils_metatypes.json new file mode 100644 index 0000000000000000000000000000000000000000..ef67169b77f0fa5207cc9944f3c0560cb644f5ca --- /dev/null +++ b/qt/6.8.1/msvc2022_64/metatypes/qt6quickdialogs2utils_metatypes.json @@ -0,0 +1,129 @@ +[ + { + "classes": [ + { + "className": "QQuickFileNameFilter", + "lineNumber": 27, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "index", + "notify": "indexChanged", + "read": "index", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setIndex" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "name", + "notify": "nameChanged", + "read": "name", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "extensions", + "notify": "extensionsChanged", + "read": "extensions", + "required": false, + "scriptable": true, + "stored": true, + "type": "QStringList", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "globs", + "notify": "globsChanged", + "read": "globs", + "required": false, + "scriptable": true, + "stored": true, + "type": "QStringList", + "user": false + } + ], + "qualifiedClassName": "QQuickFileNameFilter", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + } + ], + "index": 0, + "name": "indexChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "name", + "type": "QString" + } + ], + "index": 1, + "name": "nameChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "extensions", + "type": "QStringList" + } + ], + "index": 2, + "name": "extensionsChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "globs", + "type": "QStringList" + } + ], + "index": 3, + "name": "globsChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qquickfilenamefilter_p.h", + "outputRevision": 68 + } +] diff --git a/qt/6.8.1/msvc2022_64/metatypes/qt6quickeffectsprivate_metatypes.json b/qt/6.8.1/msvc2022_64/metatypes/qt6quickeffectsprivate_metatypes.json new file mode 100644 index 0000000000000000000000000000000000000000..6f40ef45638c533319e33ba144cbc421efeff89a --- /dev/null +++ b/qt/6.8.1/msvc2022_64/metatypes/qt6quickeffectsprivate_metatypes.json @@ -0,0 +1,818 @@ +[ + { + "classes": [ + { + "className": "QGfxSourceProxyME", + "enums": [ + { + "isClass": true, + "isFlag": false, + "name": "Interpolation", + "values": [ + "Any", + "Nearest", + "Linear" + ] + } + ], + "lineNumber": 26, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "input", + "notify": "inputChanged", + "read": "input", + "required": false, + "reset": "resetInput", + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false, + "write": "setInput" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "output", + "notify": "outputChanged", + "read": "output", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "sourceRect", + "notify": "sourceRectChanged", + "read": "sourceRect", + "required": false, + "scriptable": true, + "stored": true, + "type": "QRectF", + "user": false, + "write": "setSourceRect" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "active", + "notify": "activeChanged", + "read": "isActive", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "interpolation", + "notify": "interpolationChanged", + "read": "interpolation", + "required": false, + "scriptable": true, + "stored": true, + "type": "Interpolation", + "user": false, + "write": "setInterpolation" + } + ], + "qualifiedClassName": "QGfxSourceProxyME", + "signals": [ + { + "access": "public", + "index": 0, + "name": "inputChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "outputChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "sourceRectChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "activeChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "interpolationChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "private", + "index": 5, + "name": "repolish", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickItem" + } + ] + } + ], + "inputFile": "qgfxsourceproxy_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "MultiEffect" + }, + { + "name": "QML.AddedInVersion", + "value": "1541" + } + ], + "className": "QQuickMultiEffect", + "lineNumber": 32, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "source", + "notify": "sourceChanged", + "read": "source", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false, + "write": "setSource" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "autoPaddingEnabled", + "notify": "autoPaddingEnabledChanged", + "read": "autoPaddingEnabled", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setAutoPaddingEnabled" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "paddingRect", + "notify": "paddingRectChanged", + "read": "paddingRect", + "required": false, + "scriptable": true, + "stored": true, + "type": "QRectF", + "user": false, + "write": "setPaddingRect" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "brightness", + "notify": "brightnessChanged", + "read": "brightness", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setBrightness" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "contrast", + "notify": "contrastChanged", + "read": "contrast", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setContrast" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "saturation", + "notify": "saturationChanged", + "read": "saturation", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setSaturation" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "colorization", + "notify": "colorizationChanged", + "read": "colorization", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setColorization" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 7, + "name": "colorizationColor", + "notify": "colorizationColorChanged", + "read": "colorizationColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false, + "write": "setColorizationColor" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 8, + "name": "blurEnabled", + "notify": "blurEnabledChanged", + "read": "blurEnabled", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setBlurEnabled" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 9, + "name": "blur", + "notify": "blurChanged", + "read": "blur", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setBlur" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 10, + "name": "blurMax", + "notify": "blurMaxChanged", + "read": "blurMax", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setBlurMax" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 11, + "name": "blurMultiplier", + "notify": "blurMultiplierChanged", + "read": "blurMultiplier", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setBlurMultiplier" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 12, + "name": "shadowEnabled", + "notify": "shadowEnabledChanged", + "read": "shadowEnabled", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setShadowEnabled" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 13, + "name": "shadowOpacity", + "notify": "shadowOpacityChanged", + "read": "shadowOpacity", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setShadowOpacity" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 14, + "name": "shadowBlur", + "notify": "shadowBlurChanged", + "read": "shadowBlur", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setShadowBlur" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 15, + "name": "shadowHorizontalOffset", + "notify": "shadowHorizontalOffsetChanged", + "read": "shadowHorizontalOffset", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setShadowHorizontalOffset" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 16, + "name": "shadowVerticalOffset", + "notify": "shadowVerticalOffsetChanged", + "read": "shadowVerticalOffset", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setShadowVerticalOffset" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 17, + "name": "shadowColor", + "notify": "shadowColorChanged", + "read": "shadowColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false, + "write": "setShadowColor" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 18, + "name": "shadowScale", + "notify": "shadowScaleChanged", + "read": "shadowScale", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setShadowScale" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 19, + "name": "maskEnabled", + "notify": "maskEnabledChanged", + "read": "maskEnabled", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setMaskEnabled" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 20, + "name": "maskSource", + "notify": "maskSourceChanged", + "read": "maskSource", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false, + "write": "setMaskSource" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 21, + "name": "maskThresholdMin", + "notify": "maskThresholdMinChanged", + "read": "maskThresholdMin", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setMaskThresholdMin" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 22, + "name": "maskSpreadAtMin", + "notify": "maskSpreadAtMinChanged", + "read": "maskSpreadAtMin", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setMaskSpreadAtMin" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 23, + "name": "maskThresholdMax", + "notify": "maskThresholdMaxChanged", + "read": "maskThresholdMax", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setMaskThresholdMax" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 24, + "name": "maskSpreadAtMax", + "notify": "maskSpreadAtMaxChanged", + "read": "maskSpreadAtMax", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setMaskSpreadAtMax" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 25, + "name": "maskInverted", + "notify": "maskInvertedChanged", + "read": "maskInverted", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setMaskInverted" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 26, + "name": "itemRect", + "notify": "itemRectChanged", + "read": "itemRect", + "required": false, + "scriptable": true, + "stored": true, + "type": "QRectF", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 27, + "name": "fragmentShader", + "notify": "fragmentShaderChanged", + "read": "fragmentShader", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 28, + "name": "vertexShader", + "notify": "vertexShaderChanged", + "read": "vertexShader", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 29, + "name": "hasProxySource", + "notify": "hasProxySourceChanged", + "read": "hasProxySource", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + } + ], + "qualifiedClassName": "QQuickMultiEffect", + "signals": [ + { + "access": "public", + "index": 0, + "name": "shaderChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "itemSizeChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "sourceChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "autoPaddingEnabledChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "paddingRectChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "brightnessChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "contrastChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "saturationChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 8, + "name": "colorizationChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 9, + "name": "colorizationColorChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 10, + "name": "blurEnabledChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 11, + "name": "blurChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 12, + "name": "blurMaxChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 13, + "name": "blurMultiplierChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 14, + "name": "shadowEnabledChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 15, + "name": "shadowOpacityChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 16, + "name": "shadowBlurChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 17, + "name": "shadowHorizontalOffsetChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 18, + "name": "shadowVerticalOffsetChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 19, + "name": "shadowColorChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 20, + "name": "shadowScaleChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 21, + "name": "maskEnabledChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 22, + "name": "maskSourceChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 23, + "name": "maskThresholdMinChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 24, + "name": "maskSpreadAtMinChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 25, + "name": "maskThresholdMaxChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 26, + "name": "maskSpreadAtMaxChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 27, + "name": "maskInvertedChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 28, + "name": "itemRectChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 29, + "name": "fragmentShaderChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 30, + "name": "vertexShaderChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 31, + "name": "hasProxySourceChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickItem" + } + ] + } + ], + "inputFile": "qquickmultieffect_p.h", + "outputRevision": 68 + } +] diff --git a/qt/6.8.1/msvc2022_64/metatypes/qt6quicklayouts_metatypes.json b/qt/6.8.1/msvc2022_64/metatypes/qt6quicklayouts_metatypes.json new file mode 100644 index 0000000000000000000000000000000000000000..e2b153ae29fab6ce6d90bd7b8e2e4f87a2498c47 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/metatypes/qt6quicklayouts_metatypes.json @@ -0,0 +1,1405 @@ +[ + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "LayoutItemProxy" + }, + { + "name": "QML.AddedInVersion", + "value": "1542" + } + ], + "className": "QQuickLayoutItemProxy", + "lineNumber": 23, + "methods": [ + { + "access": "public", + "index": 34, + "name": "effectiveTarget", + "returnType": "QQuickItem*" + } + ], + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "target", + "notify": "targetChanged", + "read": "target", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false, + "write": "setTarget" + } + ], + "qualifiedClassName": "QQuickLayoutItemProxy", + "signals": [ + { + "access": "public", + "index": 0, + "name": "targetChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "index": 1, + "name": "updatePos", + "returnType": "void" + }, + { + "access": "private", + "index": 2, + "name": "targetMinimumWidthChanged", + "returnType": "void" + }, + { + "access": "private", + "index": 3, + "name": "proxyMinimumWidthChanged", + "returnType": "void" + }, + { + "access": "private", + "index": 4, + "name": "targetMinimumHeightChanged", + "returnType": "void" + }, + { + "access": "private", + "index": 5, + "name": "proxyMinimumHeightChanged", + "returnType": "void" + }, + { + "access": "private", + "index": 6, + "name": "targetPreferredWidthChanged", + "returnType": "void" + }, + { + "access": "private", + "index": 7, + "name": "proxyPreferredWidthChanged", + "returnType": "void" + }, + { + "access": "private", + "index": 8, + "name": "targetPreferredHeightChanged", + "returnType": "void" + }, + { + "access": "private", + "index": 9, + "name": "proxyPreferredHeightChanged", + "returnType": "void" + }, + { + "access": "private", + "index": 10, + "name": "targetMaximumWidthChanged", + "returnType": "void" + }, + { + "access": "private", + "index": 11, + "name": "proxyMaximumWidthChanged", + "returnType": "void" + }, + { + "access": "private", + "index": 12, + "name": "targetMaximumHeightChanged", + "returnType": "void" + }, + { + "access": "private", + "index": 13, + "name": "proxyMaximumHeightChanged", + "returnType": "void" + }, + { + "access": "private", + "index": 14, + "name": "targetFillWidthChanged", + "returnType": "void" + }, + { + "access": "private", + "index": 15, + "name": "proxyFillWidthChanged", + "returnType": "void" + }, + { + "access": "private", + "index": 16, + "name": "targetFillHeightChanged", + "returnType": "void" + }, + { + "access": "private", + "index": 17, + "name": "proxyFillHeightChanged", + "returnType": "void" + }, + { + "access": "private", + "index": 18, + "name": "targetAlignmentChanged", + "returnType": "void" + }, + { + "access": "private", + "index": 19, + "name": "proxyAlignmentChanged", + "returnType": "void" + }, + { + "access": "private", + "index": 20, + "name": "targetHorizontalStretchFactorChanged", + "returnType": "void" + }, + { + "access": "private", + "index": 21, + "name": "proxyHorizontalStretchFactorChanged", + "returnType": "void" + }, + { + "access": "private", + "index": 22, + "name": "targetVerticalStretchFactorChanged", + "returnType": "void" + }, + { + "access": "private", + "index": 23, + "name": "proxyVerticalStretchFactorChanged", + "returnType": "void" + }, + { + "access": "private", + "index": 24, + "name": "targetMarginsChanged", + "returnType": "void" + }, + { + "access": "private", + "index": 25, + "name": "proxyMarginsChanged", + "returnType": "void" + }, + { + "access": "private", + "index": 26, + "name": "targetLeftMarginChanged", + "returnType": "void" + }, + { + "access": "private", + "index": 27, + "name": "proxyLeftMarginChanged", + "returnType": "void" + }, + { + "access": "private", + "index": 28, + "name": "targetTopMarginChanged", + "returnType": "void" + }, + { + "access": "private", + "index": 29, + "name": "proxyTopMarginChanged", + "returnType": "void" + }, + { + "access": "private", + "index": 30, + "name": "targetRightMarginChanged", + "returnType": "void" + }, + { + "access": "private", + "index": 31, + "name": "proxyRightMarginChanged", + "returnType": "void" + }, + { + "access": "private", + "index": 32, + "name": "targetBottomMarginChanged", + "returnType": "void" + }, + { + "access": "private", + "index": 33, + "name": "proxyBottomMarginChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickItem" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + } + ], + "className": "QQuickLayoutItemProxyAttachedData", + "lineNumber": 114, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "proxyHasControl", + "notify": "controllingProxyChanged", + "read": "proxyHasControl", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "controllingProxy", + "notify": "controllingProxyChanged", + "read": "getControllingProxy", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickLayoutItemProxy*", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "proxies", + "notify": "proxiesChanged", + "read": "getProxies", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlListProperty", + "user": false + } + ], + "qualifiedClassName": "QQuickLayoutItemProxyAttachedData", + "signals": [ + { + "access": "public", + "index": 0, + "name": "controlTaken", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "controlReleased", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "controllingProxyChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "proxiesChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qquicklayoutitemproxy_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "Layout" + }, + { + "name": "QML.AddedInVersion", + "value": "256" + }, + { + "name": "QML.Creatable", + "value": "false" + }, + { + "name": "QML.UncreatableReason", + "value": "Do not create objects of type Layout." + }, + { + "name": "QML.Attached", + "value": "QQuickLayoutAttached" + } + ], + "className": "QQuickLayout", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "SizePolicy", + "values": [ + "SizePolicyImplicit", + "SizePolicyExplicit" + ] + } + ], + "lineNumber": 34, + "methods": [ + { + "access": "public", + "index": 1, + "name": "_q_dumpLayoutTree", + "returnType": "void" + } + ], + "object": true, + "qualifiedClassName": "QQuickLayout", + "slots": [ + { + "access": "protected", + "index": 0, + "name": "invalidateSenderItem", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickItem" + }, + { + "access": "public", + "name": "QQuickItemChangeListener" + } + ] + }, + { + "className": "QQuickLayoutAttached", + "lineNumber": 166, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "minimumWidth", + "notify": "minimumWidthChanged", + "read": "minimumWidth", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setMinimumWidth" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "minimumHeight", + "notify": "minimumHeightChanged", + "read": "minimumHeight", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setMinimumHeight" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "preferredWidth", + "notify": "preferredWidthChanged", + "read": "preferredWidth", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setPreferredWidth" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "preferredHeight", + "notify": "preferredHeightChanged", + "read": "preferredHeight", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setPreferredHeight" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "maximumWidth", + "notify": "maximumWidthChanged", + "read": "maximumWidth", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setMaximumWidth" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "maximumHeight", + "notify": "maximumHeightChanged", + "read": "maximumHeight", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setMaximumHeight" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 6, + "name": "fillHeight", + "notify": "fillHeightChanged", + "read": "fillHeight", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setFillHeight" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 7, + "name": "fillWidth", + "notify": "fillWidthChanged", + "read": "fillWidth", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setFillWidth" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 8, + "name": "useDefaultSizePolicy", + "notify": "useDefaultSizePolicyChanged", + "read": "useDefaultSizePolicy", + "required": false, + "revision": 1544, + "scriptable": true, + "stored": true, + "type": "QQuickLayout::SizePolicy", + "user": false, + "write": "setUseDefaultSizePolicy" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 9, + "name": "row", + "notify": "rowChanged", + "read": "row", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setRow" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 10, + "name": "column", + "notify": "columnChanged", + "read": "column", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setColumn" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 11, + "name": "rowSpan", + "notify": "rowSpanChanged", + "read": "rowSpan", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setRowSpan" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 12, + "name": "columnSpan", + "notify": "columnSpanChanged", + "read": "columnSpan", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setColumnSpan" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 13, + "name": "alignment", + "notify": "alignmentChanged", + "read": "alignment", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::Alignment", + "user": false, + "write": "setAlignment" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 14, + "name": "horizontalStretchFactor", + "notify": "horizontalStretchFactorChanged", + "read": "horizontalStretchFactor", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setHorizontalStretchFactor" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 15, + "name": "verticalStretchFactor", + "notify": "verticalStretchFactorChanged", + "read": "verticalStretchFactor", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setVerticalStretchFactor" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 16, + "name": "margins", + "notify": "marginsChanged", + "read": "margins", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setMargins" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 17, + "name": "leftMargin", + "notify": "leftMarginChanged", + "read": "leftMargin", + "required": false, + "reset": "resetLeftMargin", + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setLeftMargin" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 18, + "name": "topMargin", + "notify": "topMarginChanged", + "read": "topMargin", + "required": false, + "reset": "resetTopMargin", + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setTopMargin" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 19, + "name": "rightMargin", + "notify": "rightMarginChanged", + "read": "rightMargin", + "required": false, + "reset": "resetRightMargin", + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setRightMargin" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 20, + "name": "bottomMargin", + "notify": "bottomMarginChanged", + "read": "bottomMargin", + "required": false, + "reset": "resetBottomMargin", + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setBottomMargin" + } + ], + "qualifiedClassName": "QQuickLayoutAttached", + "signals": [ + { + "access": "public", + "index": 0, + "name": "minimumWidthChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "minimumHeightChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "preferredWidthChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "preferredHeightChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "maximumWidthChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "maximumHeightChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "fillWidthChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "fillHeightChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 8, + "name": "useDefaultSizePolicyChanged", + "returnType": "void", + "revision": 1544 + }, + { + "access": "public", + "index": 9, + "name": "leftMarginChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 10, + "name": "topMarginChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 11, + "name": "rightMarginChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 12, + "name": "bottomMarginChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 13, + "name": "marginsChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 14, + "name": "rowChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 15, + "name": "columnChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 16, + "name": "rowSpanChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 17, + "name": "columnSpanChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 18, + "name": "alignmentChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 19, + "name": "horizontalStretchFactorChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 20, + "name": "verticalStretchFactorChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qquicklayout_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.AddedInVersion", + "value": "257" + } + ], + "className": "QQuickGridLayoutBase", + "lineNumber": 31, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "layoutDirection", + "notify": "layoutDirectionChanged", + "read": "layoutDirection", + "required": false, + "revision": 257, + "scriptable": true, + "stored": true, + "type": "Qt::LayoutDirection", + "user": false, + "write": "setLayoutDirection" + } + ], + "qualifiedClassName": "QQuickGridLayoutBase", + "signals": [ + { + "access": "public", + "index": 0, + "name": "layoutDirectionChanged", + "returnType": "void", + "revision": 257 + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickLayout" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "GridLayout" + }, + { + "name": "QML.AddedInVersion", + "value": "256" + } + ], + "className": "QQuickGridLayout", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "Flow", + "values": [ + "LeftToRight", + "TopToBottom" + ] + } + ], + "lineNumber": 114, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "columnSpacing", + "notify": "columnSpacingChanged", + "read": "columnSpacing", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setColumnSpacing" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "rowSpacing", + "notify": "rowSpacingChanged", + "read": "rowSpacing", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setRowSpacing" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "columns", + "notify": "columnsChanged", + "read": "columns", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setColumns" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "rows", + "notify": "rowsChanged", + "read": "rows", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setRows" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "flow", + "notify": "flowChanged", + "read": "flow", + "required": false, + "scriptable": true, + "stored": true, + "type": "Flow", + "user": false, + "write": "setFlow" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "uniformCellWidths", + "notify": "uniformCellWidthsChanged", + "read": "uniformCellWidths", + "required": false, + "revision": 1542, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setUniformCellWidths" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 6, + "name": "uniformCellHeights", + "notify": "uniformCellHeightsChanged", + "read": "uniformCellHeights", + "required": false, + "revision": 1542, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setUniformCellHeights" + } + ], + "qualifiedClassName": "QQuickGridLayout", + "signals": [ + { + "access": "public", + "index": 0, + "name": "columnSpacingChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "rowSpacingChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "columnsChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "rowsChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "flowChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "uniformCellWidthsChanged", + "returnType": "void", + "revision": 1542 + }, + { + "access": "public", + "index": 6, + "name": "uniformCellHeightsChanged", + "returnType": "void", + "revision": 1542 + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickGridLayoutBase" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + } + ], + "className": "QQuickLinearLayout", + "lineNumber": 186, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "spacing", + "notify": "spacingChanged", + "read": "spacing", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setSpacing" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "uniformCellSizes", + "notify": "uniformCellSizesChanged", + "read": "uniformCellSizes", + "required": false, + "revision": 1542, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setUniformCellSizes" + } + ], + "qualifiedClassName": "QQuickLinearLayout", + "signals": [ + { + "access": "public", + "index": 0, + "name": "spacingChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "uniformCellSizesChanged", + "returnType": "void", + "revision": 1542 + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickGridLayoutBase" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "RowLayout" + }, + { + "name": "QML.AddedInVersion", + "value": "256" + } + ], + "className": "QQuickRowLayout", + "lineNumber": 224, + "object": true, + "qualifiedClassName": "QQuickRowLayout", + "superClasses": [ + { + "access": "public", + "name": "QQuickLinearLayout" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "ColumnLayout" + }, + { + "name": "QML.AddedInVersion", + "value": "256" + } + ], + "className": "QQuickColumnLayout", + "lineNumber": 241, + "object": true, + "qualifiedClassName": "QQuickColumnLayout", + "superClasses": [ + { + "access": "public", + "name": "QQuickLinearLayout" + } + ] + } + ], + "inputFile": "qquicklinearlayout_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "StackLayout" + }, + { + "name": "QML.AddedInVersion", + "value": "259" + }, + { + "name": "QML.Attached", + "value": "QQuickStackLayoutAttached" + } + ], + "className": "QQuickStackLayout", + "lineNumber": 26, + "methods": [ + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + } + ], + "index": 2, + "name": "itemAt", + "returnType": "QQuickItem*" + } + ], + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "count", + "notify": "countChanged", + "read": "count", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "currentIndex", + "notify": "currentIndexChanged", + "read": "currentIndex", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setCurrentIndex" + } + ], + "qualifiedClassName": "QQuickStackLayout", + "signals": [ + { + "access": "public", + "index": 0, + "name": "currentIndexChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "countChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickLayout" + } + ] + }, + { + "className": "QQuickStackLayoutAttached", + "lineNumber": 102, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "index", + "notify": "indexChanged", + "read": "index", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "isCurrentItem", + "notify": "isCurrentItemChanged", + "read": "isCurrentItem", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "layout", + "notify": "layoutChanged", + "read": "layout", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickStackLayout*", + "user": false + } + ], + "qualifiedClassName": "QQuickStackLayoutAttached", + "signals": [ + { + "access": "public", + "index": 0, + "name": "indexChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "isCurrentItemChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "layoutChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qquickstacklayout_p.h", + "outputRevision": 68 + } +] diff --git a/qt/6.8.1/msvc2022_64/metatypes/qt6quickparticlesprivate_metatypes.json b/qt/6.8.1/msvc2022_64/metatypes/qt6quickparticlesprivate_metatypes.json new file mode 100644 index 0000000000000000000000000000000000000000..9682eef848629dc6cbf941bdac2ae24caf6e904d --- /dev/null +++ b/qt/6.8.1/msvc2022_64/metatypes/qt6quickparticlesprivate_metatypes.json @@ -0,0 +1,5839 @@ +[ + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "particle" + }, + { + "name": "QML.AddedInVersion", + "value": "1543" + } + ], + "className": "QQuickV4ParticleData", + "gadget": true, + "lineNumber": 23, + "methods": [ + { + "access": "public", + "index": 0, + "name": "discard", + "returnType": "void" + } + ], + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "initialX", + "read": "initialX", + "required": false, + "scriptable": true, + "stored": true, + "type": "float", + "user": false, + "write": "set_initialX" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "initialVX", + "read": "initialVX", + "required": false, + "scriptable": true, + "stored": true, + "type": "float", + "user": false, + "write": "set_initialVX" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "initialAX", + "read": "initialAX", + "required": false, + "scriptable": true, + "stored": true, + "type": "float", + "user": false, + "write": "set_initialAX" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "initialY", + "read": "initialY", + "required": false, + "scriptable": true, + "stored": true, + "type": "float", + "user": false, + "write": "set_initialY" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "initialVY", + "read": "initialVY", + "required": false, + "scriptable": true, + "stored": true, + "type": "float", + "user": false, + "write": "set_initialVY" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "initialAY", + "read": "initialAY", + "required": false, + "scriptable": true, + "stored": true, + "type": "float", + "user": false, + "write": "set_initialAY" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 6, + "name": "t", + "read": "t", + "required": false, + "scriptable": true, + "stored": true, + "type": "float", + "user": false, + "write": "set_t" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 7, + "name": "startSize", + "read": "startSize", + "required": false, + "scriptable": true, + "stored": true, + "type": "float", + "user": false, + "write": "set_startSize" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 8, + "name": "endSize", + "read": "endSize", + "required": false, + "scriptable": true, + "stored": true, + "type": "float", + "user": false, + "write": "set_endSize" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 9, + "name": "lifeSpan", + "read": "lifeSpan", + "required": false, + "scriptable": true, + "stored": true, + "type": "float", + "user": false, + "write": "set_lifeSpan" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 10, + "name": "rotation", + "read": "rotation", + "required": false, + "scriptable": true, + "stored": true, + "type": "float", + "user": false, + "write": "set_rotation" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 11, + "name": "rotationVelocity", + "read": "rotationVelocity", + "required": false, + "scriptable": true, + "stored": true, + "type": "float", + "user": false, + "write": "set_rotationVelocity" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 12, + "name": "autoRotate", + "read": "autoRotate", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "set_autoRotate" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 13, + "name": "update", + "read": "update", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "set_update" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 14, + "name": "xDeformationVectorX", + "read": "xDeformationVectorX", + "required": false, + "scriptable": true, + "stored": true, + "type": "float", + "user": false, + "write": "set_xDeformationVectorX" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 15, + "name": "yDeformationVectorX", + "read": "yDeformationVectorX", + "required": false, + "scriptable": true, + "stored": true, + "type": "float", + "user": false, + "write": "set_yDeformationVectorX" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 16, + "name": "xDeformationVectorY", + "read": "xDeformationVectorY", + "required": false, + "scriptable": true, + "stored": true, + "type": "float", + "user": false, + "write": "set_xDeformationVectorY" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 17, + "name": "yDeformationVectorY", + "read": "yDeformationVectorY", + "required": false, + "scriptable": true, + "stored": true, + "type": "float", + "user": false, + "write": "set_yDeformationVectorY" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 18, + "name": "animationIndex", + "read": "animationIndex", + "required": false, + "scriptable": true, + "stored": true, + "type": "float", + "user": false, + "write": "set_animationIndex" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 19, + "name": "frameDuration", + "read": "frameDuration", + "required": false, + "scriptable": true, + "stored": true, + "type": "float", + "user": false, + "write": "set_frameDuration" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 20, + "name": "frameAt", + "read": "frameAt", + "required": false, + "scriptable": true, + "stored": true, + "type": "float", + "user": false, + "write": "set_frameAt" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 21, + "name": "frameCount", + "read": "frameCount", + "required": false, + "scriptable": true, + "stored": true, + "type": "float", + "user": false, + "write": "set_frameCount" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 22, + "name": "animationT", + "read": "animationT", + "required": false, + "scriptable": true, + "stored": true, + "type": "float", + "user": false, + "write": "set_animationT" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 23, + "name": "x", + "read": "x", + "required": false, + "scriptable": true, + "stored": true, + "type": "float", + "user": false, + "write": "set_x" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 24, + "name": "vx", + "read": "vx", + "required": false, + "scriptable": true, + "stored": true, + "type": "float", + "user": false, + "write": "set_vx" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 25, + "name": "ax", + "read": "ax", + "required": false, + "scriptable": true, + "stored": true, + "type": "float", + "user": false, + "write": "set_ax" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 26, + "name": "y", + "read": "y", + "required": false, + "scriptable": true, + "stored": true, + "type": "float", + "user": false, + "write": "set_y" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 27, + "name": "vy", + "read": "vy", + "required": false, + "scriptable": true, + "stored": true, + "type": "float", + "user": false, + "write": "set_vy" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 28, + "name": "ay", + "read": "ay", + "required": false, + "scriptable": true, + "stored": true, + "type": "float", + "user": false, + "write": "set_ay" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 29, + "name": "red", + "read": "red", + "required": false, + "scriptable": true, + "stored": true, + "type": "float", + "user": false, + "write": "set_red" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 30, + "name": "green", + "read": "green", + "required": false, + "scriptable": true, + "stored": true, + "type": "float", + "user": false, + "write": "set_green" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 31, + "name": "blue", + "read": "blue", + "required": false, + "scriptable": true, + "stored": true, + "type": "float", + "user": false, + "write": "set_blue" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 32, + "name": "alpha", + "read": "alpha", + "required": false, + "scriptable": true, + "stored": true, + "type": "float", + "user": false, + "write": "set_alpha" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 33, + "name": "lifeLeft", + "read": "lifeLeft", + "required": false, + "scriptable": true, + "stored": true, + "type": "float", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 34, + "name": "currentSize", + "read": "currentSize", + "required": false, + "scriptable": true, + "stored": true, + "type": "float", + "user": false + } + ], + "qualifiedClassName": "QQuickV4ParticleData" + } + ], + "inputFile": "qquickv4particledata_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "Age" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickAgeAffector", + "lineNumber": 21, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "lifeLeft", + "notify": "lifeLeftChanged", + "read": "lifeLeft", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setLifeLeft" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "advancePosition", + "notify": "advancePositionChanged", + "read": "advancePosition", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setAdvancePosition" + } + ], + "qualifiedClassName": "QQuickAgeAffector", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "int" + } + ], + "index": 0, + "name": "lifeLeftChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "bool" + } + ], + "index": 1, + "name": "advancePositionChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "int" + } + ], + "index": 2, + "name": "setLifeLeft", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "bool" + } + ], + "index": 3, + "name": "setAdvancePosition", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickParticleAffector" + } + ] + } + ], + "inputFile": "qquickage_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "AngleDirection" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickAngleDirection", + "lineNumber": 23, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "angle", + "notify": "angleChanged", + "read": "angle", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setAngle" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "magnitude", + "notify": "magnitudeChanged", + "read": "magnitude", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setMagnitude" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "angleVariation", + "notify": "angleVariationChanged", + "read": "angleVariation", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setAngleVariation" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "magnitudeVariation", + "notify": "magnitudeVariationChanged", + "read": "magnitudeVariation", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setMagnitudeVariation" + } + ], + "qualifiedClassName": "QQuickAngleDirection", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 0, + "name": "angleChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 1, + "name": "magnitudeChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 2, + "name": "angleVariationChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 3, + "name": "magnitudeVariationChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 4, + "name": "setAngle", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 5, + "name": "setMagnitude", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 6, + "name": "setAngleVariation", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 7, + "name": "setMagnitudeVariation", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickDirection" + } + ] + } + ], + "inputFile": "qquickangledirection_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "DefaultProperty", + "value": "directions" + }, + { + "name": "QML.Element", + "value": "CumulativeDirection" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickCumulativeDirection", + "lineNumber": 24, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "directions", + "read": "directions", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlListProperty", + "user": false + } + ], + "qualifiedClassName": "QQuickCumulativeDirection", + "superClasses": [ + { + "access": "public", + "name": "QQuickDirection" + } + ] + } + ], + "inputFile": "qquickcumulativedirection_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "Affector" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickCustomAffector", + "lineNumber": 27, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "relative", + "notify": "relativeChanged", + "read": "relative", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setRelative" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "position", + "notify": "positionChanged", + "read": "position", + "required": false, + "reset": "positionReset", + "scriptable": true, + "stored": true, + "type": "QQuickDirection*", + "user": false, + "write": "setPosition" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "velocity", + "notify": "velocityChanged", + "read": "velocity", + "required": false, + "reset": "velocityReset", + "scriptable": true, + "stored": true, + "type": "QQuickDirection*", + "user": false, + "write": "setVelocity" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "acceleration", + "notify": "accelerationChanged", + "read": "acceleration", + "required": false, + "reset": "accelerationReset", + "scriptable": true, + "stored": true, + "type": "QQuickDirection*", + "user": false, + "write": "setAcceleration" + } + ], + "qualifiedClassName": "QQuickCustomAffector", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "particles", + "type": "QList" + }, + { + "name": "dt", + "type": "qreal" + } + ], + "index": 0, + "name": "affectParticles", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "QQuickDirection*" + } + ], + "index": 1, + "name": "positionChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "QQuickDirection*" + } + ], + "index": 2, + "name": "velocityChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "QQuickDirection*" + } + ], + "index": 3, + "name": "accelerationChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "bool" + } + ], + "index": 4, + "name": "relativeChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "QQuickDirection*" + } + ], + "index": 5, + "name": "setPosition", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "QQuickDirection*" + } + ], + "index": 6, + "name": "setVelocity", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "QQuickDirection*" + } + ], + "index": 7, + "name": "setAcceleration", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "bool" + } + ], + "index": 8, + "name": "setRelative", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickParticleAffector" + } + ] + } + ], + "inputFile": "qquickcustomaffector_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "NullVector" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + }, + { + "name": "QML.Creatable", + "value": "false" + }, + { + "name": "QML.UncreatableReason", + "value": "Abstract type. Use one of the inheriting types instead." + } + ], + "className": "QQuickDirection", + "lineNumber": 26, + "object": true, + "qualifiedClassName": "QQuickDirection", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qquickdirection_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "EllipseShape" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickEllipseExtruder", + "lineNumber": 21, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "fill", + "notify": "fillChanged", + "read": "fill", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setFill" + } + ], + "qualifiedClassName": "QQuickEllipseExtruder", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "bool" + } + ], + "index": 0, + "name": "fillChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "bool" + } + ], + "index": 1, + "name": "setFill", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickParticleExtruder" + } + ] + } + ], + "inputFile": "qquickellipseextruder_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "Friction" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickFrictionAffector", + "lineNumber": 21, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "factor", + "notify": "factorChanged", + "read": "factor", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setFactor" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "threshold", + "notify": "thresholdChanged", + "read": "threshold", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setThreshold" + } + ], + "qualifiedClassName": "QQuickFrictionAffector", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 0, + "name": "factorChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 1, + "name": "thresholdChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 2, + "name": "setFactor", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 3, + "name": "setThreshold", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickParticleAffector" + } + ] + } + ], + "inputFile": "qquickfriction_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "Gravity" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickGravityAffector", + "lineNumber": 22, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "magnitude", + "notify": "magnitudeChanged", + "read": "magnitude", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setMagnitude" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "acceleration", + "notify": "magnitudeChanged", + "read": "magnitude", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setAcceleration" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "angle", + "notify": "angleChanged", + "read": "angle", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setAngle" + } + ], + "qualifiedClassName": "QQuickGravityAffector", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 0, + "name": "magnitudeChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 1, + "name": "angleChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 2, + "name": "setMagnitude", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 3, + "name": "setAcceleration", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 4, + "name": "setAngle", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickParticleAffector" + } + ] + } + ], + "inputFile": "qquickgravity_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "GroupGoal" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickGroupGoalAffector", + "lineNumber": 23, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "goalState", + "notify": "goalStateChanged", + "read": "goalState", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setGoalState" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "jump", + "notify": "jumpChanged", + "read": "jump", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setJump" + } + ], + "qualifiedClassName": "QQuickGroupGoalAffector", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "QString" + } + ], + "index": 0, + "name": "goalStateChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "bool" + } + ], + "index": 1, + "name": "jumpChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "QString" + } + ], + "index": 2, + "name": "setGoalState", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "bool" + } + ], + "index": 3, + "name": "setJump", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickParticleAffector" + } + ] + } + ], + "inputFile": "qquickgroupgoal_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "ImageParticle" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickImageParticle", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "Status", + "values": [ + "Null", + "Ready", + "Loading", + "Error" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "EntryEffect", + "values": [ + "None", + "Fade", + "Scale" + ] + } + ], + "lineNumber": 149, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "source", + "notify": "imageChanged", + "read": "image", + "required": false, + "scriptable": true, + "stored": true, + "type": "QUrl", + "user": false, + "write": "setImage" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "sprites", + "read": "sprites", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlListProperty", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "status", + "notify": "statusChanged", + "read": "status", + "required": false, + "scriptable": true, + "stored": true, + "type": "Status", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "colorTable", + "notify": "colortableChanged", + "read": "colortable", + "required": false, + "scriptable": true, + "stored": true, + "type": "QUrl", + "user": false, + "write": "setColortable" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "sizeTable", + "notify": "sizetableChanged", + "read": "sizetable", + "required": false, + "scriptable": true, + "stored": true, + "type": "QUrl", + "user": false, + "write": "setSizetable" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "opacityTable", + "notify": "opacitytableChanged", + "read": "opacitytable", + "required": false, + "scriptable": true, + "stored": true, + "type": "QUrl", + "user": false, + "write": "setOpacitytable" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "color", + "notify": "colorChanged", + "read": "color", + "required": false, + "reset": "resetColor", + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false, + "write": "setColor" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 7, + "name": "colorVariation", + "notify": "colorVariationChanged", + "read": "colorVariation", + "required": false, + "reset": "resetColor", + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setColorVariation" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 8, + "name": "redVariation", + "notify": "redVariationChanged", + "read": "redVariation", + "required": false, + "reset": "resetColor", + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setRedVariation" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 9, + "name": "greenVariation", + "notify": "greenVariationChanged", + "read": "greenVariation", + "required": false, + "reset": "resetColor", + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setGreenVariation" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 10, + "name": "blueVariation", + "notify": "blueVariationChanged", + "read": "blueVariation", + "required": false, + "reset": "resetColor", + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setBlueVariation" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 11, + "name": "alpha", + "notify": "alphaChanged", + "read": "alpha", + "required": false, + "reset": "resetColor", + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setAlpha" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 12, + "name": "alphaVariation", + "notify": "alphaVariationChanged", + "read": "alphaVariation", + "required": false, + "reset": "resetColor", + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setAlphaVariation" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 13, + "name": "rotation", + "notify": "rotationChanged", + "read": "rotation", + "required": false, + "reset": "resetRotation", + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setRotation" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 14, + "name": "rotationVariation", + "notify": "rotationVariationChanged", + "read": "rotationVariation", + "required": false, + "reset": "resetRotation", + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setRotationVariation" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 15, + "name": "rotationVelocity", + "notify": "rotationVelocityChanged", + "read": "rotationVelocity", + "required": false, + "reset": "resetRotation", + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setRotationVelocity" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 16, + "name": "rotationVelocityVariation", + "notify": "rotationVelocityVariationChanged", + "read": "rotationVelocityVariation", + "required": false, + "reset": "resetRotation", + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setRotationVelocityVariation" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 17, + "name": "autoRotation", + "notify": "autoRotationChanged", + "read": "autoRotation", + "required": false, + "reset": "resetRotation", + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setAutoRotation" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 18, + "name": "xVector", + "notify": "xVectorChanged", + "read": "xVector", + "required": false, + "reset": "resetDeformation", + "scriptable": true, + "stored": true, + "type": "QQuickDirection*", + "user": false, + "write": "setXVector" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 19, + "name": "yVector", + "notify": "yVectorChanged", + "read": "yVector", + "required": false, + "reset": "resetDeformation", + "scriptable": true, + "stored": true, + "type": "QQuickDirection*", + "user": false, + "write": "setYVector" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 20, + "name": "spritesInterpolate", + "notify": "spritesInterpolateChanged", + "read": "spritesInterpolate", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setSpritesInterpolate" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 21, + "name": "entryEffect", + "notify": "entryEffectChanged", + "read": "entryEffect", + "required": false, + "scriptable": true, + "stored": true, + "type": "EntryEffect", + "user": false, + "write": "setEntryEffect" + } + ], + "qualifiedClassName": "QQuickImageParticle", + "signals": [ + { + "access": "public", + "index": 0, + "name": "imageChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "colortableChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "sizetableChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "opacitytableChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "colorChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "colorVariationChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 6, + "name": "alphaVariationChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 7, + "name": "alphaChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 8, + "name": "redVariationChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 9, + "name": "greenVariationChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 10, + "name": "blueVariationChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 11, + "name": "rotationChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 12, + "name": "rotationVariationChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 13, + "name": "rotationVelocityChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 14, + "name": "rotationVelocityVariationChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "bool" + } + ], + "index": 15, + "name": "autoRotationChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "QQuickDirection*" + } + ], + "index": 16, + "name": "xVectorChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "QQuickDirection*" + } + ], + "index": 17, + "name": "yVectorChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "bool" + } + ], + "index": 18, + "name": "spritesInterpolateChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "bool" + } + ], + "index": 19, + "name": "bypassOptimizationsChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "EntryEffect" + } + ], + "index": 20, + "name": "entryEffectChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "Status" + } + ], + "index": 21, + "name": "statusChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 22, + "name": "setAlphaVariation", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 23, + "name": "setAlpha", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 24, + "name": "setRedVariation", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 25, + "name": "setGreenVariation", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 26, + "name": "setBlueVariation", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 27, + "name": "setRotation", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 28, + "name": "setRotationVariation", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 29, + "name": "setRotationVelocity", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 30, + "name": "setRotationVelocityVariation", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "bool" + } + ], + "index": 31, + "name": "setAutoRotation", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "QQuickDirection*" + } + ], + "index": 32, + "name": "setXVector", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "QQuickDirection*" + } + ], + "index": 33, + "name": "setYVector", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "bool" + } + ], + "index": 34, + "name": "setSpritesInterpolate", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "bool" + } + ], + "index": 35, + "name": "setBypassOptimizations", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "EntryEffect" + } + ], + "index": 36, + "name": "setEntryEffect", + "returnType": "void" + }, + { + "access": "private", + "index": 37, + "name": "createEngine", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "spriteIndex", + "type": "int" + } + ], + "index": 38, + "name": "spriteAdvance", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "time", + "type": "qreal" + } + ], + "index": 39, + "name": "spritesUpdate", + "returnType": "void" + }, + { + "access": "private", + "index": 40, + "isCloned": true, + "name": "spritesUpdate", + "returnType": "void" + }, + { + "access": "private", + "index": 41, + "name": "mainThreadFetchImageData", + "returnType": "void" + }, + { + "access": "private", + "index": 42, + "name": "invalidateSceneGraph", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickParticlePainter" + } + ] + } + ], + "inputFile": "qquickimageparticle_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "ItemParticle" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + }, + { + "name": "QML.Attached", + "value": "QQuickItemParticleAttached" + } + ], + "className": "QQuickItemParticle", + "lineNumber": 25, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "fade", + "notify": "fadeChanged", + "read": "fade", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setFade" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "delegate", + "notify": "delegateChanged", + "read": "delegate", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlComponent*", + "user": false, + "write": "setDelegate" + } + ], + "qualifiedClassName": "QQuickItemParticle", + "signals": [ + { + "access": "public", + "index": 0, + "name": "fadeChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "QQmlComponent*" + } + ], + "index": 1, + "name": "delegateChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "item", + "type": "QQuickItem*" + } + ], + "index": 2, + "name": "freeze", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "item", + "type": "QQuickItem*" + } + ], + "index": 3, + "name": "unfreeze", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "item", + "type": "QQuickItem*" + }, + { + "name": "prioritize", + "type": "bool" + } + ], + "index": 4, + "name": "take", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "item", + "type": "QQuickItem*" + } + ], + "index": 5, + "isCloned": true, + "name": "take", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "item", + "type": "QQuickItem*" + } + ], + "index": 6, + "name": "give", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "bool" + } + ], + "index": 7, + "name": "setFade", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "QQmlComponent*" + } + ], + "index": 8, + "name": "setDelegate", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickParticlePainter" + } + ] + }, + { + "className": "QQuickItemParticleAttached", + "lineNumber": 98, + "object": true, + "properties": [ + { + "constant": true, + "designable": true, + "final": true, + "index": 0, + "name": "particle", + "read": "particle", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickItemParticle*", + "user": false + } + ], + "qualifiedClassName": "QQuickItemParticleAttached", + "signals": [ + { + "access": "public", + "index": 0, + "name": "detached", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "attached", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qquickitemparticle_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "LineShape" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickLineExtruder", + "lineNumber": 19, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "mirrored", + "notify": "mirroredChanged", + "read": "mirrored", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setMirrored" + } + ], + "qualifiedClassName": "QQuickLineExtruder", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "bool" + } + ], + "index": 0, + "name": "mirroredChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "bool" + } + ], + "index": 1, + "name": "setMirrored", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickParticleExtruder" + } + ] + } + ], + "inputFile": "qquicklineextruder_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "MaskShape" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickMaskExtruder", + "lineNumber": 24, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "source", + "notify": "sourceChanged", + "read": "source", + "required": false, + "scriptable": true, + "stored": true, + "type": "QUrl", + "user": false, + "write": "setSource" + } + ], + "qualifiedClassName": "QQuickMaskExtruder", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "QUrl" + } + ], + "index": 0, + "name": "sourceChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "QUrl" + } + ], + "index": 1, + "name": "setSource", + "returnType": "void" + }, + { + "access": "private", + "index": 2, + "name": "startMaskLoading", + "returnType": "void" + }, + { + "access": "private", + "index": 3, + "name": "finishMaskLoading", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickParticleExtruder" + } + ] + } + ], + "inputFile": "qquickmaskextruder_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "ParticleAffector" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + }, + { + "name": "QML.Creatable", + "value": "false" + }, + { + "name": "QML.UncreatableReason", + "value": "Abstract type. Use one of the inheriting types instead." + } + ], + "className": "QQuickParticleAffector", + "lineNumber": 26, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "system", + "notify": "systemChanged", + "read": "system", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickParticleSystem*", + "user": false, + "write": "setSystem" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "groups", + "notify": "groupsChanged", + "read": "groups", + "required": false, + "scriptable": true, + "stored": true, + "type": "QStringList", + "user": false, + "write": "setGroups" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "whenCollidingWith", + "notify": "whenCollidingWithChanged", + "read": "whenCollidingWith", + "required": false, + "scriptable": true, + "stored": true, + "type": "QStringList", + "user": false, + "write": "setWhenCollidingWith" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "enabled", + "notify": "enabledChanged", + "read": "enabled", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setEnabled" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "once", + "notify": "onceChanged", + "read": "onceOff", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setOnceOff" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "shape", + "notify": "shapeChanged", + "read": "shape", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickParticleExtruder*", + "user": false, + "write": "setShape" + } + ], + "qualifiedClassName": "QQuickParticleAffector", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "QQuickParticleSystem*" + } + ], + "index": 0, + "name": "systemChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "QStringList" + } + ], + "index": 1, + "name": "groupsChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "bool" + } + ], + "index": 2, + "name": "enabledChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "bool" + } + ], + "index": 3, + "name": "onceChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "QQuickParticleExtruder*" + } + ], + "index": 4, + "name": "shapeChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "x", + "type": "qreal" + }, + { + "name": "y", + "type": "qreal" + } + ], + "index": 5, + "name": "affected", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "QStringList" + } + ], + "index": 6, + "name": "whenCollidingWithChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "QQuickParticleSystem*" + } + ], + "index": 7, + "name": "setSystem", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "QStringList" + } + ], + "index": 8, + "name": "setGroups", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "bool" + } + ], + "index": 9, + "name": "setEnabled", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "bool" + } + ], + "index": 10, + "name": "setOnceOff", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "QQuickParticleExtruder*" + } + ], + "index": 11, + "name": "setShape", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "QStringList" + } + ], + "index": 12, + "name": "setWhenCollidingWith", + "returnType": "void" + }, + { + "access": "public", + "index": 13, + "name": "updateOffsets", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickItem" + } + ] + } + ], + "inputFile": "qquickparticleaffector_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "Emitter" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickParticleEmitter", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "Lifetime", + "values": [ + "InfiniteLife" + ] + } + ], + "lineNumber": 29, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "system", + "notify": "systemChanged", + "read": "system", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickParticleSystem*", + "user": false, + "write": "setSystem" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "group", + "notify": "groupChanged", + "read": "group", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setGroup" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "shape", + "notify": "extruderChanged", + "read": "extruder", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickParticleExtruder*", + "user": false, + "write": "setExtruder" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "enabled", + "notify": "enabledChanged", + "read": "enabled", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setEnabled" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "startTime", + "notify": "startTimeChanged", + "read": "startTime", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setStartTime" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "emitRate", + "notify": "particlesPerSecondChanged", + "read": "particlesPerSecond", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setParticlesPerSecond" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "lifeSpan", + "notify": "particleDurationChanged", + "read": "particleDuration", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setParticleDuration" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 7, + "name": "lifeSpanVariation", + "notify": "particleDurationVariationChanged", + "read": "particleDurationVariation", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setParticleDurationVariation" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 8, + "name": "maximumEmitted", + "notify": "maximumEmittedChanged", + "read": "maxParticleCount", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setMaxParticleCount" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 9, + "name": "size", + "notify": "particleSizeChanged", + "read": "particleSize", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setParticleSize" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 10, + "name": "endSize", + "notify": "particleEndSizeChanged", + "read": "particleEndSize", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setParticleEndSize" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 11, + "name": "sizeVariation", + "notify": "particleSizeVariationChanged", + "read": "particleSizeVariation", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setParticleSizeVariation" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 12, + "name": "velocity", + "notify": "velocityChanged", + "read": "velocity", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickDirection*", + "user": false, + "write": "setVelocity" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 13, + "name": "acceleration", + "notify": "accelerationChanged", + "read": "acceleration", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickDirection*", + "user": false, + "write": "setAcceleration" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 14, + "name": "velocityFromMovement", + "notify": "velocityFromMovementChanged", + "read": "velocityFromMovement", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setVelocityFromMovement" + } + ], + "qualifiedClassName": "QQuickParticleEmitter", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "particles", + "type": "QList" + } + ], + "index": 0, + "name": "emitParticles", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "qreal" + } + ], + "index": 1, + "name": "particlesPerSecondChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "int" + } + ], + "index": 2, + "name": "particleDurationChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "bool" + } + ], + "index": 3, + "name": "enabledChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "QQuickParticleSystem*" + } + ], + "index": 4, + "name": "systemChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "QString" + } + ], + "index": 5, + "name": "groupChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "int" + } + ], + "index": 6, + "name": "particleDurationVariationChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "QQuickParticleExtruder*" + } + ], + "index": 7, + "name": "extruderChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 8, + "name": "particleSizeChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 9, + "name": "particleEndSizeChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 10, + "name": "particleSizeVariationChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "QQuickDirection*" + } + ], + "index": 11, + "name": "velocityChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "QQuickDirection*" + } + ], + "index": 12, + "name": "accelerationChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "int" + } + ], + "index": 13, + "name": "maximumEmittedChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 14, + "name": "particleCountChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 15, + "name": "velocityFromMovementChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "int" + } + ], + "index": 16, + "name": "startTimeChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "milliseconds", + "type": "int" + } + ], + "index": 17, + "name": "pulse", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "num", + "type": "int" + } + ], + "index": 18, + "name": "burst", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "num", + "type": "int" + }, + { + "name": "x", + "type": "qreal" + }, + { + "name": "y", + "type": "qreal" + } + ], + "index": 19, + "name": "burst", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "bool" + } + ], + "index": 20, + "name": "setEnabled", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 21, + "name": "setParticlesPerSecond", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "int" + } + ], + "index": 22, + "name": "setParticleDuration", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "QQuickParticleSystem*" + } + ], + "index": 23, + "name": "setSystem", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "QString" + } + ], + "index": 24, + "name": "setGroup", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "int" + } + ], + "index": 25, + "name": "setParticleDurationVariation", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "QQuickParticleExtruder*" + } + ], + "index": 26, + "name": "setExtruder", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 27, + "name": "setParticleSize", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 28, + "name": "setParticleEndSize", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 29, + "name": "setParticleSizeVariation", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "QQuickDirection*" + } + ], + "index": 30, + "name": "setVelocity", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "QQuickDirection*" + } + ], + "index": 31, + "name": "setAcceleration", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "int" + } + ], + "index": 32, + "name": "setMaxParticleCount", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "int" + } + ], + "index": 33, + "name": "setStartTime", + "returnType": "void" + }, + { + "access": "public", + "index": 34, + "name": "reset", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickItem" + } + ] + } + ], + "inputFile": "qquickparticleemitter_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "ParticleExtruder" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + }, + { + "name": "QML.Creatable", + "value": "false" + }, + { + "name": "QML.UncreatableReason", + "value": "Abstract type. Use one of the inheriting types instead." + } + ], + "className": "QQuickParticleExtruder", + "lineNumber": 27, + "object": true, + "qualifiedClassName": "QQuickParticleExtruder", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qquickparticleextruder_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "DefaultProperty", + "value": "particleChildren" + }, + { + "name": "QML.Element", + "value": "ParticleGroup" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickParticleGroup", + "interfaces": [ + [ + { + "className": "QQmlParserStatus", + "id": "\"org.qt-project.Qt.QQmlParserStatus\"" + } + ] + ], + "lineNumber": 22, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "system", + "notify": "systemChanged", + "read": "system", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickParticleSystem*", + "user": false, + "write": "setSystem" + }, + { + "constant": false, + "designable": false, + "final": false, + "index": 1, + "name": "particleChildren", + "read": "particleChildren", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlListProperty", + "user": false + } + ], + "qualifiedClassName": "QQuickParticleGroup", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "QQuickParticleSystem*" + } + ], + "index": 0, + "name": "systemChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "QQuickParticleSystem*" + } + ], + "index": 1, + "name": "setSystem", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "obj", + "type": "QObject*" + } + ], + "index": 2, + "name": "delayRedirect", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickStochasticState" + }, + { + "access": "public", + "name": "QQmlParserStatus" + } + ] + } + ], + "inputFile": "qquickparticlegroup_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "ParticlePainter" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + }, + { + "name": "QML.Creatable", + "value": "false" + }, + { + "name": "QML.UncreatableReason", + "value": "Abstract type. Use one of the inheriting types instead." + } + ], + "className": "QQuickParticlePainter", + "lineNumber": 25, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "system", + "notify": "systemChanged", + "read": "system", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickParticleSystem*", + "user": false, + "write": "setSystem" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "groups", + "notify": "groupsChanged", + "read": "groups", + "required": false, + "scriptable": true, + "stored": true, + "type": "QStringList", + "user": false, + "write": "setGroups" + } + ], + "qualifiedClassName": "QQuickParticlePainter", + "signals": [ + { + "access": "public", + "index": 0, + "name": "countChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "QQuickParticleSystem*" + } + ], + "index": 1, + "name": "systemChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "QStringList" + } + ], + "index": 2, + "name": "groupsChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "QQuickParticleSystem*" + } + ], + "index": 3, + "name": "setSystem", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "QStringList" + } + ], + "index": 4, + "name": "setGroups", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "resetPending", + "type": "bool" + } + ], + "index": 5, + "name": "calcSystemOffset", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "isCloned": true, + "name": "calcSystemOffset", + "returnType": "void" + }, + { + "access": "private", + "index": 7, + "name": "sceneGraphInvalidated", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickItem" + } + ] + } + ], + "inputFile": "qquickparticlepainter_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "ParticleSystem" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickParticleSystem", + "lineNumber": 308, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "running", + "notify": "runningChanged", + "read": "isRunning", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setRunning" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "paused", + "notify": "pausedChanged", + "read": "isPaused", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setPaused" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "empty", + "notify": "emptyChanged", + "read": "isEmpty", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + } + ], + "qualifiedClassName": "QQuickParticleSystem", + "signals": [ + { + "access": "public", + "index": 0, + "name": "systemInitialized", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "bool" + } + ], + "index": 1, + "name": "runningChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "bool" + } + ], + "index": 2, + "name": "pausedChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "bool" + } + ], + "index": 3, + "name": "emptyChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "index": 4, + "name": "start", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "stop", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "restart", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "pause", + "returnType": "void" + }, + { + "access": "public", + "index": 8, + "name": "resume", + "returnType": "void" + }, + { + "access": "public", + "index": 9, + "name": "reset", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "bool" + } + ], + "index": 10, + "name": "setRunning", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "bool" + } + ], + "index": 11, + "name": "setPaused", + "returnType": "void" + }, + { + "access": "public", + "index": 12, + "name": "duration", + "returnType": "int" + }, + { + "access": "private", + "index": 13, + "name": "emittersChanged", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "p", + "type": "QQuickParticlePainter*" + } + ], + "index": 14, + "name": "loadPainter", + "returnType": "void" + }, + { + "access": "private", + "index": 15, + "name": "createEngine", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "idx", + "type": "int" + } + ], + "index": 16, + "name": "particleStateChange", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickItem" + } + ] + }, + { + "className": "QQuickParticleSystemAnimation", + "lineNumber": 438, + "object": true, + "qualifiedClassName": "QQuickParticleSystemAnimation", + "superClasses": [ + { + "access": "public", + "name": "QAbstractAnimation" + } + ] + } + ], + "inputFile": "qquickparticlesystem_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "Attractor" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickAttractorAffector", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "Proportion", + "values": [ + "Constant", + "Linear", + "Quadratic", + "InverseLinear", + "InverseQuadratic" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "AffectableParameters", + "values": [ + "Position", + "Velocity", + "Acceleration" + ] + } + ], + "lineNumber": 21, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "strength", + "notify": "strengthChanged", + "read": "strength", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setStrength" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "pointX", + "notify": "pointXChanged", + "read": "pointX", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setPointX" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "pointY", + "notify": "pointYChanged", + "read": "pointY", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setPointY" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "affectedParameter", + "notify": "affectedParameterChanged", + "read": "affectedParameter", + "required": false, + "scriptable": true, + "stored": true, + "type": "AffectableParameters", + "user": false, + "write": "setAffectedParameter" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "proportionalToDistance", + "notify": "proportionalToDistanceChanged", + "read": "proportionalToDistance", + "required": false, + "scriptable": true, + "stored": true, + "type": "Proportion", + "user": false, + "write": "setProportionalToDistance" + } + ], + "qualifiedClassName": "QQuickAttractorAffector", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 0, + "name": "strengthChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 1, + "name": "pointXChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 2, + "name": "pointYChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "AffectableParameters" + } + ], + "index": 3, + "name": "affectedParameterChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "Proportion" + } + ], + "index": 4, + "name": "proportionalToDistanceChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 5, + "name": "setStrength", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 6, + "name": "setPointX", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 7, + "name": "setPointY", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "AffectableParameters" + } + ], + "index": 8, + "name": "setAffectedParameter", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "Proportion" + } + ], + "index": 9, + "name": "setProportionalToDistance", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickParticleAffector" + } + ] + } + ], + "inputFile": "qquickpointattractor_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "PointDirection" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickPointDirection", + "lineNumber": 21, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "x", + "notify": "xChanged", + "read": "x", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setX" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "y", + "notify": "yChanged", + "read": "y", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setY" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "xVariation", + "notify": "xVariationChanged", + "read": "xVariation", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setXVariation" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "yVariation", + "notify": "yVariationChanged", + "read": "yVariation", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setYVariation" + } + ], + "qualifiedClassName": "QQuickPointDirection", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 0, + "name": "xChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 1, + "name": "yChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 2, + "name": "xVariationChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 3, + "name": "yVariationChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 4, + "name": "setX", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 5, + "name": "setY", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 6, + "name": "setXVariation", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 7, + "name": "setYVariation", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickDirection" + } + ] + } + ], + "inputFile": "qquickpointdirection_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "RectangleShape" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickRectangleExtruder", + "lineNumber": 22, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "fill", + "notify": "fillChanged", + "read": "fill", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setFill" + } + ], + "qualifiedClassName": "QQuickRectangleExtruder", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "bool" + } + ], + "index": 0, + "name": "fillChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "bool" + } + ], + "index": 1, + "name": "setFill", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickParticleExtruder" + } + ] + } + ], + "inputFile": "qquickrectangleextruder_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "SpriteGoal" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickSpriteGoalAffector", + "lineNumber": 24, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "goalState", + "notify": "goalStateChanged", + "read": "goalState", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setGoalState" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "jump", + "notify": "jumpChanged", + "read": "jump", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setJump" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "systemStates", + "notify": "systemStatesChanged", + "read": "systemStates", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setSystemStates" + } + ], + "qualifiedClassName": "QQuickSpriteGoalAffector", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "QString" + } + ], + "index": 0, + "name": "goalStateChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "bool" + } + ], + "index": 1, + "name": "jumpChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "bool" + } + ], + "index": 2, + "name": "systemStatesChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "QString" + } + ], + "index": 3, + "name": "setGoalState", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "bool" + } + ], + "index": 4, + "name": "setJump", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "bool" + } + ], + "index": 5, + "name": "setSystemStates", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickParticleAffector" + } + ] + } + ], + "inputFile": "qquickspritegoal_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "TargetDirection" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickTargetDirection", + "lineNumber": 23, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "targetX", + "notify": "targetXChanged", + "read": "targetX", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setTargetX" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "targetY", + "notify": "targetYChanged", + "read": "targetY", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setTargetY" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "targetItem", + "notify": "targetItemChanged", + "read": "targetItem", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false, + "write": "setTargetItem" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "targetVariation", + "notify": "targetVariationChanged", + "read": "targetVariation", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setTargetVariation" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "proportionalMagnitude", + "notify": "proprotionalMagnitudeChanged", + "read": "proportionalMagnitude", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setProportionalMagnitude" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "magnitude", + "notify": "magnitudeChanged", + "read": "magnitude", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setMagnitude" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "magnitudeVariation", + "notify": "magnitudeVariationChanged", + "read": "magnitudeVariation", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setMagnitudeVariation" + } + ], + "qualifiedClassName": "QQuickTargetDirection", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 0, + "name": "targetXChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 1, + "name": "targetYChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 2, + "name": "targetVariationChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 3, + "name": "magnitudeChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "bool" + } + ], + "index": 4, + "name": "proprotionalMagnitudeChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 5, + "name": "magnitudeVariationChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "QQuickItem*" + } + ], + "index": 6, + "name": "targetItemChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 7, + "name": "setTargetX", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 8, + "name": "setTargetY", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 9, + "name": "setTargetVariation", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 10, + "name": "setMagnitude", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "bool" + } + ], + "index": 11, + "name": "setProportionalMagnitude", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 12, + "name": "setMagnitudeVariation", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "QQuickItem*" + } + ], + "index": 13, + "name": "setTargetItem", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickDirection" + } + ] + } + ], + "inputFile": "qquicktargetdirection_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "TrailEmitter" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickTrailEmitter", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "EmitSize", + "values": [ + "ParticleSize" + ] + } + ], + "lineNumber": 22, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "follow", + "notify": "followChanged", + "read": "follow", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setFollow" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "emitRatePerParticle", + "notify": "particlesPerParticlePerSecondChanged", + "read": "particlesPerParticlePerSecond", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setParticlesPerParticlePerSecond" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "emitShape", + "notify": "emissionShapeChanged", + "read": "emissonShape", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickParticleExtruder*", + "user": false, + "write": "setEmissionShape" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "emitHeight", + "notify": "emitterYVariationChanged", + "read": "emitterYVariation", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setEmitterYVariation" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "emitWidth", + "notify": "emitterXVariationChanged", + "read": "emitterXVariation", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setEmitterXVariation" + } + ], + "qualifiedClassName": "QQuickTrailEmitter", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "particles", + "type": "QList" + }, + { + "name": "followed", + "type": "QQuickV4ParticleData" + } + ], + "index": 0, + "name": "emitFollowParticles", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "int" + } + ], + "index": 1, + "name": "particlesPerParticlePerSecondChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 2, + "name": "emitterXVariationChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 3, + "name": "emitterYVariationChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "QString" + } + ], + "index": 4, + "name": "followChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "QQuickParticleExtruder*" + } + ], + "index": 5, + "name": "emissionShapeChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "int" + } + ], + "index": 6, + "name": "setParticlesPerParticlePerSecond", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 7, + "name": "setEmitterXVariation", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 8, + "name": "setEmitterYVariation", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "QString" + } + ], + "index": 9, + "name": "setFollow", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "QQuickParticleExtruder*" + } + ], + "index": 10, + "name": "setEmissionShape", + "returnType": "void" + }, + { + "access": "private", + "index": 11, + "name": "recalcParticlesPerSecond", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickParticleEmitter" + } + ] + } + ], + "inputFile": "qquicktrailemitter_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "Turbulence" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickTurbulenceAffector", + "lineNumber": 24, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "strength", + "notify": "strengthChanged", + "read": "strength", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setStrength" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "noiseSource", + "notify": "noiseSourceChanged", + "read": "noiseSource", + "required": false, + "scriptable": true, + "stored": true, + "type": "QUrl", + "user": false, + "write": "setNoiseSource" + } + ], + "qualifiedClassName": "QQuickTurbulenceAffector", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 0, + "name": "strengthChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "QUrl" + } + ], + "index": 1, + "name": "noiseSourceChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 2, + "name": "setStrength", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "QUrl" + } + ], + "index": 3, + "name": "setNoiseSource", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickParticleAffector" + } + ] + } + ], + "inputFile": "qquickturbulence_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "Wander" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickWanderAffector", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "AffectableParameters", + "values": [ + "Position", + "Velocity", + "Acceleration" + ] + } + ], + "lineNumber": 31, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "pace", + "notify": "paceChanged", + "read": "pace", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setPace" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "xVariance", + "notify": "xVarianceChanged", + "read": "xVariance", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setXVariance" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "yVariance", + "notify": "yVarianceChanged", + "read": "yVariance", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setYVariance" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "affectedParameter", + "notify": "affectedParameterChanged", + "read": "affectedParameter", + "required": false, + "scriptable": true, + "stored": true, + "type": "AffectableParameters", + "user": false, + "write": "setAffectedParameter" + } + ], + "qualifiedClassName": "QQuickWanderAffector", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 0, + "name": "xVarianceChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 1, + "name": "yVarianceChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 2, + "name": "paceChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "AffectableParameters" + } + ], + "index": 3, + "name": "affectedParameterChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 4, + "name": "setXVariance", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 5, + "name": "setYVariance", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "qreal" + } + ], + "index": 6, + "name": "setPace", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "arg", + "type": "AffectableParameters" + } + ], + "index": 7, + "name": "setAffectedParameter", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickParticleAffector" + } + ] + } + ], + "inputFile": "qquickwander_p.h", + "outputRevision": 68 + } +] diff --git a/qt/6.8.1/msvc2022_64/metatypes/qt6quickshapesprivate_metatypes.json b/qt/6.8.1/msvc2022_64/metatypes/qt6quickshapesprivate_metatypes.json new file mode 100644 index 0000000000000000000000000000000000000000..80c7b008e61f0ac7839f9457630ec374a8daf841 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/metatypes/qt6quickshapesprivate_metatypes.json @@ -0,0 +1,1319 @@ +[ + { + "classes": [ + { + "className": "QQuickShapeCurveRunnable", + "lineNumber": 143, + "object": true, + "qualifiedClassName": "QQuickShapeCurveRunnable", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "self", + "type": "QQuickShapeCurveRunnable*" + } + ], + "index": 0, + "name": "done", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QRunnable" + } + ] + } + ], + "inputFile": "qquickshapecurverenderer_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "DefaultProperty", + "value": "stops" + }, + { + "name": "QML.Element", + "value": "ShapeGradient" + }, + { + "name": "QML.AddedInVersion", + "value": "256" + }, + { + "name": "QML.Creatable", + "value": "false" + }, + { + "name": "QML.UncreatableReason", + "value": "ShapeGradient is an abstract base class." + } + ], + "className": "QQuickShapeGradient", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "SpreadMode", + "values": [ + "PadSpread", + "ReflectSpread", + "RepeatSpread" + ] + } + ], + "lineNumber": 38, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "spread", + "notify": "spreadChanged", + "read": "spread", + "required": false, + "scriptable": true, + "stored": true, + "type": "SpreadMode", + "user": false, + "write": "setSpread" + } + ], + "qualifiedClassName": "QQuickShapeGradient", + "signals": [ + { + "access": "public", + "index": 0, + "name": "spreadChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickGradient" + } + ] + }, + { + "classInfos": [ + { + "name": "DefaultProperty", + "value": "stops" + }, + { + "name": "QML.Element", + "value": "LinearGradient" + }, + { + "name": "QML.AddedInVersion", + "value": "256" + } + ], + "className": "QQuickShapeLinearGradient", + "lineNumber": 68, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "x1", + "notify": "x1Changed", + "read": "x1", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setX1" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "y1", + "notify": "y1Changed", + "read": "y1", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setY1" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "x2", + "notify": "x2Changed", + "read": "x2", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setX2" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "y2", + "notify": "y2Changed", + "read": "y2", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setY2" + } + ], + "qualifiedClassName": "QQuickShapeLinearGradient", + "signals": [ + { + "access": "public", + "index": 0, + "name": "x1Changed", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "y1Changed", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "x2Changed", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "y2Changed", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickShapeGradient" + } + ] + }, + { + "classInfos": [ + { + "name": "DefaultProperty", + "value": "stops" + }, + { + "name": "QML.Element", + "value": "RadialGradient" + }, + { + "name": "QML.AddedInVersion", + "value": "256" + } + ], + "className": "QQuickShapeRadialGradient", + "lineNumber": 102, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "centerX", + "notify": "centerXChanged", + "read": "centerX", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setCenterX" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "centerY", + "notify": "centerYChanged", + "read": "centerY", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setCenterY" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "centerRadius", + "notify": "centerRadiusChanged", + "read": "centerRadius", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setCenterRadius" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "focalX", + "notify": "focalXChanged", + "read": "focalX", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setFocalX" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "focalY", + "notify": "focalYChanged", + "read": "focalY", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setFocalY" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "focalRadius", + "notify": "focalRadiusChanged", + "read": "focalRadius", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setFocalRadius" + } + ], + "qualifiedClassName": "QQuickShapeRadialGradient", + "signals": [ + { + "access": "public", + "index": 0, + "name": "centerXChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "centerYChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "focalXChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "focalYChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "centerRadiusChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "focalRadiusChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickShapeGradient" + } + ] + }, + { + "classInfos": [ + { + "name": "DefaultProperty", + "value": "stops" + }, + { + "name": "QML.Element", + "value": "ConicalGradient" + }, + { + "name": "QML.AddedInVersion", + "value": "256" + } + ], + "className": "QQuickShapeConicalGradient", + "lineNumber": 151, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "centerX", + "notify": "centerXChanged", + "read": "centerX", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setCenterX" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "centerY", + "notify": "centerYChanged", + "read": "centerY", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setCenterY" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "angle", + "notify": "angleChanged", + "read": "angle", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setAngle" + } + ], + "qualifiedClassName": "QQuickShapeConicalGradient", + "signals": [ + { + "access": "public", + "index": 0, + "name": "centerXChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "centerYChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "angleChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickShapeGradient" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "ShapePath" + }, + { + "name": "QML.AddedInVersion", + "value": "256" + } + ], + "className": "QQuickShapePath", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "FillRule", + "values": [ + "OddEvenFill", + "WindingFill" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "JoinStyle", + "values": [ + "MiterJoin", + "BevelJoin", + "RoundJoin" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "CapStyle", + "values": [ + "FlatCap", + "SquareCap", + "RoundCap" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "StrokeStyle", + "values": [ + "SolidLine", + "DashLine" + ] + }, + { + "alias": "PathHint", + "isClass": false, + "isFlag": true, + "name": "PathHints", + "values": [ + "PathLinear", + "PathQuadratic", + "PathConvex", + "PathFillOnRight", + "PathSolid", + "PathNonIntersecting", + "PathNonOverlappingControlPointTriangles" + ] + } + ], + "lineNumber": 183, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "strokeColor", + "notify": "strokeColorChanged", + "read": "strokeColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false, + "write": "setStrokeColor" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "strokeWidth", + "notify": "strokeWidthChanged", + "read": "strokeWidth", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setStrokeWidth" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "fillColor", + "notify": "fillColorChanged", + "read": "fillColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false, + "write": "setFillColor" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "fillRule", + "notify": "fillRuleChanged", + "read": "fillRule", + "required": false, + "scriptable": true, + "stored": true, + "type": "FillRule", + "user": false, + "write": "setFillRule" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "joinStyle", + "notify": "joinStyleChanged", + "read": "joinStyle", + "required": false, + "scriptable": true, + "stored": true, + "type": "JoinStyle", + "user": false, + "write": "setJoinStyle" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "miterLimit", + "notify": "miterLimitChanged", + "read": "miterLimit", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setMiterLimit" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "capStyle", + "notify": "capStyleChanged", + "read": "capStyle", + "required": false, + "scriptable": true, + "stored": true, + "type": "CapStyle", + "user": false, + "write": "setCapStyle" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 7, + "name": "strokeStyle", + "notify": "strokeStyleChanged", + "read": "strokeStyle", + "required": false, + "scriptable": true, + "stored": true, + "type": "StrokeStyle", + "user": false, + "write": "setStrokeStyle" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 8, + "name": "dashOffset", + "notify": "dashOffsetChanged", + "read": "dashOffset", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setDashOffset" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 9, + "name": "dashPattern", + "notify": "dashPatternChanged", + "read": "dashPattern", + "required": false, + "scriptable": true, + "stored": true, + "type": "QList", + "user": false, + "write": "setDashPattern" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 10, + "name": "fillGradient", + "read": "fillGradient", + "required": false, + "reset": "resetFillGradient", + "scriptable": true, + "stored": true, + "type": "QQuickShapeGradient*", + "user": false, + "write": "setFillGradient" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 11, + "name": "scale", + "notify": "scaleChanged", + "read": "scale", + "required": false, + "revision": 270, + "scriptable": true, + "stored": true, + "type": "QSizeF", + "user": false, + "write": "setScale" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 12, + "name": "pathHints", + "notify": "pathHintsChanged", + "read": "pathHints", + "required": false, + "revision": 1543, + "scriptable": true, + "stored": true, + "type": "PathHints", + "user": false, + "write": "setPathHints" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 13, + "name": "fillTransform", + "notify": "fillTransformChanged", + "read": "fillTransform", + "required": false, + "revision": 1544, + "scriptable": true, + "stored": true, + "type": "QMatrix4x4", + "user": false, + "write": "setFillTransform" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 14, + "name": "fillItem", + "notify": "fillItemChanged", + "read": "fillItem", + "required": false, + "revision": 1544, + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false, + "write": "setFillItem" + } + ], + "qualifiedClassName": "QQuickShapePath", + "signals": [ + { + "access": "public", + "index": 0, + "name": "shapePathChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "strokeColorChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "strokeWidthChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "fillColorChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "fillRuleChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "joinStyleChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "miterLimitChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "capStyleChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 8, + "name": "strokeStyleChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 9, + "name": "dashOffsetChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 10, + "name": "dashPatternChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 11, + "name": "pathHintsChanged", + "returnType": "void", + "revision": 1543 + }, + { + "access": "public", + "index": 12, + "name": "fillTransformChanged", + "returnType": "void", + "revision": 1544 + }, + { + "access": "public", + "index": 13, + "name": "fillItemChanged", + "returnType": "void", + "revision": 1544 + } + ], + "slots": [ + { + "access": "private", + "index": 14, + "name": "_q_fillGradientChanged", + "returnType": "void" + }, + { + "access": "private", + "index": 15, + "name": "_q_fillItemDestroyed", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickPath" + } + ] + }, + { + "classInfos": [ + { + "name": "DefaultProperty", + "value": "data" + }, + { + "name": "QML.Element", + "value": "Shape" + }, + { + "name": "QML.AddedInVersion", + "value": "256" + } + ], + "className": "QQuickShape", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "RendererType", + "values": [ + "UnknownRenderer", + "GeometryRenderer", + "NvprRenderer", + "SoftwareRenderer", + "CurveRenderer" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "Status", + "values": [ + "Null", + "Ready", + "Processing" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "ContainsMode", + "values": [ + "BoundingRectContains", + "FillContains" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "FillMode", + "values": [ + "NoResize", + "PreserveAspectFit", + "PreserveAspectCrop", + "Stretch" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "HAlignment", + "values": [ + "AlignLeft", + "AlignRight", + "AlignHCenter" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "VAlignment", + "values": [ + "AlignTop", + "AlignBottom", + "AlignVCenter" + ] + } + ], + "lineNumber": 316, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "rendererType", + "notify": "rendererChanged", + "read": "rendererType", + "required": false, + "scriptable": true, + "stored": true, + "type": "RendererType", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "asynchronous", + "notify": "asynchronousChanged", + "read": "asynchronous", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setAsynchronous" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "vendorExtensionsEnabled", + "notify": "vendorExtensionsEnabledChanged", + "read": "vendorExtensionsEnabled", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setVendorExtensionsEnabled" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "preferredRendererType", + "notify": "preferredRendererTypeChanged", + "read": "preferredRendererType", + "required": false, + "revision": 1542, + "scriptable": true, + "stored": true, + "type": "RendererType", + "user": false, + "write": "setPreferredRendererType" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "status", + "notify": "statusChanged", + "read": "status", + "required": false, + "scriptable": true, + "stored": true, + "type": "Status", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "containsMode", + "notify": "containsModeChanged", + "read": "containsMode", + "required": false, + "revision": 267, + "scriptable": true, + "stored": true, + "type": "ContainsMode", + "user": false, + "write": "setContainsMode" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 6, + "name": "boundingRect", + "notify": "boundingRectChanged", + "read": "boundingRect", + "required": false, + "revision": 1542, + "scriptable": true, + "stored": true, + "type": "QRectF", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 7, + "name": "fillMode", + "notify": "fillModeChanged", + "read": "fillMode", + "required": false, + "revision": 1543, + "scriptable": true, + "stored": true, + "type": "FillMode", + "user": false, + "write": "setFillMode" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 8, + "name": "horizontalAlignment", + "notify": "horizontalAlignmentChanged", + "read": "horizontalAlignment", + "required": false, + "revision": 1543, + "scriptable": true, + "stored": true, + "type": "HAlignment", + "user": false, + "write": "setHorizontalAlignment" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 9, + "name": "verticalAlignment", + "notify": "verticalAlignmentChanged", + "read": "verticalAlignment", + "required": false, + "revision": 1543, + "scriptable": true, + "stored": true, + "type": "VAlignment", + "user": false, + "write": "setVerticalAlignment" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 10, + "name": "data", + "read": "data", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlListProperty", + "user": false + } + ], + "qualifiedClassName": "QQuickShape", + "signals": [ + { + "access": "public", + "index": 0, + "name": "rendererChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "asynchronousChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "vendorExtensionsEnabledChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "statusChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "preferredRendererTypeChanged", + "returnType": "void", + "revision": 1542 + }, + { + "access": "public", + "index": 5, + "name": "boundingRectChanged", + "returnType": "void", + "revision": 1542 + }, + { + "access": "public", + "index": 6, + "name": "containsModeChanged", + "returnType": "void", + "revision": 267 + }, + { + "access": "public", + "index": 7, + "name": "fillModeChanged", + "returnType": "void", + "revision": 1543 + }, + { + "access": "public", + "index": 8, + "name": "horizontalAlignmentChanged", + "returnType": "void", + "revision": 1543 + }, + { + "access": "public", + "index": 9, + "name": "verticalAlignmentChanged", + "returnType": "void", + "revision": 1543 + } + ], + "slots": [ + { + "access": "private", + "index": 10, + "name": "_q_shapePathChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickItem" + } + ] + } + ], + "inputFile": "qquickshape_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQuickShapeFillRunnable", + "lineNumber": 139, + "object": true, + "qualifiedClassName": "QQuickShapeFillRunnable", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "self", + "type": "QQuickShapeFillRunnable*" + } + ], + "index": 0, + "name": "done", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QRunnable" + } + ] + }, + { + "className": "QQuickShapeStrokeRunnable", + "lineNumber": 163, + "object": true, + "qualifiedClassName": "QQuickShapeStrokeRunnable", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "self", + "type": "QQuickShapeStrokeRunnable*" + } + ], + "index": 0, + "name": "done", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QRunnable" + } + ] + }, + { + "className": "QQuickShapeGenericStrokeFillNode", + "lineNumber": 186, + "object": true, + "qualifiedClassName": "QQuickShapeGenericStrokeFillNode", + "slots": [ + { + "access": "private", + "index": 0, + "name": "handleTextureChanged", + "returnType": "void" + }, + { + "access": "private", + "index": 1, + "name": "handleTextureProviderDestroyed", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QSGGeometryNode" + } + ] + } + ], + "inputFile": "qquickshapegenericrenderer_p.h", + "outputRevision": 68 + } +] diff --git a/qt/6.8.1/msvc2022_64/metatypes/qt6quicktemplates2_metatypes.json b/qt/6.8.1/msvc2022_64/metatypes/qt6quicktemplates2_metatypes.json new file mode 100644 index 0000000000000000000000000000000000000000..e60b7f98bd459c5c2116116a508bbad3c0d55204 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/metatypes/qt6quicktemplates2_metatypes.json @@ -0,0 +1,16714 @@ +[ + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + } + ], + "className": "QQuickPopupWindow", + "lineNumber": 26, + "object": true, + "qualifiedClassName": "QQuickPopupWindow", + "superClasses": [ + { + "access": "public", + "name": "QQuickWindowQmlImpl" + } + ] + } + ], + "inputFile": "qquickpopupwindow_p_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "DeferredPropertyNames", + "value": "background,contentItem,indicator" + }, + { + "name": "QML.Element", + "value": "AbstractButton" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickAbstractButton", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "Display", + "values": [ + "IconOnly", + "TextOnly", + "TextBesideIcon", + "TextUnderIcon" + ] + } + ], + "lineNumber": 26, + "methods": [ + { + "access": "protected", + "index": 27, + "name": "accessiblePressAction", + "returnType": "void" + } + ], + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "text", + "notify": "textChanged", + "read": "text", + "required": false, + "reset": "resetText", + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setText" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "down", + "notify": "downChanged", + "read": "isDown", + "required": false, + "reset": "resetDown", + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setDown" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "pressed", + "notify": "pressedChanged", + "read": "isPressed", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "checked", + "notify": "checkedChanged", + "read": "isChecked", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setChecked" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "checkable", + "notify": "checkableChanged", + "read": "isCheckable", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setCheckable" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "autoExclusive", + "notify": "autoExclusiveChanged", + "read": "autoExclusive", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setAutoExclusive" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 6, + "name": "autoRepeat", + "notify": "autoRepeatChanged", + "read": "autoRepeat", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setAutoRepeat" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 7, + "name": "indicator", + "notify": "indicatorChanged", + "read": "indicator", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false, + "write": "setIndicator" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 8, + "name": "icon", + "notify": "iconChanged", + "read": "icon", + "required": false, + "revision": 515, + "scriptable": true, + "stored": true, + "type": "QQuickIcon", + "user": false, + "write": "setIcon" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 9, + "name": "display", + "notify": "displayChanged", + "read": "display", + "required": false, + "revision": 515, + "scriptable": true, + "stored": true, + "type": "Display", + "user": false, + "write": "setDisplay" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 10, + "name": "action", + "notify": "actionChanged", + "read": "action", + "required": false, + "revision": 515, + "scriptable": true, + "stored": true, + "type": "QQuickAction*", + "user": false, + "write": "setAction" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 11, + "name": "autoRepeatDelay", + "notify": "autoRepeatDelayChanged", + "read": "autoRepeatDelay", + "required": false, + "revision": 516, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setAutoRepeatDelay" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 12, + "name": "autoRepeatInterval", + "notify": "autoRepeatIntervalChanged", + "read": "autoRepeatInterval", + "required": false, + "revision": 516, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setAutoRepeatInterval" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 13, + "name": "pressX", + "notify": "pressXChanged", + "read": "pressX", + "required": false, + "revision": 516, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 14, + "name": "pressY", + "notify": "pressYChanged", + "read": "pressY", + "required": false, + "revision": 516, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 15, + "name": "implicitIndicatorWidth", + "notify": "implicitIndicatorWidthChanged", + "read": "implicitIndicatorWidth", + "required": false, + "revision": 517, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 16, + "name": "implicitIndicatorHeight", + "notify": "implicitIndicatorHeightChanged", + "read": "implicitIndicatorHeight", + "required": false, + "revision": 517, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + } + ], + "qualifiedClassName": "QQuickAbstractButton", + "signals": [ + { + "access": "public", + "index": 0, + "name": "pressed", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "released", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "canceled", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "clicked", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "pressAndHold", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "doubleClicked", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "textChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "downChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 8, + "name": "pressedChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 9, + "name": "checkedChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 10, + "name": "checkableChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 11, + "name": "autoExclusiveChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 12, + "name": "autoRepeatChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 13, + "name": "indicatorChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 14, + "name": "toggled", + "returnType": "void", + "revision": 514 + }, + { + "access": "public", + "index": 15, + "name": "iconChanged", + "returnType": "void", + "revision": 515 + }, + { + "access": "public", + "index": 16, + "name": "displayChanged", + "returnType": "void", + "revision": 515 + }, + { + "access": "public", + "index": 17, + "name": "actionChanged", + "returnType": "void", + "revision": 515 + }, + { + "access": "public", + "index": 18, + "name": "autoRepeatDelayChanged", + "returnType": "void", + "revision": 516 + }, + { + "access": "public", + "index": 19, + "name": "autoRepeatIntervalChanged", + "returnType": "void", + "revision": 516 + }, + { + "access": "public", + "index": 20, + "name": "pressXChanged", + "returnType": "void", + "revision": 516 + }, + { + "access": "public", + "index": 21, + "name": "pressYChanged", + "returnType": "void", + "revision": 516 + }, + { + "access": "public", + "index": 22, + "name": "implicitIndicatorWidthChanged", + "returnType": "void", + "revision": 517 + }, + { + "access": "public", + "index": 23, + "name": "implicitIndicatorHeightChanged", + "returnType": "void", + "revision": 517 + } + ], + "slots": [ + { + "access": "public", + "index": 24, + "name": "toggle", + "returnType": "void" + }, + { + "access": "public", + "index": 25, + "name": "click", + "returnType": "void", + "revision": 1544 + }, + { + "access": "public", + "index": 26, + "name": "animateClick", + "returnType": "void", + "revision": 1544 + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickControl" + } + ] + } + ], + "inputFile": "qquickabstractbutton_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "Action" + }, + { + "name": "QML.AddedInVersion", + "value": "515" + } + ], + "className": "QQuickAction", + "lineNumber": 28, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "text", + "notify": "textChanged", + "read": "text", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setText" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "icon", + "notify": "iconChanged", + "read": "icon", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickIcon", + "user": false, + "write": "setIcon" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "enabled", + "notify": "enabledChanged", + "read": "isEnabled", + "required": false, + "reset": "resetEnabled", + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setEnabled" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "checked", + "notify": "checkedChanged", + "read": "isChecked", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setChecked" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "checkable", + "notify": "checkableChanged", + "read": "isCheckable", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setCheckable" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "shortcut", + "notify": "shortcutChanged", + "privateClass": "QQuickAction::d_func()", + "read": "shortcut", + "required": false, + "scriptable": true, + "stored": true, + "type": "QVariant", + "user": false, + "write": "setShortcut" + } + ], + "qualifiedClassName": "QQuickAction", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "text", + "type": "QString" + } + ], + "index": 0, + "name": "textChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "icon", + "type": "QQuickIcon" + } + ], + "index": 1, + "name": "iconChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "enabled", + "type": "bool" + } + ], + "index": 2, + "name": "enabledChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "checked", + "type": "bool" + } + ], + "index": 3, + "name": "checkedChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "checkable", + "type": "bool" + } + ], + "index": 4, + "name": "checkableChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "shortcut", + "type": "QKeySequence" + } + ], + "index": 5, + "name": "shortcutChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "source", + "type": "QObject*" + } + ], + "index": 6, + "name": "toggled", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "isCloned": true, + "name": "toggled", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "source", + "type": "QObject*" + } + ], + "index": 8, + "name": "triggered", + "returnType": "void" + }, + { + "access": "public", + "index": 9, + "isCloned": true, + "name": "triggered", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "source", + "type": "QObject*" + } + ], + "index": 10, + "name": "toggle", + "returnType": "void" + }, + { + "access": "public", + "index": 11, + "isCloned": true, + "name": "toggle", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "source", + "type": "QObject*" + } + ], + "index": 12, + "name": "trigger", + "returnType": "void" + }, + { + "access": "public", + "index": 13, + "isCloned": true, + "name": "trigger", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qquickaction_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "DefaultProperty", + "value": "actions" + }, + { + "name": "QML.Element", + "value": "ActionGroup" + }, + { + "name": "QML.Attached", + "value": "QQuickActionGroupAttached" + }, + { + "name": "QML.AddedInVersion", + "value": "515" + } + ], + "className": "QQuickActionGroup", + "lineNumber": 29, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "checkedAction", + "notify": "checkedActionChanged", + "read": "checkedAction", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickAction*", + "user": false, + "write": "setCheckedAction" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "actions", + "notify": "actionsChanged", + "read": "actions", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlListProperty", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "exclusive", + "notify": "exclusiveChanged", + "read": "isExclusive", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setExclusive" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "enabled", + "notify": "enabledChanged", + "read": "isEnabled", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setEnabled" + } + ], + "qualifiedClassName": "QQuickActionGroup", + "signals": [ + { + "access": "public", + "index": 0, + "name": "checkedActionChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "actionsChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "exclusiveChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "enabledChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "action", + "type": "QQuickAction*" + } + ], + "index": 4, + "name": "triggered", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "action", + "type": "QQuickAction*" + } + ], + "index": 5, + "name": "addAction", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "action", + "type": "QQuickAction*" + } + ], + "index": 6, + "name": "removeAction", + "returnType": "void" + }, + { + "access": "private", + "index": 7, + "name": "_q_updateCurrent", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "className": "QQuickActionGroupAttached", + "lineNumber": 76, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "group", + "notify": "groupChanged", + "read": "group", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickActionGroup*", + "user": false, + "write": "setGroup" + } + ], + "qualifiedClassName": "QQuickActionGroupAttached", + "signals": [ + { + "access": "public", + "index": 0, + "name": "groupChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qquickactiongroup_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "DeferredPropertyNames", + "value": "background" + }, + { + "name": "DefaultProperty", + "value": "contentData" + }, + { + "name": "QML.Element", + "value": "ApplicationWindow" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + }, + { + "name": "QML.Attached", + "value": "QQuickApplicationWindowAttached" + } + ], + "className": "QQuickApplicationWindow", + "lineNumber": 30, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "background", + "notify": "backgroundChanged", + "read": "background", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false, + "write": "setBackground" + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 1, + "name": "contentItem", + "read": "contentItem", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "contentData", + "privateClass": "QQuickApplicationWindow::d_func()", + "read": "contentData", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlListProperty", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "activeFocusControl", + "notify": "activeFocusControlChanged", + "read": "activeFocusControl", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "header", + "notify": "headerChanged", + "read": "header", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false, + "write": "setHeader" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "footer", + "notify": "footerChanged", + "read": "footer", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false, + "write": "setFooter" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 6, + "name": "font", + "notify": "fontChanged", + "read": "font", + "required": false, + "reset": "resetFont", + "scriptable": true, + "stored": true, + "type": "QFont", + "user": false, + "write": "setFont" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 7, + "name": "locale", + "notify": "localeChanged", + "read": "locale", + "required": false, + "reset": "resetLocale", + "scriptable": true, + "stored": true, + "type": "QLocale", + "user": false, + "write": "setLocale" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 8, + "name": "menuBar", + "notify": "menuBarChanged", + "read": "menuBar", + "required": false, + "revision": 515, + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false, + "write": "setMenuBar" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 9, + "name": "palette", + "notify": "paletteChanged", + "privateClass": "QQuickApplicationWindow::d_func()", + "read": "palette", + "required": false, + "reset": "resetPalette", + "revision": 515, + "scriptable": true, + "stored": true, + "type": "QQuickPalette*", + "user": false, + "write": "setPalette" + } + ], + "qualifiedClassName": "QQuickApplicationWindow", + "signals": [ + { + "access": "public", + "index": 0, + "name": "backgroundChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "activeFocusControlChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "headerChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "footerChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "fontChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "localeChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "menuBarChanged", + "returnType": "void", + "revision": 515 + } + ], + "slots": [ + { + "access": "private", + "index": 7, + "name": "_q_updateActiveFocus", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickWindowQmlImpl" + } + ] + }, + { + "className": "QQuickApplicationWindowAttached", + "lineNumber": 102, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "window", + "notify": "windowChanged", + "read": "window", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickApplicationWindow*", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "contentItem", + "notify": "contentItemChanged", + "read": "contentItem", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "activeFocusControl", + "notify": "activeFocusControlChanged", + "read": "activeFocusControl", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "header", + "notify": "headerChanged", + "read": "header", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "footer", + "notify": "footerChanged", + "read": "footer", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "menuBar", + "notify": "menuBarChanged", + "read": "menuBar", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false + } + ], + "qualifiedClassName": "QQuickApplicationWindowAttached", + "signals": [ + { + "access": "public", + "index": 0, + "name": "windowChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "contentItemChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "activeFocusControlChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "headerChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "footerChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "menuBarChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qquickapplicationwindow_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "BusyIndicator" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickBusyIndicator", + "lineNumber": 24, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "running", + "notify": "runningChanged", + "read": "isRunning", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setRunning" + } + ], + "qualifiedClassName": "QQuickBusyIndicator", + "signals": [ + { + "access": "public", + "index": 0, + "name": "runningChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickControl" + } + ] + } + ], + "inputFile": "qquickbusyindicator_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "Button" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickButton", + "lineNumber": 24, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "highlighted", + "notify": "highlightedChanged", + "read": "isHighlighted", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setHighlighted" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "flat", + "notify": "flatChanged", + "read": "isFlat", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setFlat" + } + ], + "qualifiedClassName": "QQuickButton", + "signals": [ + { + "access": "public", + "index": 0, + "name": "highlightedChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "flatChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickAbstractButton" + } + ] + } + ], + "inputFile": "qquickbutton_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "ButtonGroup" + }, + { + "name": "QML.Attached", + "value": "QQuickButtonGroupAttached" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickButtonGroup", + "interfaces": [ + [ + { + "className": "QQmlParserStatus", + "id": "\"org.qt-project.Qt.QQmlParserStatus\"" + } + ] + ], + "lineNumber": 30, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "checkedButton", + "notify": "checkedButtonChanged", + "read": "checkedButton", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickAbstractButton*", + "user": false, + "write": "setCheckedButton" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "buttons", + "notify": "buttonsChanged", + "read": "buttons", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlListProperty", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "exclusive", + "notify": "exclusiveChanged", + "read": "isExclusive", + "required": false, + "revision": 515, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setExclusive" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "checkState", + "notify": "checkStateChanged", + "read": "checkState", + "required": false, + "revision": 516, + "scriptable": true, + "stored": true, + "type": "Qt::CheckState", + "user": false, + "write": "setCheckState" + } + ], + "qualifiedClassName": "QQuickButtonGroup", + "signals": [ + { + "access": "public", + "index": 0, + "name": "checkedButtonChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "buttonsChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "button", + "type": "QQuickAbstractButton*" + } + ], + "index": 2, + "name": "clicked", + "returnType": "void", + "revision": 513 + }, + { + "access": "public", + "index": 3, + "name": "exclusiveChanged", + "returnType": "void", + "revision": 515 + }, + { + "access": "public", + "index": 4, + "name": "checkStateChanged", + "returnType": "void", + "revision": 516 + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "button", + "type": "QQuickAbstractButton*" + } + ], + "index": 5, + "name": "addButton", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "button", + "type": "QQuickAbstractButton*" + } + ], + "index": 6, + "name": "removeButton", + "returnType": "void" + }, + { + "access": "private", + "index": 7, + "name": "_q_updateCurrent", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QQmlParserStatus" + } + ] + }, + { + "className": "QQuickButtonGroupAttached", + "lineNumber": 87, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "group", + "notify": "groupChanged", + "read": "group", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickButtonGroup*", + "user": false, + "write": "setGroup" + } + ], + "qualifiedClassName": "QQuickButtonGroupAttached", + "signals": [ + { + "access": "public", + "index": 0, + "name": "groupChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qquickbuttongroup_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "Calendar" + }, + { + "name": "QML.AddedInVersion", + "value": "1539" + } + ], + "className": "QQuickCalendar", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "Month", + "values": [ + "January", + "February", + "March", + "April", + "May", + "June", + "July", + "August", + "September", + "October", + "November", + "December" + ] + } + ], + "lineNumber": 25, + "object": true, + "qualifiedClassName": "QQuickCalendar", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qquickcalendar_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "CalendarModel" + }, + { + "name": "QML.AddedInVersion", + "value": "1539" + } + ], + "className": "QQuickCalendarModel", + "interfaces": [ + [ + { + "className": "QQmlParserStatus", + "id": "\"org.qt-project.Qt.QQmlParserStatus\"" + } + ] + ], + "lineNumber": 28, + "methods": [ + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + } + ], + "index": 3, + "name": "monthAt", + "returnType": "int" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + } + ], + "index": 4, + "name": "yearAt", + "returnType": "int" + }, + { + "access": "public", + "arguments": [ + { + "name": "date", + "type": "QDate" + } + ], + "index": 5, + "name": "indexOf", + "returnType": "int" + }, + { + "access": "public", + "arguments": [ + { + "name": "year", + "type": "int" + }, + { + "name": "month", + "type": "int" + } + ], + "index": 6, + "name": "indexOf", + "returnType": "int" + } + ], + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "from", + "notify": "fromChanged", + "read": "from", + "required": false, + "scriptable": true, + "stored": true, + "type": "QDate", + "user": false, + "write": "setFrom" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "to", + "notify": "toChanged", + "read": "to", + "required": false, + "scriptable": true, + "stored": true, + "type": "QDate", + "user": false, + "write": "setTo" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "count", + "notify": "countChanged", + "read": "rowCount", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + } + ], + "qualifiedClassName": "QQuickCalendarModel", + "signals": [ + { + "access": "public", + "index": 0, + "name": "fromChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "toChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "countChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QAbstractListModel" + }, + { + "access": "public", + "name": "QQmlParserStatus" + } + ] + } + ], + "inputFile": "qquickcalendarmodel_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "CheckBox" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickCheckBox", + "lineNumber": 24, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "tristate", + "notify": "tristateChanged", + "read": "isTristate", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setTristate" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "checkState", + "notify": "checkStateChanged", + "read": "checkState", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::CheckState", + "user": false, + "write": "setCheckState" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "nextCheckState", + "notify": "nextCheckStateChanged", + "read": "getNextCheckState", + "required": false, + "revision": 516, + "scriptable": true, + "stored": true, + "type": "QJSValue", + "user": false, + "write": "setNextCheckState" + } + ], + "qualifiedClassName": "QQuickCheckBox", + "signals": [ + { + "access": "public", + "index": 0, + "name": "tristateChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "checkStateChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "nextCheckStateChanged", + "returnType": "void", + "revision": 516 + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickAbstractButton" + } + ] + } + ], + "inputFile": "qquickcheckbox_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "CheckDelegate" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickCheckDelegate", + "lineNumber": 24, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "tristate", + "notify": "tristateChanged", + "read": "isTristate", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setTristate" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "checkState", + "notify": "checkStateChanged", + "read": "checkState", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::CheckState", + "user": false, + "write": "setCheckState" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "member": "nextCheckState", + "name": "nextCheckState", + "notify": "nextCheckStateChanged", + "privateClass": "QQuickCheckDelegate::d_func()", + "required": false, + "revision": 516, + "scriptable": true, + "stored": true, + "type": "QJSValue", + "user": false, + "write": "setNextCheckState" + } + ], + "qualifiedClassName": "QQuickCheckDelegate", + "signals": [ + { + "access": "public", + "index": 0, + "name": "tristateChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "checkStateChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "nextCheckStateChanged", + "returnType": "void", + "revision": 516 + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickItemDelegate" + } + ] + } + ], + "inputFile": "qquickcheckdelegate_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "DeferredPropertyNames", + "value": "background,contentItem,indicator,popup" + }, + { + "name": "QML.Element", + "value": "ComboBox" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickComboBox", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "ImplicitContentWidthPolicy", + "values": [ + "ContentItemImplicitWidth", + "WidestText", + "WidestTextWhenCompleted" + ] + } + ], + "lineNumber": 33, + "methods": [ + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + } + ], + "index": 32, + "name": "textAt", + "returnType": "QString" + }, + { + "access": "public", + "arguments": [ + { + "name": "text", + "type": "QString" + }, + { + "name": "flags", + "type": "Qt::MatchFlags" + } + ], + "index": 33, + "name": "find", + "returnType": "int" + }, + { + "access": "public", + "arguments": [ + { + "name": "text", + "type": "QString" + } + ], + "index": 34, + "isCloned": true, + "name": "find", + "returnType": "int" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + } + ], + "index": 35, + "name": "valueAt", + "returnType": "QVariant", + "revision": 526 + }, + { + "access": "public", + "arguments": [ + { + "name": "value", + "type": "QVariant" + } + ], + "index": 36, + "name": "indexOfValue", + "returnType": "int", + "revision": 526 + } + ], + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "count", + "notify": "countChanged", + "read": "count", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "model", + "notify": "modelChanged", + "read": "model", + "required": false, + "scriptable": true, + "stored": true, + "type": "QVariant", + "user": false, + "write": "setModel" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "delegateModel", + "notify": "delegateModelChanged", + "read": "delegateModel", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlInstanceModel*", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "pressed", + "notify": "pressedChanged", + "read": "isPressed", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "highlightedIndex", + "notify": "highlightedIndexChanged", + "read": "highlightedIndex", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "currentIndex", + "notify": "currentIndexChanged", + "read": "currentIndex", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setCurrentIndex" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 6, + "name": "currentText", + "notify": "currentTextChanged", + "read": "currentText", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 7, + "name": "displayText", + "notify": "displayTextChanged", + "read": "displayText", + "required": false, + "reset": "resetDisplayText", + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setDisplayText" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 8, + "name": "textRole", + "notify": "textRoleChanged", + "read": "textRole", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setTextRole" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 9, + "name": "delegate", + "notify": "delegateChanged", + "read": "delegate", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlComponent*", + "user": false, + "write": "setDelegate" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 10, + "name": "indicator", + "notify": "indicatorChanged", + "read": "indicator", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false, + "write": "setIndicator" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 11, + "name": "popup", + "notify": "popupChanged", + "read": "popup", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickPopup*", + "user": false, + "write": "setPopup" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 12, + "name": "flat", + "notify": "flatChanged", + "read": "isFlat", + "required": false, + "revision": 513, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setFlat" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 13, + "name": "down", + "notify": "downChanged", + "read": "isDown", + "required": false, + "reset": "resetDown", + "revision": 514, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setDown" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 14, + "name": "editable", + "notify": "editableChanged", + "read": "isEditable", + "required": false, + "revision": 514, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setEditable" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 15, + "name": "editText", + "notify": "editTextChanged", + "read": "editText", + "required": false, + "reset": "resetEditText", + "revision": 514, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setEditText" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 16, + "name": "validator", + "notify": "validatorChanged", + "read": "validator", + "required": false, + "revision": 514, + "scriptable": true, + "stored": true, + "type": "QValidator*", + "user": false, + "write": "setValidator" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 17, + "name": "inputMethodHints", + "notify": "inputMethodHintsChanged", + "read": "inputMethodHints", + "required": false, + "revision": 514, + "scriptable": true, + "stored": true, + "type": "Qt::InputMethodHints", + "user": false, + "write": "setInputMethodHints" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 18, + "name": "inputMethodComposing", + "notify": "inputMethodComposingChanged", + "read": "isInputMethodComposing", + "required": false, + "revision": 514, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 19, + "name": "acceptableInput", + "notify": "acceptableInputChanged", + "read": "hasAcceptableInput", + "required": false, + "revision": 514, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 20, + "name": "implicitIndicatorWidth", + "notify": "implicitIndicatorWidthChanged", + "read": "implicitIndicatorWidth", + "required": false, + "revision": 517, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 21, + "name": "implicitIndicatorHeight", + "notify": "implicitIndicatorHeightChanged", + "read": "implicitIndicatorHeight", + "required": false, + "revision": 517, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 22, + "name": "currentValue", + "notify": "currentValueChanged", + "read": "currentValue", + "required": false, + "revision": 526, + "scriptable": true, + "stored": true, + "type": "QVariant", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 23, + "name": "valueRole", + "notify": "valueRoleChanged", + "read": "valueRole", + "required": false, + "revision": 526, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setValueRole" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 24, + "name": "selectTextByMouse", + "notify": "selectTextByMouseChanged", + "read": "selectTextByMouse", + "required": false, + "revision": 527, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setSelectTextByMouse" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 25, + "name": "implicitContentWidthPolicy", + "notify": "implicitContentWidthPolicyChanged", + "read": "implicitContentWidthPolicy", + "required": false, + "revision": 1536, + "scriptable": true, + "stored": true, + "type": "ImplicitContentWidthPolicy", + "user": false, + "write": "setImplicitContentWidthPolicy" + } + ], + "qualifiedClassName": "QQuickComboBox", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + } + ], + "index": 0, + "name": "activated", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + } + ], + "index": 1, + "name": "highlighted", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "countChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "modelChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "delegateModelChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "pressedChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "highlightedIndexChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "currentIndexChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 8, + "name": "currentTextChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 9, + "name": "displayTextChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 10, + "name": "textRoleChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 11, + "name": "delegateChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 12, + "name": "indicatorChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 13, + "name": "popupChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 14, + "name": "flatChanged", + "returnType": "void", + "revision": 513 + }, + { + "access": "public", + "index": 15, + "name": "accepted", + "returnType": "void", + "revision": 514 + }, + { + "access": "public", + "index": 16, + "name": "downChanged", + "returnType": "void", + "revision": 514 + }, + { + "access": "public", + "index": 17, + "name": "editableChanged", + "returnType": "void", + "revision": 514 + }, + { + "access": "public", + "index": 18, + "name": "editTextChanged", + "returnType": "void", + "revision": 514 + }, + { + "access": "public", + "index": 19, + "name": "validatorChanged", + "returnType": "void", + "revision": 514 + }, + { + "access": "public", + "index": 20, + "name": "inputMethodHintsChanged", + "returnType": "void", + "revision": 514 + }, + { + "access": "public", + "index": 21, + "name": "inputMethodComposingChanged", + "returnType": "void", + "revision": 514 + }, + { + "access": "public", + "index": 22, + "name": "acceptableInputChanged", + "returnType": "void", + "revision": 514 + }, + { + "access": "public", + "index": 23, + "name": "implicitIndicatorWidthChanged", + "returnType": "void", + "revision": 517 + }, + { + "access": "public", + "index": 24, + "name": "implicitIndicatorHeightChanged", + "returnType": "void", + "revision": 517 + }, + { + "access": "public", + "index": 25, + "name": "valueRoleChanged", + "returnType": "void", + "revision": 526 + }, + { + "access": "public", + "index": 26, + "name": "currentValueChanged", + "returnType": "void", + "revision": 526 + }, + { + "access": "public", + "index": 27, + "name": "selectTextByMouseChanged", + "returnType": "void", + "revision": 527 + }, + { + "access": "public", + "index": 28, + "name": "implicitContentWidthPolicyChanged", + "returnType": "void", + "revision": 1536 + } + ], + "slots": [ + { + "access": "public", + "index": 29, + "name": "incrementCurrentIndex", + "returnType": "void" + }, + { + "access": "public", + "index": 30, + "name": "decrementCurrentIndex", + "returnType": "void" + }, + { + "access": "public", + "index": 31, + "name": "selectAll", + "returnType": "void", + "revision": 514 + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickControl" + } + ] + } + ], + "inputFile": "qquickcombobox_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "DefaultProperty", + "value": "contentData" + }, + { + "name": "QML.Element", + "value": "Container" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickContainer", + "lineNumber": 27, + "methods": [ + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + } + ], + "index": 10, + "name": "itemAt", + "returnType": "QQuickItem*" + }, + { + "access": "public", + "arguments": [ + { + "name": "item", + "type": "QQuickItem*" + } + ], + "index": 11, + "name": "addItem", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + }, + { + "name": "item", + "type": "QQuickItem*" + } + ], + "index": 12, + "name": "insertItem", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "from", + "type": "int" + }, + { + "name": "to", + "type": "int" + } + ], + "index": 13, + "name": "moveItem", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "item", + "type": "QQuickItem*" + } + ], + "index": 14, + "name": "removeItem", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + } + ], + "index": 15, + "name": "takeItem", + "returnType": "QQuickItem*", + "revision": 515 + } + ], + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "count", + "notify": "countChanged", + "read": "count", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 1, + "name": "contentModel", + "read": "contentModel", + "required": false, + "scriptable": true, + "stored": true, + "type": "QVariant", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "contentData", + "read": "contentData", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlListProperty", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "contentChildren", + "notify": "contentChildrenChanged", + "read": "contentChildren", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlListProperty", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "currentIndex", + "notify": "currentIndexChanged", + "read": "currentIndex", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setCurrentIndex" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "currentItem", + "notify": "currentItemChanged", + "read": "currentItem", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 6, + "name": "contentWidth", + "notify": "contentWidthChanged", + "read": "contentWidth", + "required": false, + "reset": "resetContentWidth", + "revision": 517, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setContentWidth" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 7, + "name": "contentHeight", + "notify": "contentHeightChanged", + "read": "contentHeight", + "required": false, + "reset": "resetContentHeight", + "revision": 517, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setContentHeight" + } + ], + "qualifiedClassName": "QQuickContainer", + "signals": [ + { + "access": "public", + "index": 0, + "name": "countChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "contentChildrenChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "currentIndexChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "currentItemChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "contentWidthChanged", + "returnType": "void", + "revision": 517 + }, + { + "access": "public", + "index": 5, + "name": "contentHeightChanged", + "returnType": "void", + "revision": 517 + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + } + ], + "index": 6, + "name": "setCurrentIndex", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "incrementCurrentIndex", + "returnType": "void", + "revision": 513 + }, + { + "access": "public", + "index": 8, + "name": "decrementCurrentIndex", + "returnType": "void", + "revision": 513 + }, + { + "access": "private", + "index": 9, + "name": "_q_currentIndexChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickControl" + } + ] + } + ], + "inputFile": "qquickcontainer_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQuickContentItem", + "lineNumber": 23, + "object": true, + "qualifiedClassName": "QQuickContentItem", + "superClasses": [ + { + "access": "public", + "name": "QQuickItem" + } + ] + } + ], + "inputFile": "qquickcontentitem_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "DeferredPropertyNames", + "value": "background,contentItem" + }, + { + "name": "QML.Element", + "value": "Control" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickControl", + "lineNumber": 28, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "font", + "notify": "fontChanged", + "read": "font", + "required": false, + "reset": "resetFont", + "scriptable": true, + "stored": true, + "type": "QFont", + "user": false, + "write": "setFont" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "availableWidth", + "notify": "availableWidthChanged", + "read": "availableWidth", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "availableHeight", + "notify": "availableHeightChanged", + "read": "availableHeight", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "padding", + "notify": "paddingChanged", + "read": "padding", + "required": false, + "reset": "resetPadding", + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setPadding" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "topPadding", + "notify": "topPaddingChanged", + "read": "topPadding", + "required": false, + "reset": "resetTopPadding", + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setTopPadding" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "leftPadding", + "notify": "leftPaddingChanged", + "read": "leftPadding", + "required": false, + "reset": "resetLeftPadding", + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setLeftPadding" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 6, + "name": "rightPadding", + "notify": "rightPaddingChanged", + "read": "rightPadding", + "required": false, + "reset": "resetRightPadding", + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setRightPadding" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 7, + "name": "bottomPadding", + "notify": "bottomPaddingChanged", + "read": "bottomPadding", + "required": false, + "reset": "resetBottomPadding", + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setBottomPadding" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 8, + "name": "spacing", + "notify": "spacingChanged", + "read": "spacing", + "required": false, + "reset": "resetSpacing", + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setSpacing" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 9, + "name": "locale", + "notify": "localeChanged", + "read": "locale", + "required": false, + "reset": "resetLocale", + "scriptable": true, + "stored": true, + "type": "QLocale", + "user": false, + "write": "setLocale" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 10, + "name": "mirrored", + "notify": "mirroredChanged", + "read": "isMirrored", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 11, + "name": "focusPolicy", + "notify": "focusPolicyChanged", + "read": "focusPolicy", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::FocusPolicy", + "user": false, + "write": "setFocusPolicy" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 12, + "name": "focusReason", + "notify": "focusReasonChanged", + "read": "focusReason", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::FocusReason", + "user": false, + "write": "setFocusReason" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 13, + "name": "visualFocus", + "notify": "visualFocusChanged", + "read": "hasVisualFocus", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 14, + "name": "hovered", + "notify": "hoveredChanged", + "read": "isHovered", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 15, + "name": "hoverEnabled", + "notify": "hoverEnabledChanged", + "read": "isHoverEnabled", + "required": false, + "reset": "resetHoverEnabled", + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setHoverEnabled" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 16, + "name": "wheelEnabled", + "notify": "wheelEnabledChanged", + "read": "isWheelEnabled", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setWheelEnabled" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 17, + "name": "background", + "notify": "backgroundChanged", + "read": "background", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false, + "write": "setBackground" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 18, + "name": "contentItem", + "notify": "contentItemChanged", + "read": "contentItem", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false, + "write": "setContentItem" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 19, + "name": "baselineOffset", + "notify": "baselineOffsetChanged", + "read": "baselineOffset", + "required": false, + "reset": "resetBaselineOffset", + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setBaselineOffset" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 20, + "name": "horizontalPadding", + "notify": "horizontalPaddingChanged", + "read": "horizontalPadding", + "required": false, + "reset": "resetHorizontalPadding", + "revision": 517, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setHorizontalPadding" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 21, + "name": "verticalPadding", + "notify": "verticalPaddingChanged", + "read": "verticalPadding", + "required": false, + "reset": "resetVerticalPadding", + "revision": 517, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setVerticalPadding" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 22, + "name": "implicitContentWidth", + "notify": "implicitContentWidthChanged", + "read": "implicitContentWidth", + "required": false, + "revision": 517, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 23, + "name": "implicitContentHeight", + "notify": "implicitContentHeightChanged", + "read": "implicitContentHeight", + "required": false, + "revision": 517, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 24, + "name": "implicitBackgroundWidth", + "notify": "implicitBackgroundWidthChanged", + "read": "implicitBackgroundWidth", + "required": false, + "revision": 517, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 25, + "name": "implicitBackgroundHeight", + "notify": "implicitBackgroundHeightChanged", + "read": "implicitBackgroundHeight", + "required": false, + "revision": 517, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 26, + "name": "topInset", + "notify": "topInsetChanged", + "read": "topInset", + "required": false, + "reset": "resetTopInset", + "revision": 517, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setTopInset" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 27, + "name": "leftInset", + "notify": "leftInsetChanged", + "read": "leftInset", + "required": false, + "reset": "resetLeftInset", + "revision": 517, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setLeftInset" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 28, + "name": "rightInset", + "notify": "rightInsetChanged", + "read": "rightInset", + "required": false, + "reset": "resetRightInset", + "revision": 517, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setRightInset" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 29, + "name": "bottomInset", + "notify": "bottomInsetChanged", + "read": "bottomInset", + "required": false, + "reset": "resetBottomInset", + "revision": 517, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setBottomInset" + } + ], + "qualifiedClassName": "QQuickControl", + "signals": [ + { + "access": "public", + "index": 0, + "name": "fontChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "availableWidthChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "availableHeightChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "paddingChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "topPaddingChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "leftPaddingChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "rightPaddingChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "bottomPaddingChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 8, + "name": "spacingChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 9, + "name": "localeChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 10, + "name": "focusReasonChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 11, + "name": "mirroredChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 12, + "name": "visualFocusChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 13, + "name": "hoveredChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 14, + "name": "hoverEnabledChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 15, + "name": "wheelEnabledChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 16, + "name": "backgroundChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 17, + "name": "contentItemChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 18, + "name": "baselineOffsetChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 19, + "name": "horizontalPaddingChanged", + "returnType": "void", + "revision": 517 + }, + { + "access": "public", + "index": 20, + "name": "verticalPaddingChanged", + "returnType": "void", + "revision": 517 + }, + { + "access": "public", + "index": 21, + "name": "implicitContentWidthChanged", + "returnType": "void", + "revision": 517 + }, + { + "access": "public", + "index": 22, + "name": "implicitContentHeightChanged", + "returnType": "void", + "revision": 517 + }, + { + "access": "public", + "index": 23, + "name": "implicitBackgroundWidthChanged", + "returnType": "void", + "revision": 517 + }, + { + "access": "public", + "index": 24, + "name": "implicitBackgroundHeightChanged", + "returnType": "void", + "revision": 517 + }, + { + "access": "public", + "index": 25, + "name": "topInsetChanged", + "returnType": "void", + "revision": 517 + }, + { + "access": "public", + "index": 26, + "name": "leftInsetChanged", + "returnType": "void", + "revision": 517 + }, + { + "access": "public", + "index": 27, + "name": "rightInsetChanged", + "returnType": "void", + "revision": 517 + }, + { + "access": "public", + "index": 28, + "name": "bottomInsetChanged", + "returnType": "void", + "revision": 517 + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickItem" + } + ] + } + ], + "inputFile": "qquickcontrol_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQuickDayOfWeekModel", + "lineNumber": 27, + "methods": [ + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + } + ], + "index": 1, + "name": "dayAt", + "returnType": "int" + } + ], + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "locale", + "notify": "localeChanged", + "read": "locale", + "required": false, + "scriptable": true, + "stored": true, + "type": "QLocale", + "user": false, + "write": "setLocale" + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 1, + "name": "count", + "read": "rowCount", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + } + ], + "qualifiedClassName": "QQuickDayOfWeekModel", + "signals": [ + { + "access": "public", + "index": 0, + "name": "localeChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QAbstractListModel" + } + ] + } + ], + "inputFile": "qquickdayofweekmodel_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "AbstractDayOfWeekRow" + }, + { + "name": "QML.AddedInVersion", + "value": "1539" + } + ], + "className": "QQuickDayOfWeekRow", + "lineNumber": 25, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "source", + "notify": "sourceChanged", + "read": "source", + "required": false, + "scriptable": true, + "stored": true, + "type": "QVariant", + "user": false, + "write": "setSource" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "delegate", + "notify": "delegateChanged", + "read": "delegate", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlComponent*", + "user": false, + "write": "setDelegate" + } + ], + "qualifiedClassName": "QQuickDayOfWeekRow", + "signals": [ + { + "access": "public", + "index": 0, + "name": "sourceChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "delegateChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickControl" + } + ] + } + ], + "inputFile": "qquickdayofweekrow_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "DelayButton" + }, + { + "name": "QML.AddedInVersion", + "value": "514" + } + ], + "className": "QQuickDelayButton", + "lineNumber": 25, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "delay", + "notify": "delayChanged", + "read": "delay", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setDelay" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "progress", + "notify": "progressChanged", + "read": "progress", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setProgress" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "transition", + "notify": "transitionChanged", + "read": "transition", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickTransition*", + "user": false, + "write": "setTransition" + } + ], + "qualifiedClassName": "QQuickDelayButton", + "signals": [ + { + "access": "public", + "index": 0, + "name": "activated", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "delayChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "progressChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "transitionChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickAbstractButton" + } + ] + } + ], + "inputFile": "qquickdelaybutton_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "DeferredPropertyNames", + "value": "background,handle" + }, + { + "name": "QML.Element", + "value": "Dial" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickDial", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "SnapMode", + "values": [ + "NoSnap", + "SnapAlways", + "SnapOnRelease" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "InputMode", + "values": [ + "Circular", + "Horizontal", + "Vertical" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "WrapDirection", + "values": [ + "Clockwise", + "CounterClockwise" + ] + } + ], + "lineNumber": 27, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "from", + "notify": "fromChanged", + "read": "from", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setFrom" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "to", + "notify": "toChanged", + "read": "to", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setTo" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "value", + "notify": "valueChanged", + "read": "value", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setValue" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "position", + "notify": "positionChanged", + "read": "position", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "angle", + "notify": "angleChanged", + "read": "angle", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "startAngle", + "notify": "startAngleChanged", + "read": "startAngle", + "required": false, + "revision": 1542, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setStartAngle" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 6, + "name": "endAngle", + "notify": "endAngleChanged", + "read": "endAngle", + "required": false, + "revision": 1542, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setEndAngle" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 7, + "name": "stepSize", + "notify": "stepSizeChanged", + "read": "stepSize", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setStepSize" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 8, + "name": "snapMode", + "notify": "snapModeChanged", + "read": "snapMode", + "required": false, + "scriptable": true, + "stored": true, + "type": "SnapMode", + "user": false, + "write": "setSnapMode" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 9, + "name": "wrap", + "notify": "wrapChanged", + "read": "wrap", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setWrap" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 10, + "name": "pressed", + "notify": "pressedChanged", + "read": "isPressed", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 11, + "name": "handle", + "notify": "handleChanged", + "read": "handle", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false, + "write": "setHandle" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 12, + "name": "live", + "notify": "liveChanged", + "read": "live", + "required": false, + "revision": 514, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setLive" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 13, + "name": "inputMode", + "notify": "inputModeChanged", + "read": "inputMode", + "required": false, + "revision": 517, + "scriptable": true, + "stored": true, + "type": "InputMode", + "user": false, + "write": "setInputMode" + } + ], + "qualifiedClassName": "QQuickDial", + "signals": [ + { + "access": "public", + "index": 0, + "name": "fromChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "toChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "valueChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "positionChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "angleChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "stepSizeChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "snapModeChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "wrapChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 8, + "name": "pressedChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 9, + "name": "handleChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 10, + "name": "moved", + "returnType": "void", + "revision": 514 + }, + { + "access": "public", + "index": 11, + "name": "liveChanged", + "returnType": "void", + "revision": 514 + }, + { + "access": "public", + "index": 12, + "name": "inputModeChanged", + "returnType": "void", + "revision": 517 + }, + { + "access": "public", + "index": 13, + "name": "startAngleChanged", + "returnType": "void", + "revision": 1542 + }, + { + "access": "public", + "index": 14, + "name": "endAngleChanged", + "returnType": "void", + "revision": 1542 + }, + { + "access": "public", + "arguments": [ + { + "type": "WrapDirection" + } + ], + "index": 15, + "name": "wrapped", + "returnType": "void", + "revision": 1542 + } + ], + "slots": [ + { + "access": "public", + "index": 16, + "name": "increase", + "returnType": "void" + }, + { + "access": "public", + "index": 17, + "name": "decrease", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickControl" + } + ] + } + ], + "inputFile": "qquickdial_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Extended", + "value": "QPlatformDialogHelper" + }, + { + "name": "QML.ExtensionIsNamespace", + "value": "true" + }, + { + "name": "QML.Element", + "value": "Dialog" + }, + { + "name": "QML.AddedInVersion", + "value": "513" + } + ], + "className": "QQuickDialog", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "StandardCode", + "values": [ + "Rejected", + "Accepted" + ] + } + ], + "lineNumber": 28, + "methods": [ + { + "access": "public", + "arguments": [ + { + "name": "button", + "type": "QPlatformDialogHelper::StandardButton" + } + ], + "index": 18, + "name": "standardButton", + "returnType": "QQuickAbstractButton*", + "revision": 515 + } + ], + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "title", + "notify": "titleChanged", + "read": "title", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setTitle" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "header", + "notify": "headerChanged", + "read": "header", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false, + "write": "setHeader" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "footer", + "notify": "footerChanged", + "read": "footer", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false, + "write": "setFooter" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "standardButtons", + "notify": "standardButtonsChanged", + "read": "standardButtons", + "required": false, + "scriptable": true, + "stored": true, + "type": "QPlatformDialogHelper::StandardButtons", + "user": false, + "write": "setStandardButtons" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "result", + "notify": "resultChanged", + "read": "result", + "required": false, + "revision": 515, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setResult" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "implicitHeaderWidth", + "notify": "implicitHeaderWidthChanged", + "read": "implicitHeaderWidth", + "required": false, + "revision": 517, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 6, + "name": "implicitHeaderHeight", + "notify": "implicitHeaderHeightChanged", + "read": "implicitHeaderHeight", + "required": false, + "revision": 517, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 7, + "name": "implicitFooterWidth", + "notify": "implicitFooterWidthChanged", + "read": "implicitFooterWidth", + "required": false, + "revision": 517, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 8, + "name": "implicitFooterHeight", + "notify": "implicitFooterHeightChanged", + "read": "implicitFooterHeight", + "required": false, + "revision": 517, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + } + ], + "qualifiedClassName": "QQuickDialog", + "signals": [ + { + "access": "public", + "index": 0, + "name": "accepted", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "rejected", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "titleChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "headerChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "footerChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "standardButtonsChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "applied", + "returnType": "void", + "revision": 515 + }, + { + "access": "public", + "index": 7, + "name": "reset", + "returnType": "void", + "revision": 515 + }, + { + "access": "public", + "index": 8, + "name": "discarded", + "returnType": "void", + "revision": 515 + }, + { + "access": "public", + "index": 9, + "name": "helpRequested", + "returnType": "void", + "revision": 515 + }, + { + "access": "public", + "index": 10, + "name": "resultChanged", + "returnType": "void", + "revision": 515 + }, + { + "access": "public", + "index": 11, + "name": "implicitHeaderWidthChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 12, + "name": "implicitHeaderHeightChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 13, + "name": "implicitFooterWidthChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 14, + "name": "implicitFooterHeightChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "index": 15, + "name": "accept", + "returnType": "void" + }, + { + "access": "public", + "index": 16, + "name": "reject", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "result", + "type": "int" + } + ], + "index": 17, + "name": "done", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickPopup" + } + ] + } + ], + "inputFile": "qquickdialog_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "DialogButtonBox" + }, + { + "name": "QML.Attached", + "value": "QQuickDialogButtonBoxAttached" + }, + { + "name": "QML.Extended", + "value": "QPlatformDialogHelper" + }, + { + "name": "QML.ExtensionIsNamespace", + "value": "true" + }, + { + "name": "QML.AddedInVersion", + "value": "513" + } + ], + "className": "QQuickDialogButtonBox", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "Position", + "values": [ + "Header", + "Footer" + ] + } + ], + "lineNumber": 31, + "methods": [ + { + "access": "public", + "arguments": [ + { + "name": "button", + "type": "QPlatformDialogHelper::StandardButton" + } + ], + "index": 12, + "name": "standardButton", + "returnType": "QQuickAbstractButton*" + } + ], + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "position", + "notify": "positionChanged", + "read": "position", + "required": false, + "scriptable": true, + "stored": true, + "type": "Position", + "user": false, + "write": "setPosition" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "alignment", + "notify": "alignmentChanged", + "read": "alignment", + "required": false, + "reset": "resetAlignment", + "scriptable": true, + "stored": true, + "type": "Qt::Alignment", + "user": false, + "write": "setAlignment" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "standardButtons", + "notify": "standardButtonsChanged", + "read": "standardButtons", + "required": false, + "scriptable": true, + "stored": true, + "type": "QPlatformDialogHelper::StandardButtons", + "user": false, + "write": "setStandardButtons" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "delegate", + "notify": "delegateChanged", + "read": "delegate", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlComponent*", + "user": false, + "write": "setDelegate" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "buttonLayout", + "notify": "buttonLayoutChanged", + "read": "buttonLayout", + "required": false, + "reset": "resetButtonLayout", + "revision": 517, + "scriptable": true, + "stored": true, + "type": "QPlatformDialogHelper::ButtonLayout", + "user": false, + "write": "setButtonLayout" + } + ], + "qualifiedClassName": "QQuickDialogButtonBox", + "signals": [ + { + "access": "public", + "index": 0, + "name": "accepted", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "rejected", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "helpRequested", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "button", + "type": "QQuickAbstractButton*" + } + ], + "index": 3, + "name": "clicked", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "positionChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "alignmentChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "standardButtonsChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "delegateChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 8, + "name": "applied", + "returnType": "void", + "revision": 515 + }, + { + "access": "public", + "index": 9, + "name": "reset", + "returnType": "void", + "revision": 515 + }, + { + "access": "public", + "index": 10, + "name": "discarded", + "returnType": "void", + "revision": 515 + }, + { + "access": "public", + "index": 11, + "name": "buttonLayoutChanged", + "returnType": "void", + "revision": 517 + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickContainer" + } + ] + }, + { + "className": "QQuickDialogButtonBoxAttached", + "lineNumber": 110, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "buttonBox", + "notify": "buttonBoxChanged", + "read": "buttonBox", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickDialogButtonBox*", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "buttonRole", + "notify": "buttonRoleChanged", + "read": "buttonRole", + "required": false, + "scriptable": true, + "stored": true, + "type": "QPlatformDialogHelper::ButtonRole", + "user": false, + "write": "setButtonRole" + } + ], + "qualifiedClassName": "QQuickDialogButtonBoxAttached", + "signals": [ + { + "access": "public", + "index": 0, + "name": "buttonBoxChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "buttonRoleChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qquickdialogbuttonbox_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "Drawer" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickDrawer", + "lineNumber": 24, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "edge", + "notify": "edgeChanged", + "read": "edge", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::Edge", + "user": false, + "write": "setEdge" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "position", + "notify": "positionChanged", + "read": "position", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setPosition" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "dragMargin", + "notify": "dragMarginChanged", + "read": "dragMargin", + "required": false, + "reset": "resetDragMargin", + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setDragMargin" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "interactive", + "notify": "interactiveChanged", + "read": "isInteractive", + "required": false, + "revision": 514, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setInteractive" + } + ], + "qualifiedClassName": "QQuickDrawer", + "signals": [ + { + "access": "public", + "index": 0, + "name": "edgeChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "positionChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "dragMarginChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "interactiveChanged", + "returnType": "void", + "revision": 514 + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickPopup" + } + ] + } + ], + "inputFile": "qquickdrawer_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "Frame" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickFrame", + "lineNumber": 24, + "object": true, + "qualifiedClassName": "QQuickFrame", + "superClasses": [ + { + "access": "public", + "name": "QQuickPane" + } + ] + } + ], + "inputFile": "qquickframe_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "DeferredPropertyNames", + "value": "background,contentItem,label" + }, + { + "name": "QML.Element", + "value": "GroupBox" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickGroupBox", + "lineNumber": 24, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "title", + "notify": "titleChanged", + "read": "title", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setTitle" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "label", + "notify": "labelChanged", + "read": "label", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false, + "write": "setLabel" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "implicitLabelWidth", + "notify": "implicitLabelWidthChanged", + "read": "implicitLabelWidth", + "required": false, + "revision": 517, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "implicitLabelHeight", + "notify": "implicitLabelHeightChanged", + "read": "implicitLabelHeight", + "required": false, + "revision": 517, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + } + ], + "qualifiedClassName": "QQuickGroupBox", + "signals": [ + { + "access": "public", + "index": 0, + "name": "titleChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "labelChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "implicitLabelWidthChanged", + "returnType": "void", + "revision": 517 + }, + { + "access": "public", + "index": 3, + "name": "implicitLabelHeightChanged", + "returnType": "void", + "revision": 517 + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickFrame" + } + ] + } + ], + "inputFile": "qquickgroupbox_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQuickHeaderViewBase", + "lineNumber": 25, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "textRole", + "notify": "textRoleChanged", + "read": "textRole", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setTextRole" + } + ], + "qualifiedClassName": "QQuickHeaderViewBase", + "signals": [ + { + "access": "public", + "index": 0, + "name": "textRoleChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickTableView" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "HorizontalHeaderView" + }, + { + "name": "QML.AddedInVersion", + "value": "527" + } + ], + "className": "QQuickHorizontalHeaderView", + "lineNumber": 51, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "movableColumns", + "notify": "movableColumnsChanged", + "read": "movableColumns", + "required": false, + "revision": 1544, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setMovableColumns" + } + ], + "qualifiedClassName": "QQuickHorizontalHeaderView", + "signals": [ + { + "access": "public", + "index": 0, + "name": "movableColumnsChanged", + "returnType": "void", + "revision": 1544 + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickHeaderViewBase" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "VerticalHeaderView" + }, + { + "name": "QML.AddedInVersion", + "value": "527" + } + ], + "className": "QQuickVerticalHeaderView", + "lineNumber": 77, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "movableRows", + "notify": "movableRowsChanged", + "read": "movableRows", + "required": false, + "revision": 1544, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setMovableRows" + } + ], + "qualifiedClassName": "QQuickVerticalHeaderView", + "signals": [ + { + "access": "public", + "index": 0, + "name": "movableRowsChanged", + "returnType": "void", + "revision": 1544 + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickHeaderViewBase" + } + ] + } + ], + "inputFile": "qquickheaderview_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QHeaderDataProxyModel", + "lineNumber": 28, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "sourceModel", + "read": "sourceModel", + "required": false, + "scriptable": true, + "stored": true, + "type": "QAbstractItemModel*", + "user": false + } + ], + "qualifiedClassName": "QHeaderDataProxyModel", + "superClasses": [ + { + "access": "public", + "name": "QAbstractItemModel" + } + ] + } + ], + "inputFile": "qquickheaderview_p_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.AddedInVersion", + "value": "515" + } + ], + "className": "QQuickIcon", + "gadget": true, + "lineNumber": 30, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "name", + "read": "name", + "required": false, + "reset": "resetName", + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setName" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "source", + "read": "source", + "required": false, + "reset": "resetSource", + "scriptable": true, + "stored": true, + "type": "QUrl", + "user": false, + "write": "setSource" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "width", + "read": "width", + "required": false, + "reset": "resetWidth", + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setWidth" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "height", + "read": "height", + "required": false, + "reset": "resetHeight", + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setHeight" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "color", + "read": "color", + "required": false, + "reset": "resetColor", + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false, + "write": "setColor" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "cache", + "read": "cache", + "required": false, + "reset": "resetCache", + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setCache" + } + ], + "qualifiedClassName": "QQuickIcon" + } + ], + "inputFile": "qquickicon_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "DeferredPropertyNames", + "value": "indicator" + }, + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickIndicatorButton", + "lineNumber": 25, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "pressed", + "notify": "pressedChanged", + "read": "isPressed", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setPressed" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "indicator", + "notify": "indicatorChanged", + "read": "indicator", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false, + "write": "setIndicator" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "hovered", + "notify": "hoveredChanged", + "read": "isHovered", + "required": false, + "revision": 513, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setHovered" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "implicitIndicatorWidth", + "notify": "implicitIndicatorWidthChanged", + "read": "implicitIndicatorWidth", + "required": false, + "revision": 517, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "implicitIndicatorHeight", + "notify": "implicitIndicatorHeightChanged", + "read": "implicitIndicatorHeight", + "required": false, + "revision": 517, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + } + ], + "qualifiedClassName": "QQuickIndicatorButton", + "signals": [ + { + "access": "public", + "index": 0, + "name": "pressedChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "indicatorChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "hoveredChanged", + "returnType": "void", + "revision": 513 + }, + { + "access": "public", + "index": 3, + "name": "implicitIndicatorWidthChanged", + "returnType": "void", + "revision": 517 + }, + { + "access": "public", + "index": 4, + "name": "implicitIndicatorHeightChanged", + "returnType": "void", + "revision": 517 + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qquickindicatorbutton_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "ItemDelegate" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickItemDelegate", + "lineNumber": 24, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "highlighted", + "notify": "highlightedChanged", + "read": "isHighlighted", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setHighlighted" + } + ], + "qualifiedClassName": "QQuickItemDelegate", + "signals": [ + { + "access": "public", + "index": 0, + "name": "highlightedChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickAbstractButton" + } + ] + } + ], + "inputFile": "qquickitemdelegate_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "DeferredPropertyNames", + "value": "background" + }, + { + "name": "QML.Element", + "value": "Label" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickLabel", + "lineNumber": 26, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "font", + "notify": "fontChanged", + "read": "font", + "required": false, + "scriptable": true, + "stored": true, + "type": "QFont", + "user": false, + "write": "setFont" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "background", + "notify": "backgroundChanged", + "read": "background", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false, + "write": "setBackground" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "implicitBackgroundWidth", + "notify": "implicitBackgroundWidthChanged", + "read": "implicitBackgroundWidth", + "required": false, + "revision": 517, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "implicitBackgroundHeight", + "notify": "implicitBackgroundHeightChanged", + "read": "implicitBackgroundHeight", + "required": false, + "revision": 517, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "topInset", + "notify": "topInsetChanged", + "read": "topInset", + "required": false, + "reset": "resetTopInset", + "revision": 517, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setTopInset" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "leftInset", + "notify": "leftInsetChanged", + "read": "leftInset", + "required": false, + "reset": "resetLeftInset", + "revision": 517, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setLeftInset" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 6, + "name": "rightInset", + "notify": "rightInsetChanged", + "read": "rightInset", + "required": false, + "reset": "resetRightInset", + "revision": 517, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setRightInset" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 7, + "name": "bottomInset", + "notify": "bottomInsetChanged", + "read": "bottomInset", + "required": false, + "reset": "resetBottomInset", + "revision": 517, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setBottomInset" + } + ], + "qualifiedClassName": "QQuickLabel", + "signals": [ + { + "access": "public", + "index": 0, + "name": "fontChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "backgroundChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "implicitBackgroundWidthChanged", + "returnType": "void", + "revision": 517 + }, + { + "access": "public", + "index": 3, + "name": "implicitBackgroundHeightChanged", + "returnType": "void", + "revision": 517 + }, + { + "access": "public", + "index": 4, + "name": "topInsetChanged", + "returnType": "void", + "revision": 517 + }, + { + "access": "public", + "index": 5, + "name": "leftInsetChanged", + "returnType": "void", + "revision": 517 + }, + { + "access": "public", + "index": 6, + "name": "rightInsetChanged", + "returnType": "void", + "revision": 517 + }, + { + "access": "public", + "index": 7, + "name": "bottomInsetChanged", + "returnType": "void", + "revision": 517 + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickText" + } + ] + } + ], + "inputFile": "qquicklabel_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "DefaultProperty", + "value": "contentData" + }, + { + "name": "QML.Element", + "value": "Menu" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickMenu", + "lineNumber": 34, + "methods": [ + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + } + ], + "index": 7, + "name": "itemAt", + "returnType": "QQuickItem*" + }, + { + "access": "public", + "arguments": [ + { + "name": "item", + "type": "QQuickItem*" + } + ], + "index": 8, + "name": "addItem", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + }, + { + "name": "item", + "type": "QQuickItem*" + } + ], + "index": 9, + "name": "insertItem", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "from", + "type": "int" + }, + { + "name": "to", + "type": "int" + } + ], + "index": 10, + "name": "moveItem", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "item", + "type": "QQuickItem*" + } + ], + "index": 11, + "name": "removeItem", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + } + ], + "index": 12, + "name": "takeItem", + "returnType": "QQuickItem*", + "revision": 515 + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + } + ], + "index": 13, + "name": "menuAt", + "returnType": "QQuickMenu*", + "revision": 515 + }, + { + "access": "public", + "arguments": [ + { + "name": "menu", + "type": "QQuickMenu*" + } + ], + "index": 14, + "name": "addMenu", + "returnType": "void", + "revision": 515 + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + }, + { + "name": "menu", + "type": "QQuickMenu*" + } + ], + "index": 15, + "name": "insertMenu", + "returnType": "void", + "revision": 515 + }, + { + "access": "public", + "arguments": [ + { + "name": "menu", + "type": "QQuickMenu*" + } + ], + "index": 16, + "name": "removeMenu", + "returnType": "void", + "revision": 515 + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + } + ], + "index": 17, + "name": "takeMenu", + "returnType": "QQuickMenu*", + "revision": 515 + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + } + ], + "index": 18, + "name": "actionAt", + "returnType": "QQuickAction*", + "revision": 515 + }, + { + "access": "public", + "arguments": [ + { + "name": "action", + "type": "QQuickAction*" + } + ], + "index": 19, + "name": "addAction", + "returnType": "void", + "revision": 515 + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + }, + { + "name": "action", + "type": "QQuickAction*" + } + ], + "index": 20, + "name": "insertAction", + "returnType": "void", + "revision": 515 + }, + { + "access": "public", + "arguments": [ + { + "name": "action", + "type": "QQuickAction*" + } + ], + "index": 21, + "name": "removeAction", + "returnType": "void", + "revision": 515 + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + } + ], + "index": 22, + "name": "takeAction", + "returnType": "QQuickAction*", + "revision": 515 + }, + { + "access": "public", + "arguments": [ + { + "name": "args", + "type": "QQmlV4FunctionPtr" + } + ], + "index": 23, + "name": "popup", + "returnType": "void", + "revision": 515 + }, + { + "access": "public", + "index": 24, + "name": "dismiss", + "returnType": "void", + "revision": 515 + } + ], + "object": true, + "properties": [ + { + "constant": true, + "designable": true, + "final": true, + "index": 0, + "name": "contentModel", + "read": "contentModel", + "required": false, + "scriptable": true, + "stored": true, + "type": "QVariant", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "contentData", + "read": "contentData", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlListProperty", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "title", + "notify": "titleChanged", + "read": "title", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setTitle" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "count", + "notify": "countChanged", + "read": "count", + "required": false, + "revision": 515, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "cascade", + "notify": "cascadeChanged", + "read": "cascade", + "required": false, + "reset": "resetCascade", + "revision": 515, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setCascade" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "overlap", + "notify": "overlapChanged", + "read": "overlap", + "required": false, + "revision": 515, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setOverlap" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 6, + "name": "delegate", + "notify": "delegateChanged", + "read": "delegate", + "required": false, + "revision": 515, + "scriptable": true, + "stored": true, + "type": "QQmlComponent*", + "user": false, + "write": "setDelegate" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 7, + "name": "currentIndex", + "notify": "currentIndexChanged", + "read": "currentIndex", + "required": false, + "revision": 515, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setCurrentIndex" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 8, + "name": "icon", + "notify": "iconChanged", + "read": "icon", + "required": false, + "revision": 1541, + "scriptable": true, + "stored": true, + "type": "QQuickIcon", + "user": false, + "write": "setIcon" + } + ], + "qualifiedClassName": "QQuickMenu", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "title", + "type": "QString" + } + ], + "index": 0, + "name": "titleChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "countChanged", + "returnType": "void", + "revision": 515 + }, + { + "access": "public", + "arguments": [ + { + "name": "cascade", + "type": "bool" + } + ], + "index": 2, + "name": "cascadeChanged", + "returnType": "void", + "revision": 515 + }, + { + "access": "public", + "index": 3, + "name": "overlapChanged", + "returnType": "void", + "revision": 515 + }, + { + "access": "public", + "index": 4, + "name": "delegateChanged", + "returnType": "void", + "revision": 515 + }, + { + "access": "public", + "index": 5, + "name": "currentIndexChanged", + "returnType": "void", + "revision": 515 + }, + { + "access": "public", + "arguments": [ + { + "name": "icon", + "type": "QQuickIcon" + } + ], + "index": 6, + "name": "iconChanged", + "returnType": "void", + "revision": 1541 + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickPopup" + } + ] + } + ], + "inputFile": "qquickmenu_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "MenuBar" + }, + { + "name": "QML.AddedInVersion", + "value": "515" + } + ], + "className": "QQuickMenuBar", + "lineNumber": 27, + "methods": [ + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + } + ], + "index": 2, + "name": "menuAt", + "returnType": "QQuickMenu*" + }, + { + "access": "public", + "arguments": [ + { + "name": "menu", + "type": "QQuickMenu*" + } + ], + "index": 3, + "name": "addMenu", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + }, + { + "name": "menu", + "type": "QQuickMenu*" + } + ], + "index": 4, + "name": "insertMenu", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "menu", + "type": "QQuickMenu*" + } + ], + "index": 5, + "name": "removeMenu", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + } + ], + "index": 6, + "name": "takeMenu", + "returnType": "QQuickMenu*" + } + ], + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "delegate", + "notify": "delegateChanged", + "read": "delegate", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlComponent*", + "user": false, + "write": "setDelegate" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "menus", + "notify": "menusChanged", + "privateClass": "QQuickMenuBar::d_func()", + "read": "menus", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlListProperty", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "contentData", + "privateClass": "QQuickMenuBar::d_func()", + "read": "contentData", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlListProperty", + "user": false + } + ], + "qualifiedClassName": "QQuickMenuBar", + "signals": [ + { + "access": "public", + "index": 0, + "name": "delegateChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "menusChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickContainer" + } + ] + } + ], + "inputFile": "qquickmenubar_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "MenuBarItem" + }, + { + "name": "QML.AddedInVersion", + "value": "515" + } + ], + "className": "QQuickMenuBarItem", + "lineNumber": 28, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "menuBar", + "notify": "menuBarChanged", + "read": "menuBar", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickMenuBar*", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "menu", + "notify": "menuChanged", + "read": "menu", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickMenu*", + "user": false, + "write": "setMenu" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "highlighted", + "notify": "highlightedChanged", + "read": "isHighlighted", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setHighlighted" + } + ], + "qualifiedClassName": "QQuickMenuBarItem", + "signals": [ + { + "access": "public", + "index": 0, + "name": "triggered", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "menuBarChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "menuChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "highlightedChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickAbstractButton" + } + ] + } + ], + "inputFile": "qquickmenubaritem_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "DeferredPropertyNames", + "value": "arrow,background,contentItem,indicator" + }, + { + "name": "QML.Element", + "value": "MenuItem" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickMenuItem", + "lineNumber": 28, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "highlighted", + "notify": "highlightedChanged", + "read": "isHighlighted", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setHighlighted" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "arrow", + "notify": "arrowChanged", + "read": "arrow", + "required": false, + "revision": 515, + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false, + "write": "setArrow" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "menu", + "notify": "menuChanged", + "read": "menu", + "required": false, + "revision": 515, + "scriptable": true, + "stored": true, + "type": "QQuickMenu*", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "subMenu", + "notify": "subMenuChanged", + "read": "subMenu", + "required": false, + "revision": 515, + "scriptable": true, + "stored": true, + "type": "QQuickMenu*", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "implicitTextPadding", + "notify": "implicitTextPaddingChanged", + "read": "implicitTextPadding", + "required": false, + "revision": 1544, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setImplicitTextPadding" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "textPadding", + "notify": "textPaddingChanged", + "read": "textPadding", + "required": false, + "revision": 1544, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + } + ], + "qualifiedClassName": "QQuickMenuItem", + "signals": [ + { + "access": "public", + "index": 0, + "name": "triggered", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "highlightedChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "arrowChanged", + "returnType": "void", + "revision": 515 + }, + { + "access": "public", + "index": 3, + "name": "menuChanged", + "returnType": "void", + "revision": 515 + }, + { + "access": "public", + "index": 4, + "name": "subMenuChanged", + "returnType": "void", + "revision": 515 + }, + { + "access": "public", + "index": 5, + "name": "implicitTextPaddingChanged", + "returnType": "void", + "revision": 1544 + }, + { + "access": "public", + "index": 6, + "name": "textPaddingChanged", + "returnType": "void", + "revision": 1544 + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickAbstractButton" + } + ] + } + ], + "inputFile": "qquickmenuitem_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "MenuSeparator" + }, + { + "name": "QML.AddedInVersion", + "value": "513" + } + ], + "className": "QQuickMenuSeparator", + "lineNumber": 25, + "object": true, + "qualifiedClassName": "QQuickMenuSeparator", + "superClasses": [ + { + "access": "public", + "name": "QQuickControl" + } + ] + } + ], + "inputFile": "qquickmenuseparator_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "AbstractMonthGrid" + }, + { + "name": "QML.AddedInVersion", + "value": "1539" + } + ], + "className": "QQuickMonthGrid", + "lineNumber": 25, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "month", + "notify": "monthChanged", + "read": "month", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setMonth" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "year", + "notify": "yearChanged", + "read": "year", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setYear" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "source", + "notify": "sourceChanged", + "read": "source", + "required": false, + "scriptable": true, + "stored": true, + "type": "QVariant", + "user": false, + "write": "setSource" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "title", + "notify": "titleChanged", + "read": "title", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setTitle" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "delegate", + "notify": "delegateChanged", + "read": "delegate", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlComponent*", + "user": false, + "write": "setDelegate" + } + ], + "qualifiedClassName": "QQuickMonthGrid", + "signals": [ + { + "access": "public", + "index": 0, + "name": "monthChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "yearChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "sourceChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "titleChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "delegateChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "date", + "type": "QDate" + } + ], + "index": 5, + "name": "pressed", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "date", + "type": "QDate" + } + ], + "index": 6, + "name": "released", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "date", + "type": "QDate" + } + ], + "index": 7, + "name": "clicked", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "date", + "type": "QDate" + } + ], + "index": 8, + "name": "pressAndHold", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickControl" + } + ] + } + ], + "inputFile": "qquickmonthgrid_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQuickMonthModel", + "lineNumber": 28, + "methods": [ + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + } + ], + "index": 4, + "name": "dateAt", + "returnType": "QDate" + }, + { + "access": "public", + "arguments": [ + { + "name": "date", + "type": "QDate" + } + ], + "index": 5, + "name": "indexOf", + "returnType": "int" + } + ], + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "month", + "notify": "monthChanged", + "read": "month", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setMonth" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "year", + "notify": "yearChanged", + "read": "year", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setYear" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "locale", + "notify": "localeChanged", + "read": "locale", + "required": false, + "scriptable": true, + "stored": true, + "type": "QLocale", + "user": false, + "write": "setLocale" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "title", + "notify": "titleChanged", + "read": "title", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setTitle" + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 4, + "name": "count", + "read": "rowCount", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + } + ], + "qualifiedClassName": "QQuickMonthModel", + "signals": [ + { + "access": "public", + "index": 0, + "name": "monthChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "yearChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "localeChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "titleChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QAbstractListModel" + } + ] + } + ], + "inputFile": "qquickmonthmodel_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + } + ], + "className": "QQuickNativeIcon", + "gadget": true, + "lineNumber": 28, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "source", + "read": "source", + "required": false, + "scriptable": true, + "stored": true, + "type": "QUrl", + "user": false, + "write": "setSource" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "name", + "read": "name", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setName" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "mask", + "read": "isMask", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setMask" + } + ], + "qualifiedClassName": "QQuickNativeIcon" + } + ], + "inputFile": "qquicknativeicon_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQuickNativeMenuItem", + "lineNumber": 30, + "object": true, + "qualifiedClassName": "QQuickNativeMenuItem", + "slots": [ + { + "access": "private", + "index": 0, + "name": "updateIcon", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qquicknativemenuitem_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "Overlay" + }, + { + "name": "QML.Attached", + "value": "QQuickOverlayAttached" + }, + { + "name": "QML.Creatable", + "value": "false" + }, + { + "name": "QML.UncreatableReason", + "value": "" + }, + { + "name": "QML.AddedInVersion", + "value": "515" + } + ], + "className": "QQuickOverlay", + "lineNumber": 28, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "modal", + "notify": "modalChanged", + "read": "modal", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlComponent*", + "user": false, + "write": "setModal" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "modeless", + "notify": "modelessChanged", + "read": "modeless", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlComponent*", + "user": false, + "write": "setModeless" + } + ], + "qualifiedClassName": "QQuickOverlay", + "signals": [ + { + "access": "public", + "index": 0, + "name": "modalChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "modelessChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "pressed", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "released", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickItem" + } + ] + }, + { + "className": "QQuickOverlayAttached", + "lineNumber": 79, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "overlay", + "notify": "overlayChanged", + "read": "overlay", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickOverlay*", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "modal", + "notify": "modalChanged", + "read": "modal", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlComponent*", + "user": false, + "write": "setModal" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "modeless", + "notify": "modelessChanged", + "read": "modeless", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlComponent*", + "user": false, + "write": "setModeless" + } + ], + "qualifiedClassName": "QQuickOverlayAttached", + "signals": [ + { + "access": "public", + "index": 0, + "name": "overlayChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "modalChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "modelessChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "pressed", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "released", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qquickoverlay_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "Page" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickPage", + "lineNumber": 25, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "title", + "notify": "titleChanged", + "read": "title", + "required": false, + "reset": "resetTitle", + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setTitle" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "header", + "notify": "headerChanged", + "read": "header", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false, + "write": "setHeader" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "footer", + "notify": "footerChanged", + "read": "footer", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false, + "write": "setFooter" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "implicitHeaderWidth", + "notify": "implicitHeaderWidthChanged", + "read": "implicitHeaderWidth", + "required": false, + "revision": 517, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "implicitHeaderHeight", + "notify": "implicitHeaderHeightChanged", + "read": "implicitHeaderHeight", + "required": false, + "revision": 517, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "implicitFooterWidth", + "notify": "implicitFooterWidthChanged", + "read": "implicitFooterWidth", + "required": false, + "revision": 517, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 6, + "name": "implicitFooterHeight", + "notify": "implicitFooterHeightChanged", + "read": "implicitFooterHeight", + "required": false, + "revision": 517, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + } + ], + "qualifiedClassName": "QQuickPage", + "signals": [ + { + "access": "public", + "index": 0, + "name": "titleChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "headerChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "footerChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "implicitHeaderWidthChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "implicitHeaderHeightChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "implicitFooterWidthChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "implicitFooterHeightChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickPane" + } + ] + } + ], + "inputFile": "qquickpage_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "PageIndicator" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickPageIndicator", + "lineNumber": 25, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "count", + "notify": "countChanged", + "read": "count", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setCount" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "currentIndex", + "notify": "currentIndexChanged", + "read": "currentIndex", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setCurrentIndex" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "interactive", + "notify": "interactiveChanged", + "read": "isInteractive", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setInteractive" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "delegate", + "notify": "delegateChanged", + "read": "delegate", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlComponent*", + "user": false, + "write": "setDelegate" + } + ], + "qualifiedClassName": "QQuickPageIndicator", + "signals": [ + { + "access": "public", + "index": 0, + "name": "countChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "currentIndexChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "interactiveChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "delegateChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickControl" + } + ] + } + ], + "inputFile": "qquickpageindicator_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "DefaultProperty", + "value": "contentData" + }, + { + "name": "QML.Element", + "value": "Pane" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickPane", + "lineNumber": 25, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "contentWidth", + "notify": "contentWidthChanged", + "read": "contentWidth", + "required": false, + "reset": "resetContentWidth", + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setContentWidth" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "contentHeight", + "notify": "contentHeightChanged", + "read": "contentHeight", + "required": false, + "reset": "resetContentHeight", + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setContentHeight" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "contentData", + "privateClass": "QQuickPane::d_func()", + "read": "contentData", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlListProperty", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "contentChildren", + "notify": "contentChildrenChanged", + "privateClass": "QQuickPane::d_func()", + "read": "contentChildren", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlListProperty", + "user": false + } + ], + "qualifiedClassName": "QQuickPane", + "signals": [ + { + "access": "public", + "index": 0, + "name": "contentWidthChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "contentHeightChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "contentChildrenChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickControl" + } + ] + } + ], + "inputFile": "qquickpane_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "DeferredPropertyNames", + "value": "background,contentItem" + }, + { + "name": "DefaultProperty", + "value": "contentData" + }, + { + "name": "QML.Element", + "value": "Popup" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickPopup", + "enums": [ + { + "alias": "ClosePolicyFlag", + "isClass": false, + "isFlag": true, + "name": "ClosePolicy", + "values": [ + "NoAutoClose", + "CloseOnPressOutside", + "CloseOnPressOutsideParent", + "CloseOnReleaseOutside", + "CloseOnReleaseOutsideParent", + "CloseOnEscape" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "TransformOrigin", + "values": [ + "TopLeft", + "Top", + "TopRight", + "Left", + "Center", + "Right", + "BottomLeft", + "Bottom", + "BottomRight" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "PopupType", + "values": [ + "Item", + "Window", + "Native" + ] + } + ], + "interfaces": [ + [ + { + "className": "QQmlParserStatus", + "id": "\"org.qt-project.Qt.QQmlParserStatus\"" + } + ] + ], + "lineNumber": 41, + "methods": [ + { + "access": "public", + "arguments": [ + { + "name": "reason", + "type": "Qt::FocusReason" + } + ], + "index": 62, + "name": "forceActiveFocus", + "returnType": "void" + }, + { + "access": "public", + "index": 63, + "isCloned": true, + "name": "forceActiveFocus", + "returnType": "void" + } + ], + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "x", + "notify": "xChanged", + "read": "x", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setX" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "y", + "notify": "yChanged", + "read": "y", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setY" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "z", + "notify": "zChanged", + "read": "z", + "required": false, + "reset": "resetZ", + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setZ" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "width", + "notify": "widthChanged", + "read": "width", + "required": false, + "reset": "resetWidth", + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setWidth" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "height", + "notify": "heightChanged", + "read": "height", + "required": false, + "reset": "resetHeight", + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setHeight" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "implicitWidth", + "notify": "implicitWidthChanged", + "read": "implicitWidth", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setImplicitWidth" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 6, + "name": "implicitHeight", + "notify": "implicitHeightChanged", + "read": "implicitHeight", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setImplicitHeight" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 7, + "name": "contentWidth", + "notify": "contentWidthChanged", + "read": "contentWidth", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setContentWidth" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 8, + "name": "contentHeight", + "notify": "contentHeightChanged", + "read": "contentHeight", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setContentHeight" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 9, + "name": "availableWidth", + "notify": "availableWidthChanged", + "read": "availableWidth", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 10, + "name": "availableHeight", + "notify": "availableHeightChanged", + "read": "availableHeight", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 11, + "name": "margins", + "notify": "marginsChanged", + "read": "margins", + "required": false, + "reset": "resetMargins", + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setMargins" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 12, + "name": "topMargin", + "notify": "topMarginChanged", + "read": "topMargin", + "required": false, + "reset": "resetTopMargin", + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setTopMargin" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 13, + "name": "leftMargin", + "notify": "leftMarginChanged", + "read": "leftMargin", + "required": false, + "reset": "resetLeftMargin", + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setLeftMargin" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 14, + "name": "rightMargin", + "notify": "rightMarginChanged", + "read": "rightMargin", + "required": false, + "reset": "resetRightMargin", + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setRightMargin" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 15, + "name": "bottomMargin", + "notify": "bottomMarginChanged", + "read": "bottomMargin", + "required": false, + "reset": "resetBottomMargin", + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setBottomMargin" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 16, + "name": "padding", + "notify": "paddingChanged", + "read": "padding", + "required": false, + "reset": "resetPadding", + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setPadding" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 17, + "name": "topPadding", + "notify": "topPaddingChanged", + "read": "topPadding", + "required": false, + "reset": "resetTopPadding", + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setTopPadding" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 18, + "name": "leftPadding", + "notify": "leftPaddingChanged", + "read": "leftPadding", + "required": false, + "reset": "resetLeftPadding", + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setLeftPadding" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 19, + "name": "rightPadding", + "notify": "rightPaddingChanged", + "read": "rightPadding", + "required": false, + "reset": "resetRightPadding", + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setRightPadding" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 20, + "name": "bottomPadding", + "notify": "bottomPaddingChanged", + "read": "bottomPadding", + "required": false, + "reset": "resetBottomPadding", + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setBottomPadding" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 21, + "name": "locale", + "notify": "localeChanged", + "read": "locale", + "required": false, + "reset": "resetLocale", + "scriptable": true, + "stored": true, + "type": "QLocale", + "user": false, + "write": "setLocale" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 22, + "name": "font", + "notify": "fontChanged", + "read": "font", + "required": false, + "reset": "resetFont", + "scriptable": true, + "stored": true, + "type": "QFont", + "user": false, + "write": "setFont" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 23, + "name": "parent", + "notify": "parentChanged", + "read": "parentItem", + "required": false, + "reset": "resetParentItem", + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false, + "write": "setParentItem" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 24, + "name": "background", + "notify": "backgroundChanged", + "read": "background", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false, + "write": "setBackground" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 25, + "name": "contentItem", + "notify": "contentItemChanged", + "read": "contentItem", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false, + "write": "setContentItem" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 26, + "name": "contentData", + "privateClass": "QQuickPopup::d_func()", + "read": "contentData", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlListProperty", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 27, + "name": "contentChildren", + "notify": "contentChildrenChanged", + "privateClass": "QQuickPopup::d_func()", + "read": "contentChildren", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlListProperty", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 28, + "name": "clip", + "notify": "clipChanged", + "read": "clip", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setClip" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 29, + "name": "focus", + "notify": "focusChanged", + "read": "hasFocus", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setFocus" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 30, + "name": "activeFocus", + "notify": "activeFocusChanged", + "read": "hasActiveFocus", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 31, + "name": "modal", + "notify": "modalChanged", + "read": "isModal", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setModal" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 32, + "name": "dim", + "notify": "dimChanged", + "read": "dim", + "required": false, + "reset": "resetDim", + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setDim" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 33, + "name": "visible", + "notify": "visibleChanged", + "read": "isVisible", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setVisible" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 34, + "name": "opacity", + "notify": "opacityChanged", + "read": "opacity", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setOpacity" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 35, + "name": "scale", + "notify": "scaleChanged", + "read": "scale", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setScale" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 36, + "name": "closePolicy", + "notify": "closePolicyChanged", + "read": "closePolicy", + "required": false, + "reset": "resetClosePolicy", + "scriptable": true, + "stored": true, + "type": "ClosePolicy", + "user": false, + "write": "setClosePolicy" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 37, + "name": "transformOrigin", + "read": "transformOrigin", + "required": false, + "scriptable": true, + "stored": true, + "type": "TransformOrigin", + "user": false, + "write": "setTransformOrigin" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 38, + "name": "enter", + "notify": "enterChanged", + "read": "enter", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickTransition*", + "user": false, + "write": "setEnter" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 39, + "name": "exit", + "notify": "exitChanged", + "read": "exit", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickTransition*", + "user": false, + "write": "setExit" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 40, + "name": "spacing", + "notify": "spacingChanged", + "read": "spacing", + "required": false, + "reset": "resetSpacing", + "revision": 513, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setSpacing" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 41, + "name": "opened", + "notify": "openedChanged", + "read": "isOpened", + "required": false, + "revision": 515, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 42, + "name": "mirrored", + "notify": "mirroredChanged", + "read": "isMirrored", + "required": false, + "revision": 515, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 43, + "name": "enabled", + "notify": "enabledChanged", + "read": "isEnabled", + "required": false, + "revision": 515, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setEnabled" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 44, + "name": "palette", + "notify": "paletteChanged", + "privateClass": "QQuickPopup::d_func()", + "read": "palette", + "required": false, + "reset": "resetPalette", + "revision": 515, + "scriptable": true, + "stored": true, + "type": "QQuickPalette*", + "user": false, + "write": "setPalette" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 45, + "name": "horizontalPadding", + "notify": "horizontalPaddingChanged", + "read": "horizontalPadding", + "required": false, + "reset": "resetHorizontalPadding", + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setHorizontalPadding" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 46, + "name": "verticalPadding", + "notify": "verticalPaddingChanged", + "read": "verticalPadding", + "required": false, + "reset": "resetVerticalPadding", + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setVerticalPadding" + }, + { + "constant": true, + "designable": false, + "final": true, + "index": 47, + "name": "anchors", + "privateClass": "QQuickPopup::d_func()", + "read": "getAnchors", + "required": false, + "revision": 517, + "scriptable": true, + "stored": true, + "type": "QQuickPopupAnchors*", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 48, + "name": "implicitContentWidth", + "notify": "implicitContentWidthChanged", + "read": "implicitContentWidth", + "required": false, + "revision": 517, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 49, + "name": "implicitContentHeight", + "notify": "implicitContentHeightChanged", + "read": "implicitContentHeight", + "required": false, + "revision": 517, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 50, + "name": "implicitBackgroundWidth", + "notify": "implicitBackgroundWidthChanged", + "read": "implicitBackgroundWidth", + "required": false, + "revision": 517, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 51, + "name": "implicitBackgroundHeight", + "notify": "implicitBackgroundHeightChanged", + "read": "implicitBackgroundHeight", + "required": false, + "revision": 517, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 52, + "name": "topInset", + "notify": "topInsetChanged", + "read": "topInset", + "required": false, + "reset": "resetTopInset", + "revision": 517, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setTopInset" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 53, + "name": "leftInset", + "notify": "leftInsetChanged", + "read": "leftInset", + "required": false, + "reset": "resetLeftInset", + "revision": 517, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setLeftInset" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 54, + "name": "rightInset", + "notify": "rightInsetChanged", + "read": "rightInset", + "required": false, + "reset": "resetRightInset", + "revision": 517, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setRightInset" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 55, + "name": "bottomInset", + "notify": "bottomInsetChanged", + "read": "bottomInset", + "required": false, + "reset": "resetBottomInset", + "revision": 517, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setBottomInset" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 56, + "name": "popupType", + "notify": "popupTypeChanged", + "read": "popupType", + "required": false, + "revision": 1544, + "scriptable": true, + "stored": true, + "type": "PopupType", + "user": false, + "write": "setPopupType" + } + ], + "qualifiedClassName": "QQuickPopup", + "signals": [ + { + "access": "public", + "index": 0, + "name": "opened", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "closed", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "aboutToShow", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "aboutToHide", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "xChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "yChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "zChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "widthChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 8, + "name": "heightChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 9, + "name": "implicitWidthChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 10, + "name": "implicitHeightChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 11, + "name": "contentWidthChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 12, + "name": "contentHeightChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 13, + "name": "availableWidthChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 14, + "name": "availableHeightChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 15, + "name": "marginsChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 16, + "name": "topMarginChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 17, + "name": "leftMarginChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 18, + "name": "rightMarginChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 19, + "name": "bottomMarginChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 20, + "name": "paddingChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 21, + "name": "topPaddingChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 22, + "name": "leftPaddingChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 23, + "name": "rightPaddingChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 24, + "name": "bottomPaddingChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 25, + "name": "fontChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 26, + "name": "localeChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 27, + "name": "parentChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 28, + "name": "backgroundChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 29, + "name": "contentItemChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 30, + "name": "contentChildrenChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 31, + "name": "clipChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 32, + "name": "focusChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 33, + "name": "activeFocusChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 34, + "name": "modalChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 35, + "name": "dimChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 36, + "name": "visibleChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 37, + "name": "opacityChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 38, + "name": "scaleChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 39, + "name": "closePolicyChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 40, + "name": "enterChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 41, + "name": "exitChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "window", + "type": "QQuickWindow*" + } + ], + "index": 42, + "name": "windowChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 43, + "name": "spacingChanged", + "returnType": "void", + "revision": 513 + }, + { + "access": "public", + "index": 44, + "name": "openedChanged", + "returnType": "void", + "revision": 515 + }, + { + "access": "public", + "index": 45, + "name": "mirroredChanged", + "returnType": "void", + "revision": 515 + }, + { + "access": "public", + "index": 46, + "name": "enabledChanged", + "returnType": "void", + "revision": 515 + }, + { + "access": "public", + "index": 47, + "name": "paletteChanged", + "returnType": "void", + "revision": 515 + }, + { + "access": "public", + "index": 48, + "name": "paletteCreated", + "returnType": "void", + "revision": 515 + }, + { + "access": "public", + "index": 49, + "name": "horizontalPaddingChanged", + "returnType": "void", + "revision": 517 + }, + { + "access": "public", + "index": 50, + "name": "verticalPaddingChanged", + "returnType": "void", + "revision": 517 + }, + { + "access": "public", + "index": 51, + "name": "implicitContentWidthChanged", + "returnType": "void", + "revision": 517 + }, + { + "access": "public", + "index": 52, + "name": "implicitContentHeightChanged", + "returnType": "void", + "revision": 517 + }, + { + "access": "public", + "index": 53, + "name": "implicitBackgroundWidthChanged", + "returnType": "void", + "revision": 517 + }, + { + "access": "public", + "index": 54, + "name": "implicitBackgroundHeightChanged", + "returnType": "void", + "revision": 517 + }, + { + "access": "public", + "index": 55, + "name": "topInsetChanged", + "returnType": "void", + "revision": 517 + }, + { + "access": "public", + "index": 56, + "name": "leftInsetChanged", + "returnType": "void", + "revision": 517 + }, + { + "access": "public", + "index": 57, + "name": "rightInsetChanged", + "returnType": "void", + "revision": 517 + }, + { + "access": "public", + "index": 58, + "name": "bottomInsetChanged", + "returnType": "void", + "revision": 517 + }, + { + "access": "public", + "index": 59, + "name": "popupTypeChanged", + "returnType": "void", + "revision": 1544 + } + ], + "slots": [ + { + "access": "public", + "index": 60, + "name": "open", + "returnType": "void" + }, + { + "access": "public", + "index": 61, + "name": "close", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QQmlParserStatus" + } + ] + } + ], + "inputFile": "qquickpopup_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.AddedInVersion", + "value": "517" + } + ], + "className": "QQuickPopupAnchors", + "lineNumber": 29, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "centerIn", + "notify": "centerInChanged", + "read": "centerIn", + "required": false, + "reset": "resetCenterIn", + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false, + "write": "setCenterIn" + } + ], + "qualifiedClassName": "QQuickPopupAnchors", + "signals": [ + { + "access": "public", + "index": 0, + "name": "centerInChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QQuickItemChangeListener" + } + ] + } + ], + "inputFile": "qquickpopupanchors_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQuickPopupItem", + "lineNumber": 26, + "object": true, + "qualifiedClassName": "QQuickPopupItem", + "superClasses": [ + { + "access": "public", + "name": "QQuickPage" + } + ] + } + ], + "inputFile": "qquickpopupitem_p_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "ProgressBar" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickProgressBar", + "lineNumber": 24, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "from", + "notify": "fromChanged", + "read": "from", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setFrom" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "to", + "notify": "toChanged", + "read": "to", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setTo" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "value", + "notify": "valueChanged", + "read": "value", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setValue" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "position", + "notify": "positionChanged", + "read": "position", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "visualPosition", + "notify": "visualPositionChanged", + "read": "visualPosition", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "indeterminate", + "notify": "indeterminateChanged", + "read": "isIndeterminate", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setIndeterminate" + } + ], + "qualifiedClassName": "QQuickProgressBar", + "signals": [ + { + "access": "public", + "index": 0, + "name": "fromChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "toChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "valueChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "positionChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "visualPositionChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "indeterminateChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickControl" + } + ] + } + ], + "inputFile": "qquickprogressbar_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "RadioButton" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickRadioButton", + "lineNumber": 25, + "object": true, + "qualifiedClassName": "QQuickRadioButton", + "superClasses": [ + { + "access": "public", + "name": "QQuickAbstractButton" + } + ] + } + ], + "inputFile": "qquickradiobutton_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "RadioDelegate" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickRadioDelegate", + "lineNumber": 24, + "object": true, + "qualifiedClassName": "QQuickRadioDelegate", + "superClasses": [ + { + "access": "public", + "name": "QQuickItemDelegate" + } + ] + } + ], + "inputFile": "qquickradiodelegate_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "RangeSlider" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickRangeSlider", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "SnapMode", + "values": [ + "NoSnap", + "SnapAlways", + "SnapOnRelease" + ] + } + ], + "lineNumber": 25, + "methods": [ + { + "access": "public", + "arguments": [ + { + "name": "firstValue", + "type": "qreal" + }, + { + "name": "secondValue", + "type": "qreal" + } + ], + "index": 7, + "name": "setValues", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "position", + "type": "qreal" + } + ], + "index": 8, + "name": "valueAt", + "returnType": "qreal", + "revision": 517 + } + ], + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "from", + "notify": "fromChanged", + "read": "from", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setFrom" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "to", + "notify": "toChanged", + "read": "to", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setTo" + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 2, + "name": "first", + "read": "first", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickRangeSliderNode*", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 3, + "name": "second", + "read": "second", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickRangeSliderNode*", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "stepSize", + "notify": "stepSizeChanged", + "read": "stepSize", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setStepSize" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "snapMode", + "notify": "snapModeChanged", + "read": "snapMode", + "required": false, + "scriptable": true, + "stored": true, + "type": "SnapMode", + "user": false, + "write": "setSnapMode" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 6, + "name": "orientation", + "notify": "orientationChanged", + "read": "orientation", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::Orientation", + "user": false, + "write": "setOrientation" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 7, + "name": "live", + "notify": "liveChanged", + "read": "live", + "required": false, + "revision": 514, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setLive" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 8, + "name": "horizontal", + "notify": "orientationChanged", + "read": "isHorizontal", + "required": false, + "revision": 515, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 9, + "name": "vertical", + "notify": "orientationChanged", + "read": "isVertical", + "required": false, + "revision": 515, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 10, + "name": "touchDragThreshold", + "notify": "touchDragThresholdChanged", + "read": "touchDragThreshold", + "required": false, + "reset": "resetTouchDragThreshold", + "revision": 517, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setTouchDragThreshold" + } + ], + "qualifiedClassName": "QQuickRangeSlider", + "signals": [ + { + "access": "public", + "index": 0, + "name": "fromChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "toChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "stepSizeChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "snapModeChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "orientationChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "liveChanged", + "returnType": "void", + "revision": 514 + }, + { + "access": "public", + "index": 6, + "name": "touchDragThresholdChanged", + "returnType": "void", + "revision": 517 + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickControl" + } + ] + }, + { + "classInfos": [ + { + "name": "DeferredPropertyNames", + "value": "handle" + }, + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickRangeSliderNode", + "lineNumber": 129, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "value", + "notify": "valueChanged", + "read": "value", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setValue" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "position", + "notify": "positionChanged", + "read": "position", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "visualPosition", + "notify": "visualPositionChanged", + "read": "visualPosition", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "handle", + "notify": "handleChanged", + "read": "handle", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false, + "write": "setHandle" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "pressed", + "notify": "pressedChanged", + "read": "isPressed", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setPressed" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "hovered", + "notify": "hoveredChanged", + "read": "isHovered", + "required": false, + "revision": 513, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setHovered" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 6, + "name": "implicitHandleWidth", + "notify": "implicitHandleWidthChanged", + "read": "implicitHandleWidth", + "required": false, + "revision": 517, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 7, + "name": "implicitHandleHeight", + "notify": "implicitHandleHeightChanged", + "read": "implicitHandleHeight", + "required": false, + "revision": 517, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + } + ], + "qualifiedClassName": "QQuickRangeSliderNode", + "signals": [ + { + "access": "public", + "index": 0, + "name": "valueChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "positionChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "visualPositionChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "handleChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "pressedChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "hoveredChanged", + "returnType": "void", + "revision": 513 + }, + { + "access": "public", + "index": 6, + "name": "moved", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "implicitHandleWidthChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 8, + "name": "implicitHandleHeightChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "index": 9, + "name": "increase", + "returnType": "void" + }, + { + "access": "public", + "index": 10, + "name": "decrease", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qquickrangeslider_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "RoundButton" + }, + { + "name": "QML.AddedInVersion", + "value": "513" + } + ], + "className": "QQuickRoundButton", + "lineNumber": 24, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "radius", + "notify": "radiusChanged", + "read": "radius", + "required": false, + "reset": "resetRadius", + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setRadius" + } + ], + "qualifiedClassName": "QQuickRoundButton", + "signals": [ + { + "access": "public", + "index": 0, + "name": "radiusChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickButton" + } + ] + } + ], + "inputFile": "qquickroundbutton_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "ScrollBar" + }, + { + "name": "QML.Attached", + "value": "QQuickScrollBarAttached" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickScrollBar", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "SnapMode", + "values": [ + "NoSnap", + "SnapAlways", + "SnapOnRelease" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "Policy", + "values": [ + "AsNeeded", + "AlwaysOff", + "AlwaysOn" + ] + } + ], + "lineNumber": 25, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "size", + "notify": "sizeChanged", + "read": "size", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setSize" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "position", + "notify": "positionChanged", + "read": "position", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setPosition" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "stepSize", + "notify": "stepSizeChanged", + "read": "stepSize", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setStepSize" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "active", + "notify": "activeChanged", + "read": "isActive", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setActive" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "pressed", + "notify": "pressedChanged", + "read": "isPressed", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setPressed" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "orientation", + "notify": "orientationChanged", + "read": "orientation", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::Orientation", + "user": false, + "write": "setOrientation" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 6, + "name": "snapMode", + "notify": "snapModeChanged", + "read": "snapMode", + "required": false, + "revision": 514, + "scriptable": true, + "stored": true, + "type": "SnapMode", + "user": false, + "write": "setSnapMode" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 7, + "name": "interactive", + "notify": "interactiveChanged", + "read": "isInteractive", + "required": false, + "reset": "resetInteractive", + "revision": 514, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setInteractive" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 8, + "name": "policy", + "notify": "policyChanged", + "read": "policy", + "required": false, + "revision": 514, + "scriptable": true, + "stored": true, + "type": "Policy", + "user": false, + "write": "setPolicy" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 9, + "name": "horizontal", + "notify": "orientationChanged", + "read": "isHorizontal", + "required": false, + "revision": 515, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 10, + "name": "vertical", + "notify": "orientationChanged", + "read": "isVertical", + "required": false, + "revision": 515, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 11, + "name": "minimumSize", + "notify": "minimumSizeChanged", + "read": "minimumSize", + "required": false, + "revision": 516, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setMinimumSize" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 12, + "name": "visualSize", + "notify": "visualSizeChanged", + "read": "visualSize", + "required": false, + "revision": 516, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 13, + "name": "visualPosition", + "notify": "visualPositionChanged", + "read": "visualPosition", + "required": false, + "revision": 516, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 14, + "name": "__decreaseVisual", + "read": "decreaseVisual", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickIndicatorButton*", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 15, + "name": "__increaseVisual", + "read": "increaseVisual", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickIndicatorButton*", + "user": false + } + ], + "qualifiedClassName": "QQuickScrollBar", + "signals": [ + { + "access": "public", + "index": 0, + "name": "sizeChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "positionChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "stepSizeChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "activeChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "pressedChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "orientationChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "snapModeChanged", + "returnType": "void", + "revision": 514 + }, + { + "access": "public", + "index": 7, + "name": "interactiveChanged", + "returnType": "void", + "revision": 514 + }, + { + "access": "public", + "index": 8, + "name": "policyChanged", + "returnType": "void", + "revision": 514 + }, + { + "access": "public", + "index": 9, + "name": "minimumSizeChanged", + "returnType": "void", + "revision": 516 + }, + { + "access": "public", + "index": 10, + "name": "visualSizeChanged", + "returnType": "void", + "revision": 516 + }, + { + "access": "public", + "index": 11, + "name": "visualPositionChanged", + "returnType": "void", + "revision": 516 + } + ], + "slots": [ + { + "access": "public", + "index": 12, + "name": "increase", + "returnType": "void" + }, + { + "access": "public", + "index": 13, + "name": "decrease", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "size", + "type": "qreal" + } + ], + "index": 14, + "name": "setSize", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "position", + "type": "qreal" + } + ], + "index": 15, + "name": "setPosition", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickControl" + } + ] + }, + { + "className": "QQuickScrollBarAttached", + "lineNumber": 159, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "horizontal", + "notify": "horizontalChanged", + "read": "horizontal", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickScrollBar*", + "user": false, + "write": "setHorizontal" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "vertical", + "notify": "verticalChanged", + "read": "vertical", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickScrollBar*", + "user": false, + "write": "setVertical" + } + ], + "qualifiedClassName": "QQuickScrollBarAttached", + "signals": [ + { + "access": "public", + "index": 0, + "name": "horizontalChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "verticalChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qquickscrollbar_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "ScrollIndicator" + }, + { + "name": "QML.Attached", + "value": "QQuickScrollIndicatorAttached" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickScrollIndicator", + "lineNumber": 26, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "size", + "notify": "sizeChanged", + "read": "size", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setSize" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "position", + "notify": "positionChanged", + "read": "position", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setPosition" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "active", + "notify": "activeChanged", + "read": "isActive", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setActive" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "orientation", + "notify": "orientationChanged", + "read": "orientation", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::Orientation", + "user": false, + "write": "setOrientation" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "horizontal", + "notify": "orientationChanged", + "read": "isHorizontal", + "required": false, + "revision": 515, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "vertical", + "notify": "orientationChanged", + "read": "isVertical", + "required": false, + "revision": 515, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 6, + "name": "minimumSize", + "notify": "minimumSizeChanged", + "read": "minimumSize", + "required": false, + "revision": 516, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setMinimumSize" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 7, + "name": "visualSize", + "notify": "visualSizeChanged", + "read": "visualSize", + "required": false, + "revision": 516, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 8, + "name": "visualPosition", + "notify": "visualPositionChanged", + "read": "visualPosition", + "required": false, + "revision": 516, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + } + ], + "qualifiedClassName": "QQuickScrollIndicator", + "signals": [ + { + "access": "public", + "index": 0, + "name": "sizeChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "positionChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "activeChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "orientationChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "minimumSizeChanged", + "returnType": "void", + "revision": 516 + }, + { + "access": "public", + "index": 5, + "name": "visualSizeChanged", + "returnType": "void", + "revision": 516 + }, + { + "access": "public", + "index": 6, + "name": "visualPositionChanged", + "returnType": "void", + "revision": 516 + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "size", + "type": "qreal" + } + ], + "index": 7, + "name": "setSize", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "position", + "type": "qreal" + } + ], + "index": 8, + "name": "setPosition", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickControl" + } + ] + }, + { + "className": "QQuickScrollIndicatorAttached", + "lineNumber": 99, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "horizontal", + "notify": "horizontalChanged", + "read": "horizontal", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickScrollIndicator*", + "user": false, + "write": "setHorizontal" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "vertical", + "notify": "verticalChanged", + "read": "vertical", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickScrollIndicator*", + "user": false, + "write": "setVertical" + } + ], + "qualifiedClassName": "QQuickScrollIndicatorAttached", + "signals": [ + { + "access": "public", + "index": 0, + "name": "horizontalChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "verticalChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qquickscrollindicator_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "ScrollView" + }, + { + "name": "QML.AddedInVersion", + "value": "514" + } + ], + "className": "QQuickScrollView", + "lineNumber": 25, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "effectiveScrollBarWidth", + "notify": "effectiveScrollBarWidthChanged", + "read": "effectiveScrollBarWidth", + "required": false, + "revision": 1542, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "effectiveScrollBarHeight", + "notify": "effectiveScrollBarHeightChanged", + "read": "effectiveScrollBarHeight", + "required": false, + "revision": 1542, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + } + ], + "qualifiedClassName": "QQuickScrollView", + "signals": [ + { + "access": "public", + "index": 0, + "name": "effectiveScrollBarWidthChanged", + "returnType": "void", + "revision": 1542 + }, + { + "access": "public", + "index": 1, + "name": "effectiveScrollBarHeightChanged", + "returnType": "void", + "revision": 1542 + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickPane" + } + ] + } + ], + "inputFile": "qquickscrollview_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "SelectionRectangle" + }, + { + "name": "QML.Attached", + "value": "QQuickSelectionRectangleAttached" + }, + { + "name": "QML.AddedInVersion", + "value": "1538" + } + ], + "className": "QQuickSelectionRectangle", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "SelectionMode", + "values": [ + "Drag", + "PressAndHold", + "Auto" + ] + } + ], + "lineNumber": 29, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "selectionMode", + "notify": "selectionModeChanged", + "read": "selectionMode", + "required": false, + "scriptable": true, + "stored": true, + "type": "SelectionMode", + "user": false, + "write": "setSelectionMode" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "target", + "notify": "targetChanged", + "read": "target", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false, + "write": "setTarget" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "topLeftHandle", + "notify": "topLeftHandleChanged", + "read": "topLeftHandle", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlComponent*", + "user": false, + "write": "setTopLeftHandle" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "bottomRightHandle", + "notify": "bottomRightHandleChanged", + "read": "bottomRightHandle", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlComponent*", + "user": false, + "write": "setBottomRightHandle" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "active", + "notify": "activeChanged", + "read": "active", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "dragging", + "notify": "draggingChanged", + "read": "dragging", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + } + ], + "qualifiedClassName": "QQuickSelectionRectangle", + "signals": [ + { + "access": "public", + "index": 0, + "name": "targetChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "activeChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "draggingChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "topLeftHandleChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "bottomRightHandleChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "selectionModeChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickControl" + } + ] + }, + { + "className": "QQuickSelectionRectangleAttached", + "lineNumber": 82, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "control", + "notify": "controlChanged", + "read": "control", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickSelectionRectangle*", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "dragging", + "notify": "draggingChanged", + "read": "dragging", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + } + ], + "qualifiedClassName": "QQuickSelectionRectangleAttached", + "signals": [ + { + "access": "public", + "index": 0, + "name": "controlChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "draggingChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qquickselectionrectangle_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "DeferredPropertyNames", + "value": "background,handle" + }, + { + "name": "QML.Element", + "value": "Slider" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickSlider", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "SnapMode", + "values": [ + "NoSnap", + "SnapAlways", + "SnapOnRelease" + ] + } + ], + "lineNumber": 24, + "methods": [ + { + "access": "public", + "arguments": [ + { + "name": "position", + "type": "qreal" + } + ], + "index": 17, + "name": "valueAt", + "returnType": "qreal", + "revision": 513 + } + ], + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "from", + "notify": "fromChanged", + "read": "from", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setFrom" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "to", + "notify": "toChanged", + "read": "to", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setTo" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "value", + "notify": "valueChanged", + "read": "value", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setValue" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "position", + "notify": "positionChanged", + "read": "position", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "visualPosition", + "notify": "visualPositionChanged", + "read": "visualPosition", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "stepSize", + "notify": "stepSizeChanged", + "read": "stepSize", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setStepSize" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 6, + "name": "snapMode", + "notify": "snapModeChanged", + "read": "snapMode", + "required": false, + "scriptable": true, + "stored": true, + "type": "SnapMode", + "user": false, + "write": "setSnapMode" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 7, + "name": "pressed", + "notify": "pressedChanged", + "read": "isPressed", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setPressed" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 8, + "name": "orientation", + "notify": "orientationChanged", + "read": "orientation", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::Orientation", + "user": false, + "write": "setOrientation" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 9, + "name": "handle", + "notify": "handleChanged", + "read": "handle", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false, + "write": "setHandle" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 10, + "name": "live", + "notify": "liveChanged", + "read": "live", + "required": false, + "revision": 514, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setLive" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 11, + "name": "horizontal", + "notify": "orientationChanged", + "read": "isHorizontal", + "required": false, + "revision": 515, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 12, + "name": "vertical", + "notify": "orientationChanged", + "read": "isVertical", + "required": false, + "revision": 515, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 13, + "name": "touchDragThreshold", + "notify": "touchDragThresholdChanged", + "read": "touchDragThreshold", + "required": false, + "reset": "resetTouchDragThreshold", + "revision": 517, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setTouchDragThreshold" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 14, + "name": "implicitHandleWidth", + "notify": "implicitHandleWidthChanged", + "read": "implicitHandleWidth", + "required": false, + "revision": 517, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 15, + "name": "implicitHandleHeight", + "notify": "implicitHandleHeightChanged", + "read": "implicitHandleHeight", + "required": false, + "revision": 517, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + } + ], + "qualifiedClassName": "QQuickSlider", + "signals": [ + { + "access": "public", + "index": 0, + "name": "fromChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "toChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "valueChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "positionChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "visualPositionChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "stepSizeChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "snapModeChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "pressedChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 8, + "name": "orientationChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 9, + "name": "handleChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 10, + "name": "moved", + "returnType": "void", + "revision": 514 + }, + { + "access": "public", + "index": 11, + "name": "liveChanged", + "returnType": "void", + "revision": 514 + }, + { + "access": "public", + "index": 12, + "name": "touchDragThresholdChanged", + "returnType": "void", + "revision": 517 + }, + { + "access": "public", + "index": 13, + "name": "implicitHandleWidthChanged", + "returnType": "void", + "revision": 517 + }, + { + "access": "public", + "index": 14, + "name": "implicitHandleHeightChanged", + "returnType": "void", + "revision": 517 + } + ], + "slots": [ + { + "access": "public", + "index": 15, + "name": "increase", + "returnType": "void" + }, + { + "access": "public", + "index": 16, + "name": "decrease", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickControl" + } + ] + } + ], + "inputFile": "qquickslider_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "SpinBox" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickSpinBox", + "lineNumber": 27, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "from", + "notify": "fromChanged", + "read": "from", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setFrom" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "to", + "notify": "toChanged", + "read": "to", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setTo" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "value", + "notify": "valueChanged", + "read": "value", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setValue" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "stepSize", + "notify": "stepSizeChanged", + "read": "stepSize", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setStepSize" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "editable", + "notify": "editableChanged", + "read": "isEditable", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setEditable" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "live", + "notify": "liveChanged", + "read": "isLive", + "required": false, + "revision": 1542, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setLive" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 6, + "name": "validator", + "notify": "validatorChanged", + "read": "validator", + "required": false, + "scriptable": true, + "stored": true, + "type": "QValidator*", + "user": false, + "write": "setValidator" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 7, + "name": "textFromValue", + "notify": "textFromValueChanged", + "read": "textFromValue", + "required": false, + "scriptable": true, + "stored": true, + "type": "QJSValue", + "user": false, + "write": "setTextFromValue" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 8, + "name": "valueFromText", + "notify": "valueFromTextChanged", + "read": "valueFromText", + "required": false, + "scriptable": true, + "stored": true, + "type": "QJSValue", + "user": false, + "write": "setValueFromText" + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 9, + "name": "up", + "read": "up", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickIndicatorButton*", + "user": false + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 10, + "name": "down", + "read": "down", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickIndicatorButton*", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 11, + "name": "inputMethodHints", + "notify": "inputMethodHintsChanged", + "read": "inputMethodHints", + "required": false, + "revision": 514, + "scriptable": true, + "stored": true, + "type": "Qt::InputMethodHints", + "user": false, + "write": "setInputMethodHints" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 12, + "name": "inputMethodComposing", + "notify": "inputMethodComposingChanged", + "read": "isInputMethodComposing", + "required": false, + "revision": 514, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 13, + "name": "wrap", + "notify": "wrapChanged", + "read": "wrap", + "required": false, + "revision": 515, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setWrap" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 14, + "name": "displayText", + "notify": "displayTextChanged", + "read": "displayText", + "required": false, + "revision": 516, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + } + ], + "qualifiedClassName": "QQuickSpinBox", + "signals": [ + { + "access": "public", + "index": 0, + "name": "fromChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "toChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "valueChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "stepSizeChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "editableChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "liveChanged", + "returnType": "void", + "revision": 1542 + }, + { + "access": "public", + "index": 6, + "name": "validatorChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "textFromValueChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 8, + "name": "valueFromTextChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 9, + "name": "valueModified", + "returnType": "void", + "revision": 514 + }, + { + "access": "public", + "index": 10, + "name": "inputMethodHintsChanged", + "returnType": "void", + "revision": 514 + }, + { + "access": "public", + "index": 11, + "name": "inputMethodComposingChanged", + "returnType": "void", + "revision": 514 + }, + { + "access": "public", + "index": 12, + "name": "wrapChanged", + "returnType": "void", + "revision": 515 + }, + { + "access": "public", + "index": 13, + "name": "displayTextChanged", + "returnType": "void", + "revision": 516 + } + ], + "slots": [ + { + "access": "public", + "index": 14, + "name": "increase", + "returnType": "void" + }, + { + "access": "public", + "index": 15, + "name": "decrease", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickControl" + } + ] + } + ], + "inputFile": "qquickspinbox_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "SplitView" + }, + { + "name": "QML.Attached", + "value": "QQuickSplitViewAttached" + }, + { + "name": "QML.AddedInVersion", + "value": "525" + } + ], + "className": "QQuickSplitView", + "lineNumber": 31, + "methods": [ + { + "access": "public", + "index": 3, + "name": "saveState", + "returnType": "QVariant" + }, + { + "access": "public", + "arguments": [ + { + "name": "state", + "type": "QVariant" + } + ], + "index": 4, + "name": "restoreState", + "returnType": "bool" + } + ], + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "orientation", + "notify": "orientationChanged", + "read": "orientation", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::Orientation", + "user": false, + "write": "setOrientation" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "resizing", + "notify": "resizingChanged", + "read": "isResizing", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "handle", + "notify": "handleChanged", + "read": "handle", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlComponent*", + "user": false, + "write": "setHandle" + } + ], + "qualifiedClassName": "QQuickSplitView", + "signals": [ + { + "access": "public", + "index": 0, + "name": "orientationChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "resizingChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "handleChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickContainer" + } + ] + }, + { + "className": "QQuickSplitViewAttached", + "lineNumber": 91, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "view", + "notify": "viewChanged", + "read": "view", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickSplitView*", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "minimumWidth", + "notify": "minimumWidthChanged", + "read": "minimumWidth", + "required": false, + "reset": "resetMinimumWidth", + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setMinimumWidth" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "minimumHeight", + "notify": "minimumHeightChanged", + "read": "minimumHeight", + "required": false, + "reset": "resetMinimumHeight", + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setMinimumHeight" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "preferredWidth", + "notify": "preferredWidthChanged", + "read": "preferredWidth", + "required": false, + "reset": "resetPreferredWidth", + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setPreferredWidth" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "preferredHeight", + "notify": "preferredHeightChanged", + "read": "preferredHeight", + "required": false, + "reset": "resetPreferredHeight", + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setPreferredHeight" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "maximumWidth", + "notify": "maximumWidthChanged", + "read": "maximumWidth", + "required": false, + "reset": "resetMaximumWidth", + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setMaximumWidth" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 6, + "name": "maximumHeight", + "notify": "maximumHeightChanged", + "read": "maximumHeight", + "required": false, + "reset": "resetMaximumHeight", + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setMaximumHeight" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 7, + "name": "fillHeight", + "notify": "fillHeightChanged", + "read": "fillHeight", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setFillHeight" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 8, + "name": "fillWidth", + "notify": "fillWidthChanged", + "read": "fillWidth", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setFillWidth" + } + ], + "qualifiedClassName": "QQuickSplitViewAttached", + "signals": [ + { + "access": "public", + "index": 0, + "name": "viewChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "minimumWidthChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "minimumHeightChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "preferredWidthChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "preferredHeightChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "maximumWidthChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "maximumHeightChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "fillWidthChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 8, + "name": "fillHeightChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "SplitHandle" + }, + { + "name": "QML.Attached", + "value": "QQuickSplitHandleAttached" + }, + { + "name": "QML.Creatable", + "value": "false" + }, + { + "name": "QML.UncreatableReason", + "value": "" + }, + { + "name": "QML.AddedInVersion", + "value": "525" + } + ], + "className": "QQuickSplitHandleAttached", + "lineNumber": 161, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "hovered", + "notify": "hoveredChanged", + "read": "isHovered", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "pressed", + "notify": "pressedChanged", + "read": "isPressed", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + } + ], + "qualifiedClassName": "QQuickSplitHandleAttached", + "signals": [ + { + "access": "public", + "index": 0, + "name": "hoveredChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "pressedChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qquicksplitview_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Creatable", + "value": "true" + }, + { + "name": "QML.CreationMethod", + "value": "construct" + }, + { + "name": "QML.Element", + "value": "anonymous" + } + ], + "className": "QQuickStackViewArg", + "constructors": [ + { + "access": "public", + "arguments": [ + { + "name": "item", + "type": "QQuickItem*" + } + ], + "index": 0, + "name": "QQuickStackViewArg", + "returnType": "" + }, + { + "access": "public", + "arguments": [ + { + "name": "url", + "type": "QUrl" + } + ], + "index": 1, + "name": "QQuickStackViewArg", + "returnType": "" + }, + { + "access": "public", + "arguments": [ + { + "name": "component", + "type": "QQmlComponent*" + } + ], + "index": 2, + "name": "QQuickStackViewArg", + "returnType": "" + }, + { + "access": "public", + "arguments": [ + { + "name": "properties", + "type": "QVariantMap" + } + ], + "index": 3, + "name": "QQuickStackViewArg", + "returnType": "" + } + ], + "gadget": true, + "lineNumber": 37, + "qualifiedClassName": "QQuickStackViewArg" + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "StackView" + }, + { + "name": "QML.Attached", + "value": "QQuickStackViewAttached" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickStackView", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "Status", + "values": [ + "Inactive", + "Deactivating", + "Activating", + "Active" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "LoadBehavior", + "values": [ + "DontLoad", + "ForceLoad" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "Operation", + "values": [ + "Transition", + "Immediate", + "PushTransition", + "ReplaceTransition", + "PopTransition" + ] + } + ], + "lineNumber": 64, + "methods": [ + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + }, + { + "name": "behavior", + "type": "QQuickStackView::LoadBehavior" + } + ], + "index": 12, + "name": "get", + "returnType": "QQuickItem*" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + } + ], + "index": 13, + "isCloned": true, + "name": "get", + "returnType": "QQuickItem*" + }, + { + "access": "public", + "arguments": [ + { + "name": "callback", + "type": "QJSValue" + }, + { + "name": "behavior", + "type": "QQuickStackView::LoadBehavior" + } + ], + "index": 14, + "name": "find", + "returnType": "QQuickItem*" + }, + { + "access": "public", + "arguments": [ + { + "name": "callback", + "type": "QJSValue" + } + ], + "index": 15, + "isCloned": true, + "name": "find", + "returnType": "QQuickItem*" + }, + { + "access": "public", + "arguments": [ + { + "name": "args", + "type": "QQmlV4FunctionPtr" + } + ], + "index": 16, + "name": "push", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "args", + "type": "QQmlV4FunctionPtr" + } + ], + "index": 17, + "name": "pop", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "args", + "type": "QQmlV4FunctionPtr" + } + ], + "index": 18, + "name": "replace", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "args", + "type": "QList" + }, + { + "name": "operation", + "type": "Operation" + } + ], + "index": 19, + "name": "pushItems", + "returnType": "QQuickItem*", + "revision": 1543 + }, + { + "access": "public", + "arguments": [ + { + "name": "args", + "type": "QList" + } + ], + "index": 20, + "isCloned": true, + "name": "pushItems", + "returnType": "QQuickItem*", + "revision": 1543 + }, + { + "access": "public", + "arguments": [ + { + "name": "item", + "type": "QQuickItem*" + }, + { + "name": "properties", + "type": "QVariantMap" + }, + { + "name": "operation", + "type": "Operation" + } + ], + "index": 21, + "name": "pushItem", + "returnType": "QQuickItem*", + "revision": 1543 + }, + { + "access": "public", + "arguments": [ + { + "name": "item", + "type": "QQuickItem*" + }, + { + "name": "properties", + "type": "QVariantMap" + } + ], + "index": 22, + "isCloned": true, + "name": "pushItem", + "returnType": "QQuickItem*", + "revision": 1543 + }, + { + "access": "public", + "arguments": [ + { + "name": "item", + "type": "QQuickItem*" + } + ], + "index": 23, + "isCloned": true, + "name": "pushItem", + "returnType": "QQuickItem*", + "revision": 1543 + }, + { + "access": "public", + "arguments": [ + { + "name": "component", + "type": "QQmlComponent*" + }, + { + "name": "properties", + "type": "QVariantMap" + }, + { + "name": "operation", + "type": "Operation" + } + ], + "index": 24, + "name": "pushItem", + "returnType": "QQuickItem*", + "revision": 1543 + }, + { + "access": "public", + "arguments": [ + { + "name": "component", + "type": "QQmlComponent*" + }, + { + "name": "properties", + "type": "QVariantMap" + } + ], + "index": 25, + "isCloned": true, + "name": "pushItem", + "returnType": "QQuickItem*", + "revision": 1543 + }, + { + "access": "public", + "arguments": [ + { + "name": "component", + "type": "QQmlComponent*" + } + ], + "index": 26, + "isCloned": true, + "name": "pushItem", + "returnType": "QQuickItem*", + "revision": 1543 + }, + { + "access": "public", + "arguments": [ + { + "name": "url", + "type": "QUrl" + }, + { + "name": "properties", + "type": "QVariantMap" + }, + { + "name": "operation", + "type": "Operation" + } + ], + "index": 27, + "name": "pushItem", + "returnType": "QQuickItem*", + "revision": 1543 + }, + { + "access": "public", + "arguments": [ + { + "name": "url", + "type": "QUrl" + }, + { + "name": "properties", + "type": "QVariantMap" + } + ], + "index": 28, + "isCloned": true, + "name": "pushItem", + "returnType": "QQuickItem*", + "revision": 1543 + }, + { + "access": "public", + "arguments": [ + { + "name": "url", + "type": "QUrl" + } + ], + "index": 29, + "isCloned": true, + "name": "pushItem", + "returnType": "QQuickItem*", + "revision": 1543 + }, + { + "access": "public", + "arguments": [ + { + "name": "item", + "type": "QQuickItem*" + }, + { + "name": "operation", + "type": "Operation" + } + ], + "index": 30, + "name": "popToItem", + "returnType": "QQuickItem*", + "revision": 1543 + }, + { + "access": "public", + "arguments": [ + { + "name": "item", + "type": "QQuickItem*" + } + ], + "index": 31, + "isCloned": true, + "name": "popToItem", + "returnType": "QQuickItem*", + "revision": 1543 + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + }, + { + "name": "operation", + "type": "Operation" + } + ], + "index": 32, + "name": "popToIndex", + "returnType": "QQuickItem*", + "revision": 1543 + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + } + ], + "index": 33, + "isCloned": true, + "name": "popToIndex", + "returnType": "QQuickItem*", + "revision": 1543 + }, + { + "access": "public", + "arguments": [ + { + "name": "operation", + "type": "Operation" + } + ], + "index": 34, + "name": "popCurrentItem", + "returnType": "QQuickItem*", + "revision": 1543 + }, + { + "access": "public", + "index": 35, + "isCloned": true, + "name": "popCurrentItem", + "returnType": "QQuickItem*", + "revision": 1543 + }, + { + "access": "public", + "arguments": [ + { + "name": "args", + "type": "QList" + }, + { + "name": "operation", + "type": "Operation" + } + ], + "index": 36, + "name": "replaceCurrentItem", + "returnType": "QQuickItem*", + "revision": 1543 + }, + { + "access": "public", + "arguments": [ + { + "name": "args", + "type": "QList" + } + ], + "index": 37, + "isCloned": true, + "name": "replaceCurrentItem", + "returnType": "QQuickItem*", + "revision": 1543 + }, + { + "access": "public", + "arguments": [ + { + "name": "item", + "type": "QQuickItem*" + }, + { + "name": "properties", + "type": "QVariantMap" + }, + { + "name": "operation", + "type": "Operation" + } + ], + "index": 38, + "name": "replaceCurrentItem", + "returnType": "QQuickItem*", + "revision": 1543 + }, + { + "access": "public", + "arguments": [ + { + "name": "item", + "type": "QQuickItem*" + }, + { + "name": "properties", + "type": "QVariantMap" + } + ], + "index": 39, + "isCloned": true, + "name": "replaceCurrentItem", + "returnType": "QQuickItem*", + "revision": 1543 + }, + { + "access": "public", + "arguments": [ + { + "name": "item", + "type": "QQuickItem*" + } + ], + "index": 40, + "isCloned": true, + "name": "replaceCurrentItem", + "returnType": "QQuickItem*", + "revision": 1543 + }, + { + "access": "public", + "arguments": [ + { + "name": "component", + "type": "QQmlComponent*" + }, + { + "name": "properties", + "type": "QVariantMap" + }, + { + "name": "operation", + "type": "Operation" + } + ], + "index": 41, + "name": "replaceCurrentItem", + "returnType": "QQuickItem*", + "revision": 1543 + }, + { + "access": "public", + "arguments": [ + { + "name": "component", + "type": "QQmlComponent*" + }, + { + "name": "properties", + "type": "QVariantMap" + } + ], + "index": 42, + "isCloned": true, + "name": "replaceCurrentItem", + "returnType": "QQuickItem*", + "revision": 1543 + }, + { + "access": "public", + "arguments": [ + { + "name": "component", + "type": "QQmlComponent*" + } + ], + "index": 43, + "isCloned": true, + "name": "replaceCurrentItem", + "returnType": "QQuickItem*", + "revision": 1543 + }, + { + "access": "public", + "arguments": [ + { + "name": "url", + "type": "QUrl" + }, + { + "name": "properties", + "type": "QVariantMap" + }, + { + "name": "operation", + "type": "Operation" + } + ], + "index": 44, + "name": "replaceCurrentItem", + "returnType": "QQuickItem*", + "revision": 1543 + }, + { + "access": "public", + "arguments": [ + { + "name": "url", + "type": "QUrl" + }, + { + "name": "properties", + "type": "QVariantMap" + } + ], + "index": 45, + "isCloned": true, + "name": "replaceCurrentItem", + "returnType": "QQuickItem*", + "revision": 1543 + }, + { + "access": "public", + "arguments": [ + { + "name": "url", + "type": "QUrl" + } + ], + "index": 46, + "isCloned": true, + "name": "replaceCurrentItem", + "returnType": "QQuickItem*", + "revision": 1543 + } + ], + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "busy", + "notify": "busyChanged", + "read": "isBusy", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "depth", + "notify": "depthChanged", + "read": "depth", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "currentItem", + "notify": "currentItemChanged", + "read": "currentItem", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "initialItem", + "read": "initialItem", + "required": false, + "scriptable": true, + "stored": true, + "type": "QJSValue", + "user": false, + "write": "setInitialItem" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "popEnter", + "notify": "popEnterChanged", + "read": "popEnter", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickTransition*", + "user": false, + "write": "setPopEnter" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "popExit", + "notify": "popExitChanged", + "read": "popExit", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickTransition*", + "user": false, + "write": "setPopExit" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 6, + "name": "pushEnter", + "notify": "pushEnterChanged", + "read": "pushEnter", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickTransition*", + "user": false, + "write": "setPushEnter" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 7, + "name": "pushExit", + "notify": "pushExitChanged", + "read": "pushExit", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickTransition*", + "user": false, + "write": "setPushExit" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 8, + "name": "replaceEnter", + "notify": "replaceEnterChanged", + "read": "replaceEnter", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickTransition*", + "user": false, + "write": "setReplaceEnter" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 9, + "name": "replaceExit", + "notify": "replaceExitChanged", + "read": "replaceExit", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickTransition*", + "user": false, + "write": "setReplaceExit" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 10, + "name": "empty", + "notify": "emptyChanged", + "read": "isEmpty", + "required": false, + "revision": 515, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + } + ], + "qualifiedClassName": "QQuickStackView", + "signals": [ + { + "access": "public", + "index": 0, + "name": "busyChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "depthChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "currentItemChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "popEnterChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "popExitChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "pushEnterChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "pushExitChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "replaceEnterChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 8, + "name": "replaceExitChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 9, + "name": "emptyChanged", + "returnType": "void", + "revision": 515 + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "operation", + "type": "Operation" + } + ], + "index": 10, + "name": "clear", + "returnType": "void" + }, + { + "access": "public", + "index": 11, + "isCloned": true, + "name": "clear", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickControl" + } + ] + }, + { + "className": "QQuickStackViewAttached", + "lineNumber": 209, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "index", + "notify": "indexChanged", + "read": "index", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "view", + "notify": "viewChanged", + "read": "view", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickStackView*", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "status", + "notify": "statusChanged", + "read": "status", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickStackView::Status", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "visible", + "notify": "visibleChanged", + "read": "isVisible", + "required": false, + "reset": "resetVisible", + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setVisible" + } + ], + "qualifiedClassName": "QQuickStackViewAttached", + "signals": [ + { + "access": "public", + "index": 0, + "name": "indexChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "viewChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "statusChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "activated", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "activating", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "deactivated", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "deactivating", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "removed", + "returnType": "void" + }, + { + "access": "public", + "index": 8, + "name": "visibleChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qquickstackview_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickSwipe", + "lineNumber": 29, + "methods": [ + { + "access": "public", + "index": 13, + "name": "close", + "returnType": "void", + "revision": 513 + }, + { + "access": "public", + "arguments": [ + { + "name": "side", + "type": "QQuickSwipeDelegate::Side" + } + ], + "index": 14, + "name": "open", + "returnType": "void", + "revision": 514 + } + ], + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "position", + "notify": "positionChanged", + "read": "position", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setPosition" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "complete", + "notify": "completeChanged", + "read": "isComplete", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "left", + "notify": "leftChanged", + "read": "left", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlComponent*", + "user": false, + "write": "setLeft" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "behind", + "notify": "behindChanged", + "read": "behind", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlComponent*", + "user": false, + "write": "setBehind" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "right", + "notify": "rightChanged", + "read": "right", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlComponent*", + "user": false, + "write": "setRight" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "leftItem", + "notify": "leftItemChanged", + "read": "leftItem", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 6, + "name": "behindItem", + "notify": "behindItemChanged", + "read": "behindItem", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 7, + "name": "rightItem", + "notify": "rightItemChanged", + "read": "rightItem", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 8, + "name": "enabled", + "notify": "enabledChanged", + "read": "isEnabled", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setEnabled" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 9, + "name": "transition", + "notify": "transitionChanged", + "read": "transition", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickTransition*", + "user": false, + "write": "setTransition" + } + ], + "qualifiedClassName": "QQuickSwipe", + "signals": [ + { + "access": "public", + "index": 0, + "name": "positionChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "completeChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "leftChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "behindChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "rightChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "leftItemChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "behindItemChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "rightItemChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 8, + "name": "completed", + "returnType": "void" + }, + { + "access": "public", + "index": 9, + "name": "opened", + "returnType": "void" + }, + { + "access": "public", + "index": 10, + "name": "closed", + "returnType": "void" + }, + { + "access": "public", + "index": 11, + "name": "enabledChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 12, + "name": "transitionChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qquickswipe_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "SwipeDelegate" + }, + { + "name": "QML.Attached", + "value": "QQuickSwipeDelegateAttached" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickSwipeDelegate", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "Side", + "values": [ + "Left", + "Right" + ] + } + ], + "lineNumber": 27, + "object": true, + "properties": [ + { + "constant": true, + "designable": true, + "final": true, + "index": 0, + "name": "swipe", + "read": "swipe", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickSwipe*", + "user": false + } + ], + "qualifiedClassName": "QQuickSwipeDelegate", + "superClasses": [ + { + "access": "public", + "name": "QQuickItemDelegate" + } + ] + }, + { + "className": "QQuickSwipeDelegateAttached", + "lineNumber": 67, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "pressed", + "notify": "pressedChanged", + "read": "isPressed", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + } + ], + "qualifiedClassName": "QQuickSwipeDelegateAttached", + "signals": [ + { + "access": "public", + "index": 0, + "name": "pressedChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "clicked", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qquickswipedelegate_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "SwipeView" + }, + { + "name": "QML.Attached", + "value": "QQuickSwipeViewAttached" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickSwipeView", + "lineNumber": 27, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "interactive", + "notify": "interactiveChanged", + "read": "isInteractive", + "required": false, + "revision": 513, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setInteractive" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "orientation", + "notify": "orientationChanged", + "read": "orientation", + "required": false, + "revision": 514, + "scriptable": true, + "stored": true, + "type": "Qt::Orientation", + "user": false, + "write": "setOrientation" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "horizontal", + "notify": "orientationChanged", + "read": "isHorizontal", + "required": false, + "revision": 515, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "vertical", + "notify": "orientationChanged", + "read": "isVertical", + "required": false, + "revision": 515, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + } + ], + "qualifiedClassName": "QQuickSwipeView", + "signals": [ + { + "access": "public", + "index": 0, + "name": "interactiveChanged", + "returnType": "void", + "revision": 513 + }, + { + "access": "public", + "index": 1, + "name": "orientationChanged", + "returnType": "void", + "revision": 514 + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickContainer" + } + ] + }, + { + "className": "QQuickSwipeViewAttached", + "lineNumber": 82, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "index", + "notify": "indexChanged", + "read": "index", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "isCurrentItem", + "notify": "isCurrentItemChanged", + "read": "isCurrentItem", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "view", + "notify": "viewChanged", + "read": "view", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickSwipeView*", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "isNextItem", + "notify": "isNextItemChanged", + "read": "isNextItem", + "required": false, + "revision": 513, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "isPreviousItem", + "notify": "isPreviousItemChanged", + "read": "isPreviousItem", + "required": false, + "revision": 513, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + } + ], + "qualifiedClassName": "QQuickSwipeViewAttached", + "signals": [ + { + "access": "public", + "index": 0, + "name": "indexChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "isCurrentItemChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "viewChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "isNextItemChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "isPreviousItemChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qquickswipeview_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "Switch" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickSwitch", + "lineNumber": 24, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "position", + "notify": "positionChanged", + "read": "position", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setPosition" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "visualPosition", + "notify": "visualPositionChanged", + "read": "visualPosition", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + } + ], + "qualifiedClassName": "QQuickSwitch", + "signals": [ + { + "access": "public", + "index": 0, + "name": "positionChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "visualPositionChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickAbstractButton" + } + ] + } + ], + "inputFile": "qquickswitch_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "SwitchDelegate" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickSwitchDelegate", + "lineNumber": 24, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "position", + "notify": "positionChanged", + "read": "position", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setPosition" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "visualPosition", + "notify": "visualPositionChanged", + "read": "visualPosition", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + } + ], + "qualifiedClassName": "QQuickSwitchDelegate", + "signals": [ + { + "access": "public", + "index": 0, + "name": "positionChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "visualPositionChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickItemDelegate" + } + ] + } + ], + "inputFile": "qquickswitchdelegate_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "TabBar" + }, + { + "name": "QML.Attached", + "value": "QQuickTabBarAttached" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickTabBar", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "Position", + "values": [ + "Header", + "Footer" + ] + } + ], + "lineNumber": 28, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "position", + "notify": "positionChanged", + "read": "position", + "required": false, + "scriptable": true, + "stored": true, + "type": "Position", + "user": false, + "write": "setPosition" + } + ], + "qualifiedClassName": "QQuickTabBar", + "signals": [ + { + "access": "public", + "index": 0, + "name": "positionChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickContainer" + } + ] + }, + { + "className": "QQuickTabBarAttached", + "lineNumber": 76, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "index", + "notify": "indexChanged", + "read": "index", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "tabBar", + "notify": "tabBarChanged", + "read": "tabBar", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickTabBar*", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "position", + "notify": "positionChanged", + "read": "position", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickTabBar::Position", + "user": false + } + ], + "qualifiedClassName": "QQuickTabBarAttached", + "signals": [ + { + "access": "public", + "index": 0, + "name": "indexChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "tabBarChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "positionChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qquicktabbar_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "TabButton" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickTabButton", + "lineNumber": 24, + "object": true, + "qualifiedClassName": "QQuickTabButton", + "superClasses": [ + { + "access": "public", + "name": "QQuickAbstractButton" + } + ] + } + ], + "inputFile": "qquicktabbutton_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "DeferredPropertyNames", + "value": "background" + }, + { + "name": "QML.Element", + "value": "TextArea" + }, + { + "name": "QML.Attached", + "value": "QQuickTextAreaAttached" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickTextArea", + "lineNumber": 29, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "font", + "notify": "fontChanged", + "read": "font", + "required": false, + "scriptable": true, + "stored": true, + "type": "QFont", + "user": false, + "write": "setFont" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "implicitWidth", + "notify": "implicitWidthChanged3", + "read": "implicitWidth", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setImplicitWidth" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "implicitHeight", + "notify": "implicitHeightChanged3", + "read": "implicitHeight", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setImplicitHeight" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "background", + "notify": "backgroundChanged", + "read": "background", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false, + "write": "setBackground" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "placeholderText", + "notify": "placeholderTextChanged", + "read": "placeholderText", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setPlaceholderText" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "focusReason", + "notify": "focusReasonChanged", + "read": "focusReason", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::FocusReason", + "user": false, + "write": "setFocusReason" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 6, + "name": "hovered", + "notify": "hoveredChanged", + "read": "isHovered", + "required": false, + "revision": 513, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 7, + "name": "hoverEnabled", + "notify": "hoverEnabledChanged", + "read": "isHoverEnabled", + "required": false, + "reset": "resetHoverEnabled", + "revision": 513, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setHoverEnabled" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 8, + "name": "placeholderTextColor", + "notify": "placeholderTextColorChanged", + "read": "placeholderTextColor", + "required": false, + "revision": 517, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false, + "write": "setPlaceholderTextColor" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 9, + "name": "implicitBackgroundWidth", + "notify": "implicitBackgroundWidthChanged", + "read": "implicitBackgroundWidth", + "required": false, + "revision": 517, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 10, + "name": "implicitBackgroundHeight", + "notify": "implicitBackgroundHeightChanged", + "read": "implicitBackgroundHeight", + "required": false, + "revision": 517, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 11, + "name": "topInset", + "notify": "topInsetChanged", + "read": "topInset", + "required": false, + "reset": "resetTopInset", + "revision": 517, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setTopInset" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 12, + "name": "leftInset", + "notify": "leftInsetChanged", + "read": "leftInset", + "required": false, + "reset": "resetLeftInset", + "revision": 517, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setLeftInset" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 13, + "name": "rightInset", + "notify": "rightInsetChanged", + "read": "rightInset", + "required": false, + "reset": "resetRightInset", + "revision": 517, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setRightInset" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 14, + "name": "bottomInset", + "notify": "bottomInsetChanged", + "read": "bottomInset", + "required": false, + "reset": "resetBottomInset", + "revision": 517, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setBottomInset" + } + ], + "qualifiedClassName": "QQuickTextArea", + "signals": [ + { + "access": "public", + "index": 0, + "name": "fontChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "implicitWidthChanged3", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "implicitHeightChanged3", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "backgroundChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "placeholderTextChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "focusReasonChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "event", + "type": "QQuickMouseEvent*" + } + ], + "index": 6, + "name": "pressAndHold", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "event", + "type": "QQuickMouseEvent*" + } + ], + "index": 7, + "name": "pressed", + "returnType": "void", + "revision": 513 + }, + { + "access": "public", + "arguments": [ + { + "name": "event", + "type": "QQuickMouseEvent*" + } + ], + "index": 8, + "name": "released", + "returnType": "void", + "revision": 513 + }, + { + "access": "public", + "index": 9, + "name": "hoveredChanged", + "returnType": "void", + "revision": 513 + }, + { + "access": "public", + "index": 10, + "name": "hoverEnabledChanged", + "returnType": "void", + "revision": 513 + }, + { + "access": "public", + "index": 11, + "name": "placeholderTextColorChanged", + "returnType": "void", + "revision": 517 + }, + { + "access": "public", + "index": 12, + "name": "implicitBackgroundWidthChanged", + "returnType": "void", + "revision": 517 + }, + { + "access": "public", + "index": 13, + "name": "implicitBackgroundHeightChanged", + "returnType": "void", + "revision": 517 + }, + { + "access": "public", + "index": 14, + "name": "topInsetChanged", + "returnType": "void", + "revision": 517 + }, + { + "access": "public", + "index": 15, + "name": "leftInsetChanged", + "returnType": "void", + "revision": 517 + }, + { + "access": "public", + "index": 16, + "name": "rightInsetChanged", + "returnType": "void", + "revision": 517 + }, + { + "access": "public", + "index": 17, + "name": "bottomInsetChanged", + "returnType": "void", + "revision": 517 + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickTextEdit" + } + ] + }, + { + "className": "QQuickTextAreaAttached", + "lineNumber": 158, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "flickable", + "notify": "flickableChanged", + "read": "flickable", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickTextArea*", + "user": false, + "write": "setFlickable" + } + ], + "qualifiedClassName": "QQuickTextAreaAttached", + "signals": [ + { + "access": "public", + "index": 0, + "name": "flickableChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qquicktextarea_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "DeferredPropertyNames", + "value": "background" + }, + { + "name": "QML.Element", + "value": "TextField" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickTextField", + "lineNumber": 27, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "font", + "notify": "fontChanged", + "read": "font", + "required": false, + "scriptable": true, + "stored": true, + "type": "QFont", + "user": false, + "write": "setFont" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "implicitWidth", + "notify": "implicitWidthChanged3", + "read": "implicitWidth", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setImplicitWidth" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "implicitHeight", + "notify": "implicitHeightChanged3", + "read": "implicitHeight", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setImplicitHeight" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "background", + "notify": "backgroundChanged", + "read": "background", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false, + "write": "setBackground" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "placeholderText", + "notify": "placeholderTextChanged", + "read": "placeholderText", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setPlaceholderText" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "focusReason", + "notify": "focusReasonChanged", + "read": "focusReason", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::FocusReason", + "user": false, + "write": "setFocusReason" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 6, + "name": "hovered", + "notify": "hoveredChanged", + "read": "isHovered", + "required": false, + "revision": 513, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 7, + "name": "hoverEnabled", + "notify": "hoverEnabledChanged", + "read": "isHoverEnabled", + "required": false, + "reset": "resetHoverEnabled", + "revision": 513, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setHoverEnabled" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 8, + "name": "placeholderTextColor", + "notify": "placeholderTextColorChanged", + "read": "placeholderTextColor", + "required": false, + "revision": 517, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false, + "write": "setPlaceholderTextColor" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 9, + "name": "implicitBackgroundWidth", + "notify": "implicitBackgroundWidthChanged", + "read": "implicitBackgroundWidth", + "required": false, + "revision": 517, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 10, + "name": "implicitBackgroundHeight", + "notify": "implicitBackgroundHeightChanged", + "read": "implicitBackgroundHeight", + "required": false, + "revision": 517, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 11, + "name": "topInset", + "notify": "topInsetChanged", + "read": "topInset", + "required": false, + "reset": "resetTopInset", + "revision": 517, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setTopInset" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 12, + "name": "leftInset", + "notify": "leftInsetChanged", + "read": "leftInset", + "required": false, + "reset": "resetLeftInset", + "revision": 517, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setLeftInset" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 13, + "name": "rightInset", + "notify": "rightInsetChanged", + "read": "rightInset", + "required": false, + "reset": "resetRightInset", + "revision": 517, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setRightInset" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 14, + "name": "bottomInset", + "notify": "bottomInsetChanged", + "read": "bottomInset", + "required": false, + "reset": "resetBottomInset", + "revision": 517, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setBottomInset" + } + ], + "qualifiedClassName": "QQuickTextField", + "signals": [ + { + "access": "public", + "index": 0, + "name": "fontChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "implicitWidthChanged3", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "implicitHeightChanged3", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "backgroundChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "placeholderTextChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "focusReasonChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "event", + "type": "QQuickMouseEvent*" + } + ], + "index": 6, + "name": "pressAndHold", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "event", + "type": "QQuickMouseEvent*" + } + ], + "index": 7, + "name": "pressed", + "returnType": "void", + "revision": 513 + }, + { + "access": "public", + "arguments": [ + { + "name": "event", + "type": "QQuickMouseEvent*" + } + ], + "index": 8, + "name": "released", + "returnType": "void", + "revision": 513 + }, + { + "access": "public", + "index": 9, + "name": "hoveredChanged", + "returnType": "void", + "revision": 513 + }, + { + "access": "public", + "index": 10, + "name": "hoverEnabledChanged", + "returnType": "void", + "revision": 513 + }, + { + "access": "public", + "index": 11, + "name": "placeholderTextColorChanged", + "returnType": "void", + "revision": 517 + }, + { + "access": "public", + "index": 12, + "name": "implicitBackgroundWidthChanged", + "returnType": "void", + "revision": 517 + }, + { + "access": "public", + "index": 13, + "name": "implicitBackgroundHeightChanged", + "returnType": "void", + "revision": 517 + }, + { + "access": "public", + "index": 14, + "name": "topInsetChanged", + "returnType": "void", + "revision": 517 + }, + { + "access": "public", + "index": 15, + "name": "leftInsetChanged", + "returnType": "void", + "revision": 517 + }, + { + "access": "public", + "index": 16, + "name": "rightInsetChanged", + "returnType": "void", + "revision": 517 + }, + { + "access": "public", + "index": 17, + "name": "bottomInsetChanged", + "returnType": "void", + "revision": 517 + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickTextInput" + } + ] + } + ], + "inputFile": "qquicktextfield_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "ToolBar" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickToolBar", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "Position", + "values": [ + "Header", + "Footer" + ] + } + ], + "lineNumber": 24, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "position", + "notify": "positionChanged", + "read": "position", + "required": false, + "scriptable": true, + "stored": true, + "type": "Position", + "user": false, + "write": "setPosition" + } + ], + "qualifiedClassName": "QQuickToolBar", + "signals": [ + { + "access": "public", + "index": 0, + "name": "positionChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickPane" + } + ] + } + ], + "inputFile": "qquicktoolbar_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "ToolButton" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickToolButton", + "lineNumber": 24, + "object": true, + "qualifiedClassName": "QQuickToolButton", + "superClasses": [ + { + "access": "public", + "name": "QQuickButton" + } + ] + } + ], + "inputFile": "qquicktoolbutton_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "ToolSeparator" + }, + { + "name": "QML.AddedInVersion", + "value": "513" + } + ], + "className": "QQuickToolSeparator", + "lineNumber": 24, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "orientation", + "notify": "orientationChanged", + "read": "orientation", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::Orientation", + "user": false, + "write": "setOrientation" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "horizontal", + "notify": "orientationChanged", + "read": "isHorizontal", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "vertical", + "notify": "orientationChanged", + "read": "isVertical", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + } + ], + "qualifiedClassName": "QQuickToolSeparator", + "signals": [ + { + "access": "public", + "index": 0, + "name": "orientationChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickControl" + } + ] + } + ], + "inputFile": "qquicktoolseparator_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "ToolTip" + }, + { + "name": "QML.Attached", + "value": "QQuickToolTipAttached" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickToolTip", + "lineNumber": 26, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "delay", + "notify": "delayChanged", + "read": "delay", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setDelay" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "timeout", + "notify": "timeoutChanged", + "read": "timeout", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setTimeout" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "text", + "notify": "textChanged", + "read": "text", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setText" + } + ], + "qualifiedClassName": "QQuickToolTip", + "signals": [ + { + "access": "public", + "index": 0, + "name": "textChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "delayChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "timeoutChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "text", + "type": "QString" + }, + { + "name": "ms", + "type": "int" + } + ], + "index": 3, + "name": "show", + "returnType": "void", + "revision": 517 + }, + { + "access": "public", + "arguments": [ + { + "name": "text", + "type": "QString" + } + ], + "index": 4, + "isCloned": true, + "name": "show", + "returnType": "void", + "revision": 517 + }, + { + "access": "public", + "index": 5, + "name": "hide", + "returnType": "void", + "revision": 517 + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickPopup" + } + ] + }, + { + "className": "QQuickToolTipAttached", + "lineNumber": 77, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "text", + "notify": "textChanged", + "read": "text", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setText" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "delay", + "notify": "delayChanged", + "read": "delay", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setDelay" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "timeout", + "notify": "timeoutChanged", + "read": "timeout", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setTimeout" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "visible", + "notify": "visibleChanged", + "read": "isVisible", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setVisible" + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 4, + "name": "toolTip", + "read": "toolTip", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickToolTip*", + "user": false + } + ], + "qualifiedClassName": "QQuickToolTipAttached", + "signals": [ + { + "access": "public", + "index": 0, + "name": "textChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "delayChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "timeoutChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "visibleChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "text", + "type": "QString" + }, + { + "name": "ms", + "type": "int" + } + ], + "index": 4, + "name": "show", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "text", + "type": "QString" + } + ], + "index": 5, + "isCloned": true, + "name": "show", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "hide", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qquicktooltip_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "TreeViewDelegate" + }, + { + "name": "QML.AddedInVersion", + "value": "1539" + } + ], + "className": "QQuickTreeViewDelegate", + "lineNumber": 27, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "indentation", + "notify": "indentationChanged", + "read": "indentation", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setIndentation" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "leftMargin", + "notify": "leftMarginChanged", + "read": "leftMargin", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setLeftMargin" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "rightMargin", + "notify": "rightMarginChanged", + "read": "rightMargin", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setRightMargin" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "treeView", + "notify": "treeviewChanged", + "read": "treeView", + "required": true, + "scriptable": true, + "stored": true, + "type": "QQuickTreeView*", + "user": false, + "write": "setTreeView" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "isTreeNode", + "notify": "isTreeNodeChanged", + "read": "isTreeNode", + "required": true, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setIsTreeNode" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "hasChildren", + "notify": "hasChildrenChanged", + "read": "hasChildren", + "required": true, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setHasChildren" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 6, + "name": "expanded", + "notify": "expandedChanged", + "read": "expanded", + "required": true, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setExpanded" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 7, + "name": "depth", + "notify": "depthChanged", + "read": "depth", + "required": true, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setDepth" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 8, + "name": "current", + "notify": "currentChanged", + "read": "current", + "required": true, + "revision": 1540, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setCurrent" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 9, + "name": "selected", + "notify": "selectedChanged", + "read": "selected", + "required": true, + "revision": 1540, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setSelected" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 10, + "name": "editing", + "notify": "editingChanged", + "read": "editing", + "required": true, + "revision": 1541, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setEditing" + } + ], + "qualifiedClassName": "QQuickTreeViewDelegate", + "signals": [ + { + "access": "public", + "index": 0, + "name": "indicatorChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "indentationChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "isTreeNodeChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "hasChildrenChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "expandedChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "depthChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "treeviewChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "leftMarginChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 8, + "name": "rightMarginChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 9, + "name": "currentChanged", + "returnType": "void", + "revision": 1540 + }, + { + "access": "public", + "index": 10, + "name": "selectedChanged", + "returnType": "void", + "revision": 1540 + }, + { + "access": "public", + "index": 11, + "name": "editingChanged", + "returnType": "void", + "revision": 1541 + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickItemDelegate" + } + ] + } + ], + "inputFile": "qquicktreeviewdelegate_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "Tumbler" + }, + { + "name": "QML.Attached", + "value": "QQuickTumblerAttached" + }, + { + "name": "QML.AddedInVersion", + "value": "512" + } + ], + "className": "QQuickTumbler", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "PositionMode", + "values": [ + "Beginning", + "Center", + "End", + "Visible", + "Contain", + "SnapPosition" + ] + } + ], + "lineNumber": 27, + "methods": [ + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + }, + { + "name": "mode", + "type": "PositionMode" + } + ], + "index": 14, + "name": "positionViewAtIndex", + "returnType": "void", + "revision": 517 + } + ], + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "model", + "notify": "modelChanged", + "read": "model", + "required": false, + "scriptable": true, + "stored": true, + "type": "QVariant", + "user": false, + "write": "setModel" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "count", + "notify": "countChanged", + "read": "count", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "currentIndex", + "notify": "currentIndexChanged", + "read": "currentIndex", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setCurrentIndex" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "currentItem", + "notify": "currentItemChanged", + "read": "currentItem", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickItem*", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "delegate", + "notify": "delegateChanged", + "read": "delegate", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlComponent*", + "user": false, + "write": "setDelegate" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "visibleItemCount", + "notify": "visibleItemCountChanged", + "read": "visibleItemCount", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setVisibleItemCount" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 6, + "name": "wrap", + "notify": "wrapChanged", + "read": "wrap", + "required": false, + "reset": "resetWrap", + "revision": 513, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setWrap" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 7, + "name": "moving", + "notify": "movingChanged", + "read": "isMoving", + "required": false, + "revision": 514, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + } + ], + "qualifiedClassName": "QQuickTumbler", + "signals": [ + { + "access": "public", + "index": 0, + "name": "modelChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "countChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "currentIndexChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "currentItemChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "delegateChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "visibleItemCountChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "wrapChanged", + "returnType": "void", + "revision": 513 + }, + { + "access": "public", + "index": 7, + "name": "movingChanged", + "returnType": "void", + "revision": 514 + } + ], + "slots": [ + { + "access": "private", + "index": 8, + "name": "_q_updateItemWidths", + "returnType": "void" + }, + { + "access": "private", + "index": 9, + "name": "_q_updateItemHeights", + "returnType": "void" + }, + { + "access": "private", + "index": 10, + "name": "_q_onViewCurrentIndexChanged", + "returnType": "void" + }, + { + "access": "private", + "index": 11, + "name": "_q_onViewCountChanged", + "returnType": "void" + }, + { + "access": "private", + "index": 12, + "name": "_q_onViewOffsetChanged", + "returnType": "void" + }, + { + "access": "private", + "index": 13, + "name": "_q_onViewContentYChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickControl" + } + ] + }, + { + "className": "QQuickTumblerAttached", + "lineNumber": 121, + "object": true, + "properties": [ + { + "constant": true, + "designable": true, + "final": true, + "index": 0, + "name": "tumbler", + "read": "tumbler", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQuickTumbler*", + "user": false + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "displacement", + "notify": "displacementChanged", + "read": "displacement", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false + } + ], + "qualifiedClassName": "QQuickTumblerAttached", + "signals": [ + { + "access": "public", + "index": 0, + "name": "displacementChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qquicktumbler_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "AbstractWeekNumberColumn" + }, + { + "name": "QML.AddedInVersion", + "value": "1539" + } + ], + "className": "QQuickWeekNumberColumn", + "lineNumber": 25, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "month", + "notify": "monthChanged", + "read": "month", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setMonth" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "year", + "notify": "yearChanged", + "read": "year", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setYear" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "source", + "notify": "sourceChanged", + "read": "source", + "required": false, + "scriptable": true, + "stored": true, + "type": "QVariant", + "user": false, + "write": "setSource" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "delegate", + "notify": "delegateChanged", + "read": "delegate", + "required": false, + "scriptable": true, + "stored": true, + "type": "QQmlComponent*", + "user": false, + "write": "setDelegate" + } + ], + "qualifiedClassName": "QQuickWeekNumberColumn", + "signals": [ + { + "access": "public", + "index": 0, + "name": "monthChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "yearChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "sourceChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "delegateChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickControl" + } + ] + } + ], + "inputFile": "qquickweeknumbercolumn_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQuickWeekNumberModel", + "lineNumber": 27, + "methods": [ + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + } + ], + "index": 3, + "name": "weekNumberAt", + "returnType": "int" + }, + { + "access": "public", + "arguments": [ + { + "name": "weekNumber", + "type": "int" + } + ], + "index": 4, + "name": "indexOf", + "returnType": "int" + } + ], + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "month", + "notify": "monthChanged", + "read": "month", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setMonth" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "year", + "notify": "yearChanged", + "read": "year", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setYear" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 2, + "name": "locale", + "notify": "localeChanged", + "read": "locale", + "required": false, + "scriptable": true, + "stored": true, + "type": "QLocale", + "user": false, + "write": "setLocale" + }, + { + "constant": true, + "designable": true, + "final": true, + "index": 3, + "name": "count", + "read": "rowCount", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + } + ], + "qualifiedClassName": "QQuickWeekNumberModel", + "signals": [ + { + "access": "public", + "index": 0, + "name": "monthChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "yearChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "localeChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QAbstractListModel" + } + ] + } + ], + "inputFile": "qquickweeknumbermodel_p.h", + "outputRevision": 68 + } +] diff --git a/qt/6.8.1/msvc2022_64/metatypes/qt6quicktest_metatypes.json b/qt/6.8.1/msvc2022_64/metatypes/qt6quicktest_metatypes.json new file mode 100644 index 0000000000000000000000000000000000000000..e34d780a8a5144e8c9801c8c0e93ffbfa95e4cdf --- /dev/null +++ b/qt/6.8.1/msvc2022_64/metatypes/qt6quicktest_metatypes.json @@ -0,0 +1,1659 @@ +[ + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Singleton", + "value": "true" + }, + { + "name": "QML.Element", + "value": "auto" + }, + { + "name": "QML.AddedInVersion", + "value": "256" + } + ], + "className": "QTestRootObject", + "lineNumber": 28, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "windowShown", + "notify": "windowShownChanged", + "read": "windowShown", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "hasTestCase", + "notify": "hasTestCaseChanged", + "read": "hasTestCase", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setHasTestCase" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "defined", + "read": "defined", + "required": false, + "scriptable": true, + "stored": true, + "type": "QObject*", + "user": false + } + ], + "qualifiedClassName": "QTestRootObject", + "signals": [ + { + "access": "public", + "index": 0, + "name": "windowShownChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "hasTestCaseChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "private", + "index": 2, + "name": "quit", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "quicktest_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "anonymous" + }, + { + "name": "QML.AddedInVersion", + "value": "256" + } + ], + "className": "QQuickTouchEventSequence", + "lineNumber": 28, + "object": true, + "qualifiedClassName": "QQuickTouchEventSequence", + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "touchId", + "type": "int" + }, + { + "name": "item", + "type": "QObject*" + }, + { + "name": "x", + "type": "qreal" + }, + { + "name": "y", + "type": "qreal" + } + ], + "index": 0, + "name": "press", + "returnType": "QObject*" + }, + { + "access": "public", + "arguments": [ + { + "name": "touchId", + "type": "int" + }, + { + "name": "item", + "type": "QObject*" + }, + { + "name": "x", + "type": "qreal" + }, + { + "name": "y", + "type": "qreal" + } + ], + "index": 1, + "name": "move", + "returnType": "QObject*" + }, + { + "access": "public", + "arguments": [ + { + "name": "touchId", + "type": "int" + }, + { + "name": "item", + "type": "QObject*" + }, + { + "name": "x", + "type": "qreal" + }, + { + "name": "y", + "type": "qreal" + } + ], + "index": 2, + "name": "release", + "returnType": "QObject*" + }, + { + "access": "public", + "arguments": [ + { + "name": "touchId", + "type": "int" + } + ], + "index": 3, + "name": "stationary", + "returnType": "QObject*" + }, + { + "access": "public", + "index": 4, + "name": "commit", + "returnType": "QObject*" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "classInfos": [ + { + "name": "QML.Element", + "value": "TestEvent" + }, + { + "name": "QML.AddedInVersion", + "value": "256" + } + ], + "className": "QuickTestEvent", + "lineNumber": 48, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": true, + "index": 0, + "name": "defaultMouseDelay", + "read": "defaultMouseDelay", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + } + ], + "qualifiedClassName": "QuickTestEvent", + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "key", + "type": "int" + }, + { + "name": "modifiers", + "type": "int" + }, + { + "name": "delay", + "type": "int" + } + ], + "index": 0, + "name": "keyPress", + "returnType": "bool" + }, + { + "access": "public", + "arguments": [ + { + "name": "key", + "type": "int" + }, + { + "name": "modifiers", + "type": "int" + }, + { + "name": "delay", + "type": "int" + } + ], + "index": 1, + "name": "keyRelease", + "returnType": "bool" + }, + { + "access": "public", + "arguments": [ + { + "name": "key", + "type": "int" + }, + { + "name": "modifiers", + "type": "int" + }, + { + "name": "delay", + "type": "int" + } + ], + "index": 2, + "name": "keyClick", + "returnType": "bool" + }, + { + "access": "public", + "arguments": [ + { + "name": "character", + "type": "QString" + }, + { + "name": "modifiers", + "type": "int" + }, + { + "name": "delay", + "type": "int" + } + ], + "index": 3, + "name": "keyPressChar", + "returnType": "bool" + }, + { + "access": "public", + "arguments": [ + { + "name": "character", + "type": "QString" + }, + { + "name": "modifiers", + "type": "int" + }, + { + "name": "delay", + "type": "int" + } + ], + "index": 4, + "name": "keyReleaseChar", + "returnType": "bool" + }, + { + "access": "public", + "arguments": [ + { + "name": "character", + "type": "QString" + }, + { + "name": "modifiers", + "type": "int" + }, + { + "name": "delay", + "type": "int" + } + ], + "index": 5, + "name": "keyClickChar", + "returnType": "bool" + }, + { + "access": "public", + "arguments": [ + { + "name": "keySequence", + "type": "QVariant" + } + ], + "index": 6, + "name": "keySequence", + "returnType": "bool", + "revision": 258 + }, + { + "access": "public", + "arguments": [ + { + "name": "item", + "type": "QObject*" + }, + { + "name": "x", + "type": "qreal" + }, + { + "name": "y", + "type": "qreal" + }, + { + "name": "button", + "type": "int" + }, + { + "name": "modifiers", + "type": "int" + }, + { + "name": "delay", + "type": "int" + } + ], + "index": 7, + "name": "mousePress", + "returnType": "bool" + }, + { + "access": "public", + "arguments": [ + { + "name": "item", + "type": "QObject*" + }, + { + "name": "x", + "type": "qreal" + }, + { + "name": "y", + "type": "qreal" + }, + { + "name": "button", + "type": "int" + }, + { + "name": "modifiers", + "type": "int" + }, + { + "name": "delay", + "type": "int" + } + ], + "index": 8, + "name": "mouseRelease", + "returnType": "bool" + }, + { + "access": "public", + "arguments": [ + { + "name": "item", + "type": "QObject*" + }, + { + "name": "x", + "type": "qreal" + }, + { + "name": "y", + "type": "qreal" + }, + { + "name": "button", + "type": "int" + }, + { + "name": "modifiers", + "type": "int" + }, + { + "name": "delay", + "type": "int" + } + ], + "index": 9, + "name": "mouseClick", + "returnType": "bool" + }, + { + "access": "public", + "arguments": [ + { + "name": "item", + "type": "QObject*" + }, + { + "name": "x", + "type": "qreal" + }, + { + "name": "y", + "type": "qreal" + }, + { + "name": "button", + "type": "int" + }, + { + "name": "modifiers", + "type": "int" + }, + { + "name": "delay", + "type": "int" + } + ], + "index": 10, + "name": "mouseDoubleClick", + "returnType": "bool" + }, + { + "access": "public", + "arguments": [ + { + "name": "item", + "type": "QObject*" + }, + { + "name": "x", + "type": "qreal" + }, + { + "name": "y", + "type": "qreal" + }, + { + "name": "button", + "type": "int" + }, + { + "name": "modifiers", + "type": "int" + }, + { + "name": "delay", + "type": "int" + } + ], + "index": 11, + "name": "mouseDoubleClickSequence", + "returnType": "bool" + }, + { + "access": "public", + "arguments": [ + { + "name": "item", + "type": "QObject*" + }, + { + "name": "x", + "type": "qreal" + }, + { + "name": "y", + "type": "qreal" + }, + { + "name": "delay", + "type": "int" + }, + { + "name": "buttons", + "type": "int" + }, + { + "name": "modifiers", + "type": "int" + } + ], + "index": 12, + "name": "mouseMove", + "returnType": "bool" + }, + { + "access": "public", + "arguments": [ + { + "name": "item", + "type": "QObject*" + }, + { + "name": "x", + "type": "qreal" + }, + { + "name": "y", + "type": "qreal" + }, + { + "name": "buttons", + "type": "int" + }, + { + "name": "modifiers", + "type": "int" + }, + { + "name": "xDelta", + "type": "int" + }, + { + "name": "yDelta", + "type": "int" + }, + { + "name": "delay", + "type": "int" + } + ], + "index": 13, + "name": "mouseWheel", + "returnType": "bool" + }, + { + "access": "public", + "arguments": [ + { + "name": "item", + "type": "QObject*" + } + ], + "index": 14, + "name": "touchEvent", + "returnType": "QQuickTouchEventSequence*" + }, + { + "access": "public", + "index": 15, + "isCloned": true, + "name": "touchEvent", + "returnType": "QQuickTouchEventSequence*" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "quicktestevent_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "TestResult" + }, + { + "name": "QML.AddedInVersion", + "value": "256" + } + ], + "className": "QuickTestResult", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "RunMode", + "values": [ + "RepeatUntilValidMeasurement", + "RunOnce" + ] + } + ], + "lineNumber": 31, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "testCaseName", + "notify": "testCaseNameChanged", + "read": "testCaseName", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setTestCaseName" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "functionName", + "notify": "functionNameChanged", + "read": "functionName", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setFunctionName" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "dataTag", + "notify": "dataTagChanged", + "read": "dataTag", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setDataTag" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "failed", + "read": "isFailed", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "skipped", + "notify": "skippedChanged", + "read": "isSkipped", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setSkipped" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "passCount", + "read": "passCount", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "failCount", + "read": "failCount", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 7, + "name": "skipCount", + "read": "skipCount", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 8, + "name": "functionsToRun", + "read": "functionsToRun", + "required": false, + "scriptable": true, + "stored": true, + "type": "QStringList", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 9, + "name": "tagsToRun", + "read": "tagsToRun", + "required": false, + "scriptable": true, + "stored": true, + "type": "QStringList", + "user": false + } + ], + "qualifiedClassName": "QuickTestResult", + "signals": [ + { + "access": "public", + "index": 0, + "name": "programNameChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "testCaseNameChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "functionNameChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "dataTagChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "skippedChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "index": 5, + "name": "reset", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "startLogging", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "stopLogging", + "returnType": "void" + }, + { + "access": "public", + "index": 8, + "name": "initTestTable", + "returnType": "void" + }, + { + "access": "public", + "index": 9, + "name": "clearTestTable", + "returnType": "void" + }, + { + "access": "public", + "index": 10, + "name": "finishTestData", + "returnType": "void" + }, + { + "access": "public", + "index": 11, + "name": "finishTestDataCleanup", + "returnType": "void" + }, + { + "access": "public", + "index": 12, + "name": "finishTestFunction", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "args", + "type": "QQmlV4FunctionPtr" + } + ], + "index": 13, + "name": "stringify", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "message", + "type": "QString" + }, + { + "name": "location", + "type": "QUrl" + }, + { + "name": "line", + "type": "int" + } + ], + "index": 14, + "name": "fail", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "success", + "type": "bool" + }, + { + "name": "message", + "type": "QString" + }, + { + "name": "location", + "type": "QUrl" + }, + { + "name": "line", + "type": "int" + } + ], + "index": 15, + "name": "verify", + "returnType": "bool" + }, + { + "access": "public", + "arguments": [ + { + "name": "success", + "type": "bool" + }, + { + "name": "message", + "type": "QString" + }, + { + "name": "val1", + "type": "QVariant" + }, + { + "name": "val2", + "type": "QVariant" + }, + { + "name": "location", + "type": "QUrl" + }, + { + "name": "line", + "type": "int" + } + ], + "index": 16, + "name": "compare", + "returnType": "bool" + }, + { + "access": "public", + "arguments": [ + { + "name": "actual", + "type": "QVariant" + }, + { + "name": "expected", + "type": "QVariant" + }, + { + "name": "delta", + "type": "qreal" + } + ], + "index": 17, + "name": "fuzzyCompare", + "returnType": "bool" + }, + { + "access": "public", + "arguments": [ + { + "name": "message", + "type": "QString" + }, + { + "name": "location", + "type": "QUrl" + }, + { + "name": "line", + "type": "int" + } + ], + "index": 18, + "name": "skip", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "tag", + "type": "QString" + }, + { + "name": "comment", + "type": "QString" + }, + { + "name": "location", + "type": "QUrl" + }, + { + "name": "line", + "type": "int" + } + ], + "index": 19, + "name": "expectFail", + "returnType": "bool" + }, + { + "access": "public", + "arguments": [ + { + "name": "tag", + "type": "QString" + }, + { + "name": "comment", + "type": "QString" + }, + { + "name": "location", + "type": "QUrl" + }, + { + "name": "line", + "type": "int" + } + ], + "index": 20, + "name": "expectFailContinue", + "returnType": "bool" + }, + { + "access": "public", + "arguments": [ + { + "name": "message", + "type": "QString" + }, + { + "name": "location", + "type": "QUrl" + }, + { + "name": "line", + "type": "int" + } + ], + "index": 21, + "name": "warn", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "message", + "type": "QJSValue" + } + ], + "index": 22, + "name": "ignoreWarning", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "message", + "type": "QJSValue" + } + ], + "index": 23, + "name": "failOnWarning", + "returnType": "void", + "revision": 1539 + }, + { + "access": "public", + "arguments": [ + { + "name": "ms", + "type": "int" + } + ], + "index": 24, + "name": "wait", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "ms", + "type": "int" + } + ], + "index": 25, + "name": "sleep", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "item", + "type": "QQuickItem*" + }, + { + "name": "timeout", + "type": "int" + } + ], + "index": 26, + "name": "waitForRendering", + "returnType": "bool" + }, + { + "access": "public", + "arguments": [ + { + "name": "item", + "type": "QQuickItem*" + } + ], + "index": 27, + "isCloned": true, + "name": "waitForRendering", + "returnType": "bool" + }, + { + "access": "public", + "index": 28, + "name": "startMeasurement", + "returnType": "void" + }, + { + "access": "public", + "index": 29, + "name": "beginDataRun", + "returnType": "void" + }, + { + "access": "public", + "index": 30, + "name": "endDataRun", + "returnType": "void" + }, + { + "access": "public", + "index": 31, + "name": "measurementAccepted", + "returnType": "bool" + }, + { + "access": "public", + "index": 32, + "name": "needsMoreMeasurements", + "returnType": "bool" + }, + { + "access": "public", + "arguments": [ + { + "name": "runMode", + "type": "RunMode" + }, + { + "name": "tag", + "type": "QString" + } + ], + "index": 33, + "name": "startBenchmark", + "returnType": "void" + }, + { + "access": "public", + "index": 34, + "name": "isBenchmarkDone", + "returnType": "bool" + }, + { + "access": "public", + "index": 35, + "name": "nextBenchmark", + "returnType": "void" + }, + { + "access": "public", + "index": 36, + "name": "stopBenchmark", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "item", + "type": "QQuickItem*" + } + ], + "index": 37, + "name": "grabImage", + "returnType": "QObject*" + }, + { + "access": "public", + "arguments": [ + { + "name": "parent", + "type": "QObject*" + }, + { + "name": "objectName", + "type": "QString" + } + ], + "index": 38, + "name": "findChild", + "returnType": "QObject*", + "revision": 257 + }, + { + "access": "public", + "arguments": [ + { + "name": "itemOrWindow", + "type": "QObject*" + } + ], + "index": 39, + "name": "isPolishScheduled", + "returnType": "bool", + "revision": 269 + }, + { + "access": "public", + "arguments": [ + { + "name": "itemOrWindow", + "type": "QObject*" + }, + { + "name": "timeout", + "type": "int" + } + ], + "index": 40, + "name": "waitForPolish", + "returnType": "bool", + "revision": 1541 + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "quicktestresult_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "TestUtil" + }, + { + "name": "QML.AddedInVersion", + "value": "256" + } + ], + "className": "QuickTestUtil", + "lineNumber": 27, + "methods": [ + { + "access": "public", + "arguments": [ + { + "name": "lineCount", + "type": "int" + } + ], + "index": 9, + "name": "populateClipboardText", + "returnType": "void" + } + ], + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "printAvailableFunctions", + "notify": "printAvailableFunctionsChanged", + "read": "printAvailableFunctions", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "dragThreshold", + "notify": "dragThresholdChanged", + "read": "dragThreshold", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + } + ], + "qualifiedClassName": "QuickTestUtil", + "signals": [ + { + "access": "public", + "index": 0, + "name": "printAvailableFunctionsChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "dragThresholdChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "v", + "type": "QVariant" + } + ], + "index": 2, + "name": "typeName", + "returnType": "QJSValue" + }, + { + "access": "public", + "arguments": [ + { + "name": "act", + "type": "QVariant" + }, + { + "name": "exp", + "type": "QVariant" + } + ], + "index": 3, + "name": "compare", + "returnType": "bool" + }, + { + "access": "public", + "arguments": [ + { + "name": "frameIndex", + "type": "int" + } + ], + "index": 4, + "name": "callerFile", + "returnType": "QJSValue" + }, + { + "access": "public", + "index": 5, + "isCloned": true, + "name": "callerFile", + "returnType": "QJSValue" + }, + { + "access": "public", + "arguments": [ + { + "name": "frameIndex", + "type": "int" + } + ], + "index": 6, + "name": "callerLine", + "returnType": "int" + }, + { + "access": "public", + "index": 7, + "isCloned": true, + "name": "callerLine", + "returnType": "int" + }, + { + "access": "public", + "arguments": [ + { + "name": "signalName", + "type": "QString" + } + ], + "index": 8, + "name": "signalHandlerName", + "returnType": "QString", + "revision": 1543 + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "quicktestutil_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "SimpleReceiver", + "lineNumber": 233, + "object": true, + "qualifiedClassName": "SimpleReceiver", + "slots": [ + { + "access": "public", + "index": 0, + "name": "slotFun", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "quicktest.cpp", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QuickTestImageObject", + "lineNumber": 44, + "object": true, + "properties": [ + { + "constant": true, + "designable": true, + "final": false, + "index": 0, + "name": "width", + "read": "width", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 1, + "name": "height", + "read": "height", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": true, + "designable": true, + "final": false, + "index": 2, + "name": "size", + "read": "size", + "required": false, + "scriptable": true, + "stored": true, + "type": "QSize", + "user": false + } + ], + "qualifiedClassName": "QuickTestImageObject", + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "x", + "type": "int" + }, + { + "name": "y", + "type": "int" + } + ], + "index": 0, + "name": "red", + "returnType": "int" + }, + { + "access": "public", + "arguments": [ + { + "name": "x", + "type": "int" + }, + { + "name": "y", + "type": "int" + } + ], + "index": 1, + "name": "green", + "returnType": "int" + }, + { + "access": "public", + "arguments": [ + { + "name": "x", + "type": "int" + }, + { + "name": "y", + "type": "int" + } + ], + "index": 2, + "name": "blue", + "returnType": "int" + }, + { + "access": "public", + "arguments": [ + { + "name": "x", + "type": "int" + }, + { + "name": "y", + "type": "int" + } + ], + "index": 3, + "name": "alpha", + "returnType": "int" + }, + { + "access": "public", + "arguments": [ + { + "name": "x", + "type": "int" + }, + { + "name": "y", + "type": "int" + } + ], + "index": 4, + "name": "pixel", + "returnType": "QVariant" + }, + { + "access": "public", + "arguments": [ + { + "name": "other", + "type": "QuickTestImageObject*" + } + ], + "index": 5, + "name": "equals", + "returnType": "bool" + }, + { + "access": "public", + "arguments": [ + { + "name": "filePath", + "type": "QString" + } + ], + "index": 6, + "name": "save", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "quicktestresult.cpp", + "outputRevision": 68 + } +] diff --git a/qt/6.8.1/msvc2022_64/metatypes/qt6quicktestutilsprivate_metatypes.json b/qt/6.8.1/msvc2022_64/metatypes/qt6quicktestutilsprivate_metatypes.json new file mode 100644 index 0000000000000000000000000000000000000000..b955ab79239a8646bd060a5e6158885bee66dcc8 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/metatypes/qt6quicktestutilsprivate_metatypes.json @@ -0,0 +1,214 @@ +[ + { + "classes": [ + { + "className": "QSizeChangeListener", + "lineNumber": 27, + "object": true, + "qualifiedClassName": "QSizeChangeListener", + "slots": [ + { + "access": "private", + "index": 0, + "name": "onSizeChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QVector" + } + ] + } + ], + "inputFile": "geometrytestutils_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQmlDataTest", + "lineNumber": 30, + "object": true, + "qualifiedClassName": "QQmlDataTest", + "slots": [ + { + "access": "public", + "index": 0, + "name": "initTestCase", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "init", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qmlutils_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "TestHTTPServer", + "lineNumber": 32, + "object": true, + "qualifiedClassName": "TestHTTPServer", + "slots": [ + { + "access": "private", + "index": 0, + "name": "newConnection", + "returnType": "void" + }, + { + "access": "private", + "index": 1, + "name": "disconnected", + "returnType": "void" + }, + { + "access": "private", + "index": 2, + "name": "readyRead", + "returnType": "void" + }, + { + "access": "private", + "index": 3, + "name": "sendOne", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "className": "ThreadedTestHTTPServer", + "lineNumber": 96, + "object": true, + "qualifiedClassName": "ThreadedTestHTTPServer", + "superClasses": [ + { + "access": "public", + "name": "QThread" + } + ] + } + ], + "inputFile": "testhttpserver_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QaimModel", + "lineNumber": 57, + "methods": [ + { + "access": "public", + "arguments": [ + { + "name": "name", + "type": "QString" + }, + { + "name": "number", + "type": "QString" + } + ], + "index": 0, + "name": "addItem", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + } + ], + "index": 1, + "name": "removeItem", + "returnType": "void" + } + ], + "object": true, + "qualifiedClassName": "QQuickViewTestUtils::QaimModel", + "superClasses": [ + { + "access": "public", + "name": "QAbstractListModel" + } + ] + }, + { + "className": "StressTestModel", + "lineNumber": 150, + "object": true, + "qualifiedClassName": "QQuickViewTestUtils::StressTestModel", + "slots": [ + { + "access": "public", + "index": 0, + "name": "updateModel", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QAbstractListModel" + } + ] + } + ], + "inputFile": "viewtestutils_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "SignalMultiSpy", + "lineNumber": 131, + "object": true, + "qualifiedClassName": "QQuickVisualTestUtils::SignalMultiSpy", + "slots": [ + { + "access": "public", + "index": 0, + "name": "receive", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "visualtestutils_p.h", + "outputRevision": 68 + } +] diff --git a/qt/6.8.1/msvc2022_64/metatypes/qt6quickvectorimage_metatypes.json b/qt/6.8.1/msvc2022_64/metatypes/qt6quickvectorimage_metatypes.json new file mode 100644 index 0000000000000000000000000000000000000000..ad26862d918f8395c46667bcb44b1d86e3890247 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/metatypes/qt6quickvectorimage_metatypes.json @@ -0,0 +1,123 @@ +[ + { + "classes": [ + { + "classInfos": [ + { + "name": "QML.Element", + "value": "VectorImage" + } + ], + "className": "QQuickVectorImage", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "FillMode", + "values": [ + "NoResize", + "PreserveAspectFit", + "PreserveAspectCrop", + "Stretch" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "RendererType", + "values": [ + "GeometryRenderer", + "CurveRenderer" + ] + } + ], + "lineNumber": 25, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "source", + "notify": "sourceChanged", + "read": "source", + "required": false, + "scriptable": true, + "stored": true, + "type": "QUrl", + "user": false, + "write": "setSource" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "fillMode", + "notify": "fillModeChanged", + "read": "fillMode", + "required": false, + "scriptable": true, + "stored": true, + "type": "FillMode", + "user": false, + "write": "setFillMode" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "preferredRendererType", + "notify": "preferredRendererTypeChanged", + "read": "preferredRendererType", + "required": false, + "scriptable": true, + "stored": true, + "type": "RendererType", + "user": false, + "write": "setPreferredRendererType" + } + ], + "qualifiedClassName": "QQuickVectorImage", + "signals": [ + { + "access": "public", + "index": 0, + "name": "sourceChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "fillModeChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "preferredRendererTypeChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "private", + "index": 3, + "name": "updateSvgItemScale", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QQuickItem" + } + ] + } + ], + "inputFile": "qquickvectorimage_p.h", + "outputRevision": 68 + } +] diff --git a/qt/6.8.1/msvc2022_64/metatypes/qt6quickvectorimagegeneratorprivate_metatypes.json b/qt/6.8.1/msvc2022_64/metatypes/qt6quickvectorimagegeneratorprivate_metatypes.json new file mode 100644 index 0000000000000000000000000000000000000000..0d4f101c7a37a4c875e6999bee1a287fdb733380 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/metatypes/qt6quickvectorimagegeneratorprivate_metatypes.json @@ -0,0 +1,2 @@ +[ +] diff --git a/qt/6.8.1/msvc2022_64/metatypes/qt6quickwidgets_metatypes.json b/qt/6.8.1/msvc2022_64/metatypes/qt6quickwidgets_metatypes.json new file mode 100644 index 0000000000000000000000000000000000000000..c46a99b00465e032f5b42c089898dd6ccb7e0e40 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/metatypes/qt6quickwidgets_metatypes.json @@ -0,0 +1,202 @@ +[ + { + "classes": [ + { + "className": "QQuickWidget", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "ResizeMode", + "values": [ + "SizeViewToRootObject", + "SizeRootObjectToView" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "Status", + "values": [ + "Null", + "Ready", + "Loading", + "Error" + ] + } + ], + "lineNumber": 22, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "resizeMode", + "read": "resizeMode", + "required": false, + "scriptable": true, + "stored": true, + "type": "ResizeMode", + "user": false, + "write": "setResizeMode" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "status", + "notify": "statusChanged", + "read": "status", + "required": false, + "scriptable": true, + "stored": true, + "type": "Status", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "source", + "read": "source", + "required": false, + "scriptable": true, + "stored": true, + "type": "QUrl", + "user": false, + "write": "setSource" + } + ], + "qualifiedClassName": "QQuickWidget", + "signals": [ + { + "access": "public", + "arguments": [ + { + "type": "QQuickWidget::Status" + } + ], + "index": 0, + "name": "statusChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "error", + "type": "QQuickWindow::SceneGraphError" + }, + { + "name": "message", + "type": "QString" + } + ], + "index": 1, + "name": "sceneGraphError", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "type": "QUrl" + } + ], + "index": 2, + "name": "setSource", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "url", + "type": "QUrl" + }, + { + "name": "component", + "type": "QQmlComponent*" + }, + { + "name": "item", + "type": "QObject*" + } + ], + "index": 3, + "name": "setContent", + "returnType": "void" + }, + { + "access": "private", + "index": 4, + "name": "continueExecute", + "returnType": "void" + }, + { + "access": "private", + "index": 5, + "name": "createFramebufferObject", + "returnType": "void" + }, + { + "access": "private", + "index": 6, + "name": "destroyFramebufferObject", + "returnType": "void" + }, + { + "access": "private", + "index": 7, + "name": "triggerUpdate", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "focusObject", + "type": "QObject*" + } + ], + "index": 8, + "name": "propagateFocusObjectChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + } + ], + "inputFile": "qquickwidget.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QQuickWidgetOffscreenWindow", + "lineNumber": 116, + "object": true, + "qualifiedClassName": "QQuickWidgetOffscreenWindow", + "superClasses": [ + { + "access": "public", + "name": "QQuickWindow" + } + ] + } + ], + "inputFile": "qquickwidget_p.h", + "outputRevision": 68 + } +] diff --git a/qt/6.8.1/msvc2022_64/metatypes/qt6shadertools_metatypes.json b/qt/6.8.1/msvc2022_64/metatypes/qt6shadertools_metatypes.json new file mode 100644 index 0000000000000000000000000000000000000000..0d4f101c7a37a4c875e6999bee1a287fdb733380 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/metatypes/qt6shadertools_metatypes.json @@ -0,0 +1,2 @@ +[ +] diff --git a/qt/6.8.1/msvc2022_64/metatypes/qt6sql_metatypes.json b/qt/6.8.1/msvc2022_64/metatypes/qt6sql_metatypes.json new file mode 100644 index 0000000000000000000000000000000000000000..2eb2fde0e9c5d0739ba2c1e7b07ecd745f1fd906 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/metatypes/qt6sql_metatypes.json @@ -0,0 +1,554 @@ +[ + { + "classes": [ + { + "className": "QSqlDatabase", + "gadget": true, + "lineNumber": 37, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "numericalPrecisionPolicy", + "read": "numericalPrecisionPolicy", + "required": false, + "scriptable": true, + "stored": true, + "type": "QSql::NumericalPrecisionPolicy", + "user": false, + "write": "setNumericalPrecisionPolicy" + } + ], + "qualifiedClassName": "QSqlDatabase" + } + ], + "inputFile": "qsqldatabase.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QSqlDriver", + "lineNumber": 25, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "numericalPrecisionPolicy", + "read": "numericalPrecisionPolicy", + "required": false, + "scriptable": true, + "stored": true, + "type": "QSql::NumericalPrecisionPolicy", + "user": false, + "write": "setNumericalPrecisionPolicy" + } + ], + "qualifiedClassName": "QSqlDriver", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "name", + "type": "QString" + }, + { + "name": "source", + "type": "QSqlDriver::NotificationSource" + }, + { + "name": "payload", + "type": "QVariant" + } + ], + "index": 0, + "name": "notification", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "index": 1, + "name": "cancelQuery", + "returnType": "bool" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qsqldriver.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QSqlDriverPlugin", + "lineNumber": 18, + "object": true, + "qualifiedClassName": "QSqlDriverPlugin", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qsqldriverplugin.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QSqlField", + "gadget": true, + "lineNumber": 18, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "value", + "read": "value", + "required": false, + "scriptable": true, + "stored": true, + "type": "QVariant", + "user": false, + "write": "setValue" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "defaultValue", + "read": "defaultValue", + "required": false, + "scriptable": true, + "stored": true, + "type": "QVariant", + "user": false, + "write": "setDefaultValue" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "name", + "read": "name", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setName" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "tableName", + "read": "tableName", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setTableName" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "metaType", + "read": "metaType", + "required": false, + "scriptable": true, + "stored": true, + "type": "QMetaType", + "user": false, + "write": "setMetaType" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "requiredStatus", + "read": "requiredStatus", + "required": false, + "scriptable": true, + "stored": true, + "type": "RequiredStatus", + "user": false, + "write": "setRequiredStatus" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "readOnly", + "read": "isReadOnly", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setReadOnly" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 7, + "name": "generated", + "read": "isGenerated", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setGenerated" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 8, + "name": "autoValue", + "read": "isAutoValue", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setAutoValue" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 9, + "name": "length", + "read": "length", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setLength" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 10, + "name": "precision", + "read": "precision", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setPrecision" + } + ], + "qualifiedClassName": "QSqlField" + } + ], + "inputFile": "qsqlfield.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QSqlIndex", + "gadget": true, + "lineNumber": 17, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "name", + "read": "name", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setName" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "cursorName", + "read": "cursorName", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setCursorName" + } + ], + "qualifiedClassName": "QSqlIndex", + "superClasses": [ + { + "access": "public", + "name": "QSqlRecord" + } + ] + } + ], + "inputFile": "qsqlindex.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QSqlQuery", + "gadget": true, + "lineNumber": 23, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "forwardOnly", + "read": "isForwardOnly", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setForwardOnly" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "positionalBindingEnabled", + "read": "isPositionalBindingEnabled", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setPositionalBindingEnabled" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "numericalPrecisionPolicy", + "read": "numericalPrecisionPolicy", + "required": false, + "scriptable": true, + "stored": true, + "type": "QSql::NumericalPrecisionPolicy", + "user": false, + "write": "setNumericalPrecisionPolicy" + } + ], + "qualifiedClassName": "QSqlQuery" + } + ], + "inputFile": "qsqlquery.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QSqlQueryModel", + "lineNumber": 20, + "object": true, + "qualifiedClassName": "QSqlQueryModel", + "superClasses": [ + { + "access": "public", + "name": "QAbstractTableModel" + } + ] + } + ], + "inputFile": "qsqlquerymodel.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QSqlRelationalTableModel", + "lineNumber": 47, + "object": true, + "qualifiedClassName": "QSqlRelationalTableModel", + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "row", + "type": "int" + } + ], + "index": 0, + "name": "revertRow", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QSqlTableModel" + } + ] + } + ], + "inputFile": "qsqlrelationaltablemodel.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QSqlTableModel", + "lineNumber": 21, + "object": true, + "qualifiedClassName": "QSqlTableModel", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "row", + "type": "int" + }, + { + "name": "record", + "type": "QSqlRecord&" + } + ], + "index": 0, + "name": "primeInsert", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "record", + "type": "QSqlRecord&" + } + ], + "index": 1, + "name": "beforeInsert", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "row", + "type": "int" + }, + { + "name": "record", + "type": "QSqlRecord&" + } + ], + "index": 2, + "name": "beforeUpdate", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "row", + "type": "int" + } + ], + "index": 3, + "name": "beforeDelete", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "index": 4, + "name": "select", + "returnType": "bool" + }, + { + "access": "public", + "arguments": [ + { + "name": "row", + "type": "int" + } + ], + "index": 5, + "name": "selectRow", + "returnType": "bool" + }, + { + "access": "public", + "index": 6, + "name": "submit", + "returnType": "bool" + }, + { + "access": "public", + "index": 7, + "name": "revert", + "returnType": "void" + }, + { + "access": "public", + "index": 8, + "name": "submitAll", + "returnType": "bool" + }, + { + "access": "public", + "index": 9, + "name": "revertAll", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QSqlQueryModel" + } + ] + } + ], + "inputFile": "qsqltablemodel.h", + "outputRevision": 68 + } +] diff --git a/qt/6.8.1/msvc2022_64/metatypes/qt6svg_metatypes.json b/qt/6.8.1/msvc2022_64/metatypes/qt6svg_metatypes.json new file mode 100644 index 0000000000000000000000000000000000000000..c5225c95c82d64d994b3601af54267f2fdaebae0 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/metatypes/qt6svg_metatypes.json @@ -0,0 +1,217 @@ +[ + { + "classes": [ + { + "className": "QSvgRenderer", + "lineNumber": 23, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "viewBox", + "read": "viewBoxF", + "required": false, + "scriptable": true, + "stored": true, + "type": "QRectF", + "user": false, + "write": "setViewBox" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "framesPerSecond", + "read": "framesPerSecond", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setFramesPerSecond" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "currentFrame", + "read": "currentFrame", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setCurrentFrame" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "aspectRatioMode", + "read": "aspectRatioMode", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::AspectRatioMode", + "user": false, + "write": "setAspectRatioMode" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "options", + "read": "options", + "required": false, + "scriptable": true, + "stored": true, + "type": "QtSvg::Options", + "user": false, + "write": "setOptions" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "animationEnabled", + "read": "isAnimationEnabled", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setAnimationEnabled" + } + ], + "qualifiedClassName": "QSvgRenderer", + "signals": [ + { + "access": "public", + "index": 0, + "name": "repaintNeeded", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "filename", + "type": "QString" + } + ], + "index": 1, + "name": "load", + "returnType": "bool" + }, + { + "access": "public", + "arguments": [ + { + "name": "contents", + "type": "QByteArray" + } + ], + "index": 2, + "name": "load", + "returnType": "bool" + }, + { + "access": "public", + "arguments": [ + { + "name": "contents", + "type": "QXmlStreamReader*" + } + ], + "index": 3, + "name": "load", + "returnType": "bool" + }, + { + "access": "public", + "arguments": [ + { + "name": "p", + "type": "QPainter*" + } + ], + "index": 4, + "name": "render", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "p", + "type": "QPainter*" + }, + { + "name": "bounds", + "type": "QRectF" + } + ], + "index": 5, + "name": "render", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "p", + "type": "QPainter*" + }, + { + "name": "elementId", + "type": "QString" + }, + { + "name": "bounds", + "type": "QRectF" + } + ], + "index": 6, + "name": "render", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "p", + "type": "QPainter*" + }, + { + "name": "elementId", + "type": "QString" + } + ], + "index": 7, + "isCloned": true, + "name": "render", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qsvgrenderer.h", + "outputRevision": 68 + } +] diff --git a/qt/6.8.1/msvc2022_64/metatypes/qt6svgwidgets_metatypes.json b/qt/6.8.1/msvc2022_64/metatypes/qt6svgwidgets_metatypes.json new file mode 100644 index 0000000000000000000000000000000000000000..815bfdb3ac0e59f978f6e23a1fa93abdfd8a63ae --- /dev/null +++ b/qt/6.8.1/msvc2022_64/metatypes/qt6svgwidgets_metatypes.json @@ -0,0 +1,110 @@ +[ + { + "classes": [ + { + "className": "QSvgWidget", + "lineNumber": 18, + "object": true, + "qualifiedClassName": "QSvgWidget", + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "file", + "type": "QString" + } + ], + "index": 0, + "name": "load", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "contents", + "type": "QByteArray" + } + ], + "index": 1, + "name": "load", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + } + ], + "inputFile": "qsvgwidget.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QGraphicsSvgItem", + "interfaces": [ + [ + { + "className": "QGraphicsItem", + "id": "\"org.qt-project.Qt.QGraphicsItem\"" + } + ] + ], + "lineNumber": 18, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "elementId", + "read": "elementId", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setElementId" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "maximumCacheSize", + "read": "maximumCacheSize", + "required": false, + "scriptable": true, + "stored": true, + "type": "QSize", + "user": false, + "write": "setMaximumCacheSize" + } + ], + "qualifiedClassName": "QGraphicsSvgItem", + "slots": [ + { + "access": "private", + "index": 0, + "name": "_q_repaintItem", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QGraphicsObject" + } + ] + } + ], + "inputFile": "qgraphicssvgitem.h", + "outputRevision": 68 + } +] diff --git a/qt/6.8.1/msvc2022_64/metatypes/qt6test_metatypes.json b/qt/6.8.1/msvc2022_64/metatypes/qt6test_metatypes.json new file mode 100644 index 0000000000000000000000000000000000000000..aadb95f408f086028577d8243c3f0f535721bffb --- /dev/null +++ b/qt/6.8.1/msvc2022_64/metatypes/qt6test_metatypes.json @@ -0,0 +1,74 @@ +[ + { + "classes": [ + { + "className": "QTestEventLoop", + "lineNumber": 19, + "object": true, + "qualifiedClassName": "QTestEventLoop", + "slots": [ + { + "access": "public", + "index": 0, + "name": "exitLoop", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qtesteventloop.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QAbstractItemModelTester", + "lineNumber": 33, + "object": true, + "qualifiedClassName": "QAbstractItemModelTester", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qabstractitemmodeltester.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QTestLog", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "LogMode", + "values": [ + "Plain", + "XML", + "LightXML", + "JUnitXML", + "CSV", + "TeamCity", + "TAP" + ] + } + ], + "gadget": true, + "lineNumber": 33, + "qualifiedClassName": "QTestLog" + } + ], + "inputFile": "qtestlog_p.h", + "outputRevision": 68 + } +] diff --git a/qt/6.8.1/msvc2022_64/metatypes/qt6uitools_metatypes.json b/qt/6.8.1/msvc2022_64/metatypes/qt6uitools_metatypes.json new file mode 100644 index 0000000000000000000000000000000000000000..490ed2ae35e2933614bbedd116581db5903fc9f8 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/metatypes/qt6uitools_metatypes.json @@ -0,0 +1,292 @@ +[ + { + "classes": [ + { + "className": "QUiLoader", + "lineNumber": 22, + "object": true, + "qualifiedClassName": "QUiLoader", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "quiloader.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QAbstractFormBuilderGadget", + "lineNumber": 47, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "itemFlags", + "read": "fakeItemFlags", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::ItemFlags", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "checkState", + "read": "fakeCheckState", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::CheckState", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "textAlignment", + "read": "fakeAlignment", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::Alignment", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "orientation", + "read": "fakeOrientation", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::Orientation", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "sizeType", + "read": "fakeSizeType", + "required": false, + "scriptable": true, + "stored": true, + "type": "QSizePolicy::Policy", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "colorRole", + "read": "fakeColorRole", + "required": false, + "scriptable": true, + "stored": true, + "type": "QPalette::ColorRole", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "colorGroup", + "read": "fakeColorGroup", + "required": false, + "scriptable": true, + "stored": true, + "type": "QPalette::ColorGroup", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 7, + "name": "styleStrategy", + "read": "fakeStyleStrategy", + "required": false, + "scriptable": true, + "stored": true, + "type": "QFont::StyleStrategy", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 8, + "name": "hintingPreference", + "read": "fakeHintingPreference", + "required": false, + "scriptable": true, + "stored": true, + "type": "QFont::HintingPreference", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 9, + "name": "fontWeight", + "read": "fakeFontWeight", + "required": false, + "scriptable": true, + "stored": true, + "type": "QFont::Weight", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 10, + "name": "cursorShape", + "read": "fakeCursorShape", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::CursorShape", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 11, + "name": "brushStyle", + "read": "fakeBrushStyle", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::BrushStyle", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 12, + "name": "toolBarArea", + "read": "fakeToolBarArea", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::ToolBarArea", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 13, + "name": "gradientType", + "read": "fakeGradientType", + "required": false, + "scriptable": true, + "stored": true, + "type": "QGradient::Type", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 14, + "name": "gradientSpread", + "read": "fakeGradientSpread", + "required": false, + "scriptable": true, + "stored": true, + "type": "QGradient::Spread", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 15, + "name": "gradientCoordinate", + "read": "fakeGradientCoordinate", + "required": false, + "scriptable": true, + "stored": true, + "type": "QGradient::CoordinateMode", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 16, + "name": "language", + "read": "fakeLanguage", + "required": false, + "scriptable": true, + "stored": true, + "type": "QLocale::Language", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 17, + "name": "country", + "read": "fakeCountry", + "required": false, + "scriptable": true, + "stored": true, + "type": "QLocale::Country", + "user": false + } + ], + "qualifiedClassName": "QFormInternal::QAbstractFormBuilderGadget", + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + } + ], + "inputFile": "properties_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "TranslationWatcher", + "lineNumber": 188, + "object": true, + "qualifiedClassName": "QFormInternal::TranslationWatcher", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "quiloader.cpp", + "outputRevision": 68 + } +] diff --git a/qt/6.8.1/msvc2022_64/metatypes/qt6widgets_metatypes.json b/qt/6.8.1/msvc2022_64/metatypes/qt6widgets_metatypes.json new file mode 100644 index 0000000000000000000000000000000000000000..4ab236cefb3e5cd69b5e588d9d602d7c6d3fac78 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/metatypes/qt6widgets_metatypes.json @@ -0,0 +1,23229 @@ +[ + { + "classes": [ + { + "className": "QRhiWidget", + "enums": [ + { + "isClass": true, + "isFlag": false, + "name": "Api", + "values": [ + "Null", + "OpenGL", + "Metal", + "Vulkan", + "Direct3D11", + "Direct3D12" + ] + }, + { + "isClass": true, + "isFlag": false, + "name": "TextureFormat", + "values": [ + "RGBA8", + "RGBA16F", + "RGBA32F", + "RGB10A2" + ] + } + ], + "lineNumber": 18, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "sampleCount", + "notify": "sampleCountChanged", + "read": "sampleCount", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setSampleCount" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "colorBufferFormat", + "notify": "colorBufferFormatChanged", + "read": "colorBufferFormat", + "required": false, + "scriptable": true, + "stored": true, + "type": "TextureFormat", + "user": false, + "write": "setColorBufferFormat" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "fixedColorBufferSize", + "notify": "fixedColorBufferSizeChanged", + "read": "fixedColorBufferSize", + "required": false, + "scriptable": true, + "stored": true, + "type": "QSize", + "user": false, + "write": "setFixedColorBufferSize" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "mirrorVertically", + "notify": "mirrorVerticallyChanged", + "read": "isMirrorVerticallyEnabled", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setMirrorVertically" + } + ], + "qualifiedClassName": "QRhiWidget", + "signals": [ + { + "access": "public", + "index": 0, + "name": "frameSubmitted", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "renderFailed", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "samples", + "type": "int" + } + ], + "index": 2, + "name": "sampleCountChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "format", + "type": "TextureFormat" + } + ], + "index": 3, + "name": "colorBufferFormatChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "pixelSize", + "type": "QSize" + } + ], + "index": 4, + "name": "fixedColorBufferSizeChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "enabled", + "type": "bool" + } + ], + "index": 5, + "name": "mirrorVerticallyChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + } + ], + "inputFile": "qrhiwidget.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QAbstractButton", + "lineNumber": 22, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "text", + "read": "text", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setText" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "icon", + "read": "icon", + "required": false, + "scriptable": true, + "stored": true, + "type": "QIcon", + "user": false, + "write": "setIcon" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "iconSize", + "read": "iconSize", + "required": false, + "scriptable": true, + "stored": true, + "type": "QSize", + "user": false, + "write": "setIconSize" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "shortcut", + "read": "shortcut", + "required": false, + "scriptable": true, + "stored": true, + "type": "QKeySequence", + "user": false, + "write": "setShortcut" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "checkable", + "read": "isCheckable", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setCheckable" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "checked", + "notify": "toggled", + "read": "isChecked", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": true, + "write": "setChecked" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "autoRepeat", + "read": "autoRepeat", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setAutoRepeat" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 7, + "name": "autoExclusive", + "read": "autoExclusive", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setAutoExclusive" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 8, + "name": "autoRepeatDelay", + "read": "autoRepeatDelay", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setAutoRepeatDelay" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 9, + "name": "autoRepeatInterval", + "read": "autoRepeatInterval", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setAutoRepeatInterval" + }, + { + "constant": false, + "designable": false, + "final": false, + "index": 10, + "name": "down", + "read": "isDown", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setDown" + } + ], + "qualifiedClassName": "QAbstractButton", + "signals": [ + { + "access": "public", + "index": 0, + "name": "pressed", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "released", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "checked", + "type": "bool" + } + ], + "index": 2, + "name": "clicked", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "isCloned": true, + "name": "clicked", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "checked", + "type": "bool" + } + ], + "index": 4, + "name": "toggled", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "size", + "type": "QSize" + } + ], + "index": 5, + "name": "setIconSize", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "animateClick", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "click", + "returnType": "void" + }, + { + "access": "public", + "index": 8, + "name": "toggle", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "bool" + } + ], + "index": 9, + "name": "setChecked", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + } + ], + "inputFile": "qabstractbutton.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QAbstractItemDelegate", + "lineNumber": 22, + "object": true, + "qualifiedClassName": "QAbstractItemDelegate", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "editor", + "type": "QWidget*" + } + ], + "index": 0, + "name": "commitData", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "editor", + "type": "QWidget*" + }, + { + "name": "hint", + "type": "QAbstractItemDelegate::EndEditHint" + } + ], + "index": 1, + "name": "closeEditor", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "editor", + "type": "QWidget*" + } + ], + "index": 2, + "isCloned": true, + "name": "closeEditor", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QModelIndex" + } + ], + "index": 3, + "name": "sizeHintChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "private", + "arguments": [ + { + "type": "QWidget*" + } + ], + "index": 4, + "name": "_q_commitDataAndCloseEditor", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qabstractitemdelegate.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QAbstractItemView", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "SelectionMode", + "values": [ + "NoSelection", + "SingleSelection", + "MultiSelection", + "ExtendedSelection", + "ContiguousSelection" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "SelectionBehavior", + "values": [ + "SelectItems", + "SelectRows", + "SelectColumns" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "ScrollHint", + "values": [ + "EnsureVisible", + "PositionAtTop", + "PositionAtBottom", + "PositionAtCenter" + ] + }, + { + "alias": "EditTrigger", + "isClass": false, + "isFlag": true, + "name": "EditTriggers", + "values": [ + "NoEditTriggers", + "CurrentChanged", + "DoubleClicked", + "SelectedClicked", + "EditKeyPressed", + "AnyKeyPressed", + "AllEditTriggers" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "ScrollMode", + "values": [ + "ScrollPerItem", + "ScrollPerPixel" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "DragDropMode", + "values": [ + "NoDragDrop", + "DragOnly", + "DropOnly", + "DragDrop", + "InternalMove" + ] + } + ], + "lineNumber": 25, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "autoScroll", + "read": "hasAutoScroll", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setAutoScroll" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "autoScrollMargin", + "read": "autoScrollMargin", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setAutoScrollMargin" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "editTriggers", + "read": "editTriggers", + "required": false, + "scriptable": true, + "stored": true, + "type": "EditTriggers", + "user": false, + "write": "setEditTriggers" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "tabKeyNavigation", + "read": "tabKeyNavigation", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setTabKeyNavigation" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "showDropIndicator", + "read": "showDropIndicator", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setDropIndicatorShown" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "dragEnabled", + "read": "dragEnabled", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setDragEnabled" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "dragDropOverwriteMode", + "read": "dragDropOverwriteMode", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setDragDropOverwriteMode" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 7, + "name": "dragDropMode", + "read": "dragDropMode", + "required": false, + "scriptable": true, + "stored": true, + "type": "DragDropMode", + "user": false, + "write": "setDragDropMode" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 8, + "name": "defaultDropAction", + "read": "defaultDropAction", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::DropAction", + "user": false, + "write": "setDefaultDropAction" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 9, + "name": "alternatingRowColors", + "read": "alternatingRowColors", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setAlternatingRowColors" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 10, + "name": "selectionMode", + "read": "selectionMode", + "required": false, + "scriptable": true, + "stored": true, + "type": "SelectionMode", + "user": false, + "write": "setSelectionMode" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 11, + "name": "selectionBehavior", + "read": "selectionBehavior", + "required": false, + "scriptable": true, + "stored": true, + "type": "SelectionBehavior", + "user": false, + "write": "setSelectionBehavior" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 12, + "name": "iconSize", + "notify": "iconSizeChanged", + "read": "iconSize", + "required": false, + "scriptable": true, + "stored": true, + "type": "QSize", + "user": false, + "write": "setIconSize" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 13, + "name": "textElideMode", + "read": "textElideMode", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::TextElideMode", + "user": false, + "write": "setTextElideMode" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 14, + "name": "verticalScrollMode", + "read": "verticalScrollMode", + "required": false, + "reset": "resetVerticalScrollMode", + "scriptable": true, + "stored": true, + "type": "ScrollMode", + "user": false, + "write": "setVerticalScrollMode" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 15, + "name": "horizontalScrollMode", + "read": "horizontalScrollMode", + "required": false, + "reset": "resetHorizontalScrollMode", + "scriptable": true, + "stored": true, + "type": "ScrollMode", + "user": false, + "write": "setHorizontalScrollMode" + } + ], + "qualifiedClassName": "QAbstractItemView", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "QModelIndex" + } + ], + "index": 0, + "name": "pressed", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "QModelIndex" + } + ], + "index": 1, + "name": "clicked", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "QModelIndex" + } + ], + "index": 2, + "name": "doubleClicked", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "QModelIndex" + } + ], + "index": 3, + "name": "activated", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "QModelIndex" + } + ], + "index": 4, + "name": "entered", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "viewportEntered", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "size", + "type": "QSize" + } + ], + "index": 6, + "name": "iconSizeChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "index": 7, + "name": "reset", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "QModelIndex" + } + ], + "index": 8, + "name": "setRootIndex", + "returnType": "void" + }, + { + "access": "public", + "index": 9, + "name": "doItemsLayout", + "returnType": "void" + }, + { + "access": "public", + "index": 10, + "name": "selectAll", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "QModelIndex" + } + ], + "index": 11, + "name": "edit", + "returnType": "void" + }, + { + "access": "public", + "index": 12, + "name": "clearSelection", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "QModelIndex" + } + ], + "index": 13, + "name": "setCurrentIndex", + "returnType": "void" + }, + { + "access": "public", + "index": 14, + "name": "scrollToTop", + "returnType": "void" + }, + { + "access": "public", + "index": 15, + "name": "scrollToBottom", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "QModelIndex" + } + ], + "index": 16, + "name": "update", + "returnType": "void" + }, + { + "access": "protected", + "arguments": [ + { + "name": "topLeft", + "type": "QModelIndex" + }, + { + "name": "bottomRight", + "type": "QModelIndex" + }, + { + "name": "roles", + "type": "QList" + } + ], + "index": 17, + "name": "dataChanged", + "returnType": "void" + }, + { + "access": "protected", + "arguments": [ + { + "name": "topLeft", + "type": "QModelIndex" + }, + { + "name": "bottomRight", + "type": "QModelIndex" + } + ], + "index": 18, + "isCloned": true, + "name": "dataChanged", + "returnType": "void" + }, + { + "access": "protected", + "arguments": [ + { + "name": "parent", + "type": "QModelIndex" + }, + { + "name": "start", + "type": "int" + }, + { + "name": "end", + "type": "int" + } + ], + "index": 19, + "name": "rowsInserted", + "returnType": "void" + }, + { + "access": "protected", + "arguments": [ + { + "name": "parent", + "type": "QModelIndex" + }, + { + "name": "start", + "type": "int" + }, + { + "name": "end", + "type": "int" + } + ], + "index": 20, + "name": "rowsAboutToBeRemoved", + "returnType": "void" + }, + { + "access": "protected", + "arguments": [ + { + "name": "selected", + "type": "QItemSelection" + }, + { + "name": "deselected", + "type": "QItemSelection" + } + ], + "index": 21, + "name": "selectionChanged", + "returnType": "void" + }, + { + "access": "protected", + "arguments": [ + { + "name": "current", + "type": "QModelIndex" + }, + { + "name": "previous", + "type": "QModelIndex" + } + ], + "index": 22, + "name": "currentChanged", + "returnType": "void" + }, + { + "access": "protected", + "index": 23, + "name": "updateEditorData", + "returnType": "void" + }, + { + "access": "protected", + "index": 24, + "name": "updateEditorGeometries", + "returnType": "void" + }, + { + "access": "protected", + "index": 25, + "name": "updateGeometries", + "returnType": "void" + }, + { + "access": "protected", + "arguments": [ + { + "name": "action", + "type": "int" + } + ], + "index": 26, + "name": "verticalScrollbarAction", + "returnType": "void" + }, + { + "access": "protected", + "arguments": [ + { + "name": "action", + "type": "int" + } + ], + "index": 27, + "name": "horizontalScrollbarAction", + "returnType": "void" + }, + { + "access": "protected", + "arguments": [ + { + "name": "value", + "type": "int" + } + ], + "index": 28, + "name": "verticalScrollbarValueChanged", + "returnType": "void" + }, + { + "access": "protected", + "arguments": [ + { + "name": "value", + "type": "int" + } + ], + "index": 29, + "name": "horizontalScrollbarValueChanged", + "returnType": "void" + }, + { + "access": "protected", + "arguments": [ + { + "name": "editor", + "type": "QWidget*" + }, + { + "name": "hint", + "type": "QAbstractItemDelegate::EndEditHint" + } + ], + "index": 30, + "name": "closeEditor", + "returnType": "void" + }, + { + "access": "protected", + "arguments": [ + { + "name": "editor", + "type": "QWidget*" + } + ], + "index": 31, + "name": "commitData", + "returnType": "void" + }, + { + "access": "protected", + "arguments": [ + { + "name": "editor", + "type": "QObject*" + } + ], + "index": 32, + "name": "editorDestroyed", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QAbstractScrollArea" + } + ] + } + ], + "inputFile": "qabstractitemview.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QAbstractScrollArea", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "SizeAdjustPolicy", + "values": [ + "AdjustIgnored", + "AdjustToContentsOnFirstShow", + "AdjustToContents" + ] + } + ], + "lineNumber": 19, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "verticalScrollBarPolicy", + "read": "verticalScrollBarPolicy", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::ScrollBarPolicy", + "user": false, + "write": "setVerticalScrollBarPolicy" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "horizontalScrollBarPolicy", + "read": "horizontalScrollBarPolicy", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::ScrollBarPolicy", + "user": false, + "write": "setHorizontalScrollBarPolicy" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "sizeAdjustPolicy", + "read": "sizeAdjustPolicy", + "required": false, + "scriptable": true, + "stored": true, + "type": "SizeAdjustPolicy", + "user": false, + "write": "setSizeAdjustPolicy" + } + ], + "qualifiedClassName": "QAbstractScrollArea", + "slots": [ + { + "access": "private", + "arguments": [ + { + "type": "int" + } + ], + "index": 0, + "name": "_q_hslide", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "type": "int" + } + ], + "index": 1, + "name": "_q_vslide", + "returnType": "void" + }, + { + "access": "private", + "index": 2, + "name": "_q_showOrHideScrollBars", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QFrame" + } + ] + } + ], + "inputFile": "qabstractscrollarea.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QAbstractScrollAreaFilter", + "lineNumber": 78, + "object": true, + "qualifiedClassName": "QAbstractScrollAreaFilter", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qabstractscrollarea_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QAbstractSlider", + "lineNumber": 17, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "minimum", + "read": "minimum", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setMinimum" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "maximum", + "read": "maximum", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setMaximum" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "singleStep", + "read": "singleStep", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setSingleStep" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "pageStep", + "read": "pageStep", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setPageStep" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "value", + "notify": "valueChanged", + "read": "value", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": true, + "write": "setValue" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "sliderPosition", + "notify": "sliderMoved", + "read": "sliderPosition", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setSliderPosition" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "tracking", + "read": "hasTracking", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setTracking" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 7, + "name": "orientation", + "read": "orientation", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::Orientation", + "user": false, + "write": "setOrientation" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 8, + "name": "invertedAppearance", + "read": "invertedAppearance", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setInvertedAppearance" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 9, + "name": "invertedControls", + "read": "invertedControls", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setInvertedControls" + }, + { + "constant": false, + "designable": false, + "final": false, + "index": 10, + "name": "sliderDown", + "read": "isSliderDown", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setSliderDown" + } + ], + "qualifiedClassName": "QAbstractSlider", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "value", + "type": "int" + } + ], + "index": 0, + "name": "valueChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "sliderPressed", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "position", + "type": "int" + } + ], + "index": 2, + "name": "sliderMoved", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "sliderReleased", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "min", + "type": "int" + }, + { + "name": "max", + "type": "int" + } + ], + "index": 4, + "name": "rangeChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "action", + "type": "int" + } + ], + "index": 5, + "name": "actionTriggered", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "type": "int" + } + ], + "index": 6, + "name": "setValue", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "Qt::Orientation" + } + ], + "index": 7, + "name": "setOrientation", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "min", + "type": "int" + }, + { + "name": "max", + "type": "int" + } + ], + "index": 8, + "name": "setRange", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + } + ], + "inputFile": "qabstractslider.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QAbstractSpinBox", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "ButtonSymbols", + "values": [ + "UpDownArrows", + "PlusMinus", + "NoButtons" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "CorrectionMode", + "values": [ + "CorrectToPreviousValue", + "CorrectToNearestValue" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "StepType", + "values": [ + "DefaultStepType", + "AdaptiveDecimalStepType" + ] + } + ], + "lineNumber": 20, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "wrapping", + "read": "wrapping", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setWrapping" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "frame", + "read": "hasFrame", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setFrame" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "alignment", + "read": "alignment", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::Alignment", + "user": false, + "write": "setAlignment" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "readOnly", + "read": "isReadOnly", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setReadOnly" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "buttonSymbols", + "read": "buttonSymbols", + "required": false, + "scriptable": true, + "stored": true, + "type": "ButtonSymbols", + "user": false, + "write": "setButtonSymbols" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "specialValueText", + "read": "specialValueText", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setSpecialValueText" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "text", + "read": "text", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 7, + "name": "accelerated", + "read": "isAccelerated", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setAccelerated" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 8, + "name": "correctionMode", + "read": "correctionMode", + "required": false, + "scriptable": true, + "stored": true, + "type": "CorrectionMode", + "user": false, + "write": "setCorrectionMode" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 9, + "name": "acceptableInput", + "read": "hasAcceptableInput", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 10, + "name": "keyboardTracking", + "read": "keyboardTracking", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setKeyboardTracking" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 11, + "name": "showGroupSeparator", + "read": "isGroupSeparatorShown", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setGroupSeparatorShown" + } + ], + "qualifiedClassName": "QAbstractSpinBox", + "signals": [ + { + "access": "public", + "index": 0, + "name": "editingFinished", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "index": 1, + "name": "stepUp", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "stepDown", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "selectAll", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "clear", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + } + ], + "inputFile": "qabstractspinbox.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QApplication", + "lineNumber": 31, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "cursorFlashTime", + "read": "cursorFlashTime", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setCursorFlashTime" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "doubleClickInterval", + "read": "doubleClickInterval", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setDoubleClickInterval" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "keyboardInputInterval", + "read": "keyboardInputInterval", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setKeyboardInputInterval" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "wheelScrollLines", + "read": "wheelScrollLines", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setWheelScrollLines" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "startDragTime", + "read": "startDragTime", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setStartDragTime" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "startDragDistance", + "read": "startDragDistance", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setStartDragDistance" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "styleSheet", + "read": "styleSheet", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setStyleSheet" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 7, + "name": "autoSipEnabled", + "read": "autoSipEnabled", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setAutoSipEnabled" + } + ], + "qualifiedClassName": "QApplication", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "old", + "type": "QWidget*" + }, + { + "name": "now", + "type": "QWidget*" + } + ], + "index": 0, + "name": "focusChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "sheet", + "type": "QString" + } + ], + "index": 1, + "name": "setStyleSheet", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "enabled", + "type": "bool" + } + ], + "index": 2, + "name": "setAutoSipEnabled", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "closeAllWindows", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "aboutQt", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QGuiApplication" + } + ] + } + ], + "inputFile": "qapplication.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QBoxLayout", + "lineNumber": 20, + "object": true, + "qualifiedClassName": "QBoxLayout", + "superClasses": [ + { + "access": "public", + "name": "QLayout" + } + ] + }, + { + "className": "QHBoxLayout", + "lineNumber": 77, + "object": true, + "qualifiedClassName": "QHBoxLayout", + "superClasses": [ + { + "access": "public", + "name": "QBoxLayout" + } + ] + }, + { + "className": "QVBoxLayout", + "lineNumber": 90, + "object": true, + "qualifiedClassName": "QVBoxLayout", + "superClasses": [ + { + "access": "public", + "name": "QBoxLayout" + } + ] + } + ], + "inputFile": "qboxlayout.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QButtonGroup", + "lineNumber": 18, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "exclusive", + "read": "exclusive", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setExclusive" + } + ], + "qualifiedClassName": "QButtonGroup", + "signals": [ + { + "access": "public", + "arguments": [ + { + "type": "QAbstractButton*" + } + ], + "index": 0, + "name": "buttonClicked", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QAbstractButton*" + } + ], + "index": 1, + "name": "buttonPressed", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QAbstractButton*" + } + ], + "index": 2, + "name": "buttonReleased", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QAbstractButton*" + }, + { + "type": "bool" + } + ], + "index": 3, + "name": "buttonToggled", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "int" + } + ], + "index": 4, + "name": "idClicked", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "int" + } + ], + "index": 5, + "name": "idPressed", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "int" + } + ], + "index": 6, + "name": "idReleased", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "int" + }, + { + "type": "bool" + } + ], + "index": 7, + "name": "idToggled", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qbuttongroup.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QCalendarWidget", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "HorizontalHeaderFormat", + "values": [ + "NoHorizontalHeader", + "SingleLetterDayNames", + "ShortDayNames", + "LongDayNames" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "VerticalHeaderFormat", + "values": [ + "NoVerticalHeader", + "ISOWeekNumbers" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "SelectionMode", + "values": [ + "NoSelection", + "SingleSelection" + ] + } + ], + "lineNumber": 19, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "selectedDate", + "read": "selectedDate", + "required": false, + "scriptable": true, + "stored": true, + "type": "QDate", + "user": false, + "write": "setSelectedDate" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "minimumDate", + "read": "minimumDate", + "required": false, + "reset": "clearMinimumDate", + "scriptable": true, + "stored": true, + "type": "QDate", + "user": false, + "write": "setMinimumDate" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "maximumDate", + "read": "maximumDate", + "required": false, + "reset": "clearMaximumDate", + "scriptable": true, + "stored": true, + "type": "QDate", + "user": false, + "write": "setMaximumDate" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "firstDayOfWeek", + "read": "firstDayOfWeek", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::DayOfWeek", + "user": false, + "write": "setFirstDayOfWeek" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "gridVisible", + "read": "isGridVisible", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setGridVisible" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "selectionMode", + "read": "selectionMode", + "required": false, + "scriptable": true, + "stored": true, + "type": "SelectionMode", + "user": false, + "write": "setSelectionMode" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "horizontalHeaderFormat", + "read": "horizontalHeaderFormat", + "required": false, + "scriptable": true, + "stored": true, + "type": "HorizontalHeaderFormat", + "user": false, + "write": "setHorizontalHeaderFormat" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 7, + "name": "verticalHeaderFormat", + "read": "verticalHeaderFormat", + "required": false, + "scriptable": true, + "stored": true, + "type": "VerticalHeaderFormat", + "user": false, + "write": "setVerticalHeaderFormat" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 8, + "name": "navigationBarVisible", + "read": "isNavigationBarVisible", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setNavigationBarVisible" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 9, + "name": "dateEditEnabled", + "read": "isDateEditEnabled", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setDateEditEnabled" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 10, + "name": "dateEditAcceptDelay", + "read": "dateEditAcceptDelay", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setDateEditAcceptDelay" + } + ], + "qualifiedClassName": "QCalendarWidget", + "signals": [ + { + "access": "public", + "index": 0, + "name": "selectionChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "date", + "type": "QDate" + } + ], + "index": 1, + "name": "clicked", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "date", + "type": "QDate" + } + ], + "index": 2, + "name": "activated", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "year", + "type": "int" + }, + { + "name": "month", + "type": "int" + } + ], + "index": 3, + "name": "currentPageChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "date", + "type": "QDate" + } + ], + "index": 4, + "name": "setSelectedDate", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "min", + "type": "QDate" + }, + { + "name": "max", + "type": "QDate" + } + ], + "index": 5, + "name": "setDateRange", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "year", + "type": "int" + }, + { + "name": "month", + "type": "int" + } + ], + "index": 6, + "name": "setCurrentPage", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "show", + "type": "bool" + } + ], + "index": 7, + "name": "setGridVisible", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "visible", + "type": "bool" + } + ], + "index": 8, + "name": "setNavigationBarVisible", + "returnType": "void" + }, + { + "access": "public", + "index": 9, + "name": "showNextMonth", + "returnType": "void" + }, + { + "access": "public", + "index": 10, + "name": "showPreviousMonth", + "returnType": "void" + }, + { + "access": "public", + "index": 11, + "name": "showNextYear", + "returnType": "void" + }, + { + "access": "public", + "index": 12, + "name": "showPreviousYear", + "returnType": "void" + }, + { + "access": "public", + "index": 13, + "name": "showSelectedDate", + "returnType": "void" + }, + { + "access": "public", + "index": 14, + "name": "showToday", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "date", + "type": "QDate" + } + ], + "index": 15, + "name": "_q_slotShowDate", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "date", + "type": "QDate" + } + ], + "index": 16, + "name": "_q_slotChangeDate", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "date", + "type": "QDate" + }, + { + "name": "changeMonth", + "type": "bool" + } + ], + "index": 17, + "name": "_q_slotChangeDate", + "returnType": "void" + }, + { + "access": "private", + "index": 18, + "name": "_q_editingFinished", + "returnType": "void" + }, + { + "access": "private", + "index": 19, + "name": "_q_prevMonthClicked", + "returnType": "void" + }, + { + "access": "private", + "index": 20, + "name": "_q_nextMonthClicked", + "returnType": "void" + }, + { + "access": "private", + "index": 21, + "name": "_q_yearEditingFinished", + "returnType": "void" + }, + { + "access": "private", + "index": 22, + "name": "_q_yearClicked", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "act", + "type": "QAction*" + } + ], + "index": 23, + "name": "_q_monthChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + } + ], + "inputFile": "qcalendarwidget.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QCheckBox", + "lineNumber": 18, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "tristate", + "read": "isTristate", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setTristate" + } + ], + "qualifiedClassName": "QCheckBox", + "signals": [ + { + "access": "public", + "arguments": [ + { + "type": "int" + } + ], + "index": 0, + "name": "stateChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "Qt::CheckState" + } + ], + "index": 1, + "name": "checkStateChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QAbstractButton" + } + ] + } + ], + "inputFile": "qcheckbox.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QColorDialog", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "ColorDialogOption", + "values": [ + "ShowAlphaChannel", + "NoButtons", + "DontUseNativeDialog", + "NoEyeDropperButton" + ] + } + ], + "lineNumber": 17, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "currentColor", + "notify": "currentColorChanged", + "read": "currentColor", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false, + "write": "setCurrentColor" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "options", + "read": "options", + "required": false, + "scriptable": true, + "stored": true, + "type": "ColorDialogOptions", + "user": false, + "write": "setOptions" + } + ], + "qualifiedClassName": "QColorDialog", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "color", + "type": "QColor" + } + ], + "index": 0, + "name": "currentColorChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "color", + "type": "QColor" + } + ], + "index": 1, + "name": "colorSelected", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QDialog" + } + ] + } + ], + "inputFile": "qcolordialog.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QColumnView", + "lineNumber": 16, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "resizeGripsVisible", + "read": "resizeGripsVisible", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setResizeGripsVisible" + } + ], + "qualifiedClassName": "QColumnView", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "QModelIndex" + } + ], + "index": 0, + "name": "updatePreviewWidget", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QAbstractItemView" + } + ] + } + ], + "inputFile": "qcolumnview.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QColumnViewGrip", + "lineNumber": 27, + "object": true, + "qualifiedClassName": "QColumnViewGrip", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "offset", + "type": "int" + } + ], + "index": 0, + "name": "gripMoved", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + } + ], + "inputFile": "qcolumnviewgrip_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QComboBox", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "InsertPolicy", + "values": [ + "NoInsert", + "InsertAtTop", + "InsertAtCurrent", + "InsertAtBottom", + "InsertAfterCurrent", + "InsertBeforeCurrent", + "InsertAlphabetically" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "SizeAdjustPolicy", + "values": [ + "AdjustToContents", + "AdjustToContentsOnFirstShow", + "AdjustToMinimumContentsLengthWithIcon" + ] + } + ], + "lineNumber": 23, + "methods": [ + { + "access": "public", + "arguments": [ + { + "name": "query", + "type": "Qt::InputMethodQuery" + }, + { + "name": "argument", + "type": "QVariant" + } + ], + "index": 12, + "name": "inputMethodQuery", + "returnType": "QVariant" + } + ], + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "editable", + "read": "isEditable", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setEditable" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "count", + "read": "count", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "currentText", + "notify": "currentTextChanged", + "read": "currentText", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": true, + "write": "setCurrentText" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "currentIndex", + "notify": "currentIndexChanged", + "read": "currentIndex", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setCurrentIndex" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "currentData", + "read": "currentData", + "required": false, + "scriptable": true, + "stored": true, + "type": "QVariant", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "maxVisibleItems", + "read": "maxVisibleItems", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setMaxVisibleItems" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "maxCount", + "read": "maxCount", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setMaxCount" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 7, + "name": "insertPolicy", + "read": "insertPolicy", + "required": false, + "scriptable": true, + "stored": true, + "type": "InsertPolicy", + "user": false, + "write": "setInsertPolicy" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 8, + "name": "sizeAdjustPolicy", + "read": "sizeAdjustPolicy", + "required": false, + "scriptable": true, + "stored": true, + "type": "SizeAdjustPolicy", + "user": false, + "write": "setSizeAdjustPolicy" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 9, + "name": "minimumContentsLength", + "read": "minimumContentsLength", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setMinimumContentsLength" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 10, + "name": "iconSize", + "read": "iconSize", + "required": false, + "scriptable": true, + "stored": true, + "type": "QSize", + "user": false, + "write": "setIconSize" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 11, + "name": "placeholderText", + "read": "placeholderText", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setPlaceholderText" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 12, + "name": "duplicatesEnabled", + "read": "duplicatesEnabled", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setDuplicatesEnabled" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 13, + "name": "frame", + "read": "hasFrame", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setFrame" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 14, + "name": "modelColumn", + "read": "modelColumn", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setModelColumn" + } + ], + "qualifiedClassName": "QComboBox", + "signals": [ + { + "access": "public", + "arguments": [ + { + "type": "QString" + } + ], + "index": 0, + "name": "editTextChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + } + ], + "index": 1, + "name": "activated", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QString" + } + ], + "index": 2, + "name": "textActivated", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + } + ], + "index": 3, + "name": "highlighted", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QString" + } + ], + "index": 4, + "name": "textHighlighted", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + } + ], + "index": 5, + "name": "currentIndexChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QString" + } + ], + "index": 6, + "name": "currentTextChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "index": 7, + "name": "clear", + "returnType": "void" + }, + { + "access": "public", + "index": 8, + "name": "clearEditText", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "text", + "type": "QString" + } + ], + "index": 9, + "name": "setEditText", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + } + ], + "index": 10, + "name": "setCurrentIndex", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "text", + "type": "QString" + } + ], + "index": 11, + "name": "setCurrentText", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + } + ], + "inputFile": "qcombobox.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QComboBoxListView", + "lineNumber": 47, + "object": true, + "qualifiedClassName": "QComboBoxListView", + "superClasses": [ + { + "access": "public", + "name": "QListView" + } + ] + }, + { + "className": "QComboBoxPrivateScroller", + "lineNumber": 99, + "object": true, + "qualifiedClassName": "QComboBoxPrivateScroller", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "action", + "type": "int" + } + ], + "index": 0, + "name": "doScroll", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + }, + { + "className": "QComboBoxPrivateContainer", + "lineNumber": 180, + "object": true, + "qualifiedClassName": "QComboBoxPrivateContainer", + "signals": [ + { + "access": "public", + "arguments": [ + { + "type": "QModelIndex" + } + ], + "index": 0, + "name": "itemSelected", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "resetButton", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "action", + "type": "int" + } + ], + "index": 2, + "name": "scrollItemView", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "hideScrollers", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "updateScrollers", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "viewDestroyed", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QFrame" + } + ] + }, + { + "className": "QComboMenuDelegate", + "lineNumber": 233, + "object": true, + "qualifiedClassName": "QComboMenuDelegate", + "superClasses": [ + { + "access": "public", + "name": "QAbstractItemDelegate" + } + ] + }, + { + "className": "QComboBoxDelegate", + "lineNumber": 265, + "object": true, + "qualifiedClassName": "QComboBoxDelegate", + "superClasses": [ + { + "access": "public", + "name": "QStyledItemDelegate" + } + ] + } + ], + "inputFile": "qcombobox_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QCommandLinkButton", + "lineNumber": 17, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "description", + "read": "description", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setDescription" + }, + { + "constant": false, + "designable": false, + "final": false, + "index": 1, + "name": "flat", + "read": "isFlat", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setFlat" + } + ], + "qualifiedClassName": "QCommandLinkButton", + "superClasses": [ + { + "access": "public", + "name": "QPushButton" + } + ] + } + ], + "inputFile": "qcommandlinkbutton.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QCommonStyle", + "lineNumber": 14, + "object": true, + "qualifiedClassName": "QCommonStyle", + "superClasses": [ + { + "access": "public", + "name": "QStyle" + } + ] + } + ], + "inputFile": "qcommonstyle.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QCompleter", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "CompletionMode", + "values": [ + "PopupCompletion", + "UnfilteredPopupCompletion", + "InlineCompletion" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "ModelSorting", + "values": [ + "UnsortedModel", + "CaseSensitivelySortedModel", + "CaseInsensitivelySortedModel" + ] + } + ], + "lineNumber": 23, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "completionPrefix", + "read": "completionPrefix", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setCompletionPrefix" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "modelSorting", + "read": "modelSorting", + "required": false, + "scriptable": true, + "stored": true, + "type": "ModelSorting", + "user": false, + "write": "setModelSorting" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "filterMode", + "read": "filterMode", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::MatchFlags", + "user": false, + "write": "setFilterMode" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "completionMode", + "read": "completionMode", + "required": false, + "scriptable": true, + "stored": true, + "type": "CompletionMode", + "user": false, + "write": "setCompletionMode" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "completionColumn", + "read": "completionColumn", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setCompletionColumn" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "completionRole", + "read": "completionRole", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setCompletionRole" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "maxVisibleItems", + "read": "maxVisibleItems", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setMaxVisibleItems" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 7, + "name": "caseSensitivity", + "read": "caseSensitivity", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::CaseSensitivity", + "user": false, + "write": "setCaseSensitivity" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 8, + "name": "wrapAround", + "read": "wrapAround", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setWrapAround" + } + ], + "qualifiedClassName": "QCompleter", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "text", + "type": "QString" + } + ], + "index": 0, + "name": "activated", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "QModelIndex" + } + ], + "index": 1, + "name": "activated", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "text", + "type": "QString" + } + ], + "index": 2, + "name": "highlighted", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "QModelIndex" + } + ], + "index": 3, + "name": "highlighted", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "prefix", + "type": "QString" + } + ], + "index": 4, + "name": "setCompletionPrefix", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "rect", + "type": "QRect" + } + ], + "index": 5, + "name": "complete", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "isCloned": true, + "name": "complete", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "wrap", + "type": "bool" + } + ], + "index": 7, + "name": "setWrapAround", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "type": "QModelIndex" + } + ], + "index": 8, + "name": "_q_complete", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "type": "QItemSelection" + } + ], + "index": 9, + "name": "_q_completionSelected", + "returnType": "void" + }, + { + "access": "private", + "index": 10, + "name": "_q_autoResizePopup", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "type": "QString" + } + ], + "index": 11, + "name": "_q_fileSystemModelDirectoryLoaded", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qcompleter.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QCompletionModel", + "lineNumber": 183, + "object": true, + "qualifiedClassName": "QCompletionModel", + "signals": [ + { + "access": "public", + "index": 0, + "name": "rowsAdded", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "index": 1, + "name": "invalidate", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "rowsInserted", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "modelDestroyed", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QAbstractProxyModel" + } + ] + } + ], + "inputFile": "qcompleter_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QDataWidgetMapper", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "SubmitPolicy", + "values": [ + "AutoSubmit", + "ManualSubmit" + ] + } + ], + "lineNumber": 19, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "currentIndex", + "notify": "currentIndexChanged", + "read": "currentIndex", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setCurrentIndex" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "orientation", + "read": "orientation", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::Orientation", + "user": false, + "write": "setOrientation" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "submitPolicy", + "read": "submitPolicy", + "required": false, + "scriptable": true, + "stored": true, + "type": "SubmitPolicy", + "user": false, + "write": "setSubmitPolicy" + } + ], + "qualifiedClassName": "QDataWidgetMapper", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + } + ], + "index": 0, + "name": "currentIndexChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "index": 1, + "name": "revert", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "submit", + "returnType": "bool" + }, + { + "access": "public", + "index": 3, + "name": "toFirst", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "toLast", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "toNext", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "toPrevious", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + } + ], + "index": 7, + "name": "setCurrentIndex", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "QModelIndex" + } + ], + "index": 8, + "name": "setCurrentModelIndex", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qdatawidgetmapper.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QDateTimeEdit", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "Section", + "values": [ + "NoSection", + "AmPmSection", + "MSecSection", + "SecondSection", + "MinuteSection", + "HourSection", + "DaySection", + "MonthSection", + "YearSection", + "TimeSections_Mask", + "DateSections_Mask" + ] + }, + { + "alias": "Section", + "isClass": false, + "isFlag": true, + "name": "Sections", + "values": [ + "NoSection", + "AmPmSection", + "MSecSection", + "SecondSection", + "MinuteSection", + "HourSection", + "DaySection", + "MonthSection", + "YearSection", + "TimeSections_Mask", + "DateSections_Mask" + ] + } + ], + "lineNumber": 21, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "dateTime", + "notify": "dateTimeChanged", + "read": "dateTime", + "required": false, + "scriptable": true, + "stored": true, + "type": "QDateTime", + "user": true, + "write": "setDateTime" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "date", + "notify": "dateChanged", + "read": "date", + "required": false, + "scriptable": true, + "stored": true, + "type": "QDate", + "user": false, + "write": "setDate" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "time", + "notify": "timeChanged", + "read": "time", + "required": false, + "scriptable": true, + "stored": true, + "type": "QTime", + "user": false, + "write": "setTime" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "maximumDateTime", + "read": "maximumDateTime", + "required": false, + "reset": "clearMaximumDateTime", + "scriptable": true, + "stored": true, + "type": "QDateTime", + "user": false, + "write": "setMaximumDateTime" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "minimumDateTime", + "read": "minimumDateTime", + "required": false, + "reset": "clearMinimumDateTime", + "scriptable": true, + "stored": true, + "type": "QDateTime", + "user": false, + "write": "setMinimumDateTime" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "maximumDate", + "read": "maximumDate", + "required": false, + "reset": "clearMaximumDate", + "scriptable": true, + "stored": true, + "type": "QDate", + "user": false, + "write": "setMaximumDate" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "minimumDate", + "read": "minimumDate", + "required": false, + "reset": "clearMinimumDate", + "scriptable": true, + "stored": true, + "type": "QDate", + "user": false, + "write": "setMinimumDate" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 7, + "name": "maximumTime", + "read": "maximumTime", + "required": false, + "reset": "clearMaximumTime", + "scriptable": true, + "stored": true, + "type": "QTime", + "user": false, + "write": "setMaximumTime" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 8, + "name": "minimumTime", + "read": "minimumTime", + "required": false, + "reset": "clearMinimumTime", + "scriptable": true, + "stored": true, + "type": "QTime", + "user": false, + "write": "setMinimumTime" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 9, + "name": "currentSection", + "read": "currentSection", + "required": false, + "scriptable": true, + "stored": true, + "type": "Section", + "user": false, + "write": "setCurrentSection" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 10, + "name": "displayedSections", + "read": "displayedSections", + "required": false, + "scriptable": true, + "stored": true, + "type": "Sections", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 11, + "name": "displayFormat", + "read": "displayFormat", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setDisplayFormat" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 12, + "name": "calendarPopup", + "read": "calendarPopup", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setCalendarPopup" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 13, + "name": "currentSectionIndex", + "read": "currentSectionIndex", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setCurrentSectionIndex" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 14, + "name": "sectionCount", + "read": "sectionCount", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 15, + "name": "timeSpec", + "read": "timeSpec", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::TimeSpec", + "user": false, + "write": "setTimeSpec" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 16, + "name": "timeZone", + "read": "timeZone", + "required": false, + "scriptable": true, + "stored": true, + "type": "QTimeZone", + "user": false, + "write": "setTimeZone" + } + ], + "qualifiedClassName": "QDateTimeEdit", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "dateTime", + "type": "QDateTime" + } + ], + "index": 0, + "name": "dateTimeChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "time", + "type": "QTime" + } + ], + "index": 1, + "name": "timeChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "date", + "type": "QDate" + } + ], + "index": 2, + "name": "dateChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "dateTime", + "type": "QDateTime" + } + ], + "index": 3, + "name": "setDateTime", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "date", + "type": "QDate" + } + ], + "index": 4, + "name": "setDate", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "time", + "type": "QTime" + } + ], + "index": 5, + "name": "setTime", + "returnType": "void" + }, + { + "access": "private", + "index": 6, + "name": "_q_resetButton", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QAbstractSpinBox" + } + ] + }, + { + "className": "QTimeEdit", + "lineNumber": 181, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "time", + "notify": "userTimeChanged", + "read": "time", + "required": false, + "scriptable": true, + "stored": true, + "type": "QTime", + "user": true, + "write": "setTime" + } + ], + "qualifiedClassName": "QTimeEdit", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "time", + "type": "QTime" + } + ], + "index": 0, + "name": "userTimeChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QDateTimeEdit" + } + ] + }, + { + "className": "QDateEdit", + "lineNumber": 194, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "date", + "notify": "userDateChanged", + "read": "date", + "required": false, + "scriptable": true, + "stored": true, + "type": "QDate", + "user": true, + "write": "setDate" + } + ], + "qualifiedClassName": "QDateEdit", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "date", + "type": "QDate" + } + ], + "index": 0, + "name": "userDateChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QDateTimeEdit" + } + ] + } + ], + "inputFile": "qdatetimeedit.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QCalendarPopup", + "lineNumber": 114, + "object": true, + "qualifiedClassName": "QCalendarPopup", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "date", + "type": "QDate" + } + ], + "index": 0, + "name": "activated", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "newDate", + "type": "QDate" + } + ], + "index": 1, + "name": "newDateSelected", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "oldDate", + "type": "QDate" + } + ], + "index": 2, + "name": "hidingCalendar", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "resetButton", + "returnType": "void" + } + ], + "slots": [ + { + "access": "private", + "arguments": [ + { + "name": "date", + "type": "QDate" + } + ], + "index": 4, + "name": "dateSelected", + "returnType": "void" + }, + { + "access": "private", + "index": 5, + "name": "dateSelectionChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + } + ], + "inputFile": "qdatetimeedit_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QDial", + "lineNumber": 19, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "wrapping", + "read": "wrapping", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setWrapping" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "notchSize", + "read": "notchSize", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "notchTarget", + "read": "notchTarget", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setNotchTarget" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "notchesVisible", + "read": "notchesVisible", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setNotchesVisible" + } + ], + "qualifiedClassName": "QDial", + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "visible", + "type": "bool" + } + ], + "index": 0, + "name": "setNotchesVisible", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "on", + "type": "bool" + } + ], + "index": 1, + "name": "setWrapping", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QAbstractSlider" + } + ] + } + ], + "inputFile": "qdial.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QDialog", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "DialogCode", + "values": [ + "Rejected", + "Accepted" + ] + } + ], + "lineNumber": 18, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "sizeGripEnabled", + "read": "isSizeGripEnabled", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setSizeGripEnabled" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "modal", + "read": "isModal", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setModal" + } + ], + "qualifiedClassName": "QDialog", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "result", + "type": "int" + } + ], + "index": 0, + "name": "finished", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "accepted", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "rejected", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "index": 3, + "name": "open", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "exec", + "returnType": "int" + }, + { + "access": "public", + "arguments": [ + { + "type": "int" + } + ], + "index": 5, + "name": "done", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "accept", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "reject", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + } + ], + "inputFile": "qdialog.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QDialogButtonBox", + "enums": [ + { + "alias": "StandardButton", + "isClass": false, + "isFlag": true, + "name": "StandardButtons", + "values": [ + "NoButton", + "Ok", + "Save", + "SaveAll", + "Open", + "Yes", + "YesToAll", + "No", + "NoToAll", + "Abort", + "Retry", + "Ignore", + "Close", + "Cancel", + "Discard", + "Help", + "Apply", + "Reset", + "RestoreDefaults" + ] + } + ], + "lineNumber": 19, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "orientation", + "read": "orientation", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::Orientation", + "user": false, + "write": "setOrientation" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "standardButtons", + "read": "standardButtons", + "required": false, + "scriptable": true, + "stored": true, + "type": "StandardButtons", + "user": false, + "write": "setStandardButtons" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "centerButtons", + "read": "centerButtons", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setCenterButtons" + } + ], + "qualifiedClassName": "QDialogButtonBox", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "button", + "type": "QAbstractButton*" + } + ], + "index": 0, + "name": "clicked", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "accepted", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "helpRequested", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "rejected", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + } + ], + "inputFile": "qdialogbuttonbox.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QDockWidget", + "enums": [ + { + "alias": "DockWidgetFeature", + "isClass": false, + "isFlag": true, + "name": "DockWidgetFeatures", + "values": [ + "DockWidgetClosable", + "DockWidgetMovable", + "DockWidgetFloatable", + "DockWidgetVerticalTitleBar", + "DockWidgetFeatureMask", + "NoDockWidgetFeatures", + "Reserved" + ] + } + ], + "lineNumber": 19, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "floating", + "notify": "topLevelChanged", + "read": "isFloating", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setFloating" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "features", + "notify": "featuresChanged", + "read": "features", + "required": false, + "scriptable": true, + "stored": true, + "type": "DockWidgetFeatures", + "user": false, + "write": "setFeatures" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "allowedAreas", + "notify": "allowedAreasChanged", + "read": "allowedAreas", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::DockWidgetAreas", + "user": false, + "write": "setAllowedAreas" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "windowTitle", + "read": "windowTitle", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setWindowTitle" + } + ], + "qualifiedClassName": "QDockWidget", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "features", + "type": "QDockWidget::DockWidgetFeatures" + } + ], + "index": 0, + "name": "featuresChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "topLevel", + "type": "bool" + } + ], + "index": 1, + "name": "topLevelChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "allowedAreas", + "type": "Qt::DockWidgetAreas" + } + ], + "index": 2, + "name": "allowedAreasChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "visible", + "type": "bool" + } + ], + "index": 3, + "name": "visibilityChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "area", + "type": "Qt::DockWidgetArea" + } + ], + "index": 4, + "name": "dockLocationChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + } + ], + "inputFile": "qdockwidget.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QDockWidgetLayout", + "lineNumber": 116, + "object": true, + "qualifiedClassName": "QDockWidgetLayout", + "superClasses": [ + { + "access": "public", + "name": "QLayout" + } + ] + } + ], + "inputFile": "qdockwidget_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QErrorMessage", + "lineNumber": 17, + "object": true, + "qualifiedClassName": "QErrorMessage", + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "message", + "type": "QString" + } + ], + "index": 0, + "name": "showMessage", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "message", + "type": "QString" + }, + { + "name": "type", + "type": "QString" + } + ], + "index": 1, + "name": "showMessage", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QDialog" + } + ] + } + ], + "inputFile": "qerrormessage.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QFileDialog", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "ViewMode", + "values": [ + "Detail", + "List" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "FileMode", + "values": [ + "AnyFile", + "ExistingFile", + "Directory", + "ExistingFiles" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "AcceptMode", + "values": [ + "AcceptOpen", + "AcceptSave" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "Option", + "values": [ + "ShowDirsOnly", + "DontResolveSymlinks", + "DontConfirmOverwrite", + "DontUseNativeDialog", + "ReadOnly", + "HideNameFilterDetails", + "DontUseCustomDirectoryIcons" + ] + }, + { + "alias": "Option", + "isClass": false, + "isFlag": true, + "name": "Options", + "values": [ + "ShowDirsOnly", + "DontResolveSymlinks", + "DontConfirmOverwrite", + "DontUseNativeDialog", + "ReadOnly", + "HideNameFilterDetails", + "DontUseCustomDirectoryIcons" + ] + } + ], + "lineNumber": 27, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "viewMode", + "read": "viewMode", + "required": false, + "scriptable": true, + "stored": true, + "type": "ViewMode", + "user": false, + "write": "setViewMode" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "fileMode", + "read": "fileMode", + "required": false, + "scriptable": true, + "stored": true, + "type": "FileMode", + "user": false, + "write": "setFileMode" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "acceptMode", + "read": "acceptMode", + "required": false, + "scriptable": true, + "stored": true, + "type": "AcceptMode", + "user": false, + "write": "setAcceptMode" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "defaultSuffix", + "read": "defaultSuffix", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setDefaultSuffix" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "options", + "read": "options", + "required": false, + "scriptable": true, + "stored": true, + "type": "Options", + "user": false, + "write": "setOptions" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "supportedSchemes", + "read": "supportedSchemes", + "required": false, + "scriptable": true, + "stored": true, + "type": "QStringList", + "user": false, + "write": "setSupportedSchemes" + } + ], + "qualifiedClassName": "QFileDialog", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "file", + "type": "QString" + } + ], + "index": 0, + "name": "fileSelected", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "files", + "type": "QStringList" + } + ], + "index": 1, + "name": "filesSelected", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "path", + "type": "QString" + } + ], + "index": 2, + "name": "currentChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "directory", + "type": "QString" + } + ], + "index": 3, + "name": "directoryEntered", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "url", + "type": "QUrl" + } + ], + "index": 4, + "name": "urlSelected", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "urls", + "type": "QList" + } + ], + "index": 5, + "name": "urlsSelected", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "url", + "type": "QUrl" + } + ], + "index": 6, + "name": "currentUrlChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "directory", + "type": "QUrl" + } + ], + "index": 7, + "name": "directoryUrlEntered", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "filter", + "type": "QString" + } + ], + "index": 8, + "name": "filterSelected", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QDialog" + } + ] + } + ], + "inputFile": "qfiledialog.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QFlickGesture", + "lineNumber": 34, + "object": true, + "qualifiedClassName": "QFlickGesture", + "superClasses": [ + { + "access": "public", + "name": "QGesture" + } + ] + } + ], + "inputFile": "qflickgesture_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QFocusFrame", + "lineNumber": 16, + "object": true, + "qualifiedClassName": "QFocusFrame", + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + } + ], + "inputFile": "qfocusframe.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QFontComboBox", + "enums": [ + { + "alias": "FontFilter", + "isClass": false, + "isFlag": true, + "name": "FontFilters", + "values": [ + "AllFonts", + "ScalableFonts", + "NonScalableFonts", + "MonospacedFonts", + "ProportionalFonts" + ] + } + ], + "lineNumber": 17, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "writingSystem", + "read": "writingSystem", + "required": false, + "scriptable": true, + "stored": true, + "type": "QFontDatabase::WritingSystem", + "user": false, + "write": "setWritingSystem" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "fontFilters", + "read": "fontFilters", + "required": false, + "scriptable": true, + "stored": true, + "type": "FontFilters", + "user": false, + "write": "setFontFilters" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "currentFont", + "notify": "currentFontChanged", + "read": "currentFont", + "required": false, + "scriptable": true, + "stored": true, + "type": "QFont", + "user": false, + "write": "setCurrentFont" + } + ], + "qualifiedClassName": "QFontComboBox", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "f", + "type": "QFont" + } + ], + "index": 0, + "name": "currentFontChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "f", + "type": "QFont" + } + ], + "index": 1, + "name": "setCurrentFont", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QComboBox" + } + ] + } + ], + "inputFile": "qfontcombobox.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QFontDialog", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "FontDialogOption", + "values": [ + "NoButtons", + "DontUseNativeDialog", + "ScalableFonts", + "NonScalableFonts", + "MonospacedFonts", + "ProportionalFonts" + ] + } + ], + "lineNumber": 19, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "currentFont", + "notify": "currentFontChanged", + "read": "currentFont", + "required": false, + "scriptable": true, + "stored": true, + "type": "QFont", + "user": false, + "write": "setCurrentFont" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "options", + "read": "options", + "required": false, + "scriptable": true, + "stored": true, + "type": "FontDialogOptions", + "user": false, + "write": "setOptions" + } + ], + "qualifiedClassName": "QFontDialog", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "font", + "type": "QFont" + } + ], + "index": 0, + "name": "currentFontChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "font", + "type": "QFont" + } + ], + "index": 1, + "name": "fontSelected", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QDialog" + } + ] + } + ], + "inputFile": "qfontdialog.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QFormLayout", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "FieldGrowthPolicy", + "values": [ + "FieldsStayAtSizeHint", + "ExpandingFieldsGrow", + "AllNonFixedFieldsGrow" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "RowWrapPolicy", + "values": [ + "DontWrapRows", + "WrapLongRows", + "WrapAllRows" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "ItemRole", + "values": [ + "LabelRole", + "FieldRole", + "SpanningRole" + ] + } + ], + "lineNumber": 17, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "fieldGrowthPolicy", + "read": "fieldGrowthPolicy", + "required": false, + "reset": "resetFieldGrowthPolicy", + "scriptable": true, + "stored": true, + "type": "FieldGrowthPolicy", + "user": false, + "write": "setFieldGrowthPolicy" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "rowWrapPolicy", + "read": "rowWrapPolicy", + "required": false, + "reset": "resetRowWrapPolicy", + "scriptable": true, + "stored": true, + "type": "RowWrapPolicy", + "user": false, + "write": "setRowWrapPolicy" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "labelAlignment", + "read": "labelAlignment", + "required": false, + "reset": "resetLabelAlignment", + "scriptable": true, + "stored": true, + "type": "Qt::Alignment", + "user": false, + "write": "setLabelAlignment" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "formAlignment", + "read": "formAlignment", + "required": false, + "reset": "resetFormAlignment", + "scriptable": true, + "stored": true, + "type": "Qt::Alignment", + "user": false, + "write": "setFormAlignment" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "horizontalSpacing", + "read": "horizontalSpacing", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setHorizontalSpacing" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "verticalSpacing", + "read": "verticalSpacing", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setVerticalSpacing" + } + ], + "qualifiedClassName": "QFormLayout", + "superClasses": [ + { + "access": "public", + "name": "QLayout" + } + ] + } + ], + "inputFile": "qformlayout.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QFrame", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "Shape", + "values": [ + "NoFrame", + "Box", + "Panel", + "WinPanel", + "HLine", + "VLine", + "StyledPanel" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "Shadow", + "values": [ + "Plain", + "Raised", + "Sunken" + ] + } + ], + "lineNumber": 16, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "frameShape", + "read": "frameShape", + "required": false, + "scriptable": true, + "stored": true, + "type": "Shape", + "user": false, + "write": "setFrameShape" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "frameShadow", + "read": "frameShadow", + "required": false, + "scriptable": true, + "stored": true, + "type": "Shadow", + "user": false, + "write": "setFrameShadow" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "lineWidth", + "read": "lineWidth", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setLineWidth" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "midLineWidth", + "read": "midLineWidth", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setMidLineWidth" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "frameWidth", + "read": "frameWidth", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": false, + "final": false, + "index": 5, + "name": "frameRect", + "read": "frameRect", + "required": false, + "scriptable": true, + "stored": true, + "type": "QRect", + "user": false, + "write": "setFrameRect" + } + ], + "qualifiedClassName": "QFrame", + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + } + ], + "inputFile": "qframe.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QFusionStyle", + "lineNumber": 27, + "object": true, + "qualifiedClassName": "QFusionStyle", + "superClasses": [ + { + "access": "public", + "name": "QCommonStyle" + } + ] + } + ], + "inputFile": "qfusionstyle_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QGesture", + "lineNumber": 28, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "state", + "read": "state", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::GestureState", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "gestureType", + "read": "gestureType", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::GestureType", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "gestureCancelPolicy", + "read": "gestureCancelPolicy", + "required": false, + "scriptable": true, + "stored": true, + "type": "QGesture::GestureCancelPolicy", + "user": false, + "write": "setGestureCancelPolicy" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "hotSpot", + "read": "hotSpot", + "required": false, + "reset": "unsetHotSpot", + "scriptable": true, + "stored": true, + "type": "QPointF", + "user": false, + "write": "setHotSpot" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "hasHotSpot", + "read": "hasHotSpot", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + } + ], + "qualifiedClassName": "QGesture", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "className": "QPanGesture", + "lineNumber": 72, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "lastOffset", + "read": "lastOffset", + "required": false, + "scriptable": true, + "stored": true, + "type": "QPointF", + "user": false, + "write": "setLastOffset" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "offset", + "read": "offset", + "required": false, + "scriptable": true, + "stored": true, + "type": "QPointF", + "user": false, + "write": "setOffset" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "delta", + "read": "delta", + "required": false, + "scriptable": true, + "stored": false, + "type": "QPointF", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "acceleration", + "read": "acceleration", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setAcceleration" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "horizontalVelocity", + "privateClass": "QPanGesture::d_func()", + "read": "horizontalVelocity", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setHorizontalVelocity" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "verticalVelocity", + "privateClass": "QPanGesture::d_func()", + "read": "verticalVelocity", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setVerticalVelocity" + } + ], + "qualifiedClassName": "QPanGesture", + "superClasses": [ + { + "access": "public", + "name": "QGesture" + } + ] + }, + { + "className": "QPinchGesture", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "ChangeFlag", + "values": [ + "ScaleFactorChanged", + "RotationAngleChanged", + "CenterPointChanged" + ] + }, + { + "alias": "ChangeFlag", + "isClass": false, + "isFlag": true, + "name": "ChangeFlags", + "values": [ + "ScaleFactorChanged", + "RotationAngleChanged", + "CenterPointChanged" + ] + } + ], + "lineNumber": 102, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "totalChangeFlags", + "read": "totalChangeFlags", + "required": false, + "scriptable": true, + "stored": true, + "type": "ChangeFlags", + "user": false, + "write": "setTotalChangeFlags" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "changeFlags", + "read": "changeFlags", + "required": false, + "scriptable": true, + "stored": true, + "type": "ChangeFlags", + "user": false, + "write": "setChangeFlags" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "totalScaleFactor", + "read": "totalScaleFactor", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setTotalScaleFactor" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "lastScaleFactor", + "read": "lastScaleFactor", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setLastScaleFactor" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "scaleFactor", + "read": "scaleFactor", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setScaleFactor" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "totalRotationAngle", + "read": "totalRotationAngle", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setTotalRotationAngle" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "lastRotationAngle", + "read": "lastRotationAngle", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setLastRotationAngle" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 7, + "name": "rotationAngle", + "read": "rotationAngle", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setRotationAngle" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 8, + "name": "startCenterPoint", + "read": "startCenterPoint", + "required": false, + "scriptable": true, + "stored": true, + "type": "QPointF", + "user": false, + "write": "setStartCenterPoint" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 9, + "name": "lastCenterPoint", + "read": "lastCenterPoint", + "required": false, + "scriptable": true, + "stored": true, + "type": "QPointF", + "user": false, + "write": "setLastCenterPoint" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 10, + "name": "centerPoint", + "read": "centerPoint", + "required": false, + "scriptable": true, + "stored": true, + "type": "QPointF", + "user": false, + "write": "setCenterPoint" + } + ], + "qualifiedClassName": "QPinchGesture", + "superClasses": [ + { + "access": "public", + "name": "QGesture" + } + ] + }, + { + "className": "QSwipeGesture", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "SwipeDirection", + "values": [ + "NoDirection", + "Left", + "Right", + "Up", + "Down" + ] + } + ], + "lineNumber": 176, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "horizontalDirection", + "read": "horizontalDirection", + "required": false, + "scriptable": true, + "stored": false, + "type": "SwipeDirection", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "verticalDirection", + "read": "verticalDirection", + "required": false, + "scriptable": true, + "stored": false, + "type": "SwipeDirection", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "swipeAngle", + "read": "swipeAngle", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setSwipeAngle" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "velocity", + "privateClass": "QSwipeGesture::d_func()", + "read": "velocity", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setVelocity" + } + ], + "qualifiedClassName": "QSwipeGesture", + "superClasses": [ + { + "access": "public", + "name": "QGesture" + } + ] + }, + { + "className": "QTapGesture", + "lineNumber": 203, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "position", + "read": "position", + "required": false, + "scriptable": true, + "stored": true, + "type": "QPointF", + "user": false, + "write": "setPosition" + } + ], + "qualifiedClassName": "QTapGesture", + "superClasses": [ + { + "access": "public", + "name": "QGesture" + } + ] + }, + { + "className": "QTapAndHoldGesture", + "lineNumber": 221, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "position", + "read": "position", + "required": false, + "scriptable": true, + "stored": true, + "type": "QPointF", + "user": false, + "write": "setPosition" + } + ], + "qualifiedClassName": "QTapAndHoldGesture", + "superClasses": [ + { + "access": "public", + "name": "QGesture" + } + ] + } + ], + "inputFile": "qgesture.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QGestureManager", + "lineNumber": 34, + "object": true, + "qualifiedClassName": "QGestureManager", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qgesturemanager_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QGraphicsAnchor", + "lineNumber": 19, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "spacing", + "read": "spacing", + "required": false, + "reset": "unsetSpacing", + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setSpacing" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "sizePolicy", + "read": "sizePolicy", + "required": false, + "scriptable": true, + "stored": true, + "type": "QSizePolicy::Policy", + "user": false, + "write": "setSizePolicy" + } + ], + "qualifiedClassName": "QGraphicsAnchor", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qgraphicsanchorlayout.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QGraphicsEffect", + "enums": [ + { + "alias": "ChangeFlag", + "isClass": false, + "isFlag": true, + "name": "ChangeFlags", + "values": [ + "SourceAttached", + "SourceDetached", + "SourceBoundingRectChanged", + "SourceInvalidated" + ] + } + ], + "lineNumber": 26, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "enabled", + "notify": "enabledChanged", + "read": "isEnabled", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setEnabled" + } + ], + "qualifiedClassName": "QGraphicsEffect", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "enabled", + "type": "bool" + } + ], + "index": 0, + "name": "enabledChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "enable", + "type": "bool" + } + ], + "index": 1, + "name": "setEnabled", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "update", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "className": "QGraphicsColorizeEffect", + "lineNumber": 90, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "color", + "notify": "colorChanged", + "read": "color", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false, + "write": "setColor" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "strength", + "notify": "strengthChanged", + "read": "strength", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setStrength" + } + ], + "qualifiedClassName": "QGraphicsColorizeEffect", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "color", + "type": "QColor" + } + ], + "index": 0, + "name": "colorChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "strength", + "type": "qreal" + } + ], + "index": 1, + "name": "strengthChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "c", + "type": "QColor" + } + ], + "index": 2, + "name": "setColor", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "strength", + "type": "qreal" + } + ], + "index": 3, + "name": "setStrength", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QGraphicsEffect" + } + ] + }, + { + "className": "QGraphicsBlurEffect", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "BlurHint", + "values": [ + "PerformanceHint", + "QualityHint", + "AnimationHint" + ] + }, + { + "alias": "BlurHint", + "isClass": false, + "isFlag": true, + "name": "BlurHints", + "values": [ + "PerformanceHint", + "QualityHint", + "AnimationHint" + ] + } + ], + "lineNumber": 119, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "blurRadius", + "notify": "blurRadiusChanged", + "read": "blurRadius", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setBlurRadius" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "blurHints", + "notify": "blurHintsChanged", + "read": "blurHints", + "required": false, + "scriptable": true, + "stored": true, + "type": "BlurHints", + "user": false, + "write": "setBlurHints" + } + ], + "qualifiedClassName": "QGraphicsBlurEffect", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "blurRadius", + "type": "qreal" + } + ], + "index": 0, + "name": "blurRadiusChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "hints", + "type": "BlurHints" + } + ], + "index": 1, + "name": "blurHintsChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "blurRadius", + "type": "qreal" + } + ], + "index": 2, + "name": "setBlurRadius", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "hints", + "type": "BlurHints" + } + ], + "index": 3, + "name": "setBlurHints", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QGraphicsEffect" + } + ] + }, + { + "className": "QGraphicsDropShadowEffect", + "lineNumber": 160, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "offset", + "notify": "offsetChanged", + "read": "offset", + "required": false, + "scriptable": true, + "stored": true, + "type": "QPointF", + "user": false, + "write": "setOffset" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "xOffset", + "notify": "offsetChanged", + "read": "xOffset", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setXOffset" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "yOffset", + "notify": "offsetChanged", + "read": "yOffset", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setYOffset" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "blurRadius", + "notify": "blurRadiusChanged", + "read": "blurRadius", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setBlurRadius" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "color", + "notify": "colorChanged", + "read": "color", + "required": false, + "scriptable": true, + "stored": true, + "type": "QColor", + "user": false, + "write": "setColor" + } + ], + "qualifiedClassName": "QGraphicsDropShadowEffect", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "offset", + "type": "QPointF" + } + ], + "index": 0, + "name": "offsetChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "blurRadius", + "type": "qreal" + } + ], + "index": 1, + "name": "blurRadiusChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "color", + "type": "QColor" + } + ], + "index": 2, + "name": "colorChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "ofs", + "type": "QPointF" + } + ], + "index": 3, + "name": "setOffset", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "dx", + "type": "qreal" + }, + { + "name": "dy", + "type": "qreal" + } + ], + "index": 4, + "name": "setOffset", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "d", + "type": "qreal" + } + ], + "index": 5, + "name": "setOffset", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "dx", + "type": "qreal" + } + ], + "index": 6, + "name": "setXOffset", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "dy", + "type": "qreal" + } + ], + "index": 7, + "name": "setYOffset", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "blurRadius", + "type": "qreal" + } + ], + "index": 8, + "name": "setBlurRadius", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "color", + "type": "QColor" + } + ], + "index": 9, + "name": "setColor", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QGraphicsEffect" + } + ] + }, + { + "className": "QGraphicsOpacityEffect", + "lineNumber": 216, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "opacity", + "notify": "opacityChanged", + "read": "opacity", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setOpacity" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "opacityMask", + "notify": "opacityMaskChanged", + "read": "opacityMask", + "required": false, + "scriptable": true, + "stored": true, + "type": "QBrush", + "user": false, + "write": "setOpacityMask" + } + ], + "qualifiedClassName": "QGraphicsOpacityEffect", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "opacity", + "type": "qreal" + } + ], + "index": 0, + "name": "opacityChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "mask", + "type": "QBrush" + } + ], + "index": 1, + "name": "opacityMaskChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "opacity", + "type": "qreal" + } + ], + "index": 2, + "name": "setOpacity", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "mask", + "type": "QBrush" + } + ], + "index": 3, + "name": "setOpacityMask", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QGraphicsEffect" + } + ] + } + ], + "inputFile": "qgraphicseffect.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QGraphicsEffectSource", + "lineNumber": 31, + "object": true, + "qualifiedClassName": "QGraphicsEffectSource", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qgraphicseffect_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QGraphicsObject", + "interfaces": [ + [ + { + "className": "QGraphicsItem", + "id": "\"org.qt-project.Qt.QGraphicsItem\"" + } + ] + ], + "lineNumber": 485, + "object": true, + "properties": [ + { + "constant": false, + "designable": false, + "final": false, + "index": 0, + "name": "parent", + "notify": "parentChanged", + "read": "parentObject", + "required": false, + "scriptable": true, + "stored": true, + "type": "QGraphicsObject*", + "user": false, + "write": "setParentItem" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 1, + "name": "opacity", + "notify": "opacityChanged", + "read": "opacity", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setOpacity" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "enabled", + "notify": "enabledChanged", + "read": "isEnabled", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setEnabled" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 3, + "name": "visible", + "notify": "visibleChanged", + "read": "isVisible", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setVisible" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 4, + "name": "pos", + "read": "pos", + "required": false, + "scriptable": true, + "stored": true, + "type": "QPointF", + "user": false, + "write": "setPos" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 5, + "name": "x", + "notify": "xChanged", + "read": "x", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setX" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 6, + "name": "y", + "notify": "yChanged", + "read": "y", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setY" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 7, + "name": "z", + "notify": "zChanged", + "read": "zValue", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setZValue" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 8, + "name": "rotation", + "notify": "rotationChanged", + "read": "rotation", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setRotation" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 9, + "name": "scale", + "notify": "scaleChanged", + "read": "scale", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setScale" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 10, + "name": "transformOriginPoint", + "read": "transformOriginPoint", + "required": false, + "scriptable": true, + "stored": true, + "type": "QPointF", + "user": false, + "write": "setTransformOriginPoint" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 11, + "name": "effect", + "read": "graphicsEffect", + "required": false, + "scriptable": true, + "stored": true, + "type": "QGraphicsEffect*", + "user": false, + "write": "setGraphicsEffect" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 12, + "name": "width", + "notify": "widthChanged", + "privateClass": "QGraphicsItem::d_func()", + "read": "width", + "required": false, + "reset": "resetWidth", + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setWidth" + }, + { + "constant": false, + "designable": true, + "final": true, + "index": 13, + "name": "height", + "notify": "heightChanged", + "privateClass": "QGraphicsItem::d_func()", + "read": "height", + "required": false, + "reset": "resetHeight", + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setHeight" + } + ], + "qualifiedClassName": "QGraphicsObject", + "signals": [ + { + "access": "public", + "index": 0, + "name": "parentChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "opacityChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "visibleChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "enabledChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "xChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "yChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "zChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "rotationChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 8, + "name": "scaleChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 9, + "name": "childrenChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 10, + "name": "widthChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 11, + "name": "heightChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "protected", + "index": 12, + "name": "updateMicroFocus", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QGraphicsItem" + } + ] + }, + { + "className": "QGraphicsTextItem", + "lineNumber": 818, + "object": true, + "qualifiedClassName": "QGraphicsTextItem", + "signals": [ + { + "access": "public", + "arguments": [ + { + "type": "QString" + } + ], + "index": 0, + "name": "linkActivated", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QString" + } + ], + "index": 1, + "name": "linkHovered", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QGraphicsObject" + } + ] + } + ], + "inputFile": "qgraphicsitem.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QGraphicsItemAnimation", + "lineNumber": 20, + "object": true, + "qualifiedClassName": "QGraphicsItemAnimation", + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "x", + "type": "qreal" + } + ], + "index": 0, + "name": "setStep", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qgraphicsitemanimation.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QGraphicsProxyWidget", + "lineNumber": 16, + "object": true, + "qualifiedClassName": "QGraphicsProxyWidget", + "slots": [ + { + "access": "protected", + "arguments": [ + { + "type": "const QWidget*" + } + ], + "index": 0, + "name": "newProxyWidget", + "returnType": "QGraphicsProxyWidget*" + }, + { + "access": "private", + "index": 1, + "name": "_q_removeWidgetSlot", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QGraphicsWidget" + } + ] + } + ], + "inputFile": "qgraphicsproxywidget.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QGraphicsScene", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "ItemIndexMethod", + "values": [ + "BspTreeIndex", + "NoIndex" + ] + } + ], + "lineNumber": 58, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "backgroundBrush", + "read": "backgroundBrush", + "required": false, + "scriptable": true, + "stored": true, + "type": "QBrush", + "user": false, + "write": "setBackgroundBrush" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "foregroundBrush", + "read": "foregroundBrush", + "required": false, + "scriptable": true, + "stored": true, + "type": "QBrush", + "user": false, + "write": "setForegroundBrush" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "itemIndexMethod", + "read": "itemIndexMethod", + "required": false, + "scriptable": true, + "stored": true, + "type": "ItemIndexMethod", + "user": false, + "write": "setItemIndexMethod" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "sceneRect", + "read": "sceneRect", + "required": false, + "scriptable": true, + "stored": true, + "type": "QRectF", + "user": false, + "write": "setSceneRect" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "bspTreeDepth", + "read": "bspTreeDepth", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setBspTreeDepth" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "palette", + "read": "palette", + "required": false, + "scriptable": true, + "stored": true, + "type": "QPalette", + "user": false, + "write": "setPalette" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "font", + "read": "font", + "required": false, + "scriptable": true, + "stored": true, + "type": "QFont", + "user": false, + "write": "setFont" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 7, + "name": "stickyFocus", + "read": "stickyFocus", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setStickyFocus" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 8, + "name": "minimumRenderSize", + "read": "minimumRenderSize", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setMinimumRenderSize" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 9, + "name": "focusOnTouch", + "read": "focusOnTouch", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setFocusOnTouch" + } + ], + "qualifiedClassName": "QGraphicsScene", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "region", + "type": "QList" + } + ], + "index": 0, + "name": "changed", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "rect", + "type": "QRectF" + } + ], + "index": 1, + "name": "sceneRectChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "selectionChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "newFocus", + "type": "QGraphicsItem*" + }, + { + "name": "oldFocus", + "type": "QGraphicsItem*" + }, + { + "name": "reason", + "type": "Qt::FocusReason" + } + ], + "index": 3, + "name": "focusItemChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "rect", + "type": "QRectF" + } + ], + "index": 4, + "name": "update", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "isCloned": true, + "name": "update", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "rect", + "type": "QRectF" + }, + { + "name": "layers", + "type": "SceneLayers" + } + ], + "index": 6, + "name": "invalidate", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "rect", + "type": "QRectF" + } + ], + "index": 7, + "isCloned": true, + "name": "invalidate", + "returnType": "void" + }, + { + "access": "public", + "index": 8, + "isCloned": true, + "name": "invalidate", + "returnType": "void" + }, + { + "access": "public", + "index": 9, + "name": "advance", + "returnType": "void" + }, + { + "access": "public", + "index": 10, + "name": "clearSelection", + "returnType": "void" + }, + { + "access": "public", + "index": 11, + "name": "clear", + "returnType": "void" + }, + { + "access": "protected", + "arguments": [ + { + "name": "next", + "type": "bool" + } + ], + "index": 12, + "name": "focusNextPrevChild", + "returnType": "bool" + }, + { + "access": "private", + "index": 13, + "name": "_q_emitUpdated", + "returnType": "void" + }, + { + "access": "private", + "index": 14, + "name": "_q_polishItems", + "returnType": "void" + }, + { + "access": "private", + "index": 15, + "name": "_q_processDirtyItems", + "returnType": "void" + }, + { + "access": "private", + "index": 16, + "name": "_q_updateScenePosDescendants", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qgraphicsscene.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QGraphicsSceneBspTreeIndex", + "lineNumber": 36, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "bspTreeDepth", + "read": "bspTreeDepth", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setBspTreeDepth" + } + ], + "qualifiedClassName": "QGraphicsSceneBspTreeIndex", + "slots": [ + { + "access": "protected", + "arguments": [ + { + "name": "rect", + "type": "QRectF" + } + ], + "index": 0, + "name": "updateSceneRect", + "returnType": "void" + }, + { + "access": "private", + "index": 1, + "name": "_q_updateSortCache", + "returnType": "void" + }, + { + "access": "private", + "index": 2, + "name": "_q_updateIndex", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QGraphicsSceneIndex" + } + ] + } + ], + "inputFile": "qgraphicsscenebsptreeindex_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QGraphicsSceneIndex", + "lineNumber": 38, + "object": true, + "qualifiedClassName": "QGraphicsSceneIndex", + "slots": [ + { + "access": "protected", + "arguments": [ + { + "name": "rect", + "type": "QRectF" + } + ], + "index": 0, + "name": "updateSceneRect", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qgraphicssceneindex_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QGraphicsSceneLinearIndex", + "lineNumber": 29, + "object": true, + "qualifiedClassName": "QGraphicsSceneLinearIndex", + "superClasses": [ + { + "access": "public", + "name": "QGraphicsSceneIndex" + } + ] + } + ], + "inputFile": "qgraphicsscenelinearindex_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QGraphicsTransform", + "lineNumber": 20, + "object": true, + "qualifiedClassName": "QGraphicsTransform", + "slots": [ + { + "access": "protected", + "index": 0, + "name": "update", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "className": "QGraphicsScale", + "lineNumber": 43, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "origin", + "notify": "originChanged", + "read": "origin", + "required": false, + "scriptable": true, + "stored": true, + "type": "QVector3D", + "user": false, + "write": "setOrigin" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "xScale", + "notify": "xScaleChanged", + "read": "xScale", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setXScale" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "yScale", + "notify": "yScaleChanged", + "read": "yScale", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setYScale" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "zScale", + "notify": "zScaleChanged", + "read": "zScale", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setZScale" + } + ], + "qualifiedClassName": "QGraphicsScale", + "signals": [ + { + "access": "public", + "index": 0, + "name": "originChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "xScaleChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "yScaleChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "zScaleChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "scaleChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QGraphicsTransform" + } + ] + }, + { + "className": "QGraphicsRotation", + "lineNumber": 82, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "origin", + "notify": "originChanged", + "read": "origin", + "required": false, + "scriptable": true, + "stored": true, + "type": "QVector3D", + "user": false, + "write": "setOrigin" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "angle", + "notify": "angleChanged", + "read": "angle", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setAngle" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "axis", + "notify": "axisChanged", + "read": "axis", + "required": false, + "scriptable": true, + "stored": true, + "type": "QVector3D", + "user": false, + "write": "setAxis" + } + ], + "qualifiedClassName": "QGraphicsRotation", + "signals": [ + { + "access": "public", + "index": 0, + "name": "originChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "angleChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "axisChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QGraphicsTransform" + } + ] + } + ], + "inputFile": "qgraphicstransform.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QGraphicsView", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "ViewportAnchor", + "values": [ + "NoAnchor", + "AnchorViewCenter", + "AnchorUnderMouse" + ] + }, + { + "alias": "CacheModeFlag", + "isClass": false, + "isFlag": true, + "name": "CacheMode", + "values": [ + "CacheNone", + "CacheBackground" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "DragMode", + "values": [ + "NoDrag", + "ScrollHandDrag", + "RubberBandDrag" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "ViewportUpdateMode", + "values": [ + "FullViewportUpdate", + "MinimalViewportUpdate", + "SmartViewportUpdate", + "NoViewportUpdate", + "BoundingRectViewportUpdate" + ] + }, + { + "alias": "OptimizationFlag", + "isClass": false, + "isFlag": true, + "name": "OptimizationFlags", + "values": [ + "DontSavePainterState", + "DontAdjustForAntialiasing", + "IndirectPainting" + ] + } + ], + "lineNumber": 23, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "backgroundBrush", + "read": "backgroundBrush", + "required": false, + "scriptable": true, + "stored": true, + "type": "QBrush", + "user": false, + "write": "setBackgroundBrush" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "foregroundBrush", + "read": "foregroundBrush", + "required": false, + "scriptable": true, + "stored": true, + "type": "QBrush", + "user": false, + "write": "setForegroundBrush" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "interactive", + "read": "isInteractive", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setInteractive" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "sceneRect", + "read": "sceneRect", + "required": false, + "scriptable": true, + "stored": true, + "type": "QRectF", + "user": false, + "write": "setSceneRect" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "alignment", + "read": "alignment", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::Alignment", + "user": false, + "write": "setAlignment" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "renderHints", + "read": "renderHints", + "required": false, + "scriptable": true, + "stored": true, + "type": "QPainter::RenderHints", + "user": false, + "write": "setRenderHints" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "dragMode", + "read": "dragMode", + "required": false, + "scriptable": true, + "stored": true, + "type": "DragMode", + "user": false, + "write": "setDragMode" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 7, + "name": "cacheMode", + "read": "cacheMode", + "required": false, + "scriptable": true, + "stored": true, + "type": "CacheMode", + "user": false, + "write": "setCacheMode" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 8, + "name": "transformationAnchor", + "read": "transformationAnchor", + "required": false, + "scriptable": true, + "stored": true, + "type": "ViewportAnchor", + "user": false, + "write": "setTransformationAnchor" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 9, + "name": "resizeAnchor", + "read": "resizeAnchor", + "required": false, + "scriptable": true, + "stored": true, + "type": "ViewportAnchor", + "user": false, + "write": "setResizeAnchor" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 10, + "name": "viewportUpdateMode", + "read": "viewportUpdateMode", + "required": false, + "scriptable": true, + "stored": true, + "type": "ViewportUpdateMode", + "user": false, + "write": "setViewportUpdateMode" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 11, + "name": "rubberBandSelectionMode", + "read": "rubberBandSelectionMode", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::ItemSelectionMode", + "user": false, + "write": "setRubberBandSelectionMode" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 12, + "name": "optimizationFlags", + "read": "optimizationFlags", + "required": false, + "scriptable": true, + "stored": true, + "type": "OptimizationFlags", + "user": false, + "write": "setOptimizationFlags" + } + ], + "qualifiedClassName": "QGraphicsView", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "viewportRect", + "type": "QRect" + }, + { + "name": "fromScenePoint", + "type": "QPointF" + }, + { + "name": "toScenePoint", + "type": "QPointF" + } + ], + "index": 0, + "name": "rubberBandChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "rects", + "type": "QList" + } + ], + "index": 1, + "name": "updateScene", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "rect", + "type": "QRectF" + }, + { + "name": "layers", + "type": "QGraphicsScene::SceneLayers" + } + ], + "index": 2, + "name": "invalidateScene", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "rect", + "type": "QRectF" + } + ], + "index": 3, + "isCloned": true, + "name": "invalidateScene", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "isCloned": true, + "name": "invalidateScene", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "rect", + "type": "QRectF" + } + ], + "index": 5, + "name": "updateSceneRect", + "returnType": "void" + }, + { + "access": "protected", + "arguments": [ + { + "name": "widget", + "type": "QWidget*" + } + ], + "index": 6, + "name": "setupViewport", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "type": "QCursor" + } + ], + "index": 7, + "name": "_q_setViewportCursor", + "returnType": "void" + }, + { + "access": "private", + "index": 8, + "name": "_q_unsetViewportCursor", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QAbstractScrollArea" + } + ] + } + ], + "inputFile": "qgraphicsview.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QGraphicsWidget", + "interfaces": [ + [ + { + "className": "QGraphicsItem", + "id": "\"org.qt-project.Qt.QGraphicsItem\"" + } + ], + [ + { + "className": "QGraphicsLayoutItem", + "id": "\"org.qt-project.Qt.QGraphicsLayoutItem\"" + } + ] + ], + "lineNumber": 31, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "palette", + "read": "palette", + "required": false, + "scriptable": true, + "stored": true, + "type": "QPalette", + "user": false, + "write": "setPalette" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "font", + "read": "font", + "required": false, + "scriptable": true, + "stored": true, + "type": "QFont", + "user": false, + "write": "setFont" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "layoutDirection", + "read": "layoutDirection", + "required": false, + "reset": "unsetLayoutDirection", + "scriptable": true, + "stored": true, + "type": "Qt::LayoutDirection", + "user": false, + "write": "setLayoutDirection" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "size", + "notify": "geometryChanged", + "read": "size", + "required": false, + "scriptable": true, + "stored": true, + "type": "QSizeF", + "user": false, + "write": "resize" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "minimumSize", + "read": "minimumSize", + "required": false, + "scriptable": true, + "stored": true, + "type": "QSizeF", + "user": false, + "write": "setMinimumSize" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "preferredSize", + "read": "preferredSize", + "required": false, + "scriptable": true, + "stored": true, + "type": "QSizeF", + "user": false, + "write": "setPreferredSize" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "maximumSize", + "read": "maximumSize", + "required": false, + "scriptable": true, + "stored": true, + "type": "QSizeF", + "user": false, + "write": "setMaximumSize" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 7, + "name": "sizePolicy", + "read": "sizePolicy", + "required": false, + "scriptable": true, + "stored": true, + "type": "QSizePolicy", + "user": false, + "write": "setSizePolicy" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 8, + "name": "focusPolicy", + "read": "focusPolicy", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::FocusPolicy", + "user": false, + "write": "setFocusPolicy" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 9, + "name": "windowFlags", + "read": "windowFlags", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::WindowFlags", + "user": false, + "write": "setWindowFlags" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 10, + "name": "windowTitle", + "read": "windowTitle", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setWindowTitle" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 11, + "name": "geometry", + "notify": "geometryChanged", + "read": "geometry", + "required": false, + "scriptable": true, + "stored": true, + "type": "QRectF", + "user": false, + "write": "setGeometry" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 12, + "name": "autoFillBackground", + "read": "autoFillBackground", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setAutoFillBackground" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 13, + "name": "layout", + "notify": "layoutChanged", + "read": "layout", + "required": false, + "scriptable": true, + "stored": true, + "type": "QGraphicsLayout*", + "user": false, + "write": "setLayout" + } + ], + "qualifiedClassName": "QGraphicsWidget", + "signals": [ + { + "access": "public", + "index": 0, + "name": "geometryChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "layoutChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "index": 2, + "name": "close", + "returnType": "bool" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QGraphicsObject" + }, + { + "access": "public", + "name": "QGraphicsLayoutItem" + } + ] + } + ], + "inputFile": "qgraphicswidget.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QGridLayout", + "lineNumber": 20, + "object": true, + "qualifiedClassName": "QGridLayout", + "superClasses": [ + { + "access": "public", + "name": "QLayout" + } + ] + } + ], + "inputFile": "qgridlayout.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QGroupBox", + "lineNumber": 16, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "title", + "read": "title", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setTitle" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "alignment", + "read": "alignment", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::Alignment", + "user": false, + "write": "setAlignment" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "flat", + "read": "isFlat", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setFlat" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "checkable", + "read": "isCheckable", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setCheckable" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "checked", + "notify": "toggled", + "read": "isChecked", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": true, + "write": "setChecked" + } + ], + "qualifiedClassName": "QGroupBox", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "checked", + "type": "bool" + } + ], + "index": 0, + "name": "clicked", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "isCloned": true, + "name": "clicked", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "bool" + } + ], + "index": 2, + "name": "toggled", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "checked", + "type": "bool" + } + ], + "index": 3, + "name": "setChecked", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "b", + "type": "bool" + } + ], + "index": 4, + "name": "_q_setChildrenEnabled", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + } + ], + "inputFile": "qgroupbox.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QHeaderView", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "ResizeMode", + "values": [ + "Interactive", + "Stretch", + "Fixed", + "ResizeToContents", + "Custom" + ] + } + ], + "lineNumber": 17, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "firstSectionMovable", + "read": "isFirstSectionMovable", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setFirstSectionMovable" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "showSortIndicator", + "read": "isSortIndicatorShown", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setSortIndicatorShown" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "sectionsMovable", + "read": "sectionsMovable", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setSectionsMovable" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "sectionsClickable", + "read": "sectionsClickable", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setSectionsClickable" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "highlightSections", + "read": "highlightSections", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setHighlightSections" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "stretchLastSection", + "read": "stretchLastSection", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setStretchLastSection" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "cascadingSectionResizes", + "read": "cascadingSectionResizes", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setCascadingSectionResizes" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 7, + "name": "defaultSectionSize", + "read": "defaultSectionSize", + "required": false, + "reset": "resetDefaultSectionSize", + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setDefaultSectionSize" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 8, + "name": "minimumSectionSize", + "read": "minimumSectionSize", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setMinimumSectionSize" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 9, + "name": "maximumSectionSize", + "read": "maximumSectionSize", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setMaximumSectionSize" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 10, + "name": "defaultAlignment", + "read": "defaultAlignment", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::Alignment", + "user": false, + "write": "setDefaultAlignment" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 11, + "name": "sortIndicatorClearable", + "notify": "sortIndicatorClearableChanged", + "read": "isSortIndicatorClearable", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setSortIndicatorClearable" + } + ], + "qualifiedClassName": "QHeaderView", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "logicalIndex", + "type": "int" + }, + { + "name": "oldVisualIndex", + "type": "int" + }, + { + "name": "newVisualIndex", + "type": "int" + } + ], + "index": 0, + "name": "sectionMoved", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "logicalIndex", + "type": "int" + }, + { + "name": "oldSize", + "type": "int" + }, + { + "name": "newSize", + "type": "int" + } + ], + "index": 1, + "name": "sectionResized", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "logicalIndex", + "type": "int" + } + ], + "index": 2, + "name": "sectionPressed", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "logicalIndex", + "type": "int" + } + ], + "index": 3, + "name": "sectionClicked", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "logicalIndex", + "type": "int" + } + ], + "index": 4, + "name": "sectionEntered", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "logicalIndex", + "type": "int" + } + ], + "index": 5, + "name": "sectionDoubleClicked", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "oldCount", + "type": "int" + }, + { + "name": "newCount", + "type": "int" + } + ], + "index": 6, + "name": "sectionCountChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "logicalIndex", + "type": "int" + } + ], + "index": 7, + "name": "sectionHandleDoubleClicked", + "returnType": "void" + }, + { + "access": "public", + "index": 8, + "name": "geometriesChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "logicalIndex", + "type": "int" + }, + { + "name": "order", + "type": "Qt::SortOrder" + } + ], + "index": 9, + "name": "sortIndicatorChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "clearable", + "type": "bool" + } + ], + "index": 10, + "name": "sortIndicatorClearableChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "offset", + "type": "int" + } + ], + "index": 11, + "name": "setOffset", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "visualIndex", + "type": "int" + } + ], + "index": 12, + "name": "setOffsetToSectionPosition", + "returnType": "void" + }, + { + "access": "public", + "index": 13, + "name": "setOffsetToLastSection", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "orientation", + "type": "Qt::Orientation" + }, + { + "name": "logicalFirst", + "type": "int" + }, + { + "name": "logicalLast", + "type": "int" + } + ], + "index": 14, + "name": "headerDataChanged", + "returnType": "void" + }, + { + "access": "protected", + "arguments": [ + { + "name": "logicalIndex", + "type": "int" + } + ], + "index": 15, + "name": "updateSection", + "returnType": "void" + }, + { + "access": "protected", + "index": 16, + "name": "resizeSections", + "returnType": "void" + }, + { + "access": "protected", + "arguments": [ + { + "name": "parent", + "type": "QModelIndex" + }, + { + "name": "logicalFirst", + "type": "int" + }, + { + "name": "logicalLast", + "type": "int" + } + ], + "index": 17, + "name": "sectionsInserted", + "returnType": "void" + }, + { + "access": "protected", + "arguments": [ + { + "name": "parent", + "type": "QModelIndex" + }, + { + "name": "logicalFirst", + "type": "int" + }, + { + "name": "logicalLast", + "type": "int" + } + ], + "index": 18, + "name": "sectionsAboutToBeRemoved", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QAbstractItemView" + } + ] + } + ], + "inputFile": "qheaderview.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QInputDialog", + "lineNumber": 19, + "object": true, + "qualifiedClassName": "QInputDialog", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "text", + "type": "QString" + } + ], + "index": 0, + "name": "textValueChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "text", + "type": "QString" + } + ], + "index": 1, + "name": "textValueSelected", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "value", + "type": "int" + } + ], + "index": 2, + "name": "intValueChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "value", + "type": "int" + } + ], + "index": 3, + "name": "intValueSelected", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "value", + "type": "double" + } + ], + "index": 4, + "name": "doubleValueChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "value", + "type": "double" + } + ], + "index": 5, + "name": "doubleValueSelected", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QDialog" + } + ] + } + ], + "inputFile": "qinputdialog.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QItemDelegate", + "lineNumber": 20, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "clipping", + "read": "hasClipping", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setClipping" + } + ], + "qualifiedClassName": "QItemDelegate", + "superClasses": [ + { + "access": "public", + "name": "QAbstractItemDelegate" + } + ] + } + ], + "inputFile": "qitemdelegate.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QExpandingLineEdit", + "lineNumber": 28, + "object": true, + "qualifiedClassName": "QExpandingLineEdit", + "slots": [ + { + "access": "public", + "index": 0, + "name": "resizeToContents", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QLineEdit" + } + ] + } + ], + "inputFile": "qitemeditorfactory_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QKeySequenceEdit", + "lineNumber": 16, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "keySequence", + "notify": "keySequenceChanged", + "read": "keySequence", + "required": false, + "scriptable": true, + "stored": true, + "type": "QKeySequence", + "user": true, + "write": "setKeySequence" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "clearButtonEnabled", + "read": "isClearButtonEnabled", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setClearButtonEnabled" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "maximumSequenceLength", + "read": "maximumSequenceLength", + "required": false, + "scriptable": true, + "stored": true, + "type": "qsizetype", + "user": false, + "write": "setMaximumSequenceLength" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "finishingKeyCombinations", + "read": "finishingKeyCombinations", + "required": false, + "scriptable": true, + "stored": true, + "type": "QList", + "user": false, + "write": "setFinishingKeyCombinations" + } + ], + "qualifiedClassName": "QKeySequenceEdit", + "signals": [ + { + "access": "public", + "index": 0, + "name": "editingFinished", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "keySequence", + "type": "QKeySequence" + } + ], + "index": 1, + "name": "keySequenceChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "keySequence", + "type": "QKeySequence" + } + ], + "index": 2, + "name": "setKeySequence", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "clear", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "count", + "type": "qsizetype" + } + ], + "index": 4, + "name": "setMaximumSequenceLength", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + } + ], + "inputFile": "qkeysequenceedit.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QLabel", + "lineNumber": 19, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "text", + "read": "text", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setText" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "textFormat", + "read": "textFormat", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::TextFormat", + "user": false, + "write": "setTextFormat" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "pixmap", + "read": "pixmap", + "required": false, + "scriptable": true, + "stored": true, + "type": "QPixmap", + "user": false, + "write": "setPixmap" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "scaledContents", + "read": "hasScaledContents", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setScaledContents" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "alignment", + "read": "alignment", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::Alignment", + "user": false, + "write": "setAlignment" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "wordWrap", + "read": "wordWrap", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setWordWrap" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "margin", + "read": "margin", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setMargin" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 7, + "name": "indent", + "read": "indent", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setIndent" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 8, + "name": "openExternalLinks", + "read": "openExternalLinks", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setOpenExternalLinks" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 9, + "name": "textInteractionFlags", + "read": "textInteractionFlags", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::TextInteractionFlags", + "user": false, + "write": "setTextInteractionFlags" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 10, + "name": "hasSelectedText", + "read": "hasSelectedText", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 11, + "name": "selectedText", + "read": "selectedText", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + } + ], + "qualifiedClassName": "QLabel", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "link", + "type": "QString" + } + ], + "index": 0, + "name": "linkActivated", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "link", + "type": "QString" + } + ], + "index": 1, + "name": "linkHovered", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "type": "QString" + } + ], + "index": 2, + "name": "setText", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QPixmap" + } + ], + "index": 3, + "name": "setPixmap", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QPicture" + } + ], + "index": 4, + "name": "setPicture", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "movie", + "type": "QMovie*" + } + ], + "index": 5, + "name": "setMovie", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "int" + } + ], + "index": 6, + "name": "setNum", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "double" + } + ], + "index": 7, + "name": "setNum", + "returnType": "void" + }, + { + "access": "public", + "index": 8, + "name": "clear", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QFrame" + } + ] + } + ], + "inputFile": "qlabel.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QLayout", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "SizeConstraint", + "values": [ + "SetDefaultConstraint", + "SetNoConstraint", + "SetMinimumSize", + "SetFixedSize", + "SetMaximumSize", + "SetMinAndMaxSize" + ] + } + ], + "lineNumber": 25, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "spacing", + "read": "spacing", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setSpacing" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "contentsMargins", + "read": "contentsMargins", + "required": false, + "reset": "unsetContentsMargins", + "scriptable": true, + "stored": true, + "type": "QMargins", + "user": false, + "write": "setContentsMargins" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "sizeConstraint", + "read": "sizeConstraint", + "required": false, + "scriptable": true, + "stored": true, + "type": "SizeConstraint", + "user": false, + "write": "setSizeConstraint" + } + ], + "qualifiedClassName": "QLayout", + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QLayoutItem" + } + ] + } + ], + "inputFile": "qlayout.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QLCDNumber", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "Mode", + "values": [ + "Hex", + "Dec", + "Oct", + "Bin" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "SegmentStyle", + "values": [ + "Outline", + "Filled", + "Flat" + ] + } + ], + "lineNumber": 15, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "smallDecimalPoint", + "read": "smallDecimalPoint", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setSmallDecimalPoint" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "digitCount", + "read": "digitCount", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setDigitCount" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "mode", + "read": "mode", + "required": false, + "scriptable": true, + "stored": true, + "type": "Mode", + "user": false, + "write": "setMode" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "segmentStyle", + "read": "segmentStyle", + "required": false, + "scriptable": true, + "stored": true, + "type": "SegmentStyle", + "user": false, + "write": "setSegmentStyle" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "value", + "read": "value", + "required": false, + "scriptable": true, + "stored": true, + "type": "double", + "user": false, + "write": "display" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "intValue", + "read": "intValue", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "display" + } + ], + "qualifiedClassName": "QLCDNumber", + "signals": [ + { + "access": "public", + "index": 0, + "name": "overflow", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "str", + "type": "QString" + } + ], + "index": 1, + "name": "display", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "num", + "type": "int" + } + ], + "index": 2, + "name": "display", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "num", + "type": "double" + } + ], + "index": 3, + "name": "display", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "setHexMode", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "setDecMode", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "setOctMode", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "setBinMode", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "bool" + } + ], + "index": 8, + "name": "setSmallDecimalPoint", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QFrame" + } + ] + } + ], + "inputFile": "qlcdnumber.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QLineEdit", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "ActionPosition", + "values": [ + "LeadingPosition", + "TrailingPosition" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "EchoMode", + "values": [ + "Normal", + "NoEcho", + "Password", + "PasswordEchoOnEdit" + ] + } + ], + "lineNumber": 27, + "methods": [ + { + "access": "public", + "arguments": [ + { + "name": "property", + "type": "Qt::InputMethodQuery" + }, + { + "name": "argument", + "type": "QVariant" + } + ], + "index": 15, + "name": "inputMethodQuery", + "returnType": "QVariant" + } + ], + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "inputMask", + "read": "inputMask", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setInputMask" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "text", + "notify": "textChanged", + "read": "text", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": true, + "write": "setText" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "maxLength", + "read": "maxLength", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setMaxLength" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "frame", + "read": "hasFrame", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setFrame" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "echoMode", + "read": "echoMode", + "required": false, + "scriptable": true, + "stored": true, + "type": "EchoMode", + "user": false, + "write": "setEchoMode" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "displayText", + "read": "displayText", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "cursorPosition", + "read": "cursorPosition", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setCursorPosition" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 7, + "name": "alignment", + "read": "alignment", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::Alignment", + "user": false, + "write": "setAlignment" + }, + { + "constant": false, + "designable": false, + "final": false, + "index": 8, + "name": "modified", + "read": "isModified", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setModified" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 9, + "name": "hasSelectedText", + "read": "hasSelectedText", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 10, + "name": "selectedText", + "read": "selectedText", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 11, + "name": "dragEnabled", + "read": "dragEnabled", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setDragEnabled" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 12, + "name": "readOnly", + "read": "isReadOnly", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setReadOnly" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 13, + "name": "undoAvailable", + "read": "isUndoAvailable", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 14, + "name": "redoAvailable", + "read": "isRedoAvailable", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 15, + "name": "acceptableInput", + "read": "hasAcceptableInput", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 16, + "name": "placeholderText", + "read": "placeholderText", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setPlaceholderText" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 17, + "name": "cursorMoveStyle", + "read": "cursorMoveStyle", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::CursorMoveStyle", + "user": false, + "write": "setCursorMoveStyle" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 18, + "name": "clearButtonEnabled", + "read": "isClearButtonEnabled", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setClearButtonEnabled" + } + ], + "qualifiedClassName": "QLineEdit", + "signals": [ + { + "access": "public", + "arguments": [ + { + "type": "QString" + } + ], + "index": 0, + "name": "textChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QString" + } + ], + "index": 1, + "name": "textEdited", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "int" + }, + { + "type": "int" + } + ], + "index": 2, + "name": "cursorPositionChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "returnPressed", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "editingFinished", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "selectionChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "inputRejected", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "type": "QString" + } + ], + "index": 7, + "name": "setText", + "returnType": "void" + }, + { + "access": "public", + "index": 8, + "name": "clear", + "returnType": "void" + }, + { + "access": "public", + "index": 9, + "name": "selectAll", + "returnType": "void" + }, + { + "access": "public", + "index": 10, + "name": "undo", + "returnType": "void" + }, + { + "access": "public", + "index": 11, + "name": "redo", + "returnType": "void" + }, + { + "access": "public", + "index": 12, + "name": "cut", + "returnType": "void" + }, + { + "access": "public", + "index": 13, + "name": "copy", + "returnType": "void" + }, + { + "access": "public", + "index": 14, + "name": "paste", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + } + ], + "inputFile": "qlineedit.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QLineEditIconButton", + "lineNumber": 48, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "opacity", + "read": "opacity", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setOpacity" + } + ], + "qualifiedClassName": "QLineEditIconButton", + "slots": [ + { + "access": "private", + "index": 0, + "name": "updateCursor", + "returnType": "void" + }, + { + "access": "private", + "index": 1, + "name": "onAnimationFinished", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QToolButton" + } + ] + } + ], + "inputFile": "qlineedit_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QListView", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "Movement", + "values": [ + "Static", + "Free", + "Snap" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "Flow", + "values": [ + "LeftToRight", + "TopToBottom" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "ResizeMode", + "values": [ + "Fixed", + "Adjust" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "LayoutMode", + "values": [ + "SinglePass", + "Batched" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "ViewMode", + "values": [ + "ListMode", + "IconMode" + ] + } + ], + "lineNumber": 16, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "movement", + "read": "movement", + "required": false, + "scriptable": true, + "stored": true, + "type": "Movement", + "user": false, + "write": "setMovement" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "flow", + "read": "flow", + "required": false, + "scriptable": true, + "stored": true, + "type": "Flow", + "user": false, + "write": "setFlow" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "isWrapping", + "read": "isWrapping", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setWrapping" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "resizeMode", + "read": "resizeMode", + "required": false, + "scriptable": true, + "stored": true, + "type": "ResizeMode", + "user": false, + "write": "setResizeMode" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "layoutMode", + "read": "layoutMode", + "required": false, + "scriptable": true, + "stored": true, + "type": "LayoutMode", + "user": false, + "write": "setLayoutMode" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "spacing", + "read": "spacing", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setSpacing" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "gridSize", + "read": "gridSize", + "required": false, + "scriptable": true, + "stored": true, + "type": "QSize", + "user": false, + "write": "setGridSize" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 7, + "name": "viewMode", + "read": "viewMode", + "required": false, + "scriptable": true, + "stored": true, + "type": "ViewMode", + "user": false, + "write": "setViewMode" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 8, + "name": "modelColumn", + "read": "modelColumn", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setModelColumn" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 9, + "name": "uniformItemSizes", + "read": "uniformItemSizes", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setUniformItemSizes" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 10, + "name": "batchSize", + "read": "batchSize", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setBatchSize" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 11, + "name": "wordWrap", + "read": "wordWrap", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setWordWrap" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 12, + "name": "selectionRectVisible", + "read": "isSelectionRectVisible", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setSelectionRectVisible" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 13, + "name": "itemAlignment", + "read": "itemAlignment", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::Alignment", + "user": false, + "write": "setItemAlignment" + } + ], + "qualifiedClassName": "QListView", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "indexes", + "type": "QModelIndexList" + } + ], + "index": 0, + "name": "indexesMoved", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QAbstractItemView" + } + ] + } + ], + "inputFile": "qlistview.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QListWidget", + "lineNumber": 163, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "count", + "read": "count", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "currentRow", + "notify": "currentRowChanged", + "read": "currentRow", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": true, + "write": "setCurrentRow" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "sortingEnabled", + "read": "isSortingEnabled", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setSortingEnabled" + } + ], + "qualifiedClassName": "QListWidget", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "item", + "type": "QListWidgetItem*" + } + ], + "index": 0, + "name": "itemPressed", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "item", + "type": "QListWidgetItem*" + } + ], + "index": 1, + "name": "itemClicked", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "item", + "type": "QListWidgetItem*" + } + ], + "index": 2, + "name": "itemDoubleClicked", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "item", + "type": "QListWidgetItem*" + } + ], + "index": 3, + "name": "itemActivated", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "item", + "type": "QListWidgetItem*" + } + ], + "index": 4, + "name": "itemEntered", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "item", + "type": "QListWidgetItem*" + } + ], + "index": 5, + "name": "itemChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "current", + "type": "QListWidgetItem*" + }, + { + "name": "previous", + "type": "QListWidgetItem*" + } + ], + "index": 6, + "name": "currentItemChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "currentText", + "type": "QString" + } + ], + "index": 7, + "name": "currentTextChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "currentRow", + "type": "int" + } + ], + "index": 8, + "name": "currentRowChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 9, + "name": "itemSelectionChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "item", + "type": "const QListWidgetItem*" + }, + { + "name": "hint", + "type": "QAbstractItemView::ScrollHint" + } + ], + "index": 10, + "name": "scrollToItem", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "item", + "type": "const QListWidgetItem*" + } + ], + "index": 11, + "isCloned": true, + "name": "scrollToItem", + "returnType": "void" + }, + { + "access": "public", + "index": 12, + "name": "clear", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QListView" + } + ] + } + ], + "inputFile": "qlistwidget.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QListModel", + "lineNumber": 44, + "object": true, + "qualifiedClassName": "QListModel", + "superClasses": [ + { + "access": "public", + "name": "QAbstractListModel" + } + ] + } + ], + "inputFile": "qlistwidget_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QMainWindow", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "DockOption", + "values": [ + "AnimatedDocks", + "AllowNestedDocks", + "AllowTabbedDocks", + "ForceTabbedDocks", + "VerticalTabs", + "GroupedDragging" + ] + }, + { + "alias": "DockOption", + "isClass": false, + "isFlag": true, + "name": "DockOptions", + "values": [ + "AnimatedDocks", + "AllowNestedDocks", + "AllowTabbedDocks", + "ForceTabbedDocks", + "VerticalTabs", + "GroupedDragging" + ] + } + ], + "lineNumber": 24, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "iconSize", + "read": "iconSize", + "required": false, + "scriptable": true, + "stored": true, + "type": "QSize", + "user": false, + "write": "setIconSize" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "toolButtonStyle", + "read": "toolButtonStyle", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::ToolButtonStyle", + "user": false, + "write": "setToolButtonStyle" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "animated", + "read": "isAnimated", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setAnimated" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "documentMode", + "read": "documentMode", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setDocumentMode" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "tabShape", + "read": "tabShape", + "required": false, + "scriptable": true, + "stored": true, + "type": "QTabWidget::TabShape", + "user": false, + "write": "setTabShape" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "dockNestingEnabled", + "read": "isDockNestingEnabled", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setDockNestingEnabled" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "dockOptions", + "read": "dockOptions", + "required": false, + "scriptable": true, + "stored": true, + "type": "DockOptions", + "user": false, + "write": "setDockOptions" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 7, + "name": "unifiedTitleAndToolBarOnMac", + "read": "unifiedTitleAndToolBarOnMac", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setUnifiedTitleAndToolBarOnMac" + } + ], + "qualifiedClassName": "QMainWindow", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "iconSize", + "type": "QSize" + } + ], + "index": 0, + "name": "iconSizeChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "toolButtonStyle", + "type": "Qt::ToolButtonStyle" + } + ], + "index": 1, + "name": "toolButtonStyleChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "dockWidget", + "type": "QDockWidget*" + } + ], + "index": 2, + "name": "tabifiedDockWidgetActivated", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "enabled", + "type": "bool" + } + ], + "index": 3, + "name": "setAnimated", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "enabled", + "type": "bool" + } + ], + "index": 4, + "name": "setDockNestingEnabled", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "set", + "type": "bool" + } + ], + "index": 5, + "name": "setUnifiedTitleAndToolBarOnMac", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + } + ], + "inputFile": "qmainwindow.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QDockWidgetGroupWindow", + "lineNumber": 343, + "object": true, + "qualifiedClassName": "QDockWidgetGroupWindow", + "signals": [ + { + "access": "public", + "index": 0, + "name": "resized", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + }, + { + "className": "QMainWindowLayout", + "lineNumber": 483, + "object": true, + "qualifiedClassName": "QMainWindowLayout", + "slots": [ + { + "access": "private", + "index": 0, + "name": "updateGapIndicator", + "returnType": "void" + }, + { + "access": "private", + "index": 1, + "name": "tabChanged", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "from", + "type": "int" + }, + { + "name": "to", + "type": "int" + } + ], + "index": 2, + "name": "tabMoved", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QLayout" + }, + { + "access": "public", + "name": "QMainWindowLayoutSeparatorHelper" + } + ] + } + ], + "inputFile": "qmainwindowlayout_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QMdiArea", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "WindowOrder", + "values": [ + "CreationOrder", + "StackingOrder", + "ActivationHistoryOrder" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "ViewMode", + "values": [ + "SubWindowView", + "TabbedView" + ] + } + ], + "lineNumber": 20, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "background", + "read": "background", + "required": false, + "scriptable": true, + "stored": true, + "type": "QBrush", + "user": false, + "write": "setBackground" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "activationOrder", + "read": "activationOrder", + "required": false, + "scriptable": true, + "stored": true, + "type": "WindowOrder", + "user": false, + "write": "setActivationOrder" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "viewMode", + "read": "viewMode", + "required": false, + "scriptable": true, + "stored": true, + "type": "ViewMode", + "user": false, + "write": "setViewMode" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "documentMode", + "read": "documentMode", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setDocumentMode" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "tabsClosable", + "read": "tabsClosable", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setTabsClosable" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "tabsMovable", + "read": "tabsMovable", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setTabsMovable" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "tabShape", + "read": "tabShape", + "required": false, + "scriptable": true, + "stored": true, + "type": "QTabWidget::TabShape", + "user": false, + "write": "setTabShape" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 7, + "name": "tabPosition", + "read": "tabPosition", + "required": false, + "scriptable": true, + "stored": true, + "type": "QTabWidget::TabPosition", + "user": false, + "write": "setTabPosition" + } + ], + "qualifiedClassName": "QMdiArea", + "signals": [ + { + "access": "public", + "arguments": [ + { + "type": "QMdiSubWindow*" + } + ], + "index": 0, + "name": "subWindowActivated", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "window", + "type": "QMdiSubWindow*" + } + ], + "index": 1, + "name": "setActiveSubWindow", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "tileSubWindows", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "cascadeSubWindows", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "closeActiveSubWindow", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "closeAllSubWindows", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "activateNextSubWindow", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "activatePreviousSubWindow", + "returnType": "void" + }, + { + "access": "protected", + "arguments": [ + { + "name": "viewport", + "type": "QWidget*" + } + ], + "index": 8, + "name": "setupViewport", + "returnType": "void" + }, + { + "access": "private", + "index": 9, + "name": "_q_deactivateAllWindows", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "type": "Qt::WindowStates" + }, + { + "type": "Qt::WindowStates" + } + ], + "index": 10, + "name": "_q_processWindowStateChanged", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "type": "int" + } + ], + "index": 11, + "name": "_q_currentTabChanged", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "type": "int" + } + ], + "index": 12, + "name": "_q_closeTab", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "type": "int" + }, + { + "type": "int" + } + ], + "index": 13, + "name": "_q_moveTab", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QAbstractScrollArea" + } + ] + } + ], + "inputFile": "qmdiarea.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QMdiSubWindow", + "lineNumber": 19, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "keyboardSingleStep", + "read": "keyboardSingleStep", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setKeyboardSingleStep" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "keyboardPageStep", + "read": "keyboardPageStep", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setKeyboardPageStep" + } + ], + "qualifiedClassName": "QMdiSubWindow", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "oldState", + "type": "Qt::WindowStates" + }, + { + "name": "newState", + "type": "Qt::WindowStates" + } + ], + "index": 0, + "name": "windowStateChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "aboutToActivate", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "index": 2, + "name": "showSystemMenu", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "showShaded", + "returnType": "void" + }, + { + "access": "private", + "index": 4, + "name": "_q_updateStaysOnTopHint", + "returnType": "void" + }, + { + "access": "private", + "index": 5, + "name": "_q_enterInteractiveMode", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "type": "QWidget*" + }, + { + "type": "QWidget*" + } + ], + "index": 6, + "name": "_q_processFocusChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + } + ], + "inputFile": "qmdisubwindow.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QMenu", + "lineNumber": 25, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "tearOffEnabled", + "read": "isTearOffEnabled", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setTearOffEnabled" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "title", + "read": "title", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setTitle" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "icon", + "read": "icon", + "required": false, + "scriptable": true, + "stored": true, + "type": "QIcon", + "user": false, + "write": "setIcon" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "separatorsCollapsible", + "read": "separatorsCollapsible", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setSeparatorsCollapsible" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "toolTipsVisible", + "read": "toolTipsVisible", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setToolTipsVisible" + } + ], + "qualifiedClassName": "QMenu", + "signals": [ + { + "access": "public", + "index": 0, + "name": "aboutToShow", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "aboutToHide", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "action", + "type": "QAction*" + } + ], + "index": 2, + "name": "triggered", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "action", + "type": "QAction*" + } + ], + "index": 3, + "name": "hovered", + "returnType": "void" + } + ], + "slots": [ + { + "access": "private", + "index": 4, + "name": "internalDelayedPopup", + "returnType": "void" + }, + { + "access": "private", + "index": 5, + "name": "_q_actionTriggered", + "returnType": "void" + }, + { + "access": "private", + "index": 6, + "name": "_q_actionHovered", + "returnType": "void" + }, + { + "access": "private", + "index": 7, + "name": "_q_overrideMenuActionDestroyed", + "returnType": "void" + }, + { + "access": "private", + "index": 8, + "name": "_q_platformMenuAboutToShow", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + } + ], + "inputFile": "qmenu.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QMenuBar", + "lineNumber": 19, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "defaultUp", + "read": "isDefaultUp", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setDefaultUp" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "nativeMenuBar", + "read": "isNativeMenuBar", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setNativeMenuBar" + } + ], + "qualifiedClassName": "QMenuBar", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "action", + "type": "QAction*" + } + ], + "index": 0, + "name": "triggered", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "action", + "type": "QAction*" + } + ], + "index": 1, + "name": "hovered", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "visible", + "type": "bool" + } + ], + "index": 2, + "name": "setVisible", + "returnType": "void" + }, + { + "access": "private", + "index": 3, + "name": "_q_actionTriggered", + "returnType": "void" + }, + { + "access": "private", + "index": 4, + "name": "_q_actionHovered", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "type": "int" + } + ], + "index": 5, + "name": "_q_internalShortcutActivated", + "returnType": "void" + }, + { + "access": "private", + "index": 6, + "name": "_q_updateLayout", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + } + ], + "inputFile": "qmenubar.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QMessageBox", + "enums": [ + { + "isClass": true, + "isFlag": true, + "name": "Option", + "values": [ + "DontUseNativeDialog" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "Icon", + "values": [ + "NoIcon", + "Information", + "Warning", + "Critical", + "Question" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "ButtonRole", + "values": [ + "InvalidRole", + "AcceptRole", + "RejectRole", + "DestructiveRole", + "ActionRole", + "HelpRole", + "YesRole", + "NoRole", + "ResetRole", + "ApplyRole", + "NRoles" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "StandardButton", + "values": [ + "NoButton", + "Ok", + "Save", + "SaveAll", + "Open", + "Yes", + "YesToAll", + "No", + "NoToAll", + "Abort", + "Retry", + "Ignore", + "Close", + "Cancel", + "Discard", + "Help", + "Apply", + "Reset", + "RestoreDefaults", + "FirstButton", + "LastButton", + "YesAll", + "NoAll", + "Default", + "Escape", + "FlagMask", + "ButtonMask" + ] + }, + { + "alias": "StandardButton", + "isClass": false, + "isFlag": true, + "name": "StandardButtons", + "values": [ + "NoButton", + "Ok", + "Save", + "SaveAll", + "Open", + "Yes", + "YesToAll", + "No", + "NoToAll", + "Abort", + "Retry", + "Ignore", + "Close", + "Cancel", + "Discard", + "Help", + "Apply", + "Reset", + "RestoreDefaults", + "FirstButton", + "LastButton", + "YesAll", + "NoAll", + "Default", + "Escape", + "FlagMask", + "ButtonMask" + ] + } + ], + "lineNumber": 21, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "text", + "read": "text", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setText" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "icon", + "read": "icon", + "required": false, + "scriptable": true, + "stored": true, + "type": "Icon", + "user": false, + "write": "setIcon" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "iconPixmap", + "read": "iconPixmap", + "required": false, + "scriptable": true, + "stored": true, + "type": "QPixmap", + "user": false, + "write": "setIconPixmap" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "textFormat", + "read": "textFormat", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::TextFormat", + "user": false, + "write": "setTextFormat" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "standardButtons", + "read": "standardButtons", + "required": false, + "scriptable": true, + "stored": true, + "type": "StandardButtons", + "user": false, + "write": "setStandardButtons" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "detailedText", + "read": "detailedText", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setDetailedText" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "informativeText", + "read": "informativeText", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setInformativeText" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 7, + "name": "textInteractionFlags", + "read": "textInteractionFlags", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::TextInteractionFlags", + "user": false, + "write": "setTextInteractionFlags" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 8, + "name": "options", + "read": "options", + "required": false, + "scriptable": true, + "stored": true, + "type": "Options", + "user": false, + "write": "setOptions" + } + ], + "qualifiedClassName": "QMessageBox", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "button", + "type": "QAbstractButton*" + } + ], + "index": 0, + "name": "buttonClicked", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QDialog" + } + ] + } + ], + "inputFile": "qmessagebox.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QPixmapFilter", + "lineNumber": 32, + "object": true, + "qualifiedClassName": "QPixmapFilter", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "className": "QPixmapConvolutionFilter", + "lineNumber": 61, + "object": true, + "qualifiedClassName": "QPixmapConvolutionFilter", + "superClasses": [ + { + "access": "public", + "name": "QPixmapFilter" + } + ] + }, + { + "className": "QPixmapBlurFilter", + "lineNumber": 84, + "object": true, + "qualifiedClassName": "QPixmapBlurFilter", + "superClasses": [ + { + "access": "public", + "name": "QPixmapFilter" + } + ] + }, + { + "className": "QPixmapColorizeFilter", + "lineNumber": 105, + "object": true, + "qualifiedClassName": "QPixmapColorizeFilter", + "superClasses": [ + { + "access": "public", + "name": "QPixmapFilter" + } + ] + }, + { + "className": "QPixmapDropShadowFilter", + "lineNumber": 125, + "object": true, + "qualifiedClassName": "QPixmapDropShadowFilter", + "superClasses": [ + { + "access": "public", + "name": "QPixmapFilter" + } + ] + } + ], + "inputFile": "qpixmapfilter_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QPixmapStyle", + "lineNumber": 28, + "object": true, + "qualifiedClassName": "QPixmapStyle", + "superClasses": [ + { + "access": "public", + "name": "QCommonStyle" + } + ] + } + ], + "inputFile": "qpixmapstyle_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QPlainTextEdit", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "LineWrapMode", + "values": [ + "NoWrap", + "WidgetWidth" + ] + } + ], + "lineNumber": 29, + "methods": [ + { + "access": "public", + "arguments": [ + { + "name": "query", + "type": "Qt::InputMethodQuery" + }, + { + "name": "argument", + "type": "QVariant" + } + ], + "index": 25, + "name": "inputMethodQuery", + "returnType": "QVariant" + } + ], + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "tabChangesFocus", + "read": "tabChangesFocus", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setTabChangesFocus" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "documentTitle", + "read": "documentTitle", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setDocumentTitle" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "undoRedoEnabled", + "read": "isUndoRedoEnabled", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setUndoRedoEnabled" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "lineWrapMode", + "read": "lineWrapMode", + "required": false, + "scriptable": true, + "stored": true, + "type": "LineWrapMode", + "user": false, + "write": "setLineWrapMode" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "readOnly", + "read": "isReadOnly", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setReadOnly" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "plainText", + "notify": "textChanged", + "read": "toPlainText", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": true, + "write": "setPlainText" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "overwriteMode", + "read": "overwriteMode", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setOverwriteMode" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 7, + "name": "tabStopDistance", + "read": "tabStopDistance", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setTabStopDistance" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 8, + "name": "cursorWidth", + "read": "cursorWidth", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setCursorWidth" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 9, + "name": "textInteractionFlags", + "read": "textInteractionFlags", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::TextInteractionFlags", + "user": false, + "write": "setTextInteractionFlags" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 10, + "name": "blockCount", + "read": "blockCount", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 11, + "name": "maximumBlockCount", + "read": "maximumBlockCount", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setMaximumBlockCount" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 12, + "name": "backgroundVisible", + "read": "backgroundVisible", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setBackgroundVisible" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 13, + "name": "centerOnScroll", + "read": "centerOnScroll", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setCenterOnScroll" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 14, + "name": "placeholderText", + "read": "placeholderText", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setPlaceholderText" + } + ], + "qualifiedClassName": "QPlainTextEdit", + "signals": [ + { + "access": "public", + "index": 0, + "name": "textChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "b", + "type": "bool" + } + ], + "index": 1, + "name": "undoAvailable", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "b", + "type": "bool" + } + ], + "index": 2, + "name": "redoAvailable", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "b", + "type": "bool" + } + ], + "index": 3, + "name": "copyAvailable", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "selectionChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "cursorPositionChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "rect", + "type": "QRect" + }, + { + "name": "dy", + "type": "int" + } + ], + "index": 6, + "name": "updateRequest", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "newBlockCount", + "type": "int" + } + ], + "index": 7, + "name": "blockCountChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "bool" + } + ], + "index": 8, + "name": "modificationChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "text", + "type": "QString" + } + ], + "index": 9, + "name": "setPlainText", + "returnType": "void" + }, + { + "access": "public", + "index": 10, + "name": "cut", + "returnType": "void" + }, + { + "access": "public", + "index": 11, + "name": "copy", + "returnType": "void" + }, + { + "access": "public", + "index": 12, + "name": "paste", + "returnType": "void" + }, + { + "access": "public", + "index": 13, + "name": "undo", + "returnType": "void" + }, + { + "access": "public", + "index": 14, + "name": "redo", + "returnType": "void" + }, + { + "access": "public", + "index": 15, + "name": "clear", + "returnType": "void" + }, + { + "access": "public", + "index": 16, + "name": "selectAll", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "text", + "type": "QString" + } + ], + "index": 17, + "name": "insertPlainText", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "text", + "type": "QString" + } + ], + "index": 18, + "name": "appendPlainText", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "html", + "type": "QString" + } + ], + "index": 19, + "name": "appendHtml", + "returnType": "void" + }, + { + "access": "public", + "index": 20, + "name": "centerCursor", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "range", + "type": "int" + } + ], + "index": 21, + "name": "zoomIn", + "returnType": "void" + }, + { + "access": "public", + "index": 22, + "isCloned": true, + "name": "zoomIn", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "range", + "type": "int" + } + ], + "index": 23, + "name": "zoomOut", + "returnType": "void" + }, + { + "access": "public", + "index": 24, + "isCloned": true, + "name": "zoomOut", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QAbstractScrollArea" + } + ] + }, + { + "className": "QPlainTextDocumentLayout", + "lineNumber": 249, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "cursorWidth", + "read": "cursorWidth", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setCursorWidth" + } + ], + "qualifiedClassName": "QPlainTextDocumentLayout", + "superClasses": [ + { + "access": "public", + "name": "QAbstractTextDocumentLayout" + } + ] + } + ], + "inputFile": "qplaintextedit.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QPlainTextEditControl", + "lineNumber": 46, + "object": true, + "qualifiedClassName": "QPlainTextEditControl", + "superClasses": [ + { + "access": "public", + "name": "QWidgetTextControl" + } + ] + } + ], + "inputFile": "qplaintextedit_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QProgressBar", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "Direction", + "values": [ + "TopToBottom", + "BottomToTop" + ] + } + ], + "lineNumber": 17, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "minimum", + "read": "minimum", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setMinimum" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "maximum", + "read": "maximum", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setMaximum" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "text", + "read": "text", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "value", + "notify": "valueChanged", + "read": "value", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setValue" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "alignment", + "read": "alignment", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::Alignment", + "user": false, + "write": "setAlignment" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "textVisible", + "read": "isTextVisible", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setTextVisible" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "orientation", + "read": "orientation", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::Orientation", + "user": false, + "write": "setOrientation" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 7, + "name": "invertedAppearance", + "read": "invertedAppearance", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setInvertedAppearance" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 8, + "name": "textDirection", + "read": "textDirection", + "required": false, + "scriptable": true, + "stored": true, + "type": "Direction", + "user": false, + "write": "setTextDirection" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 9, + "name": "format", + "read": "format", + "required": false, + "reset": "resetFormat", + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setFormat" + } + ], + "qualifiedClassName": "QProgressBar", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "value", + "type": "int" + } + ], + "index": 0, + "name": "valueChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "index": 1, + "name": "reset", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "minimum", + "type": "int" + }, + { + "name": "maximum", + "type": "int" + } + ], + "index": 2, + "name": "setRange", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "minimum", + "type": "int" + } + ], + "index": 3, + "name": "setMinimum", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "maximum", + "type": "int" + } + ], + "index": 4, + "name": "setMaximum", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "value", + "type": "int" + } + ], + "index": 5, + "name": "setValue", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "Qt::Orientation" + } + ], + "index": 6, + "name": "setOrientation", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + } + ], + "inputFile": "qprogressbar.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QProgressDialog", + "lineNumber": 21, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "wasCanceled", + "read": "wasCanceled", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "minimum", + "read": "minimum", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setMinimum" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "maximum", + "read": "maximum", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setMaximum" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "value", + "read": "value", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setValue" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "autoReset", + "read": "autoReset", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setAutoReset" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "autoClose", + "read": "autoClose", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setAutoClose" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "minimumDuration", + "read": "minimumDuration", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setMinimumDuration" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 7, + "name": "labelText", + "read": "labelText", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setLabelText" + } + ], + "qualifiedClassName": "QProgressDialog", + "signals": [ + { + "access": "public", + "index": 0, + "name": "canceled", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "index": 1, + "name": "cancel", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "reset", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "maximum", + "type": "int" + } + ], + "index": 3, + "name": "setMaximum", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "minimum", + "type": "int" + } + ], + "index": 4, + "name": "setMinimum", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "minimum", + "type": "int" + }, + { + "name": "maximum", + "type": "int" + } + ], + "index": 5, + "name": "setRange", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "progress", + "type": "int" + } + ], + "index": 6, + "name": "setValue", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "text", + "type": "QString" + } + ], + "index": 7, + "name": "setLabelText", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "text", + "type": "QString" + } + ], + "index": 8, + "name": "setCancelButtonText", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "ms", + "type": "int" + } + ], + "index": 9, + "name": "setMinimumDuration", + "returnType": "void" + }, + { + "access": "protected", + "index": 10, + "name": "forceShow", + "returnType": "void" + }, + { + "access": "private", + "index": 11, + "name": "_q_disconnectOnClose", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QDialog" + } + ] + } + ], + "inputFile": "qprogressdialog.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QProxyStyle", + "lineNumber": 16, + "object": true, + "qualifiedClassName": "QProxyStyle", + "superClasses": [ + { + "access": "public", + "name": "QCommonStyle" + } + ] + } + ], + "inputFile": "qproxystyle.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QPushButton", + "lineNumber": 19, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "autoDefault", + "read": "autoDefault", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setAutoDefault" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "default", + "read": "isDefault", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setDefault" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "flat", + "read": "isFlat", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setFlat" + } + ], + "qualifiedClassName": "QPushButton", + "slots": [ + { + "access": "public", + "index": 0, + "name": "showMenu", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QAbstractButton" + } + ] + } + ], + "inputFile": "qpushbutton.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QRadioButton", + "lineNumber": 18, + "object": true, + "qualifiedClassName": "QRadioButton", + "superClasses": [ + { + "access": "public", + "name": "QAbstractButton" + } + ] + } + ], + "inputFile": "qradiobutton.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QRubberBand", + "lineNumber": 17, + "object": true, + "qualifiedClassName": "QRubberBand", + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + } + ], + "inputFile": "qrubberband.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QScrollArea", + "lineNumber": 16, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "widgetResizable", + "read": "widgetResizable", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setWidgetResizable" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "alignment", + "read": "alignment", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::Alignment", + "user": false, + "write": "setAlignment" + } + ], + "qualifiedClassName": "QScrollArea", + "superClasses": [ + { + "access": "public", + "name": "QAbstractScrollArea" + } + ] + } + ], + "inputFile": "qscrollarea.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QScrollBar", + "lineNumber": 19, + "object": true, + "qualifiedClassName": "QScrollBar", + "superClasses": [ + { + "access": "public", + "name": "QAbstractSlider" + } + ] + } + ], + "inputFile": "qscrollbar.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QScroller", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "State", + "values": [ + "Inactive", + "Pressed", + "Dragging", + "Scrolling" + ] + } + ], + "lineNumber": 25, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "state", + "notify": "stateChanged", + "read": "state", + "required": false, + "scriptable": true, + "stored": true, + "type": "State", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "scrollerProperties", + "notify": "scrollerPropertiesChanged", + "read": "scrollerProperties", + "required": false, + "scriptable": true, + "stored": true, + "type": "QScrollerProperties", + "user": false, + "write": "setScrollerProperties" + } + ], + "qualifiedClassName": "QScroller", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "newstate", + "type": "QScroller::State" + } + ], + "index": 0, + "name": "stateChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QScrollerProperties" + } + ], + "index": 1, + "name": "scrollerPropertiesChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "prop", + "type": "QScrollerProperties" + } + ], + "index": 2, + "name": "setScrollerProperties", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "pos", + "type": "QPointF" + } + ], + "index": 3, + "name": "scrollTo", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "pos", + "type": "QPointF" + }, + { + "name": "scrollTime", + "type": "int" + } + ], + "index": 4, + "name": "scrollTo", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "rect", + "type": "QRectF" + }, + { + "name": "xmargin", + "type": "qreal" + }, + { + "name": "ymargin", + "type": "qreal" + } + ], + "index": 5, + "name": "ensureVisible", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "rect", + "type": "QRectF" + }, + { + "name": "xmargin", + "type": "qreal" + }, + { + "name": "ymargin", + "type": "qreal" + }, + { + "name": "scrollTime", + "type": "int" + } + ], + "index": 6, + "name": "ensureVisible", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "resendPrepareEvent", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qscroller.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QScrollerPrivate", + "lineNumber": 44, + "object": true, + "qualifiedClassName": "QScrollerPrivate", + "slots": [ + { + "access": "public", + "index": 0, + "name": "targetDestroyed", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qscroller_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QUrlModel", + "lineNumber": 39, + "object": true, + "qualifiedClassName": "QUrlModel", + "slots": [ + { + "access": "private", + "arguments": [ + { + "name": "topLeft", + "type": "QModelIndex" + }, + { + "name": "bottomRight", + "type": "QModelIndex" + } + ], + "index": 0, + "name": "dataChanged", + "returnType": "void" + }, + { + "access": "private", + "index": 1, + "name": "layoutChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QStandardItemModel" + } + ] + }, + { + "className": "QSidebar", + "lineNumber": 88, + "object": true, + "qualifiedClassName": "QSidebar", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "url", + "type": "QUrl" + } + ], + "index": 0, + "name": "goToUrl", + "returnType": "void" + } + ], + "slots": [ + { + "access": "private", + "arguments": [ + { + "name": "index", + "type": "QModelIndex" + } + ], + "index": 1, + "name": "clicked", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "position", + "type": "QPoint" + } + ], + "index": 2, + "name": "showContextMenu", + "returnType": "void" + }, + { + "access": "private", + "index": 3, + "name": "removeEntry", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QListView" + } + ] + } + ], + "inputFile": "qsidebar_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QSizeGrip", + "lineNumber": 15, + "object": true, + "qualifiedClassName": "QSizeGrip", + "slots": [ + { + "access": "private", + "index": 0, + "name": "_q_showIfNotHidden", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + } + ], + "inputFile": "qsizegrip.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QSizePolicy", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "Policy", + "values": [ + "Fixed", + "Minimum", + "Maximum", + "Preferred", + "MinimumExpanding", + "Expanding", + "Ignored" + ] + }, + { + "alias": "ControlType", + "isClass": false, + "isFlag": true, + "name": "ControlTypes", + "values": [ + "DefaultType", + "ButtonBox", + "CheckBox", + "ComboBox", + "Frame", + "GroupBox", + "Label", + "Line", + "LineEdit", + "PushButton", + "RadioButton", + "Slider", + "SpinBox", + "TabWidget", + "ToolButton" + ] + } + ], + "gadget": true, + "lineNumber": 17, + "qualifiedClassName": "QSizePolicy" + } + ], + "inputFile": "qsizepolicy.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QSlider", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "TickPosition", + "values": [ + "NoTicks", + "TicksAbove", + "TicksLeft", + "TicksBelow", + "TicksRight", + "TicksBothSides" + ] + } + ], + "lineNumber": 17, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "tickPosition", + "read": "tickPosition", + "required": false, + "scriptable": true, + "stored": true, + "type": "TickPosition", + "user": false, + "write": "setTickPosition" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "tickInterval", + "read": "tickInterval", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setTickInterval" + } + ], + "qualifiedClassName": "QSlider", + "superClasses": [ + { + "access": "public", + "name": "QAbstractSlider" + } + ] + } + ], + "inputFile": "qslider.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QSpinBox", + "lineNumber": 15, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "suffix", + "read": "suffix", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setSuffix" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "prefix", + "read": "prefix", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setPrefix" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "cleanText", + "read": "cleanText", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "minimum", + "read": "minimum", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setMinimum" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "maximum", + "read": "maximum", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setMaximum" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "singleStep", + "read": "singleStep", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setSingleStep" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "stepType", + "read": "stepType", + "required": false, + "scriptable": true, + "stored": true, + "type": "StepType", + "user": false, + "write": "setStepType" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 7, + "name": "value", + "notify": "valueChanged", + "read": "value", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": true, + "write": "setValue" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 8, + "name": "displayIntegerBase", + "read": "displayIntegerBase", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setDisplayIntegerBase" + } + ], + "qualifiedClassName": "QSpinBox", + "signals": [ + { + "access": "public", + "arguments": [ + { + "type": "int" + } + ], + "index": 0, + "name": "valueChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QString" + } + ], + "index": 1, + "name": "textChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "val", + "type": "int" + } + ], + "index": 2, + "name": "setValue", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QAbstractSpinBox" + } + ] + }, + { + "className": "QDoubleSpinBox", + "lineNumber": 81, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "prefix", + "read": "prefix", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setPrefix" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "suffix", + "read": "suffix", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setSuffix" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "cleanText", + "read": "cleanText", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "decimals", + "read": "decimals", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setDecimals" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "minimum", + "read": "minimum", + "required": false, + "scriptable": true, + "stored": true, + "type": "double", + "user": false, + "write": "setMinimum" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "maximum", + "read": "maximum", + "required": false, + "scriptable": true, + "stored": true, + "type": "double", + "user": false, + "write": "setMaximum" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "singleStep", + "read": "singleStep", + "required": false, + "scriptable": true, + "stored": true, + "type": "double", + "user": false, + "write": "setSingleStep" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 7, + "name": "stepType", + "read": "stepType", + "required": false, + "scriptable": true, + "stored": true, + "type": "StepType", + "user": false, + "write": "setStepType" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 8, + "name": "value", + "notify": "valueChanged", + "read": "value", + "required": false, + "scriptable": true, + "stored": true, + "type": "double", + "user": true, + "write": "setValue" + } + ], + "qualifiedClassName": "QDoubleSpinBox", + "signals": [ + { + "access": "public", + "arguments": [ + { + "type": "double" + } + ], + "index": 0, + "name": "valueChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QString" + } + ], + "index": 1, + "name": "textChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "val", + "type": "double" + } + ], + "index": 2, + "name": "setValue", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QAbstractSpinBox" + } + ] + } + ], + "inputFile": "qspinbox.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QSplashScreen", + "lineNumber": 17, + "object": true, + "qualifiedClassName": "QSplashScreen", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "message", + "type": "QString" + } + ], + "index": 0, + "name": "messageChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "message", + "type": "QString" + }, + { + "name": "alignment", + "type": "int" + }, + { + "name": "color", + "type": "QColor" + } + ], + "index": 1, + "name": "showMessage", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "message", + "type": "QString" + }, + { + "name": "alignment", + "type": "int" + } + ], + "index": 2, + "isCloned": true, + "name": "showMessage", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "message", + "type": "QString" + } + ], + "index": 3, + "isCloned": true, + "name": "showMessage", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "clearMessage", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + } + ], + "inputFile": "qsplashscreen.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QSplitter", + "lineNumber": 20, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "orientation", + "read": "orientation", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::Orientation", + "user": false, + "write": "setOrientation" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "opaqueResize", + "read": "opaqueResize", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setOpaqueResize" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "handleWidth", + "read": "handleWidth", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setHandleWidth" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "childrenCollapsible", + "read": "childrenCollapsible", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setChildrenCollapsible" + } + ], + "qualifiedClassName": "QSplitter", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "pos", + "type": "int" + }, + { + "name": "index", + "type": "int" + } + ], + "index": 0, + "name": "splitterMoved", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QFrame" + } + ] + }, + { + "className": "QSplitterHandle", + "lineNumber": 97, + "object": true, + "qualifiedClassName": "QSplitterHandle", + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + } + ], + "inputFile": "qsplitter.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QStackedLayout", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "StackingMode", + "values": [ + "StackOne", + "StackAll" + ] + } + ], + "lineNumber": 15, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "currentIndex", + "notify": "currentChanged", + "read": "currentIndex", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setCurrentIndex" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "stackingMode", + "read": "stackingMode", + "required": false, + "scriptable": true, + "stored": true, + "type": "StackingMode", + "user": false, + "write": "setStackingMode" + } + ], + "qualifiedClassName": "QStackedLayout", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + } + ], + "index": 0, + "name": "widgetRemoved", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + } + ], + "index": 1, + "name": "currentChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + } + ], + "index": 2, + "name": "setCurrentIndex", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "w", + "type": "QWidget*" + } + ], + "index": 3, + "name": "setCurrentWidget", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QLayout" + } + ] + } + ], + "inputFile": "qstackedlayout.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QStackedWidget", + "lineNumber": 16, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "currentIndex", + "notify": "currentChanged", + "read": "currentIndex", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setCurrentIndex" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "count", + "read": "count", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + } + ], + "qualifiedClassName": "QStackedWidget", + "signals": [ + { + "access": "public", + "arguments": [ + { + "type": "int" + } + ], + "index": 0, + "name": "currentChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + } + ], + "index": 1, + "name": "widgetRemoved", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + } + ], + "index": 2, + "name": "setCurrentIndex", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "w", + "type": "QWidget*" + } + ], + "index": 3, + "name": "setCurrentWidget", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QFrame" + } + ] + } + ], + "inputFile": "qstackedwidget.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QStatusBar", + "lineNumber": 16, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "sizeGripEnabled", + "read": "isSizeGripEnabled", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setSizeGripEnabled" + } + ], + "qualifiedClassName": "QStatusBar", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "text", + "type": "QString" + } + ], + "index": 0, + "name": "messageChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "text", + "type": "QString" + }, + { + "name": "timeout", + "type": "int" + } + ], + "index": 1, + "name": "showMessage", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "text", + "type": "QString" + } + ], + "index": 2, + "isCloned": true, + "name": "showMessage", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "clearMessage", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + } + ], + "inputFile": "qstatusbar.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QStyle", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "StateFlag", + "values": [ + "State_None", + "State_Enabled", + "State_Raised", + "State_Sunken", + "State_Off", + "State_NoChange", + "State_On", + "State_DownArrow", + "State_Horizontal", + "State_HasFocus", + "State_Top", + "State_Bottom", + "State_FocusAtBorder", + "State_AutoRaise", + "State_MouseOver", + "State_UpArrow", + "State_Selected", + "State_Active", + "State_Window", + "State_Open", + "State_Children", + "State_Item", + "State_Sibling", + "State_Editing", + "State_KeyboardFocusChange", + "State_ReadOnly", + "State_Small", + "State_Mini" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "PrimitiveElement", + "values": [ + "PE_Frame", + "PE_FrameDefaultButton", + "PE_FrameDockWidget", + "PE_FrameFocusRect", + "PE_FrameGroupBox", + "PE_FrameLineEdit", + "PE_FrameMenu", + "PE_FrameStatusBarItem", + "PE_FrameTabWidget", + "PE_FrameWindow", + "PE_FrameButtonBevel", + "PE_FrameButtonTool", + "PE_FrameTabBarBase", + "PE_PanelButtonCommand", + "PE_PanelButtonBevel", + "PE_PanelButtonTool", + "PE_PanelMenuBar", + "PE_PanelToolBar", + "PE_PanelLineEdit", + "PE_IndicatorArrowDown", + "PE_IndicatorArrowLeft", + "PE_IndicatorArrowRight", + "PE_IndicatorArrowUp", + "PE_IndicatorBranch", + "PE_IndicatorButtonDropDown", + "PE_IndicatorItemViewItemCheck", + "PE_IndicatorCheckBox", + "PE_IndicatorDockWidgetResizeHandle", + "PE_IndicatorHeaderArrow", + "PE_IndicatorMenuCheckMark", + "PE_IndicatorProgressChunk", + "PE_IndicatorRadioButton", + "PE_IndicatorSpinDown", + "PE_IndicatorSpinMinus", + "PE_IndicatorSpinPlus", + "PE_IndicatorSpinUp", + "PE_IndicatorToolBarHandle", + "PE_IndicatorToolBarSeparator", + "PE_PanelTipLabel", + "PE_IndicatorTabTear", + "PE_IndicatorTabTearLeft", + "PE_PanelScrollAreaCorner", + "PE_Widget", + "PE_IndicatorColumnViewArrow", + "PE_IndicatorItemViewItemDrop", + "PE_PanelItemViewItem", + "PE_PanelItemViewRow", + "PE_PanelStatusBar", + "PE_IndicatorTabClose", + "PE_PanelMenu", + "PE_IndicatorTabTearRight", + "PE_CustomBase" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "ControlElement", + "values": [ + "CE_PushButton", + "CE_PushButtonBevel", + "CE_PushButtonLabel", + "CE_CheckBox", + "CE_CheckBoxLabel", + "CE_RadioButton", + "CE_RadioButtonLabel", + "CE_TabBarTab", + "CE_TabBarTabShape", + "CE_TabBarTabLabel", + "CE_ProgressBar", + "CE_ProgressBarGroove", + "CE_ProgressBarContents", + "CE_ProgressBarLabel", + "CE_MenuItem", + "CE_MenuScroller", + "CE_MenuVMargin", + "CE_MenuHMargin", + "CE_MenuTearoff", + "CE_MenuEmptyArea", + "CE_MenuBarItem", + "CE_MenuBarEmptyArea", + "CE_ToolButtonLabel", + "CE_Header", + "CE_HeaderSection", + "CE_HeaderLabel", + "CE_ToolBoxTab", + "CE_SizeGrip", + "CE_Splitter", + "CE_RubberBand", + "CE_DockWidgetTitle", + "CE_ScrollBarAddLine", + "CE_ScrollBarSubLine", + "CE_ScrollBarAddPage", + "CE_ScrollBarSubPage", + "CE_ScrollBarSlider", + "CE_ScrollBarFirst", + "CE_ScrollBarLast", + "CE_FocusFrame", + "CE_ComboBoxLabel", + "CE_ToolBar", + "CE_ToolBoxTabShape", + "CE_ToolBoxTabLabel", + "CE_HeaderEmptyArea", + "CE_ColumnViewGrip", + "CE_ItemViewItem", + "CE_ShapedFrame", + "CE_CustomBase" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "SubElement", + "values": [ + "SE_PushButtonContents", + "SE_PushButtonFocusRect", + "SE_CheckBoxIndicator", + "SE_CheckBoxContents", + "SE_CheckBoxFocusRect", + "SE_CheckBoxClickRect", + "SE_RadioButtonIndicator", + "SE_RadioButtonContents", + "SE_RadioButtonFocusRect", + "SE_RadioButtonClickRect", + "SE_ComboBoxFocusRect", + "SE_SliderFocusRect", + "SE_ProgressBarGroove", + "SE_ProgressBarContents", + "SE_ProgressBarLabel", + "SE_ToolBoxTabContents", + "SE_HeaderLabel", + "SE_HeaderArrow", + "SE_TabWidgetTabBar", + "SE_TabWidgetTabPane", + "SE_TabWidgetTabContents", + "SE_TabWidgetLeftCorner", + "SE_TabWidgetRightCorner", + "SE_ItemViewItemCheckIndicator", + "SE_TabBarTearIndicator", + "SE_TabBarTearIndicatorLeft", + "SE_TreeViewDisclosureItem", + "SE_LineEditContents", + "SE_FrameContents", + "SE_DockWidgetCloseButton", + "SE_DockWidgetFloatButton", + "SE_DockWidgetTitleBarText", + "SE_DockWidgetIcon", + "SE_CheckBoxLayoutItem", + "SE_ComboBoxLayoutItem", + "SE_DateTimeEditLayoutItem", + "SE_LabelLayoutItem", + "SE_ProgressBarLayoutItem", + "SE_PushButtonLayoutItem", + "SE_RadioButtonLayoutItem", + "SE_SliderLayoutItem", + "SE_SpinBoxLayoutItem", + "SE_ToolButtonLayoutItem", + "SE_FrameLayoutItem", + "SE_GroupBoxLayoutItem", + "SE_TabWidgetLayoutItem", + "SE_ItemViewItemDecoration", + "SE_ItemViewItemText", + "SE_ItemViewItemFocusRect", + "SE_TabBarTabLeftButton", + "SE_TabBarTabRightButton", + "SE_TabBarTabText", + "SE_ShapedFrameContents", + "SE_ToolBarHandle", + "SE_TabBarScrollLeftButton", + "SE_TabBarScrollRightButton", + "SE_TabBarTearIndicatorRight", + "SE_PushButtonBevel", + "SE_CustomBase" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "ComplexControl", + "values": [ + "CC_SpinBox", + "CC_ComboBox", + "CC_ScrollBar", + "CC_Slider", + "CC_ToolButton", + "CC_TitleBar", + "CC_Dial", + "CC_GroupBox", + "CC_MdiControls", + "CC_CustomBase" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "SubControl", + "values": [ + "SC_None", + "SC_ScrollBarAddLine", + "SC_ScrollBarSubLine", + "SC_ScrollBarAddPage", + "SC_ScrollBarSubPage", + "SC_ScrollBarFirst", + "SC_ScrollBarLast", + "SC_ScrollBarSlider", + "SC_ScrollBarGroove", + "SC_SpinBoxUp", + "SC_SpinBoxDown", + "SC_SpinBoxFrame", + "SC_SpinBoxEditField", + "SC_ComboBoxFrame", + "SC_ComboBoxEditField", + "SC_ComboBoxArrow", + "SC_ComboBoxListBoxPopup", + "SC_SliderGroove", + "SC_SliderHandle", + "SC_SliderTickmarks", + "SC_ToolButton", + "SC_ToolButtonMenu", + "SC_TitleBarSysMenu", + "SC_TitleBarMinButton", + "SC_TitleBarMaxButton", + "SC_TitleBarCloseButton", + "SC_TitleBarNormalButton", + "SC_TitleBarShadeButton", + "SC_TitleBarUnshadeButton", + "SC_TitleBarContextHelpButton", + "SC_TitleBarLabel", + "SC_DialGroove", + "SC_DialHandle", + "SC_DialTickmarks", + "SC_GroupBoxCheckBox", + "SC_GroupBoxLabel", + "SC_GroupBoxContents", + "SC_GroupBoxFrame", + "SC_MdiMinButton", + "SC_MdiNormalButton", + "SC_MdiCloseButton", + "SC_CustomBase", + "SC_All" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "PixelMetric", + "values": [ + "PM_ButtonMargin", + "PM_ButtonDefaultIndicator", + "PM_MenuButtonIndicator", + "PM_ButtonShiftHorizontal", + "PM_ButtonShiftVertical", + "PM_DefaultFrameWidth", + "PM_SpinBoxFrameWidth", + "PM_ComboBoxFrameWidth", + "PM_MaximumDragDistance", + "PM_ScrollBarExtent", + "PM_ScrollBarSliderMin", + "PM_SliderThickness", + "PM_SliderControlThickness", + "PM_SliderLength", + "PM_SliderTickmarkOffset", + "PM_SliderSpaceAvailable", + "PM_DockWidgetSeparatorExtent", + "PM_DockWidgetHandleExtent", + "PM_DockWidgetFrameWidth", + "PM_TabBarTabOverlap", + "PM_TabBarTabHSpace", + "PM_TabBarTabVSpace", + "PM_TabBarBaseHeight", + "PM_TabBarBaseOverlap", + "PM_ProgressBarChunkWidth", + "PM_SplitterWidth", + "PM_TitleBarHeight", + "PM_MenuScrollerHeight", + "PM_MenuHMargin", + "PM_MenuVMargin", + "PM_MenuPanelWidth", + "PM_MenuTearoffHeight", + "PM_MenuDesktopFrameWidth", + "PM_MenuBarPanelWidth", + "PM_MenuBarItemSpacing", + "PM_MenuBarVMargin", + "PM_MenuBarHMargin", + "PM_IndicatorWidth", + "PM_IndicatorHeight", + "PM_ExclusiveIndicatorWidth", + "PM_ExclusiveIndicatorHeight", + "PM_DialogButtonsSeparator", + "PM_DialogButtonsButtonWidth", + "PM_DialogButtonsButtonHeight", + "PM_MdiSubWindowFrameWidth", + "PM_MdiSubWindowMinimizedWidth", + "PM_HeaderMargin", + "PM_HeaderMarkSize", + "PM_HeaderGripMargin", + "PM_TabBarTabShiftHorizontal", + "PM_TabBarTabShiftVertical", + "PM_TabBarScrollButtonWidth", + "PM_ToolBarFrameWidth", + "PM_ToolBarHandleExtent", + "PM_ToolBarItemSpacing", + "PM_ToolBarItemMargin", + "PM_ToolBarSeparatorExtent", + "PM_ToolBarExtensionExtent", + "PM_SpinBoxSliderHeight", + "PM_ToolBarIconSize", + "PM_ListViewIconSize", + "PM_IconViewIconSize", + "PM_SmallIconSize", + "PM_LargeIconSize", + "PM_FocusFrameVMargin", + "PM_FocusFrameHMargin", + "PM_ToolTipLabelFrameWidth", + "PM_CheckBoxLabelSpacing", + "PM_TabBarIconSize", + "PM_SizeGripSize", + "PM_DockWidgetTitleMargin", + "PM_MessageBoxIconSize", + "PM_ButtonIconSize", + "PM_DockWidgetTitleBarButtonMargin", + "PM_RadioButtonLabelSpacing", + "PM_LayoutLeftMargin", + "PM_LayoutTopMargin", + "PM_LayoutRightMargin", + "PM_LayoutBottomMargin", + "PM_LayoutHorizontalSpacing", + "PM_LayoutVerticalSpacing", + "PM_TabBar_ScrollButtonOverlap", + "PM_TextCursorWidth", + "PM_TabCloseIndicatorWidth", + "PM_TabCloseIndicatorHeight", + "PM_ScrollView_ScrollBarSpacing", + "PM_ScrollView_ScrollBarOverlap", + "PM_SubMenuOverlap", + "PM_TreeViewIndentation", + "PM_HeaderDefaultSectionSizeHorizontal", + "PM_HeaderDefaultSectionSizeVertical", + "PM_TitleBarButtonIconSize", + "PM_TitleBarButtonSize", + "PM_LineEditIconSize", + "PM_LineEditIconMargin", + "PM_CustomBase" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "ContentsType", + "values": [ + "CT_PushButton", + "CT_CheckBox", + "CT_RadioButton", + "CT_ToolButton", + "CT_ComboBox", + "CT_Splitter", + "CT_ProgressBar", + "CT_MenuItem", + "CT_MenuBarItem", + "CT_MenuBar", + "CT_Menu", + "CT_TabBarTab", + "CT_Slider", + "CT_ScrollBar", + "CT_LineEdit", + "CT_SpinBox", + "CT_SizeGrip", + "CT_TabWidget", + "CT_DialogButtons", + "CT_HeaderSection", + "CT_GroupBox", + "CT_MdiControls", + "CT_ItemViewItem", + "CT_CustomBase" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "RequestSoftwareInputPanel", + "values": [ + "RSIP_OnMouseClickAndAlreadyFocused", + "RSIP_OnMouseClick" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "StyleHint", + "values": [ + "SH_EtchDisabledText", + "SH_DitherDisabledText", + "SH_ScrollBar_MiddleClickAbsolutePosition", + "SH_ScrollBar_ScrollWhenPointerLeavesControl", + "SH_TabBar_SelectMouseType", + "SH_TabBar_Alignment", + "SH_Header_ArrowAlignment", + "SH_Slider_SnapToValue", + "SH_Slider_SloppyKeyEvents", + "SH_ProgressDialog_CenterCancelButton", + "SH_ProgressDialog_TextLabelAlignment", + "SH_PrintDialog_RightAlignButtons", + "SH_MainWindow_SpaceBelowMenuBar", + "SH_FontDialog_SelectAssociatedText", + "SH_Menu_AllowActiveAndDisabled", + "SH_Menu_SpaceActivatesItem", + "SH_Menu_SubMenuPopupDelay", + "SH_ScrollView_FrameOnlyAroundContents", + "SH_MenuBar_AltKeyNavigation", + "SH_ComboBox_ListMouseTracking", + "SH_Menu_MouseTracking", + "SH_MenuBar_MouseTracking", + "SH_ItemView_ChangeHighlightOnFocus", + "SH_Widget_ShareActivation", + "SH_Workspace_FillSpaceOnMaximize", + "SH_ComboBox_Popup", + "SH_TitleBar_NoBorder", + "SH_Slider_StopMouseOverSlider", + "SH_BlinkCursorWhenTextSelected", + "SH_RichText_FullWidthSelection", + "SH_Menu_Scrollable", + "SH_GroupBox_TextLabelVerticalAlignment", + "SH_GroupBox_TextLabelColor", + "SH_Menu_SloppySubMenus", + "SH_Table_GridLineColor", + "SH_LineEdit_PasswordCharacter", + "SH_DialogButtons_DefaultButton", + "SH_ToolBox_SelectedPageTitleBold", + "SH_TabBar_PreferNoArrows", + "SH_ScrollBar_LeftClickAbsolutePosition", + "SH_ListViewExpand_SelectMouseType", + "SH_UnderlineShortcut", + "SH_SpinBox_AnimateButton", + "SH_SpinBox_KeyPressAutoRepeatRate", + "SH_SpinBox_ClickAutoRepeatRate", + "SH_Menu_FillScreenWithScroll", + "SH_ToolTipLabel_Opacity", + "SH_DrawMenuBarSeparator", + "SH_TitleBar_ModifyNotification", + "SH_Button_FocusPolicy", + "SH_MessageBox_UseBorderForButtonSpacing", + "SH_TitleBar_AutoRaise", + "SH_ToolButton_PopupDelay", + "SH_FocusFrame_Mask", + "SH_RubberBand_Mask", + "SH_WindowFrame_Mask", + "SH_SpinControls_DisableOnBounds", + "SH_Dial_BackgroundRole", + "SH_ComboBox_LayoutDirection", + "SH_ItemView_EllipsisLocation", + "SH_ItemView_ShowDecorationSelected", + "SH_ItemView_ActivateItemOnSingleClick", + "SH_ScrollBar_ContextMenu", + "SH_ScrollBar_RollBetweenButtons", + "SH_Slider_AbsoluteSetButtons", + "SH_Slider_PageSetButtons", + "SH_Menu_KeyboardSearch", + "SH_TabBar_ElideMode", + "SH_DialogButtonLayout", + "SH_ComboBox_PopupFrameStyle", + "SH_MessageBox_TextInteractionFlags", + "SH_DialogButtonBox_ButtonsHaveIcons", + "SH_MessageBox_CenterButtons", + "SH_Menu_SelectionWrap", + "SH_ItemView_MovementWithoutUpdatingSelection", + "SH_ToolTip_Mask", + "SH_FocusFrame_AboveWidget", + "SH_TextControl_FocusIndicatorTextCharFormat", + "SH_WizardStyle", + "SH_ItemView_ArrowKeysNavigateIntoChildren", + "SH_Menu_Mask", + "SH_Menu_FlashTriggeredItem", + "SH_Menu_FadeOutOnHide", + "SH_SpinBox_ClickAutoRepeatThreshold", + "SH_ItemView_PaintAlternatingRowColorsForEmptyArea", + "SH_FormLayoutWrapPolicy", + "SH_TabWidget_DefaultTabPosition", + "SH_ToolBar_Movable", + "SH_FormLayoutFieldGrowthPolicy", + "SH_FormLayoutFormAlignment", + "SH_FormLayoutLabelAlignment", + "SH_ItemView_DrawDelegateFrame", + "SH_TabBar_CloseButtonPosition", + "SH_DockWidget_ButtonsHaveFrame", + "SH_ToolButtonStyle", + "SH_RequestSoftwareInputPanel", + "SH_ScrollBar_Transient", + "SH_Menu_SupportsSections", + "SH_ToolTip_WakeUpDelay", + "SH_ToolTip_FallAsleepDelay", + "SH_Widget_Animate", + "SH_Splitter_OpaqueResize", + "SH_ComboBox_UseNativePopup", + "SH_LineEdit_PasswordMaskDelay", + "SH_TabBar_ChangeCurrentDelay", + "SH_Menu_SubMenuUniDirection", + "SH_Menu_SubMenuUniDirectionFailCount", + "SH_Menu_SubMenuSloppySelectOtherActions", + "SH_Menu_SubMenuSloppyCloseTimeout", + "SH_Menu_SubMenuResetWhenReenteringParent", + "SH_Menu_SubMenuDontStartSloppyOnLeave", + "SH_ItemView_ScrollMode", + "SH_TitleBar_ShowToolTipsOnButtons", + "SH_Widget_Animation_Duration", + "SH_ComboBox_AllowWheelScrolling", + "SH_SpinBox_ButtonsInsideFrame", + "SH_SpinBox_StepModifier", + "SH_TabBar_AllowWheelScrolling", + "SH_Table_AlwaysDrawLeftTopGridLines", + "SH_SpinBox_SelectOnStep", + "SH_CustomBase" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "StandardPixmap", + "values": [ + "SP_TitleBarMenuButton", + "SP_TitleBarMinButton", + "SP_TitleBarMaxButton", + "SP_TitleBarCloseButton", + "SP_TitleBarNormalButton", + "SP_TitleBarShadeButton", + "SP_TitleBarUnshadeButton", + "SP_TitleBarContextHelpButton", + "SP_DockWidgetCloseButton", + "SP_MessageBoxInformation", + "SP_MessageBoxWarning", + "SP_MessageBoxCritical", + "SP_MessageBoxQuestion", + "SP_DesktopIcon", + "SP_TrashIcon", + "SP_ComputerIcon", + "SP_DriveFDIcon", + "SP_DriveHDIcon", + "SP_DriveCDIcon", + "SP_DriveDVDIcon", + "SP_DriveNetIcon", + "SP_DirOpenIcon", + "SP_DirClosedIcon", + "SP_DirLinkIcon", + "SP_DirLinkOpenIcon", + "SP_FileIcon", + "SP_FileLinkIcon", + "SP_ToolBarHorizontalExtensionButton", + "SP_ToolBarVerticalExtensionButton", + "SP_FileDialogStart", + "SP_FileDialogEnd", + "SP_FileDialogToParent", + "SP_FileDialogNewFolder", + "SP_FileDialogDetailedView", + "SP_FileDialogInfoView", + "SP_FileDialogContentsView", + "SP_FileDialogListView", + "SP_FileDialogBack", + "SP_DirIcon", + "SP_DialogOkButton", + "SP_DialogCancelButton", + "SP_DialogHelpButton", + "SP_DialogOpenButton", + "SP_DialogSaveButton", + "SP_DialogCloseButton", + "SP_DialogApplyButton", + "SP_DialogResetButton", + "SP_DialogDiscardButton", + "SP_DialogYesButton", + "SP_DialogNoButton", + "SP_ArrowUp", + "SP_ArrowDown", + "SP_ArrowLeft", + "SP_ArrowRight", + "SP_ArrowBack", + "SP_ArrowForward", + "SP_DirHomeIcon", + "SP_CommandLink", + "SP_VistaShield", + "SP_BrowserReload", + "SP_BrowserStop", + "SP_MediaPlay", + "SP_MediaStop", + "SP_MediaPause", + "SP_MediaSkipForward", + "SP_MediaSkipBackward", + "SP_MediaSeekForward", + "SP_MediaSeekBackward", + "SP_MediaVolume", + "SP_MediaVolumeMuted", + "SP_LineEditClearButton", + "SP_DialogYesToAllButton", + "SP_DialogNoToAllButton", + "SP_DialogSaveAllButton", + "SP_DialogAbortButton", + "SP_DialogRetryButton", + "SP_DialogIgnoreButton", + "SP_RestoreDefaultsButton", + "SP_TabCloseButton", + "NStandardPixmap", + "SP_CustomBase" + ] + } + ], + "lineNumber": 28, + "object": true, + "qualifiedClassName": "QStyle", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qstyle.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QStyleAnimation", + "lineNumber": 27, + "object": true, + "qualifiedClassName": "QStyleAnimation", + "slots": [ + { + "access": "public", + "index": 0, + "name": "start", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QAbstractAnimation" + } + ] + }, + { + "className": "QProgressStyleAnimation", + "lineNumber": 74, + "object": true, + "qualifiedClassName": "QProgressStyleAnimation", + "superClasses": [ + { + "access": "public", + "name": "QStyleAnimation" + } + ] + }, + { + "className": "QNumberStyleAnimation", + "lineNumber": 95, + "object": true, + "qualifiedClassName": "QNumberStyleAnimation", + "superClasses": [ + { + "access": "public", + "name": "QStyleAnimation" + } + ] + }, + { + "className": "QBlendStyleAnimation", + "lineNumber": 119, + "object": true, + "qualifiedClassName": "QBlendStyleAnimation", + "superClasses": [ + { + "access": "public", + "name": "QStyleAnimation" + } + ] + }, + { + "className": "QScrollbarStyleAnimation", + "lineNumber": 146, + "object": true, + "qualifiedClassName": "QScrollbarStyleAnimation", + "slots": [ + { + "access": "private", + "arguments": [ + { + "name": "time", + "type": "int" + } + ], + "index": 0, + "name": "updateCurrentTime", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QNumberStyleAnimation" + } + ] + } + ], + "inputFile": "qstyleanimation_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QStyledItemDelegate", + "lineNumber": 20, + "object": true, + "qualifiedClassName": "QStyledItemDelegate", + "superClasses": [ + { + "access": "public", + "name": "QAbstractItemDelegate" + } + ] + } + ], + "inputFile": "qstyleditemdelegate.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QStylePlugin", + "lineNumber": 18, + "object": true, + "qualifiedClassName": "QStylePlugin", + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qstyleplugin.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QStyleSheetStyle", + "lineNumber": 39, + "object": true, + "qualifiedClassName": "QStyleSheetStyle", + "superClasses": [ + { + "access": "public", + "name": "QWindowsStyle" + } + ] + }, + { + "className": "QStyleSheetStyleCaches", + "lineNumber": 146, + "object": true, + "qualifiedClassName": "QStyleSheetStyleCaches", + "slots": [ + { + "access": "public", + "arguments": [ + { + "type": "QObject*" + } + ], + "index": 0, + "name": "objectDestroyed", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QObject*" + } + ], + "index": 1, + "name": "styleDestroyed", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qstylesheetstyle_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QSystemTrayIcon", + "lineNumber": 25, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "toolTip", + "read": "toolTip", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setToolTip" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "icon", + "read": "icon", + "required": false, + "scriptable": true, + "stored": true, + "type": "QIcon", + "user": false, + "write": "setIcon" + }, + { + "constant": false, + "designable": false, + "final": false, + "index": 2, + "name": "visible", + "read": "isVisible", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setVisible" + } + ], + "qualifiedClassName": "QSystemTrayIcon", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "reason", + "type": "QSystemTrayIcon::ActivationReason" + } + ], + "index": 0, + "name": "activated", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "messageClicked", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "visible", + "type": "bool" + } + ], + "index": 2, + "name": "setVisible", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "show", + "returnType": "void" + }, + { + "access": "public", + "index": 4, + "name": "hide", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "title", + "type": "QString" + }, + { + "name": "msg", + "type": "QString" + }, + { + "name": "icon", + "type": "QIcon" + }, + { + "name": "msecs", + "type": "int" + } + ], + "index": 5, + "name": "showMessage", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "title", + "type": "QString" + }, + { + "name": "msg", + "type": "QString" + }, + { + "name": "icon", + "type": "QIcon" + } + ], + "index": 6, + "isCloned": true, + "name": "showMessage", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "title", + "type": "QString" + }, + { + "name": "msg", + "type": "QString" + }, + { + "name": "icon", + "type": "QSystemTrayIcon::MessageIcon" + }, + { + "name": "msecs", + "type": "int" + } + ], + "index": 7, + "name": "showMessage", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "title", + "type": "QString" + }, + { + "name": "msg", + "type": "QString" + }, + { + "name": "icon", + "type": "QSystemTrayIcon::MessageIcon" + } + ], + "index": 8, + "isCloned": true, + "name": "showMessage", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "title", + "type": "QString" + }, + { + "name": "msg", + "type": "QString" + } + ], + "index": 9, + "isCloned": true, + "name": "showMessage", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "type": "QPlatformSystemTrayIcon::ActivationReason" + } + ], + "index": 10, + "name": "_q_emitActivated", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qsystemtrayicon.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QBalloonTip", + "lineNumber": 80, + "object": true, + "qualifiedClassName": "QBalloonTip", + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + } + ], + "inputFile": "qsystemtrayicon_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QTabBar", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "Shape", + "values": [ + "RoundedNorth", + "RoundedSouth", + "RoundedWest", + "RoundedEast", + "TriangularNorth", + "TriangularSouth", + "TriangularWest", + "TriangularEast" + ] + } + ], + "lineNumber": 18, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "shape", + "read": "shape", + "required": false, + "scriptable": true, + "stored": true, + "type": "Shape", + "user": false, + "write": "setShape" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "currentIndex", + "notify": "currentChanged", + "read": "currentIndex", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setCurrentIndex" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "count", + "read": "count", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "drawBase", + "read": "drawBase", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setDrawBase" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "iconSize", + "read": "iconSize", + "required": false, + "scriptable": true, + "stored": true, + "type": "QSize", + "user": false, + "write": "setIconSize" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "elideMode", + "read": "elideMode", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::TextElideMode", + "user": false, + "write": "setElideMode" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "usesScrollButtons", + "read": "usesScrollButtons", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setUsesScrollButtons" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 7, + "name": "tabsClosable", + "read": "tabsClosable", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setTabsClosable" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 8, + "name": "selectionBehaviorOnRemove", + "read": "selectionBehaviorOnRemove", + "required": false, + "scriptable": true, + "stored": true, + "type": "SelectionBehavior", + "user": false, + "write": "setSelectionBehaviorOnRemove" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 9, + "name": "expanding", + "read": "expanding", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setExpanding" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 10, + "name": "movable", + "read": "isMovable", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setMovable" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 11, + "name": "documentMode", + "read": "documentMode", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setDocumentMode" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 12, + "name": "autoHide", + "read": "autoHide", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setAutoHide" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 13, + "name": "changeCurrentOnDrag", + "read": "changeCurrentOnDrag", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setChangeCurrentOnDrag" + } + ], + "qualifiedClassName": "QTabBar", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + } + ], + "index": 0, + "name": "currentChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + } + ], + "index": 1, + "name": "tabCloseRequested", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "from", + "type": "int" + }, + { + "name": "to", + "type": "int" + } + ], + "index": 2, + "name": "tabMoved", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + } + ], + "index": 3, + "name": "tabBarClicked", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + } + ], + "index": 4, + "name": "tabBarDoubleClicked", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + } + ], + "index": 5, + "name": "setCurrentIndex", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + } + ], + "inputFile": "qtabbar.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QTableView", + "lineNumber": 17, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "showGrid", + "read": "showGrid", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setShowGrid" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "gridStyle", + "read": "gridStyle", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::PenStyle", + "user": false, + "write": "setGridStyle" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "sortingEnabled", + "read": "isSortingEnabled", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setSortingEnabled" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "wordWrap", + "read": "wordWrap", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setWordWrap" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "cornerButtonEnabled", + "read": "isCornerButtonEnabled", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setCornerButtonEnabled" + } + ], + "qualifiedClassName": "QTableView", + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "row", + "type": "int" + } + ], + "index": 0, + "name": "selectRow", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "column", + "type": "int" + } + ], + "index": 1, + "name": "selectColumn", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "row", + "type": "int" + } + ], + "index": 2, + "name": "hideRow", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "column", + "type": "int" + } + ], + "index": 3, + "name": "hideColumn", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "row", + "type": "int" + } + ], + "index": 4, + "name": "showRow", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "column", + "type": "int" + } + ], + "index": 5, + "name": "showColumn", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "row", + "type": "int" + } + ], + "index": 6, + "name": "resizeRowToContents", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "resizeRowsToContents", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "column", + "type": "int" + } + ], + "index": 8, + "name": "resizeColumnToContents", + "returnType": "void" + }, + { + "access": "public", + "index": 9, + "name": "resizeColumnsToContents", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "column", + "type": "int" + }, + { + "name": "order", + "type": "Qt::SortOrder" + } + ], + "index": 10, + "name": "sortByColumn", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "show", + "type": "bool" + } + ], + "index": 11, + "name": "setShowGrid", + "returnType": "void" + }, + { + "access": "protected", + "arguments": [ + { + "name": "row", + "type": "int" + }, + { + "name": "oldIndex", + "type": "int" + }, + { + "name": "newIndex", + "type": "int" + } + ], + "index": 12, + "name": "rowMoved", + "returnType": "void" + }, + { + "access": "protected", + "arguments": [ + { + "name": "column", + "type": "int" + }, + { + "name": "oldIndex", + "type": "int" + }, + { + "name": "newIndex", + "type": "int" + } + ], + "index": 13, + "name": "columnMoved", + "returnType": "void" + }, + { + "access": "protected", + "arguments": [ + { + "name": "row", + "type": "int" + }, + { + "name": "oldHeight", + "type": "int" + }, + { + "name": "newHeight", + "type": "int" + } + ], + "index": 14, + "name": "rowResized", + "returnType": "void" + }, + { + "access": "protected", + "arguments": [ + { + "name": "column", + "type": "int" + }, + { + "name": "oldWidth", + "type": "int" + }, + { + "name": "newWidth", + "type": "int" + } + ], + "index": 15, + "name": "columnResized", + "returnType": "void" + }, + { + "access": "protected", + "arguments": [ + { + "name": "oldCount", + "type": "int" + }, + { + "name": "newCount", + "type": "int" + } + ], + "index": 16, + "name": "rowCountChanged", + "returnType": "void" + }, + { + "access": "protected", + "arguments": [ + { + "name": "oldCount", + "type": "int" + }, + { + "name": "newCount", + "type": "int" + } + ], + "index": 17, + "name": "columnCountChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QAbstractItemView" + } + ] + } + ], + "inputFile": "qtableview.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QTableWidget", + "lineNumber": 192, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "rowCount", + "read": "rowCount", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setRowCount" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "columnCount", + "read": "columnCount", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setColumnCount" + } + ], + "qualifiedClassName": "QTableWidget", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "item", + "type": "QTableWidgetItem*" + } + ], + "index": 0, + "name": "itemPressed", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "item", + "type": "QTableWidgetItem*" + } + ], + "index": 1, + "name": "itemClicked", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "item", + "type": "QTableWidgetItem*" + } + ], + "index": 2, + "name": "itemDoubleClicked", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "item", + "type": "QTableWidgetItem*" + } + ], + "index": 3, + "name": "itemActivated", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "item", + "type": "QTableWidgetItem*" + } + ], + "index": 4, + "name": "itemEntered", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "item", + "type": "QTableWidgetItem*" + } + ], + "index": 5, + "name": "itemChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "current", + "type": "QTableWidgetItem*" + }, + { + "name": "previous", + "type": "QTableWidgetItem*" + } + ], + "index": 6, + "name": "currentItemChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "itemSelectionChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "row", + "type": "int" + }, + { + "name": "column", + "type": "int" + } + ], + "index": 8, + "name": "cellPressed", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "row", + "type": "int" + }, + { + "name": "column", + "type": "int" + } + ], + "index": 9, + "name": "cellClicked", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "row", + "type": "int" + }, + { + "name": "column", + "type": "int" + } + ], + "index": 10, + "name": "cellDoubleClicked", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "row", + "type": "int" + }, + { + "name": "column", + "type": "int" + } + ], + "index": 11, + "name": "cellActivated", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "row", + "type": "int" + }, + { + "name": "column", + "type": "int" + } + ], + "index": 12, + "name": "cellEntered", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "row", + "type": "int" + }, + { + "name": "column", + "type": "int" + } + ], + "index": 13, + "name": "cellChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "currentRow", + "type": "int" + }, + { + "name": "currentColumn", + "type": "int" + }, + { + "name": "previousRow", + "type": "int" + }, + { + "name": "previousColumn", + "type": "int" + } + ], + "index": 14, + "name": "currentCellChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "item", + "type": "const QTableWidgetItem*" + }, + { + "name": "hint", + "type": "QAbstractItemView::ScrollHint" + } + ], + "index": 15, + "name": "scrollToItem", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "item", + "type": "const QTableWidgetItem*" + } + ], + "index": 16, + "isCloned": true, + "name": "scrollToItem", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "row", + "type": "int" + } + ], + "index": 17, + "name": "insertRow", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "column", + "type": "int" + } + ], + "index": 18, + "name": "insertColumn", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "row", + "type": "int" + } + ], + "index": 19, + "name": "removeRow", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "column", + "type": "int" + } + ], + "index": 20, + "name": "removeColumn", + "returnType": "void" + }, + { + "access": "public", + "index": 21, + "name": "clear", + "returnType": "void" + }, + { + "access": "public", + "index": 22, + "name": "clearContents", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QTableView" + } + ] + } + ], + "inputFile": "qtablewidget.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QTableWidgetMimeData", + "lineNumber": 31, + "object": true, + "qualifiedClassName": "QTableWidgetMimeData", + "superClasses": [ + { + "access": "public", + "name": "QMimeData" + } + ] + }, + { + "className": "QTableModel", + "lineNumber": 52, + "object": true, + "qualifiedClassName": "QTableModel", + "superClasses": [ + { + "access": "public", + "name": "QAbstractTableModel" + } + ] + } + ], + "inputFile": "qtablewidget_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QTabWidget", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "TabPosition", + "values": [ + "North", + "South", + "West", + "East" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "TabShape", + "values": [ + "Rounded", + "Triangular" + ] + } + ], + "lineNumber": 19, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "tabPosition", + "read": "tabPosition", + "required": false, + "scriptable": true, + "stored": true, + "type": "TabPosition", + "user": false, + "write": "setTabPosition" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "tabShape", + "read": "tabShape", + "required": false, + "scriptable": true, + "stored": true, + "type": "TabShape", + "user": false, + "write": "setTabShape" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "currentIndex", + "notify": "currentChanged", + "read": "currentIndex", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setCurrentIndex" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "count", + "read": "count", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "iconSize", + "read": "iconSize", + "required": false, + "scriptable": true, + "stored": true, + "type": "QSize", + "user": false, + "write": "setIconSize" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "elideMode", + "read": "elideMode", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::TextElideMode", + "user": false, + "write": "setElideMode" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "usesScrollButtons", + "read": "usesScrollButtons", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setUsesScrollButtons" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 7, + "name": "documentMode", + "read": "documentMode", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setDocumentMode" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 8, + "name": "tabsClosable", + "read": "tabsClosable", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setTabsClosable" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 9, + "name": "movable", + "read": "isMovable", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setMovable" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 10, + "name": "tabBarAutoHide", + "read": "tabBarAutoHide", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setTabBarAutoHide" + } + ], + "qualifiedClassName": "QTabWidget", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + } + ], + "index": 0, + "name": "currentChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + } + ], + "index": 1, + "name": "tabCloseRequested", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + } + ], + "index": 2, + "name": "tabBarClicked", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + } + ], + "index": 3, + "name": "tabBarDoubleClicked", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + } + ], + "index": 4, + "name": "setCurrentIndex", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "widget", + "type": "QWidget*" + } + ], + "index": 5, + "name": "setCurrentWidget", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + } + ], + "inputFile": "qtabwidget.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QTextBrowser", + "lineNumber": 17, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "source", + "read": "source", + "required": false, + "scriptable": true, + "stored": true, + "type": "QUrl", + "user": false, + "write": "setSource" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "sourceType", + "read": "sourceType", + "required": false, + "scriptable": true, + "stored": true, + "type": "QTextDocument::ResourceType", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "searchPaths", + "read": "searchPaths", + "required": false, + "scriptable": true, + "stored": true, + "type": "QStringList", + "user": false, + "write": "setSearchPaths" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "openExternalLinks", + "read": "openExternalLinks", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setOpenExternalLinks" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "openLinks", + "read": "openLinks", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setOpenLinks" + } + ], + "qualifiedClassName": "QTextBrowser", + "signals": [ + { + "access": "public", + "arguments": [ + { + "type": "bool" + } + ], + "index": 0, + "name": "backwardAvailable", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "bool" + } + ], + "index": 1, + "name": "forwardAvailable", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "historyChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QUrl" + } + ], + "index": 3, + "name": "sourceChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QUrl" + } + ], + "index": 4, + "name": "highlighted", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QUrl" + } + ], + "index": 5, + "name": "anchorClicked", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "name", + "type": "QUrl" + }, + { + "name": "type", + "type": "QTextDocument::ResourceType" + } + ], + "index": 6, + "name": "setSource", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "name", + "type": "QUrl" + } + ], + "index": 7, + "isCloned": true, + "name": "setSource", + "returnType": "void" + }, + { + "access": "public", + "index": 8, + "name": "backward", + "returnType": "void" + }, + { + "access": "public", + "index": 9, + "name": "forward", + "returnType": "void" + }, + { + "access": "public", + "index": 10, + "name": "home", + "returnType": "void" + }, + { + "access": "public", + "index": 11, + "name": "reload", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QTextEdit" + } + ] + } + ], + "inputFile": "qtextbrowser.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QTextEdit", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "LineWrapMode", + "values": [ + "NoWrap", + "WidgetWidth", + "FixedPixelWidth", + "FixedColumnWidth" + ] + }, + { + "alias": "AutoFormattingFlag", + "isClass": false, + "isFlag": true, + "name": "AutoFormatting", + "values": [ + "AutoNone", + "AutoBulletList", + "AutoAll" + ] + } + ], + "lineNumber": 26, + "methods": [ + { + "access": "public", + "arguments": [ + { + "name": "type", + "type": "int" + }, + { + "name": "name", + "type": "QUrl" + } + ], + "index": 35, + "name": "loadResource", + "returnType": "QVariant" + }, + { + "access": "public", + "arguments": [ + { + "name": "query", + "type": "Qt::InputMethodQuery" + }, + { + "name": "argument", + "type": "QVariant" + } + ], + "index": 36, + "name": "inputMethodQuery", + "returnType": "QVariant" + } + ], + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "autoFormatting", + "read": "autoFormatting", + "required": false, + "scriptable": true, + "stored": true, + "type": "AutoFormatting", + "user": false, + "write": "setAutoFormatting" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "tabChangesFocus", + "read": "tabChangesFocus", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setTabChangesFocus" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "documentTitle", + "read": "documentTitle", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setDocumentTitle" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "undoRedoEnabled", + "read": "isUndoRedoEnabled", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setUndoRedoEnabled" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "lineWrapMode", + "read": "lineWrapMode", + "required": false, + "scriptable": true, + "stored": true, + "type": "LineWrapMode", + "user": false, + "write": "setLineWrapMode" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "lineWrapColumnOrWidth", + "read": "lineWrapColumnOrWidth", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setLineWrapColumnOrWidth" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "readOnly", + "read": "isReadOnly", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setReadOnly" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 7, + "name": "markdown", + "notify": "textChanged", + "read": "toMarkdown", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setMarkdown" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 8, + "name": "html", + "notify": "textChanged", + "read": "toHtml", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": true, + "write": "setHtml" + }, + { + "constant": false, + "designable": false, + "final": false, + "index": 9, + "name": "plainText", + "read": "toPlainText", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setPlainText" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 10, + "name": "overwriteMode", + "read": "overwriteMode", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setOverwriteMode" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 11, + "name": "tabStopDistance", + "read": "tabStopDistance", + "required": false, + "scriptable": true, + "stored": true, + "type": "qreal", + "user": false, + "write": "setTabStopDistance" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 12, + "name": "acceptRichText", + "read": "acceptRichText", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setAcceptRichText" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 13, + "name": "cursorWidth", + "read": "cursorWidth", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setCursorWidth" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 14, + "name": "textInteractionFlags", + "read": "textInteractionFlags", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::TextInteractionFlags", + "user": false, + "write": "setTextInteractionFlags" + }, + { + "constant": false, + "designable": false, + "final": false, + "index": 15, + "name": "document", + "read": "document", + "required": false, + "scriptable": true, + "stored": true, + "type": "QTextDocument*", + "user": false, + "write": "setDocument" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 16, + "name": "placeholderText", + "read": "placeholderText", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setPlaceholderText" + } + ], + "qualifiedClassName": "QTextEdit", + "signals": [ + { + "access": "public", + "index": 0, + "name": "textChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "b", + "type": "bool" + } + ], + "index": 1, + "name": "undoAvailable", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "b", + "type": "bool" + } + ], + "index": 2, + "name": "redoAvailable", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "format", + "type": "QTextCharFormat" + } + ], + "index": 3, + "name": "currentCharFormatChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "b", + "type": "bool" + } + ], + "index": 4, + "name": "copyAvailable", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "selectionChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "cursorPositionChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "s", + "type": "qreal" + } + ], + "index": 7, + "name": "setFontPointSize", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "fontFamily", + "type": "QString" + } + ], + "index": 8, + "name": "setFontFamily", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "w", + "type": "int" + } + ], + "index": 9, + "name": "setFontWeight", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "b", + "type": "bool" + } + ], + "index": 10, + "name": "setFontUnderline", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "b", + "type": "bool" + } + ], + "index": 11, + "name": "setFontItalic", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "c", + "type": "QColor" + } + ], + "index": 12, + "name": "setTextColor", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "c", + "type": "QColor" + } + ], + "index": 13, + "name": "setTextBackgroundColor", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "f", + "type": "QFont" + } + ], + "index": 14, + "name": "setCurrentFont", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "a", + "type": "Qt::Alignment" + } + ], + "index": 15, + "name": "setAlignment", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "text", + "type": "QString" + } + ], + "index": 16, + "name": "setPlainText", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "text", + "type": "QString" + } + ], + "index": 17, + "name": "setHtml", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "markdown", + "type": "QString" + } + ], + "index": 18, + "name": "setMarkdown", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "text", + "type": "QString" + } + ], + "index": 19, + "name": "setText", + "returnType": "void" + }, + { + "access": "public", + "index": 20, + "name": "cut", + "returnType": "void" + }, + { + "access": "public", + "index": 21, + "name": "copy", + "returnType": "void" + }, + { + "access": "public", + "index": 22, + "name": "paste", + "returnType": "void" + }, + { + "access": "public", + "index": 23, + "name": "undo", + "returnType": "void" + }, + { + "access": "public", + "index": 24, + "name": "redo", + "returnType": "void" + }, + { + "access": "public", + "index": 25, + "name": "clear", + "returnType": "void" + }, + { + "access": "public", + "index": 26, + "name": "selectAll", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "text", + "type": "QString" + } + ], + "index": 27, + "name": "insertPlainText", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "text", + "type": "QString" + } + ], + "index": 28, + "name": "insertHtml", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "text", + "type": "QString" + } + ], + "index": 29, + "name": "append", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "name", + "type": "QString" + } + ], + "index": 30, + "name": "scrollToAnchor", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "range", + "type": "int" + } + ], + "index": 31, + "name": "zoomIn", + "returnType": "void" + }, + { + "access": "public", + "index": 32, + "isCloned": true, + "name": "zoomIn", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "range", + "type": "int" + } + ], + "index": 33, + "name": "zoomOut", + "returnType": "void" + }, + { + "access": "public", + "index": 34, + "isCloned": true, + "name": "zoomOut", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QAbstractScrollArea" + } + ] + } + ], + "inputFile": "qtextedit.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QToolBar", + "lineNumber": 22, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "movable", + "notify": "movableChanged", + "read": "isMovable", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setMovable" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "allowedAreas", + "notify": "allowedAreasChanged", + "read": "allowedAreas", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::ToolBarAreas", + "user": false, + "write": "setAllowedAreas" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "orientation", + "notify": "orientationChanged", + "read": "orientation", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::Orientation", + "user": false, + "write": "setOrientation" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "iconSize", + "notify": "iconSizeChanged", + "read": "iconSize", + "required": false, + "scriptable": true, + "stored": true, + "type": "QSize", + "user": false, + "write": "setIconSize" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "toolButtonStyle", + "notify": "toolButtonStyleChanged", + "read": "toolButtonStyle", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::ToolButtonStyle", + "user": false, + "write": "setToolButtonStyle" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "floating", + "read": "isFloating", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "floatable", + "read": "isFloatable", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setFloatable" + } + ], + "qualifiedClassName": "QToolBar", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "action", + "type": "QAction*" + } + ], + "index": 0, + "name": "actionTriggered", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "movable", + "type": "bool" + } + ], + "index": 1, + "name": "movableChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "allowedAreas", + "type": "Qt::ToolBarAreas" + } + ], + "index": 2, + "name": "allowedAreasChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "orientation", + "type": "Qt::Orientation" + } + ], + "index": 3, + "name": "orientationChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "iconSize", + "type": "QSize" + } + ], + "index": 4, + "name": "iconSizeChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "toolButtonStyle", + "type": "Qt::ToolButtonStyle" + } + ], + "index": 5, + "name": "toolButtonStyleChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "topLevel", + "type": "bool" + } + ], + "index": 6, + "name": "topLevelChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "visible", + "type": "bool" + } + ], + "index": 7, + "name": "visibilityChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "iconSize", + "type": "QSize" + } + ], + "index": 8, + "name": "setIconSize", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "toolButtonStyle", + "type": "Qt::ToolButtonStyle" + } + ], + "index": 9, + "name": "setToolButtonStyle", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "type": "bool" + } + ], + "index": 10, + "name": "_q_toggleView", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "type": "QSize" + } + ], + "index": 11, + "name": "_q_updateIconSize", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "type": "Qt::ToolButtonStyle" + } + ], + "index": 12, + "name": "_q_updateToolButtonStyle", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + } + ], + "inputFile": "qtoolbar.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QToolBarExtension", + "lineNumber": 25, + "object": true, + "qualifiedClassName": "QToolBarExtension", + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "o", + "type": "Qt::Orientation" + } + ], + "index": 0, + "name": "setOrientation", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QToolButton" + } + ] + } + ], + "inputFile": "qtoolbarextension_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QToolBarLayout", + "lineNumber": 41, + "object": true, + "qualifiedClassName": "QToolBarLayout", + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "b", + "type": "bool" + } + ], + "index": 0, + "name": "setExpanded", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QLayout" + } + ] + } + ], + "inputFile": "qtoolbarlayout_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QToolBarSeparator", + "lineNumber": 28, + "object": true, + "qualifiedClassName": "QToolBarSeparator", + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "orientation", + "type": "Qt::Orientation" + } + ], + "index": 0, + "name": "setOrientation", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + } + ], + "inputFile": "qtoolbarseparator_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QToolBox", + "lineNumber": 17, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "currentIndex", + "notify": "currentChanged", + "read": "currentIndex", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setCurrentIndex" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "count", + "read": "count", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + } + ], + "qualifiedClassName": "QToolBox", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + } + ], + "index": 0, + "name": "currentChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + } + ], + "index": 1, + "name": "setCurrentIndex", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "widget", + "type": "QWidget*" + } + ], + "index": 2, + "name": "setCurrentWidget", + "returnType": "void" + }, + { + "access": "private", + "index": 3, + "name": "_q_buttonClicked", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "type": "QObject*" + } + ], + "index": 4, + "name": "_q_widgetDestroyed", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QFrame" + } + ] + } + ], + "inputFile": "qtoolbox.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QToolButton", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "ToolButtonPopupMode", + "values": [ + "DelayedPopup", + "MenuButtonPopup", + "InstantPopup" + ] + } + ], + "lineNumber": 19, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "popupMode", + "read": "popupMode", + "required": false, + "scriptable": true, + "stored": true, + "type": "ToolButtonPopupMode", + "user": false, + "write": "setPopupMode" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "toolButtonStyle", + "read": "toolButtonStyle", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::ToolButtonStyle", + "user": false, + "write": "setToolButtonStyle" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "autoRaise", + "read": "autoRaise", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setAutoRaise" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "arrowType", + "read": "arrowType", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::ArrowType", + "user": false, + "write": "setArrowType" + } + ], + "qualifiedClassName": "QToolButton", + "signals": [ + { + "access": "public", + "arguments": [ + { + "type": "QAction*" + } + ], + "index": 0, + "name": "triggered", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "index": 1, + "name": "showMenu", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "style", + "type": "Qt::ToolButtonStyle" + } + ], + "index": 2, + "name": "setToolButtonStyle", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QAction*" + } + ], + "index": 3, + "name": "setDefaultAction", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QAbstractButton" + } + ] + } + ], + "inputFile": "qtoolbutton.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QTreeView", + "lineNumber": 19, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "autoExpandDelay", + "read": "autoExpandDelay", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setAutoExpandDelay" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "indentation", + "read": "indentation", + "required": false, + "reset": "resetIndentation", + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setIndentation" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "rootIsDecorated", + "read": "rootIsDecorated", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setRootIsDecorated" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "uniformRowHeights", + "read": "uniformRowHeights", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setUniformRowHeights" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "itemsExpandable", + "read": "itemsExpandable", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setItemsExpandable" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "sortingEnabled", + "read": "isSortingEnabled", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setSortingEnabled" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "animated", + "read": "isAnimated", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setAnimated" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 7, + "name": "allColumnsShowFocus", + "read": "allColumnsShowFocus", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setAllColumnsShowFocus" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 8, + "name": "wordWrap", + "read": "wordWrap", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setWordWrap" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 9, + "name": "headerHidden", + "read": "isHeaderHidden", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setHeaderHidden" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 10, + "name": "expandsOnDoubleClick", + "read": "expandsOnDoubleClick", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setExpandsOnDoubleClick" + } + ], + "qualifiedClassName": "QTreeView", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "QModelIndex" + } + ], + "index": 0, + "name": "expanded", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "QModelIndex" + } + ], + "index": 1, + "name": "collapsed", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "column", + "type": "int" + } + ], + "index": 2, + "name": "hideColumn", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "column", + "type": "int" + } + ], + "index": 3, + "name": "showColumn", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "QModelIndex" + } + ], + "index": 4, + "name": "expand", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "QModelIndex" + } + ], + "index": 5, + "name": "collapse", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "column", + "type": "int" + } + ], + "index": 6, + "name": "resizeColumnToContents", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "column", + "type": "int" + }, + { + "name": "order", + "type": "Qt::SortOrder" + } + ], + "index": 7, + "name": "sortByColumn", + "returnType": "void" + }, + { + "access": "public", + "index": 8, + "name": "expandAll", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "QModelIndex" + }, + { + "name": "depth", + "type": "int" + } + ], + "index": 9, + "name": "expandRecursively", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "QModelIndex" + } + ], + "index": 10, + "isCloned": true, + "name": "expandRecursively", + "returnType": "void" + }, + { + "access": "public", + "index": 11, + "name": "collapseAll", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "depth", + "type": "int" + } + ], + "index": 12, + "name": "expandToDepth", + "returnType": "void" + }, + { + "access": "protected", + "arguments": [ + { + "name": "column", + "type": "int" + }, + { + "name": "oldSize", + "type": "int" + }, + { + "name": "newSize", + "type": "int" + } + ], + "index": 13, + "name": "columnResized", + "returnType": "void" + }, + { + "access": "protected", + "arguments": [ + { + "name": "oldCount", + "type": "int" + }, + { + "name": "newCount", + "type": "int" + } + ], + "index": 14, + "name": "columnCountChanged", + "returnType": "void" + }, + { + "access": "protected", + "index": 15, + "name": "columnMoved", + "returnType": "void" + }, + { + "access": "protected", + "index": 16, + "name": "reexpand", + "returnType": "void" + }, + { + "access": "protected", + "arguments": [ + { + "name": "parent", + "type": "QModelIndex" + }, + { + "name": "first", + "type": "int" + }, + { + "name": "last", + "type": "int" + } + ], + "index": 17, + "name": "rowsRemoved", + "returnType": "void" + }, + { + "access": "protected", + "arguments": [ + { + "name": "value", + "type": "int" + } + ], + "index": 18, + "name": "verticalScrollbarValueChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QAbstractItemView" + } + ] + } + ], + "inputFile": "qtreeview.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QTreeWidget", + "lineNumber": 225, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "columnCount", + "read": "columnCount", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setColumnCount" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "topLevelItemCount", + "read": "topLevelItemCount", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + } + ], + "qualifiedClassName": "QTreeWidget", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "item", + "type": "QTreeWidgetItem*" + }, + { + "name": "column", + "type": "int" + } + ], + "index": 0, + "name": "itemPressed", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "item", + "type": "QTreeWidgetItem*" + }, + { + "name": "column", + "type": "int" + } + ], + "index": 1, + "name": "itemClicked", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "item", + "type": "QTreeWidgetItem*" + }, + { + "name": "column", + "type": "int" + } + ], + "index": 2, + "name": "itemDoubleClicked", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "item", + "type": "QTreeWidgetItem*" + }, + { + "name": "column", + "type": "int" + } + ], + "index": 3, + "name": "itemActivated", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "item", + "type": "QTreeWidgetItem*" + }, + { + "name": "column", + "type": "int" + } + ], + "index": 4, + "name": "itemEntered", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "item", + "type": "QTreeWidgetItem*" + }, + { + "name": "column", + "type": "int" + } + ], + "index": 5, + "name": "itemChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "item", + "type": "QTreeWidgetItem*" + } + ], + "index": 6, + "name": "itemExpanded", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "item", + "type": "QTreeWidgetItem*" + } + ], + "index": 7, + "name": "itemCollapsed", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "current", + "type": "QTreeWidgetItem*" + }, + { + "name": "previous", + "type": "QTreeWidgetItem*" + } + ], + "index": 8, + "name": "currentItemChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 9, + "name": "itemSelectionChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "item", + "type": "const QTreeWidgetItem*" + }, + { + "name": "hint", + "type": "QAbstractItemView::ScrollHint" + } + ], + "index": 10, + "name": "scrollToItem", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "item", + "type": "const QTreeWidgetItem*" + } + ], + "index": 11, + "isCloned": true, + "name": "scrollToItem", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "item", + "type": "const QTreeWidgetItem*" + } + ], + "index": 12, + "name": "expandItem", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "item", + "type": "const QTreeWidgetItem*" + } + ], + "index": 13, + "name": "collapseItem", + "returnType": "void" + }, + { + "access": "public", + "index": 14, + "name": "clear", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QTreeView" + } + ] + } + ], + "inputFile": "qtreewidget.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QTreeModel", + "lineNumber": 36, + "object": true, + "qualifiedClassName": "QTreeModel", + "superClasses": [ + { + "access": "public", + "name": "QAbstractItemModel" + } + ] + } + ], + "inputFile": "qtreewidget_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QUndoView", + "lineNumber": 21, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "emptyLabel", + "read": "emptyLabel", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setEmptyLabel" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "cleanIcon", + "read": "cleanIcon", + "required": false, + "scriptable": true, + "stored": true, + "type": "QIcon", + "user": false, + "write": "setCleanIcon" + } + ], + "qualifiedClassName": "QUndoView", + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "stack", + "type": "QUndoStack*" + } + ], + "index": 0, + "name": "setStack", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "group", + "type": "QUndoGroup*" + } + ], + "index": 1, + "name": "setGroup", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QListView" + } + ] + } + ], + "inputFile": "qundoview.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QWidget", + "lineNumber": 98, + "methods": [ + { + "access": "public", + "arguments": [ + { + "name": "rectangle", + "type": "QRect" + } + ], + "index": 27, + "name": "grab", + "returnType": "QPixmap" + }, + { + "access": "public", + "index": 28, + "isCloned": true, + "name": "grab", + "returnType": "QPixmap" + } + ], + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "modal", + "read": "isModal", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "windowModality", + "read": "windowModality", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::WindowModality", + "user": false, + "write": "setWindowModality" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "enabled", + "read": "isEnabled", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setEnabled" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "geometry", + "read": "geometry", + "required": false, + "scriptable": true, + "stored": true, + "type": "QRect", + "user": false, + "write": "setGeometry" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "frameGeometry", + "read": "frameGeometry", + "required": false, + "scriptable": true, + "stored": true, + "type": "QRect", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "normalGeometry", + "read": "normalGeometry", + "required": false, + "scriptable": true, + "stored": true, + "type": "QRect", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "x", + "read": "x", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 7, + "name": "y", + "read": "y", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": false, + "final": false, + "index": 8, + "name": "pos", + "read": "pos", + "required": false, + "scriptable": true, + "stored": false, + "type": "QPoint", + "user": false, + "write": "move" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 9, + "name": "frameSize", + "read": "frameSize", + "required": false, + "scriptable": true, + "stored": true, + "type": "QSize", + "user": false + }, + { + "constant": false, + "designable": false, + "final": false, + "index": 10, + "name": "size", + "read": "size", + "required": false, + "scriptable": true, + "stored": false, + "type": "QSize", + "user": false, + "write": "resize" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 11, + "name": "width", + "read": "width", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 12, + "name": "height", + "read": "height", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 13, + "name": "rect", + "read": "rect", + "required": false, + "scriptable": true, + "stored": true, + "type": "QRect", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 14, + "name": "childrenRect", + "read": "childrenRect", + "required": false, + "scriptable": true, + "stored": true, + "type": "QRect", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 15, + "name": "childrenRegion", + "read": "childrenRegion", + "required": false, + "scriptable": true, + "stored": true, + "type": "QRegion", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 16, + "name": "sizePolicy", + "read": "sizePolicy", + "required": false, + "scriptable": true, + "stored": true, + "type": "QSizePolicy", + "user": false, + "write": "setSizePolicy" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 17, + "name": "minimumSize", + "read": "minimumSize", + "required": false, + "scriptable": true, + "stored": true, + "type": "QSize", + "user": false, + "write": "setMinimumSize" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 18, + "name": "maximumSize", + "read": "maximumSize", + "required": false, + "scriptable": true, + "stored": true, + "type": "QSize", + "user": false, + "write": "setMaximumSize" + }, + { + "constant": false, + "designable": false, + "final": false, + "index": 19, + "name": "minimumWidth", + "read": "minimumWidth", + "required": false, + "scriptable": true, + "stored": false, + "type": "int", + "user": false, + "write": "setMinimumWidth" + }, + { + "constant": false, + "designable": false, + "final": false, + "index": 20, + "name": "minimumHeight", + "read": "minimumHeight", + "required": false, + "scriptable": true, + "stored": false, + "type": "int", + "user": false, + "write": "setMinimumHeight" + }, + { + "constant": false, + "designable": false, + "final": false, + "index": 21, + "name": "maximumWidth", + "read": "maximumWidth", + "required": false, + "scriptable": true, + "stored": false, + "type": "int", + "user": false, + "write": "setMaximumWidth" + }, + { + "constant": false, + "designable": false, + "final": false, + "index": 22, + "name": "maximumHeight", + "read": "maximumHeight", + "required": false, + "scriptable": true, + "stored": false, + "type": "int", + "user": false, + "write": "setMaximumHeight" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 23, + "name": "sizeIncrement", + "read": "sizeIncrement", + "required": false, + "scriptable": true, + "stored": true, + "type": "QSize", + "user": false, + "write": "setSizeIncrement" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 24, + "name": "baseSize", + "read": "baseSize", + "required": false, + "scriptable": true, + "stored": true, + "type": "QSize", + "user": false, + "write": "setBaseSize" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 25, + "name": "palette", + "read": "palette", + "required": false, + "scriptable": true, + "stored": true, + "type": "QPalette", + "user": false, + "write": "setPalette" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 26, + "name": "font", + "read": "font", + "required": false, + "scriptable": true, + "stored": true, + "type": "QFont", + "user": false, + "write": "setFont" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 27, + "name": "cursor", + "read": "cursor", + "required": false, + "reset": "unsetCursor", + "scriptable": true, + "stored": true, + "type": "QCursor", + "user": false, + "write": "setCursor" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 28, + "name": "mouseTracking", + "read": "hasMouseTracking", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setMouseTracking" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 29, + "name": "tabletTracking", + "read": "hasTabletTracking", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setTabletTracking" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 30, + "name": "isActiveWindow", + "read": "isActiveWindow", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 31, + "name": "focusPolicy", + "read": "focusPolicy", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::FocusPolicy", + "user": false, + "write": "setFocusPolicy" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 32, + "name": "focus", + "read": "hasFocus", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 33, + "name": "contextMenuPolicy", + "read": "contextMenuPolicy", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::ContextMenuPolicy", + "user": false, + "write": "setContextMenuPolicy" + }, + { + "constant": false, + "designable": false, + "final": false, + "index": 34, + "name": "updatesEnabled", + "read": "updatesEnabled", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setUpdatesEnabled" + }, + { + "constant": false, + "designable": false, + "final": false, + "index": 35, + "name": "visible", + "read": "isVisible", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setVisible" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 36, + "name": "minimized", + "read": "isMinimized", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 37, + "name": "maximized", + "read": "isMaximized", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 38, + "name": "fullScreen", + "read": "isFullScreen", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 39, + "name": "sizeHint", + "read": "sizeHint", + "required": false, + "scriptable": true, + "stored": true, + "type": "QSize", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 40, + "name": "minimumSizeHint", + "read": "minimumSizeHint", + "required": false, + "scriptable": true, + "stored": true, + "type": "QSize", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 41, + "name": "acceptDrops", + "read": "acceptDrops", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setAcceptDrops" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 42, + "name": "windowTitle", + "notify": "windowTitleChanged", + "read": "windowTitle", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setWindowTitle" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 43, + "name": "windowIcon", + "notify": "windowIconChanged", + "read": "windowIcon", + "required": false, + "scriptable": true, + "stored": true, + "type": "QIcon", + "user": false, + "write": "setWindowIcon" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 44, + "name": "windowIconText", + "notify": "windowIconTextChanged", + "read": "windowIconText", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setWindowIconText" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 45, + "name": "windowOpacity", + "read": "windowOpacity", + "required": false, + "scriptable": true, + "stored": true, + "type": "double", + "user": false, + "write": "setWindowOpacity" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 46, + "name": "windowModified", + "read": "isWindowModified", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setWindowModified" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 47, + "name": "toolTip", + "read": "toolTip", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setToolTip" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 48, + "name": "toolTipDuration", + "read": "toolTipDuration", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setToolTipDuration" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 49, + "name": "statusTip", + "read": "statusTip", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setStatusTip" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 50, + "name": "whatsThis", + "read": "whatsThis", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setWhatsThis" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 51, + "name": "accessibleName", + "read": "accessibleName", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setAccessibleName" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 52, + "name": "accessibleDescription", + "read": "accessibleDescription", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setAccessibleDescription" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 53, + "name": "layoutDirection", + "read": "layoutDirection", + "required": false, + "reset": "unsetLayoutDirection", + "scriptable": true, + "stored": true, + "type": "Qt::LayoutDirection", + "user": false, + "write": "setLayoutDirection" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 54, + "name": "autoFillBackground", + "read": "autoFillBackground", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setAutoFillBackground" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 55, + "name": "styleSheet", + "read": "styleSheet", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setStyleSheet" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 56, + "name": "locale", + "read": "locale", + "required": false, + "reset": "unsetLocale", + "scriptable": true, + "stored": true, + "type": "QLocale", + "user": false, + "write": "setLocale" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 57, + "name": "windowFilePath", + "read": "windowFilePath", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setWindowFilePath" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 58, + "name": "inputMethodHints", + "read": "inputMethodHints", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::InputMethodHints", + "user": false, + "write": "setInputMethodHints" + } + ], + "qualifiedClassName": "QWidget", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "title", + "type": "QString" + } + ], + "index": 0, + "name": "windowTitleChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "icon", + "type": "QIcon" + } + ], + "index": 1, + "name": "windowIconChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "iconText", + "type": "QString" + } + ], + "index": 2, + "name": "windowIconTextChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "pos", + "type": "QPoint" + } + ], + "index": 3, + "name": "customContextMenuRequested", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "type": "bool" + } + ], + "index": 4, + "name": "setEnabled", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "bool" + } + ], + "index": 5, + "name": "setDisabled", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "bool" + } + ], + "index": 6, + "name": "setWindowModified", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QString" + } + ], + "index": 7, + "name": "setWindowTitle", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "styleSheet", + "type": "QString" + } + ], + "index": 8, + "name": "setStyleSheet", + "returnType": "void" + }, + { + "access": "public", + "index": 9, + "name": "setFocus", + "returnType": "void" + }, + { + "access": "public", + "index": 10, + "name": "update", + "returnType": "void" + }, + { + "access": "public", + "index": 11, + "name": "repaint", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "visible", + "type": "bool" + } + ], + "index": 12, + "name": "setVisible", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "hidden", + "type": "bool" + } + ], + "index": 13, + "name": "setHidden", + "returnType": "void" + }, + { + "access": "public", + "index": 14, + "name": "show", + "returnType": "void" + }, + { + "access": "public", + "index": 15, + "name": "hide", + "returnType": "void" + }, + { + "access": "public", + "index": 16, + "name": "showMinimized", + "returnType": "void" + }, + { + "access": "public", + "index": 17, + "name": "showMaximized", + "returnType": "void" + }, + { + "access": "public", + "index": 18, + "name": "showFullScreen", + "returnType": "void" + }, + { + "access": "public", + "index": 19, + "name": "showNormal", + "returnType": "void" + }, + { + "access": "public", + "index": 20, + "name": "close", + "returnType": "bool" + }, + { + "access": "public", + "index": 21, + "name": "raise", + "returnType": "void" + }, + { + "access": "public", + "index": 22, + "name": "lower", + "returnType": "void" + }, + { + "access": "protected", + "arguments": [ + { + "name": "query", + "type": "Qt::InputMethodQuery" + } + ], + "index": 23, + "name": "updateMicroFocus", + "returnType": "void" + }, + { + "access": "protected", + "index": 24, + "isCloned": true, + "name": "updateMicroFocus", + "returnType": "void" + }, + { + "access": "private", + "index": 25, + "name": "_q_showIfNotHidden", + "returnType": "void" + }, + { + "access": "private", + "index": 26, + "name": "_q_closestWindowHandle", + "returnType": "QWindow*" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + }, + { + "access": "public", + "name": "QPaintDevice" + } + ] + } + ], + "inputFile": "qwidget.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QWidgetPrivate", + "enums": [ + { + "alias": "DrawWidgetFlag", + "isClass": false, + "isFlag": true, + "name": "DrawWidgetFlags", + "values": [ + "DrawAsRoot", + "DrawPaintOnScreen", + "DrawRecursive", + "DrawInvisible", + "DontSubtractOpaqueChildren", + "DontDrawOpaqueChildren", + "DontDrawNativeChildren", + "DontSetCompositionMode", + "UseEffectRegionBounds" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "Direction", + "values": [ + "DirectionNorth", + "DirectionEast", + "DirectionSouth", + "DirectionWest" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "CloseMode", + "values": [ + "CloseNoEvent", + "CloseWithEvent", + "CloseWithSpontaneousEvent" + ] + } + ], + "gadget": true, + "lineNumber": 179, + "qualifiedClassName": "QWidgetPrivate", + "superClasses": [ + { + "access": "public", + "name": "QObjectPrivate" + } + ] + } + ], + "inputFile": "qwidget_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QWidgetAction", + "lineNumber": 16, + "object": true, + "qualifiedClassName": "QWidgetAction", + "superClasses": [ + { + "access": "public", + "name": "QAction" + } + ] + } + ], + "inputFile": "qwidgetaction.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QWidgetAnimator", + "lineNumber": 30, + "object": true, + "qualifiedClassName": "QWidgetAnimator", + "slots": [ + { + "access": "private", + "index": 0, + "name": "animationFinished", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qwidgetanimator_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QWidgetLineControl", + "lineNumber": 50, + "object": true, + "qualifiedClassName": "QWidgetLineControl", + "signals": [ + { + "access": "public", + "arguments": [ + { + "type": "int" + }, + { + "type": "int" + } + ], + "index": 0, + "name": "cursorPositionChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "selectionChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QString" + } + ], + "index": 2, + "name": "displayTextChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QString" + } + ], + "index": 3, + "name": "textChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QString" + } + ], + "index": 4, + "name": "textEdited", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "resetInputContext", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "updateMicroFocus", + "returnType": "void" + }, + { + "access": "public", + "index": 7, + "name": "accepted", + "returnType": "void" + }, + { + "access": "public", + "index": 8, + "name": "editingFinished", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QRect" + } + ], + "index": 9, + "name": "updateNeeded", + "returnType": "void" + }, + { + "access": "public", + "index": 10, + "name": "inputRejected", + "returnType": "void" + } + ], + "slots": [ + { + "access": "private", + "index": 11, + "name": "_q_deleteSelected", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QInputControl" + } + ] + } + ], + "inputFile": "qwidgetlinecontrol_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QWidgetRepaintManager", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "UpdateTime", + "values": [ + "UpdateNow", + "UpdateLater" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "BufferState", + "values": [ + "BufferValid", + "BufferInvalid" + ] + } + ], + "gadget": true, + "lineNumber": 30, + "qualifiedClassName": "QWidgetRepaintManager" + } + ], + "inputFile": "qwidgetrepaintmanager_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QWidgetResizeHandler", + "lineNumber": 29, + "object": true, + "qualifiedClassName": "QWidgetResizeHandler", + "signals": [ + { + "access": "public", + "index": 0, + "name": "activate", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qwidgetresizehandler_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QWidgetTextControl", + "lineNumber": 50, + "methods": [ + { + "access": "public", + "arguments": [ + { + "name": "type", + "type": "int" + }, + { + "name": "name", + "type": "QUrl" + } + ], + "index": 36, + "name": "loadResource", + "returnType": "QVariant" + } + ], + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "html", + "notify": "textChanged", + "read": "toHtml", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": true, + "write": "setHtml" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "overwriteMode", + "read": "overwriteMode", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setOverwriteMode" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "acceptRichText", + "read": "acceptRichText", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setAcceptRichText" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "cursorWidth", + "read": "cursorWidth", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setCursorWidth" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "textInteractionFlags", + "read": "textInteractionFlags", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::TextInteractionFlags", + "user": false, + "write": "setTextInteractionFlags" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "openExternalLinks", + "read": "openExternalLinks", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setOpenExternalLinks" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 6, + "name": "ignoreUnusedNavigationEvents", + "read": "ignoreUnusedNavigationEvents", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": false, + "write": "setIgnoreUnusedNavigationEvents" + } + ], + "qualifiedClassName": "QWidgetTextControl", + "signals": [ + { + "access": "public", + "index": 0, + "name": "textChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "b", + "type": "bool" + } + ], + "index": 1, + "name": "undoAvailable", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "b", + "type": "bool" + } + ], + "index": 2, + "name": "redoAvailable", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "format", + "type": "QTextCharFormat" + } + ], + "index": 3, + "name": "currentCharFormatChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "b", + "type": "bool" + } + ], + "index": 4, + "name": "copyAvailable", + "returnType": "void" + }, + { + "access": "public", + "index": 5, + "name": "selectionChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "cursorPositionChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "rect", + "type": "QRectF" + } + ], + "index": 7, + "name": "updateRequest", + "returnType": "void" + }, + { + "access": "public", + "index": 8, + "isCloned": true, + "name": "updateRequest", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QSizeF" + } + ], + "index": 9, + "name": "documentSizeChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "newBlockCount", + "type": "int" + } + ], + "index": 10, + "name": "blockCountChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "rect", + "type": "QRectF" + } + ], + "index": 11, + "name": "visibilityRequest", + "returnType": "void" + }, + { + "access": "public", + "index": 12, + "name": "microFocusChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "link", + "type": "QString" + } + ], + "index": 13, + "name": "linkActivated", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "type": "QString" + } + ], + "index": 14, + "name": "linkHovered", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "block", + "type": "QTextBlock" + } + ], + "index": 15, + "name": "blockMarkerHovered", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "m", + "type": "bool" + } + ], + "index": 16, + "name": "modificationChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "text", + "type": "QString" + } + ], + "index": 17, + "name": "setPlainText", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "text", + "type": "QString" + } + ], + "index": 18, + "name": "setMarkdown", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "text", + "type": "QString" + } + ], + "index": 19, + "name": "setHtml", + "returnType": "void" + }, + { + "access": "public", + "index": 20, + "name": "cut", + "returnType": "void" + }, + { + "access": "public", + "index": 21, + "name": "copy", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "mode", + "type": "QClipboard::Mode" + } + ], + "index": 22, + "name": "paste", + "returnType": "void" + }, + { + "access": "public", + "index": 23, + "isCloned": true, + "name": "paste", + "returnType": "void" + }, + { + "access": "public", + "index": 24, + "name": "undo", + "returnType": "void" + }, + { + "access": "public", + "index": 25, + "name": "redo", + "returnType": "void" + }, + { + "access": "public", + "index": 26, + "name": "clear", + "returnType": "void" + }, + { + "access": "public", + "index": 27, + "name": "selectAll", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "text", + "type": "QString" + } + ], + "index": 28, + "name": "insertPlainText", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "text", + "type": "QString" + } + ], + "index": 29, + "name": "insertHtml", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "text", + "type": "QString" + } + ], + "index": 30, + "name": "append", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "html", + "type": "QString" + } + ], + "index": 31, + "name": "appendHtml", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "text", + "type": "QString" + } + ], + "index": 32, + "name": "appendPlainText", + "returnType": "void" + }, + { + "access": "public", + "index": 33, + "name": "adjustSize", + "returnType": "void" + }, + { + "access": "private", + "index": 34, + "name": "_q_deleteSelected", + "returnType": "void" + }, + { + "access": "private", + "index": 35, + "name": "_q_copyLink", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QInputControl" + } + ] + }, + { + "className": "QUnicodeControlCharacterMenu", + "lineNumber": 249, + "object": true, + "qualifiedClassName": "QUnicodeControlCharacterMenu", + "slots": [ + { + "access": "private", + "index": 0, + "name": "menuActionTriggered", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QMenu" + } + ] + } + ], + "inputFile": "qwidgettextcontrol_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QWidgetWindow", + "lineNumber": 34, + "object": true, + "qualifiedClassName": "QWidgetWindow", + "slots": [ + { + "access": "private", + "index": 0, + "name": "updateObjectName", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWindow" + } + ] + } + ], + "inputFile": "qwidgetwindow_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QWindowContainer", + "lineNumber": 25, + "object": true, + "qualifiedClassName": "QWindowContainer", + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + } + ], + "inputFile": "qwindowcontainer_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QWindowsStyle", + "lineNumber": 28, + "object": true, + "qualifiedClassName": "QWindowsStyle", + "superClasses": [ + { + "access": "public", + "name": "QCommonStyle" + } + ] + } + ], + "inputFile": "qwindowsstyle_p.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QWizard", + "enums": [ + { + "isClass": false, + "isFlag": false, + "name": "WizardStyle", + "values": [ + "ClassicStyle", + "ModernStyle", + "MacStyle", + "AeroStyle", + "NStyles" + ] + }, + { + "isClass": false, + "isFlag": false, + "name": "WizardOption", + "values": [ + "IndependentPages", + "IgnoreSubTitles", + "ExtendedWatermarkPixmap", + "NoDefaultButton", + "NoBackButtonOnStartPage", + "NoBackButtonOnLastPage", + "DisabledBackButtonOnLastPage", + "HaveNextButtonOnLastPage", + "HaveFinishButtonOnEarlyPages", + "NoCancelButton", + "CancelButtonOnLeft", + "HaveHelpButton", + "HelpButtonOnRight", + "HaveCustomButton1", + "HaveCustomButton2", + "HaveCustomButton3", + "NoCancelButtonOnLastPage" + ] + }, + { + "alias": "WizardOption", + "isClass": false, + "isFlag": true, + "name": "WizardOptions", + "values": [ + "IndependentPages", + "IgnoreSubTitles", + "ExtendedWatermarkPixmap", + "NoDefaultButton", + "NoBackButtonOnStartPage", + "NoBackButtonOnLastPage", + "DisabledBackButtonOnLastPage", + "HaveNextButtonOnLastPage", + "HaveFinishButtonOnEarlyPages", + "NoCancelButton", + "CancelButtonOnLeft", + "HaveHelpButton", + "HelpButtonOnRight", + "HaveCustomButton1", + "HaveCustomButton2", + "HaveCustomButton3", + "NoCancelButtonOnLastPage" + ] + } + ], + "lineNumber": 18, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "wizardStyle", + "read": "wizardStyle", + "required": false, + "scriptable": true, + "stored": true, + "type": "WizardStyle", + "user": false, + "write": "setWizardStyle" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "options", + "read": "options", + "required": false, + "scriptable": true, + "stored": true, + "type": "WizardOptions", + "user": false, + "write": "setOptions" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 2, + "name": "titleFormat", + "read": "titleFormat", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::TextFormat", + "user": false, + "write": "setTitleFormat" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 3, + "name": "subTitleFormat", + "read": "subTitleFormat", + "required": false, + "scriptable": true, + "stored": true, + "type": "Qt::TextFormat", + "user": false, + "write": "setSubTitleFormat" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 4, + "name": "startId", + "read": "startId", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setStartId" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 5, + "name": "currentId", + "notify": "currentIdChanged", + "read": "currentId", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false, + "write": "setCurrentId" + } + ], + "qualifiedClassName": "QWizard", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "id", + "type": "int" + } + ], + "index": 0, + "name": "currentIdChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "helpRequested", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "which", + "type": "int" + } + ], + "index": 2, + "name": "customButtonClicked", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "id", + "type": "int" + } + ], + "index": 3, + "name": "pageAdded", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "id", + "type": "int" + } + ], + "index": 4, + "name": "pageRemoved", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "index": 5, + "name": "back", + "returnType": "void" + }, + { + "access": "public", + "index": 6, + "name": "next", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "id", + "type": "int" + } + ], + "index": 7, + "name": "setCurrentId", + "returnType": "void" + }, + { + "access": "public", + "index": 8, + "name": "restart", + "returnType": "void" + }, + { + "access": "private", + "index": 9, + "name": "_q_emitCustomButtonClicked", + "returnType": "void" + }, + { + "access": "private", + "index": 10, + "name": "_q_updateButtonStates", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "type": "QObject*" + } + ], + "index": 11, + "name": "_q_handleFieldObjectDestroyed", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QDialog" + } + ] + }, + { + "className": "QWizardPage", + "lineNumber": 176, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "title", + "read": "title", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setTitle" + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "subTitle", + "read": "subTitle", + "required": false, + "scriptable": true, + "stored": true, + "type": "QString", + "user": false, + "write": "setSubTitle" + } + ], + "qualifiedClassName": "QWizardPage", + "signals": [ + { + "access": "public", + "index": 0, + "name": "completeChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "private", + "index": 1, + "name": "_q_maybeEmitCompleteChanged", + "returnType": "void" + }, + { + "access": "private", + "index": 2, + "name": "_q_updateCachedCompleteState", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + } + ], + "inputFile": "qwizard.h", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QCalendarTextNavigator", + "lineNumber": 607, + "object": true, + "qualifiedClassName": "QtPrivate::QCalendarTextNavigator", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "date", + "type": "QDate" + } + ], + "index": 0, + "name": "dateChanged", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "editingFinished", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + }, + { + "className": "QCalendarModel", + "lineNumber": 821, + "object": true, + "qualifiedClassName": "QtPrivate::QCalendarModel", + "superClasses": [ + { + "access": "public", + "name": "QAbstractTableModel" + } + ] + }, + { + "className": "QCalendarView", + "lineNumber": 899, + "object": true, + "qualifiedClassName": "QtPrivate::QCalendarView", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "date", + "type": "QDate" + } + ], + "index": 0, + "name": "showDate", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "date", + "type": "QDate" + }, + { + "name": "changeMonth", + "type": "bool" + } + ], + "index": 1, + "name": "changeDate", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "date", + "type": "QDate" + } + ], + "index": 2, + "name": "clicked", + "returnType": "void" + }, + { + "access": "public", + "index": 3, + "name": "editingFinished", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QTableView" + } + ] + }, + { + "className": "QCalendarDelegate", + "lineNumber": 1551, + "object": true, + "qualifiedClassName": "QtPrivate::QCalendarDelegate", + "superClasses": [ + { + "access": "public", + "name": "QStyledItemDelegate" + } + ] + }, + { + "className": "QPrevNextCalButton", + "lineNumber": 1596, + "object": true, + "qualifiedClassName": "QtPrivate::QPrevNextCalButton", + "superClasses": [ + { + "access": "public", + "name": "QToolButton" + } + ] + } + ], + "inputFile": "qcalendarwidget.cpp", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QWellArray", + "lineNumber": 166, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "selectedColumn", + "read": "selectedColumn", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + }, + { + "constant": false, + "designable": true, + "final": false, + "index": 1, + "name": "selectedRow", + "read": "selectedRow", + "required": false, + "scriptable": true, + "stored": true, + "type": "int", + "user": false + } + ], + "qualifiedClassName": "QtPrivate::QWellArray", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "row", + "type": "int" + }, + { + "name": "col", + "type": "int" + } + ], + "index": 0, + "name": "selected", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "row", + "type": "int" + }, + { + "name": "col", + "type": "int" + } + ], + "index": 1, + "name": "currentChanged", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "index", + "type": "int" + }, + { + "name": "color", + "type": "QRgb" + } + ], + "index": 2, + "name": "colorChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + }, + { + "className": "QColorPicker", + "lineNumber": 683, + "object": true, + "qualifiedClassName": "QtPrivate::QColorPicker", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "h", + "type": "int" + }, + { + "name": "s", + "type": "int" + } + ], + "index": 0, + "name": "newCol", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "h", + "type": "int" + }, + { + "name": "s", + "type": "int" + } + ], + "index": 1, + "name": "setCol", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QFrame" + } + ] + }, + { + "className": "QColorLuminancePicker", + "lineNumber": 724, + "object": true, + "qualifiedClassName": "QtPrivate::QColorLuminancePicker", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "h", + "type": "int" + }, + { + "name": "s", + "type": "int" + }, + { + "name": "v", + "type": "int" + } + ], + "index": 0, + "name": "newHsv", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "h", + "type": "int" + }, + { + "name": "s", + "type": "int" + }, + { + "name": "v", + "type": "int" + } + ], + "index": 1, + "name": "setCol", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "h", + "type": "int" + }, + { + "name": "s", + "type": "int" + } + ], + "index": 2, + "name": "setCol", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + }, + { + "className": "QColorShower", + "lineNumber": 990, + "object": true, + "qualifiedClassName": "QtPrivate::QColorShower", + "signals": [ + { + "access": "public", + "arguments": [ + { + "name": "rgb", + "type": "QRgb" + } + ], + "index": 0, + "name": "newCol", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "color", + "type": "QColor" + } + ], + "index": 1, + "name": "currentColorChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "rgb", + "type": "QRgb" + } + ], + "index": 2, + "name": "setRgb", + "returnType": "void" + }, + { + "access": "private", + "index": 3, + "name": "rgbEd", + "returnType": "void" + }, + { + "access": "private", + "index": 4, + "name": "hsvEd", + "returnType": "void" + }, + { + "access": "private", + "index": 5, + "name": "htmlEd", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + }, + { + "className": "QColorShowLabel", + "lineNumber": 1052, + "object": true, + "qualifiedClassName": "QtPrivate::QColorShowLabel", + "signals": [ + { + "access": "public", + "arguments": [ + { + "type": "QRgb" + } + ], + "index": 0, + "name": "colorDropped", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QFrame" + } + ] + } + ], + "inputFile": "qcolordialog.cpp", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QDockWidgetTitleButton", + "lineNumber": 88, + "object": true, + "qualifiedClassName": "QDockWidgetTitleButton", + "superClasses": [ + { + "access": "public", + "name": "QAbstractButton" + } + ] + } + ], + "inputFile": "qdockwidget.cpp", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QAlphaWidget", + "lineNumber": 29, + "object": true, + "qualifiedClassName": "QAlphaWidget", + "slots": [ + { + "access": "protected", + "index": 0, + "name": "render", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWidget" + }, + { + "access": "private", + "name": "QEffects" + } + ] + }, + { + "className": "QRollEffect", + "lineNumber": 309, + "object": true, + "qualifiedClassName": "QRollEffect", + "slots": [ + { + "access": "private", + "index": 0, + "name": "scroll", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWidget" + }, + { + "access": "private", + "name": "QEffects" + } + ] + } + ], + "inputFile": "qeffects.cpp", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QFontFamilyDelegate", + "lineNumber": 166, + "object": true, + "qualifiedClassName": "QFontFamilyDelegate", + "superClasses": [ + { + "access": "public", + "name": "QAbstractItemDelegate" + } + ] + } + ], + "inputFile": "qfontcombobox.cpp", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QFontListView", + "lineNumber": 32, + "object": true, + "qualifiedClassName": "QFontListView", + "signals": [ + { + "access": "public", + "arguments": [ + { + "type": "int" + } + ], + "index": 0, + "name": "highlighted", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QListView" + } + ] + } + ], + "inputFile": "qfontdialog.cpp", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QInputDialogSpinBox", + "lineNumber": 66, + "object": true, + "qualifiedClassName": "QInputDialogSpinBox", + "signals": [ + { + "access": "public", + "arguments": [ + { + "type": "bool" + } + ], + "index": 0, + "name": "textChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "private", + "index": 1, + "name": "notifyTextChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QSpinBox" + } + ] + }, + { + "className": "QInputDialogDoubleSpinBox", + "lineNumber": 101, + "object": true, + "qualifiedClassName": "QInputDialogDoubleSpinBox", + "signals": [ + { + "access": "public", + "arguments": [ + { + "type": "bool" + } + ], + "index": 0, + "name": "textChanged", + "returnType": "void" + } + ], + "slots": [ + { + "access": "private", + "index": 1, + "name": "notifyTextChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QDoubleSpinBox" + } + ] + } + ], + "inputFile": "qinputdialog.cpp", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QBooleanComboBox", + "lineNumber": 37, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "value", + "read": "value", + "required": false, + "scriptable": true, + "stored": true, + "type": "bool", + "user": true, + "write": "setValue" + } + ], + "qualifiedClassName": "QBooleanComboBox", + "superClasses": [ + { + "access": "public", + "name": "QComboBox" + } + ] + }, + { + "className": "QUIntSpinBox", + "lineNumber": 53, + "object": true, + "properties": [ + { + "constant": false, + "designable": true, + "final": false, + "index": 0, + "name": "value", + "notify": "uintValueChanged", + "read": "uintValue", + "required": false, + "scriptable": true, + "stored": true, + "type": "uint", + "user": true, + "write": "setUIntValue" + } + ], + "qualifiedClassName": "QUIntSpinBox", + "signals": [ + { + "access": "public", + "index": 0, + "name": "uintValueChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QSpinBox" + } + ] + } + ], + "inputFile": "qitemeditorfactory.cpp", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QListWidgetMimeData", + "lineNumber": 14, + "object": true, + "qualifiedClassName": "QListWidgetMimeData", + "superClasses": [ + { + "access": "public", + "name": "QMimeData" + } + ] + } + ], + "inputFile": "qlistwidget.cpp", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QMainWindowTabBar", + "lineNumber": 1888, + "object": true, + "qualifiedClassName": "QMainWindowTabBar", + "superClasses": [ + { + "access": "public", + "name": "QTabBar" + } + ] + } + ], + "inputFile": "qmainwindowlayout.cpp", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "ControlLabel", + "lineNumber": 359, + "object": true, + "qualifiedClassName": "QMdi::ControlLabel", + "signals": [ + { + "access": "public", + "index": 0, + "name": "_q_clicked", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "_q_doubleClicked", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + }, + { + "className": "ControllerWidget", + "lineNumber": 490, + "object": true, + "qualifiedClassName": "QMdi::ControllerWidget", + "signals": [ + { + "access": "public", + "index": 0, + "name": "_q_minimize", + "returnType": "void" + }, + { + "access": "public", + "index": 1, + "name": "_q_restore", + "returnType": "void" + }, + { + "access": "public", + "index": 2, + "name": "_q_close", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + } + ], + "inputFile": "qmdisubwindow.cpp", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QTornOffMenu", + "lineNumber": 53, + "object": true, + "qualifiedClassName": "QTornOffMenu", + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "action", + "type": "QAction*" + } + ], + "index": 0, + "name": "onTrigger", + "returnType": "void" + }, + { + "access": "public", + "arguments": [ + { + "name": "action", + "type": "QAction*" + } + ], + "index": 1, + "name": "onHovered", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QMenu" + } + ] + } + ], + "inputFile": "qmenu.cpp", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QMessageBoxDetailsText", + "lineNumber": 79, + "object": true, + "qualifiedClassName": "QMessageBoxDetailsText", + "slots": [ + { + "access": "private", + "arguments": [ + { + "name": "available", + "type": "bool" + } + ], + "index": 0, + "name": "textCopyAvailable", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + } + ], + "inputFile": "qmessagebox.cpp", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "CloseButton", + "lineNumber": 40, + "object": true, + "qualifiedClassName": "CloseButton", + "superClasses": [ + { + "access": "public", + "name": "QAbstractButton" + } + ] + } + ], + "inputFile": "qtabbar.cpp", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QTableCornerButton", + "lineNumber": 551, + "object": true, + "qualifiedClassName": "QTableCornerButton", + "superClasses": [ + { + "access": "public", + "name": "QAbstractButton" + } + ] + } + ], + "inputFile": "qtableview.cpp", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QToolBoxButton", + "lineNumber": 25, + "object": true, + "qualifiedClassName": "QToolBoxButton", + "superClasses": [ + { + "access": "public", + "name": "QAbstractButton" + } + ] + } + ], + "inputFile": "qtoolbox.cpp", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QTipLabel", + "lineNumber": 90, + "object": true, + "qualifiedClassName": "QTipLabel", + "slots": [ + { + "access": "public", + "index": 0, + "name": "styleSheetParentDestroyed", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QLabel" + } + ] + } + ], + "inputFile": "qtooltip.cpp", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QUndoModel", + "lineNumber": 17, + "object": true, + "qualifiedClassName": "QUndoModel", + "slots": [ + { + "access": "public", + "arguments": [ + { + "name": "stack", + "type": "QUndoStack*" + } + ], + "index": 0, + "name": "setStack", + "returnType": "void" + }, + { + "access": "private", + "index": 1, + "name": "stackChanged", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "obj", + "type": "QObject*" + } + ], + "index": 2, + "name": "stackDestroyed", + "returnType": "void" + }, + { + "access": "private", + "arguments": [ + { + "name": "index", + "type": "QModelIndex" + } + ], + "index": 3, + "name": "setStackCurrentIndex", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QAbstractItemModel" + } + ] + } + ], + "inputFile": "qundoview.cpp", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QWhatsThat", + "lineNumber": 100, + "object": true, + "qualifiedClassName": "QWhatsThat", + "superClasses": [ + { + "access": "public", + "name": "QWidget" + } + ] + }, + { + "className": "QWhatsThisAction", + "lineNumber": 447, + "object": true, + "qualifiedClassName": "QWhatsThisAction", + "slots": [ + { + "access": "private", + "index": 0, + "name": "actionTriggered", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QAction" + } + ] + } + ], + "inputFile": "qwhatsthis.cpp", + "outputRevision": 68 + }, + { + "classes": [ + { + "className": "QPlatformTextureListWatcher", + "lineNumber": 38, + "object": true, + "qualifiedClassName": "QPlatformTextureListWatcher", + "slots": [ + { + "access": "private", + "arguments": [ + { + "name": "locked", + "type": "bool" + } + ], + "index": 0, + "name": "onLockStatusChanged", + "returnType": "void" + } + ], + "superClasses": [ + { + "access": "public", + "name": "QObject" + } + ] + } + ], + "inputFile": "qwidgetrepaintmanager.cpp", + "outputRevision": 68 + } +] diff --git a/qt/6.8.1/msvc2022_64/metatypes/qt6xml_metatypes.json b/qt/6.8.1/msvc2022_64/metatypes/qt6xml_metatypes.json new file mode 100644 index 0000000000000000000000000000000000000000..0d4f101c7a37a4c875e6999bee1a287fdb733380 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/metatypes/qt6xml_metatypes.json @@ -0,0 +1,2 @@ +[ +] diff --git a/qt/6.8.1/msvc2022_64/mkspecs/REUSE.toml b/qt/6.8.1/msvc2022_64/mkspecs/REUSE.toml new file mode 100644 index 0000000000000000000000000000000000000000..6f4d70f3ec773643c82e3ddac37bab098247c80f --- /dev/null +++ b/qt/6.8.1/msvc2022_64/mkspecs/REUSE.toml @@ -0,0 +1,20 @@ +version = 1 + +[[annotations]] +path = ["**.plist*", "features/data/configure.json", "features/data/testserver/Dockerfile", + "features/data/testserver/docker-compose-common.yml", "features/mac/sdk.mk", + "features/uikit/xcodebuild.mk", "features/data/dummy.cpp", "features/data/macros.cpp", + "macx-ios-clang/LaunchScreen.storyboard", "macx-xcode/WorkspaceSettings.xcsettings", + "macx-xcode/default.xcscheme"] +precedence = "closest" +comment = "build system" +SPDX-FileCopyrightText = "Copyright (C) 2024 The Qt Company Ltd." +SPDX-License-Identifier = "BSD-3-Clause" + +[[annotations]] +path = ["modules/README"] +comment = "documentation" +precedence = "closest" +SPDX-FileCopyrightText = "Copyright (C) 2024 The Qt Company Ltd." +SPDX-License-Identifier = "LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only" + diff --git a/qt/6.8.1/msvc2022_64/mkspecs/qconfig.pri b/qt/6.8.1/msvc2022_64/mkspecs/qconfig.pri new file mode 100644 index 0000000000000000000000000000000000000000..0af9ca32b0ea99a6c1e44187e6c610f2cf437fe8 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/mkspecs/qconfig.pri @@ -0,0 +1,16 @@ +QT_ARCH = x86_64 +QT_BUILDABI = x86_64-little_endian-lp64 +QT_LIBCPP_ABI_TAG = +QT.global.enabled_features = version_tagging shared debug_and_release signaling_nan thread future concurrent dbus opensslv30 shared intelcet shared debug_and_release openssl +QT.global.disabled_features = static cross_compile pkg-config separate_debug_info appstore-compliant simulator_and_device rpath force_asserts framework c++20 c++2a c++2b reduce_relocations wasm-simd128 wasm-exceptions zstd openssl-linked opensslv11 +QT.global.disabled_features += release build_all +QT_CONFIG += shared no-pkg-config debug_and_release openssl release debug +CONFIG += shared plugin_manifest intelcet +QT_VERSION = 6.8.1 +QT_MAJOR_VERSION = 6 +QT_MINOR_VERSION = 8 +QT_PATCH_VERSION = 1 + +QT_MSVC_MAJOR_VERSION = 19 +QT_MSVC_MINOR_VERSION = 39 +QT_MSVC_PATCH_VERSION = 33520 diff --git a/qt/6.8.1/msvc2022_64/mkspecs/qmodule.pri b/qt/6.8.1/msvc2022_64/mkspecs/qmodule.pri new file mode 100644 index 0000000000000000000000000000000000000000..f10469a8de0e2dfe97ef68687ca3ed7251ae3867 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/mkspecs/qmodule.pri @@ -0,0 +1,7 @@ +QT_CPU_FEATURES.x86_64 = +QT.global_private.enabled_features = debug x86intrin sse2 sse3 ssse3 sse4_1 sse4_2 avx f16c avx2 avx512f avx512er avx512cd avx512pf avx512dq avx512bw avx512vl avx512ifma avx512vbmi avx512vbmi2 aesni vaes rdrnd rdseed shani localtime_s alloca_malloc_h alloca dbus gui network printsupport sql testlib widgets xml openssl relocatable intelcet msvc_obj_debug_info force_debug_info largefile precompile_header sse2 sse3 ssse3 sse4_1 sse4_2 avx f16c avx2 avx512f avx512er avx512cd avx512pf avx512dq avx512bw avx512vl avx512ifma avx512vbmi avx512vbmi2 aesni vaes rdrnd rdseed shani +QT.global_private.disabled_features = use_bfd_linker use_gold_linker use_lld_linker use_mold_linker android-style-assets gc_binaries developer-build private_tests elf_private_full_version reduce_exports no_direct_extern_access mips_dsp mips_dspr2 neon arm_crc32 arm_crypto localtime_r posix_fallocate alloca_h system-zlib stdlib-libcpp dbus-linked libudev dlopen glibc_fortify_source trivial_auto_var_init_pattern stack_protector stack_clash_protection libstdcpp_assertions libcpp_hardening relro_now_linker +CONFIG += msvc_obj_debug_info force_debug_info largefile precompile_header sse2 sse3 ssse3 sse4_1 sse4_2 avx f16c avx2 avx512f avx512er avx512cd avx512pf avx512dq avx512bw avx512vl avx512ifma avx512vbmi avx512vbmi2 aesni vaes rdrnd rdseed shani +QT_COORD_TYPE = double +QT_BUILD_PARTS = libs tools + diff --git a/qt/6.8.1/msvc2022_64/modules/Concurrent.json b/qt/6.8.1/msvc2022_64/modules/Concurrent.json new file mode 100644 index 0000000000000000000000000000000000000000..a2e9a0d9bbe7e7a067d6861a3e620eda4eda148b --- /dev/null +++ b/qt/6.8.1/msvc2022_64/modules/Concurrent.json @@ -0,0 +1,13 @@ +{ + "name": "Concurrent", + "repository": "qtbase", + "version": "6.8.1", + "built_with": { + "compiler_id": "MSVC", + "compiler_target": "", + "compiler_version": "19.39.33520.0", + "cross_compiled": false, + "target_system": "Windows", + "architecture": "x86_64" + } +} diff --git a/qt/6.8.1/msvc2022_64/modules/Core.json b/qt/6.8.1/msvc2022_64/modules/Core.json new file mode 100644 index 0000000000000000000000000000000000000000..59cac42bfe74aff012d49bfbb92c51e4d91b2759 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/modules/Core.json @@ -0,0 +1,13 @@ +{ + "name": "Core", + "repository": "qtbase", + "version": "6.8.1", + "built_with": { + "compiler_id": "MSVC", + "compiler_target": "", + "compiler_version": "19.39.33520.0", + "cross_compiled": false, + "target_system": "Windows", + "architecture": "x86_64" + } +} diff --git a/qt/6.8.1/msvc2022_64/modules/DBus.json b/qt/6.8.1/msvc2022_64/modules/DBus.json new file mode 100644 index 0000000000000000000000000000000000000000..bfb69ae316d84f6ee1e19ad80248c96d20935c87 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/modules/DBus.json @@ -0,0 +1,13 @@ +{ + "name": "DBus", + "repository": "qtbase", + "version": "6.8.1", + "built_with": { + "compiler_id": "MSVC", + "compiler_target": "", + "compiler_version": "19.39.33520.0", + "cross_compiled": false, + "target_system": "Windows", + "architecture": "x86_64" + } +} diff --git a/qt/6.8.1/msvc2022_64/modules/Designer.json b/qt/6.8.1/msvc2022_64/modules/Designer.json new file mode 100644 index 0000000000000000000000000000000000000000..7d030d37766a4fb1ea2b1295735db9201a4a8160 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/modules/Designer.json @@ -0,0 +1,14 @@ +{ + "name": "Designer", + "repository": "qttools", + "version": "6.8.1", + "plugin_types": ["designer"], + "built_with": { + "compiler_id": "MSVC", + "compiler_target": "", + "compiler_version": "19.39.33520.0", + "cross_compiled": false, + "target_system": "Windows", + "architecture": "x86_64" + } +} diff --git a/qt/6.8.1/msvc2022_64/modules/DesignerComponentsPrivate.json b/qt/6.8.1/msvc2022_64/modules/DesignerComponentsPrivate.json new file mode 100644 index 0000000000000000000000000000000000000000..6e8addd3d2f14f47d3e22f89c82a7085c353da76 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/modules/DesignerComponentsPrivate.json @@ -0,0 +1,14 @@ +{ + "name": "DesignerComponentsPrivate", + "repository": "qttools", + "version": "6.8.1", + "internal": true, + "built_with": { + "compiler_id": "MSVC", + "compiler_target": "", + "compiler_version": "19.39.33520.0", + "cross_compiled": false, + "target_system": "Windows", + "architecture": "x86_64" + } +} diff --git a/qt/6.8.1/msvc2022_64/modules/DeviceDiscoverySupportPrivate.json b/qt/6.8.1/msvc2022_64/modules/DeviceDiscoverySupportPrivate.json new file mode 100644 index 0000000000000000000000000000000000000000..6f10728e1ca61d58be7fe95c053f5bdd4feb9c53 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/modules/DeviceDiscoverySupportPrivate.json @@ -0,0 +1,14 @@ +{ + "name": "DeviceDiscoverySupportPrivate", + "repository": "qtbase", + "version": "6.8.1", + "internal": true, + "built_with": { + "compiler_id": "MSVC", + "compiler_target": "", + "compiler_version": "19.39.33520.0", + "cross_compiled": false, + "target_system": "Windows", + "architecture": "x86_64" + } +} diff --git a/qt/6.8.1/msvc2022_64/modules/EntryPointPrivate.json b/qt/6.8.1/msvc2022_64/modules/EntryPointPrivate.json new file mode 100644 index 0000000000000000000000000000000000000000..116ada0f29362a25b063c16cea644242b2d26e2f --- /dev/null +++ b/qt/6.8.1/msvc2022_64/modules/EntryPointPrivate.json @@ -0,0 +1,14 @@ +{ + "name": "EntryPointPrivate", + "repository": "qtbase", + "version": "6.8.1", + "internal": true, + "built_with": { + "compiler_id": "MSVC", + "compiler_target": "", + "compiler_version": "19.39.33520.0", + "cross_compiled": false, + "target_system": "Windows", + "architecture": "x86_64" + } +} diff --git a/qt/6.8.1/msvc2022_64/modules/ExampleIconsPrivate.json b/qt/6.8.1/msvc2022_64/modules/ExampleIconsPrivate.json new file mode 100644 index 0000000000000000000000000000000000000000..6119ea7a643f889739d6ec8d13b05741b0ec06c1 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/modules/ExampleIconsPrivate.json @@ -0,0 +1,14 @@ +{ + "name": "ExampleIconsPrivate", + "repository": "qtbase", + "version": "6.8.1", + "internal": true, + "built_with": { + "compiler_id": "MSVC", + "compiler_target": "", + "compiler_version": "19.39.33520.0", + "cross_compiled": false, + "target_system": "Windows", + "architecture": "x86_64" + } +} diff --git a/qt/6.8.1/msvc2022_64/modules/ExamplesAssetDownloaderPrivate.json b/qt/6.8.1/msvc2022_64/modules/ExamplesAssetDownloaderPrivate.json new file mode 100644 index 0000000000000000000000000000000000000000..fff1f29e0cce740115a93b37e6d5d2daf85ab541 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/modules/ExamplesAssetDownloaderPrivate.json @@ -0,0 +1,14 @@ +{ + "name": "ExamplesAssetDownloaderPrivate", + "repository": "qtbase", + "version": "6.8.1", + "internal": true, + "built_with": { + "compiler_id": "MSVC", + "compiler_target": "", + "compiler_version": "19.39.33520.0", + "cross_compiled": false, + "target_system": "Windows", + "architecture": "x86_64" + } +} diff --git a/qt/6.8.1/msvc2022_64/modules/FbSupportPrivate.json b/qt/6.8.1/msvc2022_64/modules/FbSupportPrivate.json new file mode 100644 index 0000000000000000000000000000000000000000..2c604cec537a61e2fb11c58dac05ad1a3fc5aa97 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/modules/FbSupportPrivate.json @@ -0,0 +1,14 @@ +{ + "name": "FbSupportPrivate", + "repository": "qtbase", + "version": "6.8.1", + "internal": true, + "built_with": { + "compiler_id": "MSVC", + "compiler_target": "", + "compiler_version": "19.39.33520.0", + "cross_compiled": false, + "target_system": "Windows", + "architecture": "x86_64" + } +} diff --git a/qt/6.8.1/msvc2022_64/modules/FreetypePrivate.json b/qt/6.8.1/msvc2022_64/modules/FreetypePrivate.json new file mode 100644 index 0000000000000000000000000000000000000000..290ed5d131dfe13932a7076baf16d07734883863 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/modules/FreetypePrivate.json @@ -0,0 +1,14 @@ +{ + "name": "FreetypePrivate", + "repository": "qtbase", + "version": "6.8.1", + "internal": true, + "built_with": { + "compiler_id": "MSVC", + "compiler_target": "", + "compiler_version": "19.39.33520.0", + "cross_compiled": false, + "target_system": "Windows", + "architecture": "x86_64" + } +} diff --git a/qt/6.8.1/msvc2022_64/modules/Gui.json b/qt/6.8.1/msvc2022_64/modules/Gui.json new file mode 100644 index 0000000000000000000000000000000000000000..1246c7c2df8f95b4c9dd92c2dc53aff398354643 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/modules/Gui.json @@ -0,0 +1,14 @@ +{ + "name": "Gui", + "repository": "qtbase", + "version": "6.8.1", + "plugin_types": ["accessiblebridge", "platforms", "platforms/darwin", "xcbglintegrations", "platformthemes", "platforminputcontexts", "generic", "iconengines", "imageformats", "egldeviceintegrations"], + "built_with": { + "compiler_id": "MSVC", + "compiler_target": "", + "compiler_version": "19.39.33520.0", + "cross_compiled": false, + "target_system": "Windows", + "architecture": "x86_64" + } +} diff --git a/qt/6.8.1/msvc2022_64/modules/HarfbuzzPrivate.json b/qt/6.8.1/msvc2022_64/modules/HarfbuzzPrivate.json new file mode 100644 index 0000000000000000000000000000000000000000..75906e0372fc7465759d41530d5e687d7427611b --- /dev/null +++ b/qt/6.8.1/msvc2022_64/modules/HarfbuzzPrivate.json @@ -0,0 +1,14 @@ +{ + "name": "HarfbuzzPrivate", + "repository": "qtbase", + "version": "6.8.1", + "internal": true, + "built_with": { + "compiler_id": "MSVC", + "compiler_target": "", + "compiler_version": "19.39.33520.0", + "cross_compiled": false, + "target_system": "Windows", + "architecture": "x86_64" + } +} diff --git a/qt/6.8.1/msvc2022_64/modules/Help.json b/qt/6.8.1/msvc2022_64/modules/Help.json new file mode 100644 index 0000000000000000000000000000000000000000..6340b5c5eda0638a91f8f07eb56b1e65c032d8c5 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/modules/Help.json @@ -0,0 +1,14 @@ +{ + "name": "Help", + "repository": "qttools", + "version": "6.8.1", + "plugin_types": ["help"], + "built_with": { + "compiler_id": "MSVC", + "compiler_target": "", + "compiler_version": "19.39.33520.0", + "cross_compiled": false, + "target_system": "Windows", + "architecture": "x86_64" + } +} diff --git a/qt/6.8.1/msvc2022_64/modules/JpegPrivate.json b/qt/6.8.1/msvc2022_64/modules/JpegPrivate.json new file mode 100644 index 0000000000000000000000000000000000000000..8cd9bff4a5a40261b1742428636f175df88d43bb --- /dev/null +++ b/qt/6.8.1/msvc2022_64/modules/JpegPrivate.json @@ -0,0 +1,14 @@ +{ + "name": "JpegPrivate", + "repository": "qtbase", + "version": "6.8.1", + "internal": true, + "built_with": { + "compiler_id": "MSVC", + "compiler_target": "", + "compiler_version": "19.39.33520.0", + "cross_compiled": false, + "target_system": "Windows", + "architecture": "x86_64" + } +} diff --git a/qt/6.8.1/msvc2022_64/modules/LabsAnimation.json b/qt/6.8.1/msvc2022_64/modules/LabsAnimation.json new file mode 100644 index 0000000000000000000000000000000000000000..4610fe931648733f4cd74d3511159301fa6f2549 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/modules/LabsAnimation.json @@ -0,0 +1,13 @@ +{ + "name": "LabsAnimation", + "repository": "qtdeclarative", + "version": "6.8.1", + "built_with": { + "compiler_id": "MSVC", + "compiler_target": "", + "compiler_version": "19.39.33520.0", + "cross_compiled": false, + "target_system": "Windows", + "architecture": "x86_64" + } +} diff --git a/qt/6.8.1/msvc2022_64/modules/LabsFolderListModel.json b/qt/6.8.1/msvc2022_64/modules/LabsFolderListModel.json new file mode 100644 index 0000000000000000000000000000000000000000..9e0636303f7460887384acbcc7a0d6936af9fb86 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/modules/LabsFolderListModel.json @@ -0,0 +1,13 @@ +{ + "name": "LabsFolderListModel", + "repository": "qtdeclarative", + "version": "6.8.1", + "built_with": { + "compiler_id": "MSVC", + "compiler_target": "", + "compiler_version": "19.39.33520.0", + "cross_compiled": false, + "target_system": "Windows", + "architecture": "x86_64" + } +} diff --git a/qt/6.8.1/msvc2022_64/modules/LabsPlatform.json b/qt/6.8.1/msvc2022_64/modules/LabsPlatform.json new file mode 100644 index 0000000000000000000000000000000000000000..6951bfe3420fc7946ec45a8f6ac8d212953fce99 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/modules/LabsPlatform.json @@ -0,0 +1,13 @@ +{ + "name": "LabsPlatform", + "repository": "qtdeclarative", + "version": "6.8.1", + "built_with": { + "compiler_id": "MSVC", + "compiler_target": "", + "compiler_version": "19.39.33520.0", + "cross_compiled": false, + "target_system": "Windows", + "architecture": "x86_64" + } +} diff --git a/qt/6.8.1/msvc2022_64/modules/LabsQmlModels.json b/qt/6.8.1/msvc2022_64/modules/LabsQmlModels.json new file mode 100644 index 0000000000000000000000000000000000000000..9fadb3ef31e5aada8386d175e07bf6af6b58bd1a --- /dev/null +++ b/qt/6.8.1/msvc2022_64/modules/LabsQmlModels.json @@ -0,0 +1,13 @@ +{ + "name": "LabsQmlModels", + "repository": "qtdeclarative", + "version": "6.8.1", + "built_with": { + "compiler_id": "MSVC", + "compiler_target": "", + "compiler_version": "19.39.33520.0", + "cross_compiled": false, + "target_system": "Windows", + "architecture": "x86_64" + } +} diff --git a/qt/6.8.1/msvc2022_64/modules/LabsSettings.json b/qt/6.8.1/msvc2022_64/modules/LabsSettings.json new file mode 100644 index 0000000000000000000000000000000000000000..02823dd6a4d14e300934b4f00f03bcc3cb886251 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/modules/LabsSettings.json @@ -0,0 +1,13 @@ +{ + "name": "LabsSettings", + "repository": "qtdeclarative", + "version": "6.8.1", + "built_with": { + "compiler_id": "MSVC", + "compiler_target": "", + "compiler_version": "19.39.33520.0", + "cross_compiled": false, + "target_system": "Windows", + "architecture": "x86_64" + } +} diff --git a/qt/6.8.1/msvc2022_64/modules/LabsSharedImage.json b/qt/6.8.1/msvc2022_64/modules/LabsSharedImage.json new file mode 100644 index 0000000000000000000000000000000000000000..71e3e9adb8acbe899833826fce1a0bb3eb1e4117 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/modules/LabsSharedImage.json @@ -0,0 +1,13 @@ +{ + "name": "LabsSharedImage", + "repository": "qtdeclarative", + "version": "6.8.1", + "built_with": { + "compiler_id": "MSVC", + "compiler_target": "", + "compiler_version": "19.39.33520.0", + "cross_compiled": false, + "target_system": "Windows", + "architecture": "x86_64" + } +} diff --git a/qt/6.8.1/msvc2022_64/modules/LabsWavefrontMesh.json b/qt/6.8.1/msvc2022_64/modules/LabsWavefrontMesh.json new file mode 100644 index 0000000000000000000000000000000000000000..fdbdcf484ce84b29262a0ce50677e01857f53173 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/modules/LabsWavefrontMesh.json @@ -0,0 +1,13 @@ +{ + "name": "LabsWavefrontMesh", + "repository": "qtdeclarative", + "version": "6.8.1", + "built_with": { + "compiler_id": "MSVC", + "compiler_target": "", + "compiler_version": "19.39.33520.0", + "cross_compiled": false, + "target_system": "Windows", + "architecture": "x86_64" + } +} diff --git a/qt/6.8.1/msvc2022_64/modules/Linguist.json b/qt/6.8.1/msvc2022_64/modules/Linguist.json new file mode 100644 index 0000000000000000000000000000000000000000..32978e557a05feea065e5ab7f2b79fba1bf4b652 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/modules/Linguist.json @@ -0,0 +1,13 @@ +{ + "name": "Linguist", + "repository": "qttools", + "version": "6.8.1", + "built_with": { + "compiler_id": "MSVC", + "compiler_target": "", + "compiler_version": "19.39.33520.0", + "cross_compiled": false, + "target_system": "Windows", + "architecture": "x86_64" + } +} diff --git a/qt/6.8.1/msvc2022_64/modules/Network.json b/qt/6.8.1/msvc2022_64/modules/Network.json new file mode 100644 index 0000000000000000000000000000000000000000..3caa7ab9e68f4a55314fecd9a78045d36f650600 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/modules/Network.json @@ -0,0 +1,14 @@ +{ + "name": "Network", + "repository": "qtbase", + "version": "6.8.1", + "plugin_types": ["networkaccess", "networkinformation", "tls"], + "built_with": { + "compiler_id": "MSVC", + "compiler_target": "", + "compiler_version": "19.39.33520.0", + "cross_compiled": false, + "target_system": "Windows", + "architecture": "x86_64" + } +} diff --git a/qt/6.8.1/msvc2022_64/modules/OpenGL.json b/qt/6.8.1/msvc2022_64/modules/OpenGL.json new file mode 100644 index 0000000000000000000000000000000000000000..8d2737f475560b45790a4185e2d41879ed14192e --- /dev/null +++ b/qt/6.8.1/msvc2022_64/modules/OpenGL.json @@ -0,0 +1,13 @@ +{ + "name": "OpenGL", + "repository": "qtbase", + "version": "6.8.1", + "built_with": { + "compiler_id": "MSVC", + "compiler_target": "", + "compiler_version": "19.39.33520.0", + "cross_compiled": false, + "target_system": "Windows", + "architecture": "x86_64" + } +} diff --git a/qt/6.8.1/msvc2022_64/modules/OpenGLWidgets.json b/qt/6.8.1/msvc2022_64/modules/OpenGLWidgets.json new file mode 100644 index 0000000000000000000000000000000000000000..797d171032d06ed26b6c43614b3b710b51ff65fb --- /dev/null +++ b/qt/6.8.1/msvc2022_64/modules/OpenGLWidgets.json @@ -0,0 +1,13 @@ +{ + "name": "OpenGLWidgets", + "repository": "qtbase", + "version": "6.8.1", + "built_with": { + "compiler_id": "MSVC", + "compiler_target": "", + "compiler_version": "19.39.33520.0", + "cross_compiled": false, + "target_system": "Windows", + "architecture": "x86_64" + } +} diff --git a/qt/6.8.1/msvc2022_64/modules/PacketProtocolPrivate.json b/qt/6.8.1/msvc2022_64/modules/PacketProtocolPrivate.json new file mode 100644 index 0000000000000000000000000000000000000000..529c6a340dc4bbefc4ced2df6cdb1d8d10948b9d --- /dev/null +++ b/qt/6.8.1/msvc2022_64/modules/PacketProtocolPrivate.json @@ -0,0 +1,14 @@ +{ + "name": "PacketProtocolPrivate", + "repository": "qtdeclarative", + "version": "6.8.1", + "internal": true, + "built_with": { + "compiler_id": "MSVC", + "compiler_target": "", + "compiler_version": "19.39.33520.0", + "cross_compiled": false, + "target_system": "Windows", + "architecture": "x86_64" + } +} diff --git a/qt/6.8.1/msvc2022_64/modules/PngPrivate.json b/qt/6.8.1/msvc2022_64/modules/PngPrivate.json new file mode 100644 index 0000000000000000000000000000000000000000..89e7cfcfe8343aec9ce2168135b722ad0ff48814 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/modules/PngPrivate.json @@ -0,0 +1,14 @@ +{ + "name": "PngPrivate", + "repository": "qtbase", + "version": "6.8.1", + "internal": true, + "built_with": { + "compiler_id": "MSVC", + "compiler_target": "", + "compiler_version": "19.39.33520.0", + "cross_compiled": false, + "target_system": "Windows", + "architecture": "x86_64" + } +} diff --git a/qt/6.8.1/msvc2022_64/modules/PrintSupport.json b/qt/6.8.1/msvc2022_64/modules/PrintSupport.json new file mode 100644 index 0000000000000000000000000000000000000000..45164995ee45739544dc8783cbf37b2f7dfdc8e7 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/modules/PrintSupport.json @@ -0,0 +1,14 @@ +{ + "name": "PrintSupport", + "repository": "qtbase", + "version": "6.8.1", + "plugin_types": ["printsupport"], + "built_with": { + "compiler_id": "MSVC", + "compiler_target": "", + "compiler_version": "19.39.33520.0", + "cross_compiled": false, + "target_system": "Windows", + "architecture": "x86_64" + } +} diff --git a/qt/6.8.1/msvc2022_64/modules/QDocCatchConversionsPrivate.json b/qt/6.8.1/msvc2022_64/modules/QDocCatchConversionsPrivate.json new file mode 100644 index 0000000000000000000000000000000000000000..ea3c24284ba00103ac42cf568659be9eef179c91 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/modules/QDocCatchConversionsPrivate.json @@ -0,0 +1,14 @@ +{ + "name": "QDocCatchConversionsPrivate", + "repository": "qttools", + "version": "6.8.1", + "internal": true, + "built_with": { + "compiler_id": "MSVC", + "compiler_target": "", + "compiler_version": "19.39.33520.0", + "cross_compiled": false, + "target_system": "Windows", + "architecture": "x86_64" + } +} diff --git a/qt/6.8.1/msvc2022_64/modules/QDocCatchGeneratorsPrivate.json b/qt/6.8.1/msvc2022_64/modules/QDocCatchGeneratorsPrivate.json new file mode 100644 index 0000000000000000000000000000000000000000..384d997e848bfc99d8466237ba551a7d949d82f7 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/modules/QDocCatchGeneratorsPrivate.json @@ -0,0 +1,14 @@ +{ + "name": "QDocCatchGeneratorsPrivate", + "repository": "qttools", + "version": "6.8.1", + "internal": true, + "built_with": { + "compiler_id": "MSVC", + "compiler_target": "", + "compiler_version": "19.39.33520.0", + "cross_compiled": false, + "target_system": "Windows", + "architecture": "x86_64" + } +} diff --git a/qt/6.8.1/msvc2022_64/modules/QDocCatchPrivate.json b/qt/6.8.1/msvc2022_64/modules/QDocCatchPrivate.json new file mode 100644 index 0000000000000000000000000000000000000000..25e54e805fb1a8f8892df01cb96e2e24081b0756 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/modules/QDocCatchPrivate.json @@ -0,0 +1,14 @@ +{ + "name": "QDocCatchPrivate", + "repository": "qttools", + "version": "6.8.1", + "internal": true, + "built_with": { + "compiler_id": "MSVC", + "compiler_target": "", + "compiler_version": "19.39.33520.0", + "cross_compiled": false, + "target_system": "Windows", + "architecture": "x86_64" + } +} diff --git a/qt/6.8.1/msvc2022_64/modules/Qml.json b/qt/6.8.1/msvc2022_64/modules/Qml.json new file mode 100644 index 0000000000000000000000000000000000000000..cd471e3eeff5e8b4399c62d8e89da3d442f13446 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/modules/Qml.json @@ -0,0 +1,14 @@ +{ + "name": "Qml", + "repository": "qtdeclarative", + "version": "6.8.1", + "plugin_types": ["qmltooling"], + "built_with": { + "compiler_id": "MSVC", + "compiler_target": "", + "compiler_version": "19.39.33520.0", + "cross_compiled": false, + "target_system": "Windows", + "architecture": "x86_64" + } +} diff --git a/qt/6.8.1/msvc2022_64/modules/QmlAssetDownloader.json b/qt/6.8.1/msvc2022_64/modules/QmlAssetDownloader.json new file mode 100644 index 0000000000000000000000000000000000000000..c0f425d6c806cfe5e3910d9467de172cc3f5e939 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/modules/QmlAssetDownloader.json @@ -0,0 +1,13 @@ +{ + "name": "QmlAssetDownloader", + "repository": "qtdeclarative", + "version": "6.8.1", + "built_with": { + "compiler_id": "MSVC", + "compiler_target": "", + "compiler_version": "19.39.33520.0", + "cross_compiled": false, + "target_system": "Windows", + "architecture": "x86_64" + } +} diff --git a/qt/6.8.1/msvc2022_64/modules/QmlCompiler.json b/qt/6.8.1/msvc2022_64/modules/QmlCompiler.json new file mode 100644 index 0000000000000000000000000000000000000000..b7cb122aa91ba39f9eb4c798850f81e4086fe97a --- /dev/null +++ b/qt/6.8.1/msvc2022_64/modules/QmlCompiler.json @@ -0,0 +1,14 @@ +{ + "name": "QmlCompiler", + "repository": "qtdeclarative", + "version": "6.8.1", + "plugin_types": ["qmllint"], + "built_with": { + "compiler_id": "MSVC", + "compiler_target": "", + "compiler_version": "19.39.33520.0", + "cross_compiled": false, + "target_system": "Windows", + "architecture": "x86_64" + } +} diff --git a/qt/6.8.1/msvc2022_64/modules/QmlCore.json b/qt/6.8.1/msvc2022_64/modules/QmlCore.json new file mode 100644 index 0000000000000000000000000000000000000000..313b8898436ce2b53db03cfd81eb04da8faf83b2 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/modules/QmlCore.json @@ -0,0 +1,13 @@ +{ + "name": "QmlCore", + "repository": "qtdeclarative", + "version": "6.8.1", + "built_with": { + "compiler_id": "MSVC", + "compiler_target": "", + "compiler_version": "19.39.33520.0", + "cross_compiled": false, + "target_system": "Windows", + "architecture": "x86_64" + } +} diff --git a/qt/6.8.1/msvc2022_64/modules/QmlDebugPrivate.json b/qt/6.8.1/msvc2022_64/modules/QmlDebugPrivate.json new file mode 100644 index 0000000000000000000000000000000000000000..aef8d83a44c2c5aa0a13e00707d15c434b640831 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/modules/QmlDebugPrivate.json @@ -0,0 +1,14 @@ +{ + "name": "QmlDebugPrivate", + "repository": "qtdeclarative", + "version": "6.8.1", + "internal": true, + "built_with": { + "compiler_id": "MSVC", + "compiler_target": "", + "compiler_version": "19.39.33520.0", + "cross_compiled": false, + "target_system": "Windows", + "architecture": "x86_64" + } +} diff --git a/qt/6.8.1/msvc2022_64/modules/QmlDomPrivate.json b/qt/6.8.1/msvc2022_64/modules/QmlDomPrivate.json new file mode 100644 index 0000000000000000000000000000000000000000..ac820077f02c8e9070516c418575ba75a0d15f12 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/modules/QmlDomPrivate.json @@ -0,0 +1,14 @@ +{ + "name": "QmlDomPrivate", + "repository": "qtdeclarative", + "version": "6.8.1", + "internal": true, + "built_with": { + "compiler_id": "MSVC", + "compiler_target": "", + "compiler_version": "19.39.33520.0", + "cross_compiled": false, + "target_system": "Windows", + "architecture": "x86_64" + } +} diff --git a/qt/6.8.1/msvc2022_64/modules/QmlIntegration.json b/qt/6.8.1/msvc2022_64/modules/QmlIntegration.json new file mode 100644 index 0000000000000000000000000000000000000000..a1d823e6f70f30f77ff2eba6c47e89800e74a055 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/modules/QmlIntegration.json @@ -0,0 +1,13 @@ +{ + "name": "QmlIntegration", + "repository": "qtdeclarative", + "version": "6.8.1", + "built_with": { + "compiler_id": "MSVC", + "compiler_target": "", + "compiler_version": "19.39.33520.0", + "cross_compiled": false, + "target_system": "Windows", + "architecture": "x86_64" + } +} diff --git a/qt/6.8.1/msvc2022_64/modules/QmlLSPrivate.json b/qt/6.8.1/msvc2022_64/modules/QmlLSPrivate.json new file mode 100644 index 0000000000000000000000000000000000000000..e68ebe7fdff646521c65ba34ecd7b411e1c64d40 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/modules/QmlLSPrivate.json @@ -0,0 +1,15 @@ +{ + "name": "QmlLSPrivate", + "repository": "qtdeclarative", + "version": "6.8.1", + "plugin_types": ["qmlls"], + "internal": true, + "built_with": { + "compiler_id": "MSVC", + "compiler_target": "", + "compiler_version": "19.39.33520.0", + "cross_compiled": false, + "target_system": "Windows", + "architecture": "x86_64" + } +} diff --git a/qt/6.8.1/msvc2022_64/modules/QmlLocalStorage.json b/qt/6.8.1/msvc2022_64/modules/QmlLocalStorage.json new file mode 100644 index 0000000000000000000000000000000000000000..1d52c55c1f2fcf188a89aed120f124e29586ad85 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/modules/QmlLocalStorage.json @@ -0,0 +1,13 @@ +{ + "name": "QmlLocalStorage", + "repository": "qtdeclarative", + "version": "6.8.1", + "built_with": { + "compiler_id": "MSVC", + "compiler_target": "", + "compiler_version": "19.39.33520.0", + "cross_compiled": false, + "target_system": "Windows", + "architecture": "x86_64" + } +} diff --git a/qt/6.8.1/msvc2022_64/modules/QmlMeta.json b/qt/6.8.1/msvc2022_64/modules/QmlMeta.json new file mode 100644 index 0000000000000000000000000000000000000000..24dff384c528acb6283fed2c0a2ad294a93db289 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/modules/QmlMeta.json @@ -0,0 +1,13 @@ +{ + "name": "QmlMeta", + "repository": "qtdeclarative", + "version": "6.8.1", + "built_with": { + "compiler_id": "MSVC", + "compiler_target": "", + "compiler_version": "19.39.33520.0", + "cross_compiled": false, + "target_system": "Windows", + "architecture": "x86_64" + } +} diff --git a/qt/6.8.1/msvc2022_64/modules/QmlModels.json b/qt/6.8.1/msvc2022_64/modules/QmlModels.json new file mode 100644 index 0000000000000000000000000000000000000000..e9e490c5badcb57c8253fe769e54f361423f9365 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/modules/QmlModels.json @@ -0,0 +1,13 @@ +{ + "name": "QmlModels", + "repository": "qtdeclarative", + "version": "6.8.1", + "built_with": { + "compiler_id": "MSVC", + "compiler_target": "", + "compiler_version": "19.39.33520.0", + "cross_compiled": false, + "target_system": "Windows", + "architecture": "x86_64" + } +} diff --git a/qt/6.8.1/msvc2022_64/modules/QmlNetwork.json b/qt/6.8.1/msvc2022_64/modules/QmlNetwork.json new file mode 100644 index 0000000000000000000000000000000000000000..47fffb933f49fc16b1f1113562e99417aeb190c3 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/modules/QmlNetwork.json @@ -0,0 +1,13 @@ +{ + "name": "QmlNetwork", + "repository": "qtdeclarative", + "version": "6.8.1", + "built_with": { + "compiler_id": "MSVC", + "compiler_target": "", + "compiler_version": "19.39.33520.0", + "cross_compiled": false, + "target_system": "Windows", + "architecture": "x86_64" + } +} diff --git a/qt/6.8.1/msvc2022_64/modules/QmlToolingSettingsPrivate.json b/qt/6.8.1/msvc2022_64/modules/QmlToolingSettingsPrivate.json new file mode 100644 index 0000000000000000000000000000000000000000..e4c0ede8202ce0a9864609fb3a36df7597714584 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/modules/QmlToolingSettingsPrivate.json @@ -0,0 +1,14 @@ +{ + "name": "QmlToolingSettingsPrivate", + "repository": "qtdeclarative", + "version": "6.8.1", + "internal": true, + "built_with": { + "compiler_id": "MSVC", + "compiler_target": "", + "compiler_version": "19.39.33520.0", + "cross_compiled": false, + "target_system": "Windows", + "architecture": "x86_64" + } +} diff --git a/qt/6.8.1/msvc2022_64/modules/QmlTypeRegistrarPrivate.json b/qt/6.8.1/msvc2022_64/modules/QmlTypeRegistrarPrivate.json new file mode 100644 index 0000000000000000000000000000000000000000..c2dff50c3c8d228ce4c99e7c070ad308abc13a7b --- /dev/null +++ b/qt/6.8.1/msvc2022_64/modules/QmlTypeRegistrarPrivate.json @@ -0,0 +1,14 @@ +{ + "name": "QmlTypeRegistrarPrivate", + "repository": "qtdeclarative", + "version": "6.8.1", + "internal": true, + "built_with": { + "compiler_id": "MSVC", + "compiler_target": "", + "compiler_version": "19.39.33520.0", + "cross_compiled": false, + "target_system": "Windows", + "architecture": "x86_64" + } +} diff --git a/qt/6.8.1/msvc2022_64/modules/QmlWorkerScript.json b/qt/6.8.1/msvc2022_64/modules/QmlWorkerScript.json new file mode 100644 index 0000000000000000000000000000000000000000..adca19f0b47a1bc8757b716d17a8aeee7a9c589e --- /dev/null +++ b/qt/6.8.1/msvc2022_64/modules/QmlWorkerScript.json @@ -0,0 +1,13 @@ +{ + "name": "QmlWorkerScript", + "repository": "qtdeclarative", + "version": "6.8.1", + "built_with": { + "compiler_id": "MSVC", + "compiler_target": "", + "compiler_version": "19.39.33520.0", + "cross_compiled": false, + "target_system": "Windows", + "architecture": "x86_64" + } +} diff --git a/qt/6.8.1/msvc2022_64/modules/QmlXmlListModel.json b/qt/6.8.1/msvc2022_64/modules/QmlXmlListModel.json new file mode 100644 index 0000000000000000000000000000000000000000..8690da65ca290b60ce8091b9e8ec5fe5fca204dc --- /dev/null +++ b/qt/6.8.1/msvc2022_64/modules/QmlXmlListModel.json @@ -0,0 +1,13 @@ +{ + "name": "QmlXmlListModel", + "repository": "qtdeclarative", + "version": "6.8.1", + "built_with": { + "compiler_id": "MSVC", + "compiler_target": "", + "compiler_version": "19.39.33520.0", + "cross_compiled": false, + "target_system": "Windows", + "architecture": "x86_64" + } +} diff --git a/qt/6.8.1/msvc2022_64/modules/Quick.json b/qt/6.8.1/msvc2022_64/modules/Quick.json new file mode 100644 index 0000000000000000000000000000000000000000..3f8f98c02fcb8ca48e56408d8e1db154c12601b2 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/modules/Quick.json @@ -0,0 +1,14 @@ +{ + "name": "Quick", + "repository": "qtdeclarative", + "version": "6.8.1", + "plugin_types": ["scenegraph"], + "built_with": { + "compiler_id": "MSVC", + "compiler_target": "", + "compiler_version": "19.39.33520.0", + "cross_compiled": false, + "target_system": "Windows", + "architecture": "x86_64" + } +} diff --git a/qt/6.8.1/msvc2022_64/modules/QuickControls2.json b/qt/6.8.1/msvc2022_64/modules/QuickControls2.json new file mode 100644 index 0000000000000000000000000000000000000000..f916a8d0e6ee469a52ff55b0c0349c17c4537f02 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/modules/QuickControls2.json @@ -0,0 +1,13 @@ +{ + "name": "QuickControls2", + "repository": "qtdeclarative", + "version": "6.8.1", + "built_with": { + "compiler_id": "MSVC", + "compiler_target": "", + "compiler_version": "19.39.33520.0", + "cross_compiled": false, + "target_system": "Windows", + "architecture": "x86_64" + } +} diff --git a/qt/6.8.1/msvc2022_64/modules/QuickControls2Basic.json b/qt/6.8.1/msvc2022_64/modules/QuickControls2Basic.json new file mode 100644 index 0000000000000000000000000000000000000000..9782cc26fc9ec1e569f9d08a1101bbc1699f3b44 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/modules/QuickControls2Basic.json @@ -0,0 +1,13 @@ +{ + "name": "QuickControls2Basic", + "repository": "qtdeclarative", + "version": "6.8.1", + "built_with": { + "compiler_id": "MSVC", + "compiler_target": "", + "compiler_version": "19.39.33520.0", + "cross_compiled": false, + "target_system": "Windows", + "architecture": "x86_64" + } +} diff --git a/qt/6.8.1/msvc2022_64/modules/QuickControls2BasicStyleImpl.json b/qt/6.8.1/msvc2022_64/modules/QuickControls2BasicStyleImpl.json new file mode 100644 index 0000000000000000000000000000000000000000..a9fe009f198e4adb43b049167905bba5e62e434e --- /dev/null +++ b/qt/6.8.1/msvc2022_64/modules/QuickControls2BasicStyleImpl.json @@ -0,0 +1,13 @@ +{ + "name": "QuickControls2BasicStyleImpl", + "repository": "qtdeclarative", + "version": "6.8.1", + "built_with": { + "compiler_id": "MSVC", + "compiler_target": "", + "compiler_version": "19.39.33520.0", + "cross_compiled": false, + "target_system": "Windows", + "architecture": "x86_64" + } +} diff --git a/qt/6.8.1/msvc2022_64/modules/QuickControls2FluentWinUI3StyleImpl.json b/qt/6.8.1/msvc2022_64/modules/QuickControls2FluentWinUI3StyleImpl.json new file mode 100644 index 0000000000000000000000000000000000000000..f8227ee72da34179aa6aa300d00aaf0b55fa90e8 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/modules/QuickControls2FluentWinUI3StyleImpl.json @@ -0,0 +1,13 @@ +{ + "name": "QuickControls2FluentWinUI3StyleImpl", + "repository": "qtdeclarative", + "version": "6.8.1", + "built_with": { + "compiler_id": "MSVC", + "compiler_target": "", + "compiler_version": "19.39.33520.0", + "cross_compiled": false, + "target_system": "Windows", + "architecture": "x86_64" + } +} diff --git a/qt/6.8.1/msvc2022_64/modules/QuickControls2Fusion.json b/qt/6.8.1/msvc2022_64/modules/QuickControls2Fusion.json new file mode 100644 index 0000000000000000000000000000000000000000..047a517034c3eebde7ab691e3313b0c07b7a3e0d --- /dev/null +++ b/qt/6.8.1/msvc2022_64/modules/QuickControls2Fusion.json @@ -0,0 +1,13 @@ +{ + "name": "QuickControls2Fusion", + "repository": "qtdeclarative", + "version": "6.8.1", + "built_with": { + "compiler_id": "MSVC", + "compiler_target": "", + "compiler_version": "19.39.33520.0", + "cross_compiled": false, + "target_system": "Windows", + "architecture": "x86_64" + } +} diff --git a/qt/6.8.1/msvc2022_64/modules/QuickControls2FusionStyleImpl.json b/qt/6.8.1/msvc2022_64/modules/QuickControls2FusionStyleImpl.json new file mode 100644 index 0000000000000000000000000000000000000000..d2a731d5b487381f834c6790552b96903c1b0e61 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/modules/QuickControls2FusionStyleImpl.json @@ -0,0 +1,13 @@ +{ + "name": "QuickControls2FusionStyleImpl", + "repository": "qtdeclarative", + "version": "6.8.1", + "built_with": { + "compiler_id": "MSVC", + "compiler_target": "", + "compiler_version": "19.39.33520.0", + "cross_compiled": false, + "target_system": "Windows", + "architecture": "x86_64" + } +} diff --git a/qt/6.8.1/msvc2022_64/modules/QuickControls2Imagine.json b/qt/6.8.1/msvc2022_64/modules/QuickControls2Imagine.json new file mode 100644 index 0000000000000000000000000000000000000000..18b79ea96aca7df836b0ea168ba2815af3fc4356 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/modules/QuickControls2Imagine.json @@ -0,0 +1,13 @@ +{ + "name": "QuickControls2Imagine", + "repository": "qtdeclarative", + "version": "6.8.1", + "built_with": { + "compiler_id": "MSVC", + "compiler_target": "", + "compiler_version": "19.39.33520.0", + "cross_compiled": false, + "target_system": "Windows", + "architecture": "x86_64" + } +} diff --git a/qt/6.8.1/msvc2022_64/modules/QuickControls2ImagineStyleImpl.json b/qt/6.8.1/msvc2022_64/modules/QuickControls2ImagineStyleImpl.json new file mode 100644 index 0000000000000000000000000000000000000000..c26350ac38781e3956810d0d597cc72cbb688290 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/modules/QuickControls2ImagineStyleImpl.json @@ -0,0 +1,13 @@ +{ + "name": "QuickControls2ImagineStyleImpl", + "repository": "qtdeclarative", + "version": "6.8.1", + "built_with": { + "compiler_id": "MSVC", + "compiler_target": "", + "compiler_version": "19.39.33520.0", + "cross_compiled": false, + "target_system": "Windows", + "architecture": "x86_64" + } +} diff --git a/qt/6.8.1/msvc2022_64/modules/QuickControls2Impl.json b/qt/6.8.1/msvc2022_64/modules/QuickControls2Impl.json new file mode 100644 index 0000000000000000000000000000000000000000..4ac2a6a9be23c35290caaa2eefe15992828f4a2c --- /dev/null +++ b/qt/6.8.1/msvc2022_64/modules/QuickControls2Impl.json @@ -0,0 +1,13 @@ +{ + "name": "QuickControls2Impl", + "repository": "qtdeclarative", + "version": "6.8.1", + "built_with": { + "compiler_id": "MSVC", + "compiler_target": "", + "compiler_version": "19.39.33520.0", + "cross_compiled": false, + "target_system": "Windows", + "architecture": "x86_64" + } +} diff --git a/qt/6.8.1/msvc2022_64/modules/QuickControls2Material.json b/qt/6.8.1/msvc2022_64/modules/QuickControls2Material.json new file mode 100644 index 0000000000000000000000000000000000000000..e8cac863aa16464557898f0dacf6e3278227add5 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/modules/QuickControls2Material.json @@ -0,0 +1,13 @@ +{ + "name": "QuickControls2Material", + "repository": "qtdeclarative", + "version": "6.8.1", + "built_with": { + "compiler_id": "MSVC", + "compiler_target": "", + "compiler_version": "19.39.33520.0", + "cross_compiled": false, + "target_system": "Windows", + "architecture": "x86_64" + } +} diff --git a/qt/6.8.1/msvc2022_64/modules/QuickControls2MaterialStyleImpl.json b/qt/6.8.1/msvc2022_64/modules/QuickControls2MaterialStyleImpl.json new file mode 100644 index 0000000000000000000000000000000000000000..ca8bf58871e26a192522cfec463c9778e05ea1b3 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/modules/QuickControls2MaterialStyleImpl.json @@ -0,0 +1,13 @@ +{ + "name": "QuickControls2MaterialStyleImpl", + "repository": "qtdeclarative", + "version": "6.8.1", + "built_with": { + "compiler_id": "MSVC", + "compiler_target": "", + "compiler_version": "19.39.33520.0", + "cross_compiled": false, + "target_system": "Windows", + "architecture": "x86_64" + } +} diff --git a/qt/6.8.1/msvc2022_64/modules/QuickControls2Universal.json b/qt/6.8.1/msvc2022_64/modules/QuickControls2Universal.json new file mode 100644 index 0000000000000000000000000000000000000000..2ee2330668ab82976e49184bc79012d6463b37cd --- /dev/null +++ b/qt/6.8.1/msvc2022_64/modules/QuickControls2Universal.json @@ -0,0 +1,13 @@ +{ + "name": "QuickControls2Universal", + "repository": "qtdeclarative", + "version": "6.8.1", + "built_with": { + "compiler_id": "MSVC", + "compiler_target": "", + "compiler_version": "19.39.33520.0", + "cross_compiled": false, + "target_system": "Windows", + "architecture": "x86_64" + } +} diff --git a/qt/6.8.1/msvc2022_64/modules/QuickControls2UniversalStyleImpl.json b/qt/6.8.1/msvc2022_64/modules/QuickControls2UniversalStyleImpl.json new file mode 100644 index 0000000000000000000000000000000000000000..178c781b874e46193c28738a6971b518cb692345 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/modules/QuickControls2UniversalStyleImpl.json @@ -0,0 +1,13 @@ +{ + "name": "QuickControls2UniversalStyleImpl", + "repository": "qtdeclarative", + "version": "6.8.1", + "built_with": { + "compiler_id": "MSVC", + "compiler_target": "", + "compiler_version": "19.39.33520.0", + "cross_compiled": false, + "target_system": "Windows", + "architecture": "x86_64" + } +} diff --git a/qt/6.8.1/msvc2022_64/modules/QuickControls2WindowsStyleImpl.json b/qt/6.8.1/msvc2022_64/modules/QuickControls2WindowsStyleImpl.json new file mode 100644 index 0000000000000000000000000000000000000000..e238c0319ecf4a3cfc77483311d5157ff56cdd2c --- /dev/null +++ b/qt/6.8.1/msvc2022_64/modules/QuickControls2WindowsStyleImpl.json @@ -0,0 +1,13 @@ +{ + "name": "QuickControls2WindowsStyleImpl", + "repository": "qtdeclarative", + "version": "6.8.1", + "built_with": { + "compiler_id": "MSVC", + "compiler_target": "", + "compiler_version": "19.39.33520.0", + "cross_compiled": false, + "target_system": "Windows", + "architecture": "x86_64" + } +} diff --git a/qt/6.8.1/msvc2022_64/modules/QuickControlsTestUtilsPrivate.json b/qt/6.8.1/msvc2022_64/modules/QuickControlsTestUtilsPrivate.json new file mode 100644 index 0000000000000000000000000000000000000000..60022f438e834dcc3e1fa0759076e1a2bff7a610 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/modules/QuickControlsTestUtilsPrivate.json @@ -0,0 +1,14 @@ +{ + "name": "QuickControlsTestUtilsPrivate", + "repository": "qtdeclarative", + "version": "6.8.1", + "internal": true, + "built_with": { + "compiler_id": "MSVC", + "compiler_target": "", + "compiler_version": "19.39.33520.0", + "cross_compiled": false, + "target_system": "Windows", + "architecture": "x86_64" + } +} diff --git a/qt/6.8.1/msvc2022_64/modules/QuickDialogs2.json b/qt/6.8.1/msvc2022_64/modules/QuickDialogs2.json new file mode 100644 index 0000000000000000000000000000000000000000..956b510ec9b03c26f43473ffb7f9b44bdd81f103 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/modules/QuickDialogs2.json @@ -0,0 +1,13 @@ +{ + "name": "QuickDialogs2", + "repository": "qtdeclarative", + "version": "6.8.1", + "built_with": { + "compiler_id": "MSVC", + "compiler_target": "", + "compiler_version": "19.39.33520.0", + "cross_compiled": false, + "target_system": "Windows", + "architecture": "x86_64" + } +} diff --git a/qt/6.8.1/msvc2022_64/modules/QuickDialogs2QuickImpl.json b/qt/6.8.1/msvc2022_64/modules/QuickDialogs2QuickImpl.json new file mode 100644 index 0000000000000000000000000000000000000000..01d6b7f2838de41ded1d739ef4fae0a40c23b817 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/modules/QuickDialogs2QuickImpl.json @@ -0,0 +1,13 @@ +{ + "name": "QuickDialogs2QuickImpl", + "repository": "qtdeclarative", + "version": "6.8.1", + "built_with": { + "compiler_id": "MSVC", + "compiler_target": "", + "compiler_version": "19.39.33520.0", + "cross_compiled": false, + "target_system": "Windows", + "architecture": "x86_64" + } +} diff --git a/qt/6.8.1/msvc2022_64/modules/QuickDialogs2Utils.json b/qt/6.8.1/msvc2022_64/modules/QuickDialogs2Utils.json new file mode 100644 index 0000000000000000000000000000000000000000..e0a234c071f6121775e9e41dad764e4dd1b03728 --- /dev/null +++ b/qt/6.8.1/msvc2022_64/modules/QuickDialogs2Utils.json @@ -0,0 +1,13 @@ +{ + "name": "QuickDialogs2Utils", + "repository": "qtdeclarative", + "version": "6.8.1", + "built_with": { + "compiler_id": "MSVC", + "compiler_target": "", + "compiler_version": "19.39.33520.0", + "cross_compiled": false, + "target_system": "Windows", + "architecture": "x86_64" + } +} diff --git a/qt/6.8.1/msvc2022_64/modules/QuickEffectsPrivate.json b/qt/6.8.1/msvc2022_64/modules/QuickEffectsPrivate.json new file mode 100644 index 0000000000000000000000000000000000000000..cf22150c923e1361ebe001fce156e5ff13e4e4fe --- /dev/null +++ b/qt/6.8.1/msvc2022_64/modules/QuickEffectsPrivate.json @@ -0,0 +1,14 @@ +{ + "name": "QuickEffectsPrivate", + "repository": "qtdeclarative", + "version": "6.8.1", + "internal": true, + "built_with": { + "compiler_id": "MSVC", + "compiler_target": "", + "compiler_version": "19.39.33520.0", + "cross_compiled": false, + "target_system": "Windows", + "architecture": "x86_64" + } +}